id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,400 | EnigmaBridge/client.py | ebclient/eb_create_uo.py | CreateUO.build_imported_object | def build_imported_object(configuration, tpl_import_req, import_resp):
"""
Builds uo from the imported object to the EB.
Imported object = result of CreateUserObject call in EB.
Returns usable uo - you may call ProcessData with it.
"""
if import_resp is None \
... | python | def build_imported_object(configuration, tpl_import_req, import_resp):
"""
Builds uo from the imported object to the EB.
Imported object = result of CreateUserObject call in EB.
Returns usable uo - you may call ProcessData with it.
"""
if import_resp is None \
... | [
"def",
"build_imported_object",
"(",
"configuration",
",",
"tpl_import_req",
",",
"import_resp",
")",
":",
"if",
"import_resp",
"is",
"None",
"or",
"import_resp",
".",
"response",
"is",
"None",
"or",
"'result'",
"not",
"in",
"import_resp",
".",
"response",
"or",... | Builds uo from the imported object to the EB.
Imported object = result of CreateUserObject call in EB.
Returns usable uo - you may call ProcessData with it. | [
"Builds",
"uo",
"from",
"the",
"imported",
"object",
"to",
"the",
"EB",
".",
"Imported",
"object",
"=",
"result",
"of",
"CreateUserObject",
"call",
"in",
"EB",
".",
"Returns",
"usable",
"uo",
"-",
"you",
"may",
"call",
"ProcessData",
"with",
"it",
"."
] | 0fafe3902da394da88e9f960751d695ca65bbabd | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L274-L309 |
242,401 | EnigmaBridge/client.py | ebclient/eb_create_uo.py | TemplateProcessor.read_serialized_rsa_pub_key | def read_serialized_rsa_pub_key(serialized):
"""
Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e
"""
n = None
e = None
rsa = from_hex(serialized)
pos = 0
ln = len(rsa)
... | python | def read_serialized_rsa_pub_key(serialized):
"""
Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e
"""
n = None
e = None
rsa = from_hex(serialized)
pos = 0
ln = len(rsa)
... | [
"def",
"read_serialized_rsa_pub_key",
"(",
"serialized",
")",
":",
"n",
"=",
"None",
"e",
"=",
"None",
"rsa",
"=",
"from_hex",
"(",
"serialized",
")",
"pos",
"=",
"0",
"ln",
"=",
"len",
"(",
"rsa",
")",
"while",
"pos",
"<",
"ln",
":",
"tag",
"=",
"... | Reads serialized RSA pub key
TAG|len-2B|value. 81 = exponent, 82 = modulus
:param serialized:
:return: n, e | [
"Reads",
"serialized",
"RSA",
"pub",
"key",
"TAG|len",
"-",
"2B|value",
".",
"81",
"=",
"exponent",
"82",
"=",
"modulus"
] | 0fafe3902da394da88e9f960751d695ca65bbabd | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L532-L563 |
242,402 | hobson/pug-dj | pug/dj/crawlnmine/crawlnmine/settings/common.py | env | def env(var_name, default=False):
""" Get the environment variable or assume a default, but let the user know about the error."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']:
return None
return value
except... | python | def env(var_name, default=False):
""" Get the environment variable or assume a default, but let the user know about the error."""
try:
value = os.environ[var_name]
if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']:
return None
return value
except... | [
"def",
"env",
"(",
"var_name",
",",
"default",
"=",
"False",
")",
":",
"try",
":",
"value",
"=",
"os",
".",
"environ",
"[",
"var_name",
"]",
"if",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"in",
"[",
"'false'",
"... | Get the environment variable or assume a default, but let the user know about the error. | [
"Get",
"the",
"environment",
"variable",
"or",
"assume",
"a",
"default",
"but",
"let",
"the",
"user",
"know",
"about",
"the",
"error",
"."
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/crawlnmine/settings/common.py#L20-L31 |
242,403 | saltzm/yadi | yadi/datalog2sql/ast2sql/safety_checker.py | ConjunctiveQuerySafetyChecker.check_negated_goals | def check_negated_goals(self,safe_variables,query):
''' Create a list of variables which occur in negated goals. '''
variables_in_negated_goals = \
[y for x in query.relations for y in list(x.variables) if x.is_negated()]
# And check them:
for variable in variables_in_negate... | python | def check_negated_goals(self,safe_variables,query):
''' Create a list of variables which occur in negated goals. '''
variables_in_negated_goals = \
[y for x in query.relations for y in list(x.variables) if x.is_negated()]
# And check them:
for variable in variables_in_negate... | [
"def",
"check_negated_goals",
"(",
"self",
",",
"safe_variables",
",",
"query",
")",
":",
"variables_in_negated_goals",
"=",
"[",
"y",
"for",
"x",
"in",
"query",
".",
"relations",
"for",
"y",
"in",
"list",
"(",
"x",
".",
"variables",
")",
"if",
"x",
".",... | Create a list of variables which occur in negated goals. | [
"Create",
"a",
"list",
"of",
"variables",
"which",
"occur",
"in",
"negated",
"goals",
"."
] | 755790167c350e650c1e8b15c6f9209a97be9e42 | https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/safety_checker.py#L41-L54 |
242,404 | saltzm/yadi | yadi/datalog2sql/ast2sql/safety_checker.py | ConjunctiveQuerySafetyChecker.check_non_equality_explicit_constraints | def check_non_equality_explicit_constraints(self,safe_variables,query):
''' Checking variables which occur in explicit constraints with non equality
operators '''
# Create a list of variables which occur in explicit constraints with non
# equality operators
variables_in_constrain... | python | def check_non_equality_explicit_constraints(self,safe_variables,query):
''' Checking variables which occur in explicit constraints with non equality
operators '''
# Create a list of variables which occur in explicit constraints with non
# equality operators
variables_in_constrain... | [
"def",
"check_non_equality_explicit_constraints",
"(",
"self",
",",
"safe_variables",
",",
"query",
")",
":",
"# Create a list of variables which occur in explicit constraints with non",
"# equality operators",
"variables_in_constraints_with_non_equality_operators",
"=",
"[",
"y",
"f... | Checking variables which occur in explicit constraints with non equality
operators | [
"Checking",
"variables",
"which",
"occur",
"in",
"explicit",
"constraints",
"with",
"non",
"equality",
"operators"
] | 755790167c350e650c1e8b15c6f9209a97be9e42 | https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/safety_checker.py#L56-L73 |
242,405 | tax/snor | snor/utils.py | create_database | def create_database(destroy_existing=False):
""" Create db and tables if it doesn't exist """
if not os.path.exists(DB_NAME):
logger.info('Create database: {0}'.format(DB_NAME))
open(DB_NAME, 'a').close()
Show.create_table()
Episode.create_table()
Setting.create_ta... | python | def create_database(destroy_existing=False):
""" Create db and tables if it doesn't exist """
if not os.path.exists(DB_NAME):
logger.info('Create database: {0}'.format(DB_NAME))
open(DB_NAME, 'a').close()
Show.create_table()
Episode.create_table()
Setting.create_ta... | [
"def",
"create_database",
"(",
"destroy_existing",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"DB_NAME",
")",
":",
"logger",
".",
"info",
"(",
"'Create database: {0}'",
".",
"format",
"(",
"DB_NAME",
")",
")",
"open",
"("... | Create db and tables if it doesn't exist | [
"Create",
"db",
"and",
"tables",
"if",
"it",
"doesn",
"t",
"exist"
] | 0d639bd6913066db743a64b4a14a384024e4ab7d | https://github.com/tax/snor/blob/0d639bd6913066db743a64b4a14a384024e4ab7d/snor/utils.py#L216-L223 |
242,406 | kryptn/Pantry | demo.py | magic_api | def magic_api(word):
"""
This is our magic API that we're simulating.
It'll return a random number and a cache timer.
"""
result = sum(ord(x)-65 + randint(1,50) for x in word)
delta = timedelta(seconds=result)
cached_until = datetime.now() + delta
return result, cached_until | python | def magic_api(word):
"""
This is our magic API that we're simulating.
It'll return a random number and a cache timer.
"""
result = sum(ord(x)-65 + randint(1,50) for x in word)
delta = timedelta(seconds=result)
cached_until = datetime.now() + delta
return result, cached_until | [
"def",
"magic_api",
"(",
"word",
")",
":",
"result",
"=",
"sum",
"(",
"ord",
"(",
"x",
")",
"-",
"65",
"+",
"randint",
"(",
"1",
",",
"50",
")",
"for",
"x",
"in",
"word",
")",
"delta",
"=",
"timedelta",
"(",
"seconds",
"=",
"result",
")",
"cach... | This is our magic API that we're simulating.
It'll return a random number and a cache timer. | [
"This",
"is",
"our",
"magic",
"API",
"that",
"we",
"re",
"simulating",
".",
"It",
"ll",
"return",
"a",
"random",
"number",
"and",
"a",
"cache",
"timer",
"."
] | 2e1c30f8b04127c4fd0e42451a3047d1300ac45f | https://github.com/kryptn/Pantry/blob/2e1c30f8b04127c4fd0e42451a3047d1300ac45f/demo.py#L6-L15 |
242,407 | hobson/pug-invest | pug/invest/sandbox/sim.py | portfolio_prices | def portfolio_prices(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2005, 1, 1),
end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1
normalize=True,
allocation=None,
price_type='actual_close',
):
"""Calculate the Sharpe Ratio and other perfor... | python | def portfolio_prices(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2005, 1, 1),
end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1
normalize=True,
allocation=None,
price_type='actual_close',
):
"""Calculate the Sharpe Ratio and other perfor... | [
"def",
"portfolio_prices",
"(",
"symbols",
"=",
"(",
"\"AAPL\"",
",",
"\"GLD\"",
",",
"\"GOOG\"",
",",
"\"$SPX\"",
",",
"\"XOM\"",
",",
"\"msft\"",
")",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2005",
",",
"1",
",",
"1",
")",
",",
"end",
... | Calculate the Sharpe Ratio and other performance metrics for a portfolio
Arguments:
symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc
start (datetime): The date at the start of the period being analyzed.
end (datetime): The date at the end of the period being analyzed.
normaliz... | [
"Calculate",
"the",
"Sharpe",
"Ratio",
"and",
"other",
"performance",
"metrics",
"for",
"a",
"portfolio"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L216-L253 |
242,408 | hobson/pug-invest | pug/invest/sandbox/sim.py | symbol_bollinger | def symbol_bollinger(symbol='GOOG',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR... | python | def symbol_bollinger(symbol='GOOG',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR... | [
"def",
"symbol_bollinger",
"(",
"symbol",
"=",
"'GOOG'",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2009",
",",
"12",
",",
"31",
")",
",",
"price_type",
... | Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
-1.8782... | [
"Calculate",
"the",
"Bolinger",
"indicator",
"value"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L263-L273 |
242,409 | hobson/pug-invest | pug/invest/sandbox/sim.py | symbols_bollinger | def symbols_bollinger(symbols='sp5002012',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger for a list or set of symbols
Example:
>>> symbols_bollinger(["AAPL", "GOOG", "IB... | python | def symbols_bollinger(symbols='sp5002012',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger for a list or set of symbols
Example:
>>> symbols_bollinger(["AAPL", "GOOG", "IB... | [
"def",
"symbols_bollinger",
"(",
"symbols",
"=",
"'sp5002012'",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2009",
",",
"12",
",",
"31",
")",
",",
"price_ty... | Calculate the Bolinger for a list or set of symbols
Example:
>>> symbols_bollinger(["AAPL", "GOOG", "IBM", "MSFT"], '10-12-01', '10-12-30')[-5:] # doctest: +NORMALIZE_WHITESPACE
GOOG AAPL IBM MSFT
2010-12-23 16:00:00 1.298178 1.185009 1.177220 1.237684
... | [
"Calculate",
"the",
"Bolinger",
"for",
"a",
"list",
"or",
"set",
"of",
"symbols"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L276-L292 |
242,410 | hobson/pug-invest | pug/invest/sandbox/sim.py | metrics | def metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'):
"""Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return
Arguments:
prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity
fudge (bo... | python | def metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'):
"""Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return
Arguments:
prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity
fudge (bo... | [
"def",
"metrics",
"(",
"prices",
",",
"fudge",
"=",
"False",
",",
"sharpe_days",
"=",
"252.",
",",
"baseline",
"=",
"'$SPX'",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"prices",
... | Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return
Arguments:
prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity
fudge (bool): Whether to use Tucker Balche's erroneous division by N or the more accu... | [
"Calculate",
"the",
"volatiliy",
"average",
"daily",
"return",
"Sharpe",
"ratio",
"and",
"cumulative",
"return"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L319-L372 |
242,411 | hobson/pug-invest | pug/invest/sandbox/sim.py | buy_on_drop | def buy_on_drop(symbol_set="sp5002012",
dataobj=dataobj,
start=datetime.datetime(2008, 1, 3),
end=datetime.datetime(2009, 12, 28),
market_sym='$SPX',
threshold=6,
sell_delay=5,
):
'''Compute and display an "event profile" for mul... | python | def buy_on_drop(symbol_set="sp5002012",
dataobj=dataobj,
start=datetime.datetime(2008, 1, 3),
end=datetime.datetime(2009, 12, 28),
market_sym='$SPX',
threshold=6,
sell_delay=5,
):
'''Compute and display an "event profile" for mul... | [
"def",
"buy_on_drop",
"(",
"symbol_set",
"=",
"\"sp5002012\"",
",",
"dataobj",
"=",
"dataobj",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"3",
")",
",",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2009",
",",
"12",
... | Compute and display an "event profile" for multiple sets of symbols | [
"Compute",
"and",
"display",
"an",
"event",
"profile",
"for",
"multiple",
"sets",
"of",
"symbols"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L437-L475 |
242,412 | hobson/pug-invest | pug/invest/sandbox/sim.py | generate_orders | def generate_orders(events, sell_delay=5, sep=','):
"""Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
sell_delay (float): N... | python | def generate_orders(events, sell_delay=5, sep=','):
"""Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
sell_delay (float): N... | [
"def",
"generate_orders",
"(",
"events",
",",
"sell_delay",
"=",
"5",
",",
"sep",
"=",
"','",
")",
":",
"sell_delay",
"=",
"float",
"(",
"unicode",
"(",
"sell_delay",
")",
")",
"or",
"1",
"for",
"i",
",",
"(",
"t",
",",
"row",
")",
"in",
"enumerate... | Generate CSV orders based on events indicated in a DataFrame
Arguments:
events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol.
1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent.
sell_delay (float): Number of days to wait before selling back the shares bought... | [
"Generate",
"CSV",
"orders",
"based",
"on",
"events",
"indicated",
"in",
"a",
"DataFrame"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L576-L608 |
242,413 | BlueHack-Core/blueforge | blueforge/util/trans.py | download_file | def download_file(save_path, file_url):
""" Download file from http url link """
r = requests.get(file_url) # create HTTP response object
with open(save_path, 'wb') as f:
f.write(r.content)
return save_path | python | def download_file(save_path, file_url):
""" Download file from http url link """
r = requests.get(file_url) # create HTTP response object
with open(save_path, 'wb') as f:
f.write(r.content)
return save_path | [
"def",
"download_file",
"(",
"save_path",
",",
"file_url",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"file_url",
")",
"# create HTTP response object",
"with",
"open",
"(",
"save_path",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"r",... | Download file from http url link | [
"Download",
"file",
"from",
"http",
"url",
"link"
] | ac40a888ee9c388638a8f312c51f7500b8891b6c | https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/trans.py#L6-L14 |
242,414 | BlueHack-Core/blueforge | blueforge/util/trans.py | make_url | def make_url(domain, location):
""" This function helps to make full url path."""
url = urlparse(location)
if url.scheme == '' and url.netloc == '':
return domain + url.path
elif url.scheme == '':
return 'http://' + url.netloc + url.path
else:
return url.geturl() | python | def make_url(domain, location):
""" This function helps to make full url path."""
url = urlparse(location)
if url.scheme == '' and url.netloc == '':
return domain + url.path
elif url.scheme == '':
return 'http://' + url.netloc + url.path
else:
return url.geturl() | [
"def",
"make_url",
"(",
"domain",
",",
"location",
")",
":",
"url",
"=",
"urlparse",
"(",
"location",
")",
"if",
"url",
".",
"scheme",
"==",
"''",
"and",
"url",
".",
"netloc",
"==",
"''",
":",
"return",
"domain",
"+",
"url",
".",
"path",
"elif",
"u... | This function helps to make full url path. | [
"This",
"function",
"helps",
"to",
"make",
"full",
"url",
"path",
"."
] | ac40a888ee9c388638a8f312c51f7500b8891b6c | https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/trans.py#L17-L27 |
242,415 | Kopachris/seshet | seshet/utils.py | Storage.getlist | def getlist(self, key):
"""Returns a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, `[value]` will be returned.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>>... | python | def getlist(self, key):
"""Returns a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, `[value]` will be returned.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>>... | [
"def",
"getlist",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"if",
"value",
"is",
"None",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"valu... | Returns a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, `[value]` will be returned.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>> request = Storage()
>>... | [
"Returns",
"a",
"Storage",
"value",
"as",
"a",
"list",
"."
] | d55bae01cff56762c5467138474145a2c17d1932 | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L94-L120 |
242,416 | Kopachris/seshet | seshet/utils.py | Storage.getfirst | def getfirst(self, key, default=None):
"""Returns the first value of a list or the value itself when given a
`request.vars` style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query string of `?x=... | python | def getfirst(self, key, default=None):
"""Returns the first value of a list or the value itself when given a
`request.vars` style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query string of `?x=... | [
"def",
"getfirst",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"getlist",
"(",
"key",
")",
"return",
"values",
"[",
"0",
"]",
"if",
"values",
"else",
"default"
] | Returns the first value of a list or the value itself when given a
`request.vars` style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>> request = Stor... | [
"Returns",
"the",
"first",
"value",
"of",
"a",
"list",
"or",
"the",
"value",
"itself",
"when",
"given",
"a",
"request",
".",
"vars",
"style",
"key",
"."
] | d55bae01cff56762c5467138474145a2c17d1932 | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L122-L144 |
242,417 | Kopachris/seshet | seshet/utils.py | Storage.getlast | def getlast(self, key, default=None):
"""Returns the last value of a list or value itself when given a
`request.vars` style key.
If the value is a list, the last item will be returned;
otherwise, the value will be returned as-is.
Simulated output with a query string of `?x=abc&... | python | def getlast(self, key, default=None):
"""Returns the last value of a list or value itself when given a
`request.vars` style key.
If the value is a list, the last item will be returned;
otherwise, the value will be returned as-is.
Simulated output with a query string of `?x=abc&... | [
"def",
"getlast",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"getlist",
"(",
"key",
")",
"return",
"values",
"[",
"-",
"1",
"]",
"if",
"values",
"else",
"default"
] | Returns the last value of a list or value itself when given a
`request.vars` style key.
If the value is a list, the last item will be returned;
otherwise, the value will be returned as-is.
Simulated output with a query string of `?x=abc&y=abc&y=def`::
>>> request = Storage... | [
"Returns",
"the",
"last",
"value",
"of",
"a",
"list",
"or",
"value",
"itself",
"when",
"given",
"a",
"request",
".",
"vars",
"style",
"key",
"."
] | d55bae01cff56762c5467138474145a2c17d1932 | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L146-L168 |
242,418 | francois-vincent/clingon | clingon/clingon.py | Clizer._eval_variables | def _eval_variables(self):
"""evaluates callable _variables
"""
for k, v in listitems(self._variables):
self._variables[k] = v() if hasattr(v, '__call__') else v | python | def _eval_variables(self):
"""evaluates callable _variables
"""
for k, v in listitems(self._variables):
self._variables[k] = v() if hasattr(v, '__call__') else v | [
"def",
"_eval_variables",
"(",
"self",
")",
":",
"for",
"k",
",",
"v",
"in",
"listitems",
"(",
"self",
".",
"_variables",
")",
":",
"self",
".",
"_variables",
"[",
"k",
"]",
"=",
"v",
"(",
")",
"if",
"hasattr",
"(",
"v",
",",
"'__call__'",
")",
"... | evaluates callable _variables | [
"evaluates",
"callable",
"_variables"
] | afc9db073dbc72b2562ce3e444152986a555dcbf | https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L217-L221 |
242,419 | formwork-io/lazarus | lazarus/_util.py | defer | def defer(callable):
'''Defers execution of the callable to a thread.
For example:
>>> def foo():
... print('bar')
>>> join = defer(foo)
>>> join()
'''
t = threading.Thread(target=callable)
t.start()
return t.join | python | def defer(callable):
'''Defers execution of the callable to a thread.
For example:
>>> def foo():
... print('bar')
>>> join = defer(foo)
>>> join()
'''
t = threading.Thread(target=callable)
t.start()
return t.join | [
"def",
"defer",
"(",
"callable",
")",
":",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"callable",
")",
"t",
".",
"start",
"(",
")",
"return",
"t",
".",
"join"
] | Defers execution of the callable to a thread.
For example:
>>> def foo():
... print('bar')
>>> join = defer(foo)
>>> join() | [
"Defers",
"execution",
"of",
"the",
"callable",
"to",
"a",
"thread",
"."
] | b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa | https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/_util.py#L11-L23 |
242,420 | formwork-io/lazarus | lazarus/_util.py | close_fds | def close_fds():
'''Close extraneous file descriptors.
On Linux, close everything but stdin, stdout, and stderr. On Mac, close
stdin, stdout, and stderr and everything owned by our user id.
'''
def close(fd):
with ignored(OSError):
os.close(fd)
if sys.platform == 'linux':
... | python | def close_fds():
'''Close extraneous file descriptors.
On Linux, close everything but stdin, stdout, and stderr. On Mac, close
stdin, stdout, and stderr and everything owned by our user id.
'''
def close(fd):
with ignored(OSError):
os.close(fd)
if sys.platform == 'linux':
... | [
"def",
"close_fds",
"(",
")",
":",
"def",
"close",
"(",
"fd",
")",
":",
"with",
"ignored",
"(",
"OSError",
")",
":",
"os",
".",
"close",
"(",
"fd",
")",
"if",
"sys",
".",
"platform",
"==",
"'linux'",
":",
"fd_dir",
"=",
"'/proc/self/fd'",
"fds",
"=... | Close extraneous file descriptors.
On Linux, close everything but stdin, stdout, and stderr. On Mac, close
stdin, stdout, and stderr and everything owned by our user id. | [
"Close",
"extraneous",
"file",
"descriptors",
"."
] | b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa | https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/_util.py#L48-L75 |
242,421 | HazardDede/dictmentor | dictmentor/base.py | DictMentor.bind | def bind(self, extension: Extension) -> 'DictMentor':
"""
Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining.
"""
if not Extension.is_valid_extension(extension):... | python | def bind(self, extension: Extension) -> 'DictMentor':
"""
Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining.
"""
if not Extension.is_valid_extension(extension):... | [
"def",
"bind",
"(",
"self",
",",
"extension",
":",
"Extension",
")",
"->",
"'DictMentor'",
":",
"if",
"not",
"Extension",
".",
"is_valid_extension",
"(",
"extension",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot bind extension due to missing interface requirements\... | Add any predefined or custom extension.
Args:
extension: Extension to add to the processor.
Returns:
The DictMentor itself for chaining. | [
"Add",
"any",
"predefined",
"or",
"custom",
"extension",
"."
] | f50ca26ed04f7a924cde6e4d464c4f6ccba4e320 | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L31-L45 |
242,422 | HazardDede/dictmentor | dictmentor/base.py | DictMentor.augment | def augment(self, dct: NonAugmentedDict,
document: Optional[YamlDocument] = None) -> AugmentedDict:
"""
Augments the given dictionary by using all the bound extensions.
Args:
dct: Dictionary to augment.
document: The document the dictionary was loaded fro... | python | def augment(self, dct: NonAugmentedDict,
document: Optional[YamlDocument] = None) -> AugmentedDict:
"""
Augments the given dictionary by using all the bound extensions.
Args:
dct: Dictionary to augment.
document: The document the dictionary was loaded fro... | [
"def",
"augment",
"(",
"self",
",",
"dct",
":",
"NonAugmentedDict",
",",
"document",
":",
"Optional",
"[",
"YamlDocument",
"]",
"=",
"None",
")",
"->",
"AugmentedDict",
":",
"Validator",
".",
"instance_of",
"(",
"dict",
",",
"raise_ex",
"=",
"True",
",",
... | Augments the given dictionary by using all the bound extensions.
Args:
dct: Dictionary to augment.
document: The document the dictionary was loaded from.
Returns:
The augmented dictionary. | [
"Augments",
"the",
"given",
"dictionary",
"by",
"using",
"all",
"the",
"bound",
"extensions",
"."
] | f50ca26ed04f7a924cde6e4d464c4f6ccba4e320 | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L47-L78 |
242,423 | fmenabe/python-clif | examples/backup/lib/types.py | Date | def Date(value):
"""Custom type for managing dates in the command-line."""
from datetime import datetime
try:
return datetime(*reversed([int(val) for val in value.split('/')]))
except Exception as err:
raise argparse.ArgumentTypeError("invalid date '%s'" % value) | python | def Date(value):
"""Custom type for managing dates in the command-line."""
from datetime import datetime
try:
return datetime(*reversed([int(val) for val in value.split('/')]))
except Exception as err:
raise argparse.ArgumentTypeError("invalid date '%s'" % value) | [
"def",
"Date",
"(",
"value",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"return",
"datetime",
"(",
"*",
"reversed",
"(",
"[",
"int",
"(",
"val",
")",
"for",
"val",
"in",
"value",
".",
"split",
"(",
"'/'",
")",
"]",
")",
")",
... | Custom type for managing dates in the command-line. | [
"Custom",
"type",
"for",
"managing",
"dates",
"in",
"the",
"command",
"-",
"line",
"."
] | 7d74b344337567f7951046406510a980afd7ee97 | https://github.com/fmenabe/python-clif/blob/7d74b344337567f7951046406510a980afd7ee97/examples/backup/lib/types.py#L11-L17 |
242,424 | the01/python-paps | examples/measure/echo_client.py | create | def create(clients_num, clients_host, clients_port, people_num, throttle):
"""
Prepare clients to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperClient], (str, object) -> str | None
"""
res = []
for number in range(clients_num):
sc = EchoClient({
... | python | def create(clients_num, clients_host, clients_port, people_num, throttle):
"""
Prepare clients to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperClient], (str, object) -> str | None
"""
res = []
for number in range(clients_num):
sc = EchoClient({
... | [
"def",
"create",
"(",
"clients_num",
",",
"clients_host",
",",
"clients_port",
",",
"people_num",
",",
"throttle",
")",
":",
"res",
"=",
"[",
"]",
"for",
"number",
"in",
"range",
"(",
"clients_num",
")",
":",
"sc",
"=",
"EchoClient",
"(",
"{",
"'id'",
... | Prepare clients to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperClient], (str, object) -> str | None | [
"Prepare",
"clients",
"to",
"execute"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/echo_client.py#L114-L139 |
242,425 | the01/python-paps | examples/measure/echo_client.py | EchoClient._packet_loop | def _packet_loop(self):
"""
Packet processing loop
:rtype: None
"""
while self._is_running:
# Only wait if there are no more packets in the inbox
if self.inbox.empty() \
and not self.new_packet.wait(self._packet_timeout):
... | python | def _packet_loop(self):
"""
Packet processing loop
:rtype: None
"""
while self._is_running:
# Only wait if there are no more packets in the inbox
if self.inbox.empty() \
and not self.new_packet.wait(self._packet_timeout):
... | [
"def",
"_packet_loop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_is_running",
":",
"# Only wait if there are no more packets in the inbox",
"if",
"self",
".",
"inbox",
".",
"empty",
"(",
")",
"and",
"not",
"self",
".",
"new_packet",
".",
"wait",
"(",
"sel... | Packet processing loop
:rtype: None | [
"Packet",
"processing",
"loop"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/echo_client.py#L34-L53 |
242,426 | maxweisspoker/simplebitcoinfuncs | simplebitcoinfuncs/miscfuncs.py | dechex | def dechex(num,zfill=0):
'''
Simple integer to hex converter.
The zfill is the number of bytes, even though the input is a hex
string, which means that the actual zfill is 2x what you might
initially think it would be.
For example:
>>> dechex(4,2)
'0004'
'''
if not isitint(num... | python | def dechex(num,zfill=0):
'''
Simple integer to hex converter.
The zfill is the number of bytes, even though the input is a hex
string, which means that the actual zfill is 2x what you might
initially think it would be.
For example:
>>> dechex(4,2)
'0004'
'''
if not isitint(num... | [
"def",
"dechex",
"(",
"num",
",",
"zfill",
"=",
"0",
")",
":",
"if",
"not",
"isitint",
"(",
"num",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be integer/long.\"",
")",
"o",
"=",
"hex",
"(",
"num",
")",
".",
"lstrip",
"(",
"\"0x\"",
")",
".",
... | Simple integer to hex converter.
The zfill is the number of bytes, even though the input is a hex
string, which means that the actual zfill is 2x what you might
initially think it would be.
For example:
>>> dechex(4,2)
'0004' | [
"Simple",
"integer",
"to",
"hex",
"converter",
"."
] | ad332433dfcc067e86d2e77fa0c8f1a27daffb63 | https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscfuncs.py#L106-L136 |
242,427 | selenol/selenol-python | selenol_python/params.py | selenol_params | def selenol_params(**kwargs):
"""Decorate request parameters to transform them into Selenol objects."""
def params_decorator(func):
"""Param decorator.
:param f: Function to decorate, typically on_request.
"""
def service_function_wrapper(service, message):
"""Wrap f... | python | def selenol_params(**kwargs):
"""Decorate request parameters to transform them into Selenol objects."""
def params_decorator(func):
"""Param decorator.
:param f: Function to decorate, typically on_request.
"""
def service_function_wrapper(service, message):
"""Wrap f... | [
"def",
"selenol_params",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"params_decorator",
"(",
"func",
")",
":",
"\"\"\"Param decorator.\n\n :param f: Function to decorate, typically on_request.\n \"\"\"",
"def",
"service_function_wrapper",
"(",
"service",
",",
"me... | Decorate request parameters to transform them into Selenol objects. | [
"Decorate",
"request",
"parameters",
"to",
"transform",
"them",
"into",
"Selenol",
"objects",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L21-L37 |
242,428 | selenol/selenol-python | selenol_python/params.py | _get_value | def _get_value(data_structure, key):
"""Return the value of a data_structure given a path.
:param data_structure: Dictionary, list or subscriptable object.
:param key: Array with the defined path ordered.
"""
if len(key) == 0:
raise KeyError()
value = data_structure[key[0]]
if len(k... | python | def _get_value(data_structure, key):
"""Return the value of a data_structure given a path.
:param data_structure: Dictionary, list or subscriptable object.
:param key: Array with the defined path ordered.
"""
if len(key) == 0:
raise KeyError()
value = data_structure[key[0]]
if len(k... | [
"def",
"_get_value",
"(",
"data_structure",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"==",
"0",
":",
"raise",
"KeyError",
"(",
")",
"value",
"=",
"data_structure",
"[",
"key",
"[",
"0",
"]",
"]",
"if",
"len",
"(",
"key",
")",
">",
"1",... | Return the value of a data_structure given a path.
:param data_structure: Dictionary, list or subscriptable object.
:param key: Array with the defined path ordered. | [
"Return",
"the",
"value",
"of",
"a",
"data_structure",
"given",
"a",
"path",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L40-L51 |
242,429 | selenol/selenol-python | selenol_python/params.py | get_value_from_session | def get_value_from_session(key):
"""Get a session value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_session_function(service, message):
"""Actual implementation of get_value_from_session function.
:param service: S... | python | def get_value_from_session(key):
"""Get a session value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_session_function(service, message):
"""Actual implementation of get_value_from_session function.
:param service: S... | [
"def",
"get_value_from_session",
"(",
"key",
")",
":",
"def",
"value_from_session_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_value_from_session function.\n\n :param service: SelenolService object.\n :param message: SelenolMessag... | Get a session value from the path specifed.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"a",
"session",
"value",
"from",
"the",
"path",
"specifed",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L54-L66 |
242,430 | selenol/selenol-python | selenol_python/params.py | get_value_from_content | def get_value_from_content(key):
"""Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_content_function(service, message):
"""Actual implementation of get_value_from_content function.
:param service: SelenolSe... | python | def get_value_from_content(key):
"""Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_content_function(service, message):
"""Actual implementation of get_value_from_content function.
:param service: SelenolSe... | [
"def",
"get_value_from_content",
"(",
"key",
")",
":",
"def",
"value_from_content_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_value_from_content function.\n\n :param service: SelenolService object.\n :param message: SelenolMessag... | Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"a",
"value",
"from",
"the",
"path",
"specifed",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L69-L81 |
242,431 | selenol/selenol-python | selenol_python/params.py | get_object_from_content | def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | python | def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | [
"def",
"get_object_from_content",
"(",
"entity",
",",
"key",
")",
":",
"def",
"object_from_content_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_object_from_content function.\n\n :param service: SelenolService object.\n :param ... | Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"an",
"object",
"from",
"the",
"database",
"given",
"an",
"entity",
"and",
"the",
"content",
"key",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L84-L101 |
242,432 | selenol/selenol-python | selenol_python/params.py | get_object_from_session | def get_object_from_session(entity, key):
"""Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_session_function(service, message):
... | python | def get_object_from_session(entity, key):
"""Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_session_function(service, message):
... | [
"def",
"get_object_from_session",
"(",
"entity",
",",
"key",
")",
":",
"def",
"object_from_session_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_object_from_session function.\n\n :param service: SelenolService object.\n :param ... | Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"an",
"object",
"from",
"the",
"database",
"given",
"an",
"entity",
"and",
"the",
"session",
"key",
"."
] | 53775fdfc95161f4aca350305cb3459e6f2f808d | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L104-L121 |
242,433 | uw-it-aca/uw-restclients-grad | uw_grad/petition.py | _process_json | def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = parse_datetime(item.get('submitDate'))
petition.decision_date = pars... | python | def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = parse_datetime(item.get('submitDate'))
petition.decision_date = pars... | [
"def",
"_process_json",
"(",
"data",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
":",
"petition",
"=",
"GradPetition",
"(",
")",
"petition",
".",
"description",
"=",
"item",
".",
"get",
"(",
"'description'",
")",
"petition",
".",
... | return a list of GradPetition objects. | [
"return",
"a",
"list",
"of",
"GradPetition",
"objects",
"."
] | ca06ed2f24f3683314a5690f6078e97d37fc8e52 | https://github.com/uw-it-aca/uw-restclients-grad/blob/ca06ed2f24f3683314a5690f6078e97d37fc8e52/uw_grad/petition.py#L20-L39 |
242,434 | jhazelwo/python-fileasobj | docs/examples.py | example_add_line_to_file | def example_add_line_to_file():
""" Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.add('foo')
my_file.append('bar')
# Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed.... | python | def example_add_line_to_file():
""" Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.add('foo')
my_file.append('bar')
# Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed.... | [
"def",
"example_add_line_to_file",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
"'/tmp/example_file.txt'",
")",
"my_file",
".",
"add",
"(",
"'foo'",
")",
"my_file",
".",
"append",
"(",
"'bar'",
")",
"# Add a new line to my_file that contains the word 'lol' and print... | Different methods to append a given line to the file, all work the same. | [
"Different",
"methods",
"to",
"append",
"a",
"given",
"line",
"to",
"the",
"file",
"all",
"work",
"the",
"same",
"."
] | 4bdbb575e75da830b88d10d0c1020d787ceba44d | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L63-L72 |
242,435 | jhazelwo/python-fileasobj | docs/examples.py | example_write_file_to_disk_if_changed | def example_write_file_to_disk_if_changed():
""" Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.rm(my_file.egrep('^#'))
if my_file.changed:
my_file.save() | python | def example_write_file_to_disk_if_changed():
""" Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.rm(my_file.egrep('^#'))
if my_file.changed:
my_file.save() | [
"def",
"example_write_file_to_disk_if_changed",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
"'/tmp/example_file.txt'",
")",
"my_file",
".",
"rm",
"(",
"my_file",
".",
"egrep",
"(",
"'^#'",
")",
")",
"if",
"my_file",
".",
"changed",
":",
"my_file",
".",
... | Try to remove all comments from a file, and save it if changes were made. | [
"Try",
"to",
"remove",
"all",
"comments",
"from",
"a",
"file",
"and",
"save",
"it",
"if",
"changes",
"were",
"made",
"."
] | 4bdbb575e75da830b88d10d0c1020d787ceba44d | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L132-L137 |
242,436 | jhazelwo/python-fileasobj | docs/examples.py | example_all | def example_all():
"""
Use a bunch of methods on a file.
"""
my_file = FileAsObj()
my_file.filename = '/tmp/example_file.txt'
my_file.add('# First change!')
my_file.save()
my_file = FileAsObj('/tmp/example_file.txt')
my_file.unique = True
my_file.sorted = True
my_file.add('1'... | python | def example_all():
"""
Use a bunch of methods on a file.
"""
my_file = FileAsObj()
my_file.filename = '/tmp/example_file.txt'
my_file.add('# First change!')
my_file.save()
my_file = FileAsObj('/tmp/example_file.txt')
my_file.unique = True
my_file.sorted = True
my_file.add('1'... | [
"def",
"example_all",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
")",
"my_file",
".",
"filename",
"=",
"'/tmp/example_file.txt'",
"my_file",
".",
"add",
"(",
"'# First change!'",
")",
"my_file",
".",
"save",
"(",
")",
"my_file",
"=",
"FileAsObj",
"(",
... | Use a bunch of methods on a file. | [
"Use",
"a",
"bunch",
"of",
"methods",
"on",
"a",
"file",
"."
] | 4bdbb575e75da830b88d10d0c1020d787ceba44d | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L173-L198 |
242,437 | ryanjdillon/pylleo | pylleo/lleocal.py | get_cal_data | def get_cal_data(data_df, cal_dict, param):
'''Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of l... | python | def get_cal_data(data_df, cal_dict, param):
'''Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of l... | [
"def",
"get_cal_data",
"(",
"data_df",
",",
"cal_dict",
",",
"param",
")",
":",
"param",
"=",
"param",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"idx_lower_start",
"=",
"cal_dict... | Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration p... | [
"Get",
"data",
"along",
"specified",
"axis",
"during",
"calibration",
"intervals"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L2-L38 |
242,438 | ryanjdillon/pylleo | pylleo/lleocal.py | read_cal | def read_cal(cal_yaml_path):
'''Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data
'''
from collections import OrderedDict
import datetim... | python | def read_cal(cal_yaml_path):
'''Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data
'''
from collections import OrderedDict
import datetim... | [
"def",
"read_cal",
"(",
"cal_yaml_path",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"import",
"datetime",
"import",
"os",
"import",
"warnings",
"import",
"yamlord",
"from",
".",
"import",
"utils",
"def",
"__create_cal",
"(",
"cal_yaml_path",
")",
... | Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data | [
"Load",
"calibration",
"file",
"if",
"exists",
"else",
"create"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L41-L85 |
242,439 | ryanjdillon/pylleo | pylleo/lleocal.py | update | def update(data_df, cal_dict, param, bound, start, end):
'''Update calibration times for give parameter and boundary'''
from collections import OrderedDict
if param not in cal_dict['parameters']:
cal_dict['parameters'][param] = OrderedDict()
if bound not in cal_dict['parameters'][param]:
... | python | def update(data_df, cal_dict, param, bound, start, end):
'''Update calibration times for give parameter and boundary'''
from collections import OrderedDict
if param not in cal_dict['parameters']:
cal_dict['parameters'][param] = OrderedDict()
if bound not in cal_dict['parameters'][param]:
... | [
"def",
"update",
"(",
"data_df",
",",
"cal_dict",
",",
"param",
",",
"bound",
",",
"start",
",",
"end",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"if",
"param",
"not",
"in",
"cal_dict",
"[",
"'parameters'",
"]",
":",
"cal_dict",
"[",
"'pa... | Update calibration times for give parameter and boundary | [
"Update",
"calibration",
"times",
"for",
"give",
"parameter",
"and",
"boundary"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L88-L100 |
242,440 | ryanjdillon/pylleo | pylleo/lleocal.py | fit1d | def fit1d(lower, upper):
'''Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration posit... | python | def fit1d(lower, upper):
'''Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration posit... | [
"def",
"fit1d",
"(",
"lower",
",",
"upper",
")",
":",
"import",
"numpy",
"# Get smallest size as index position for slicing",
"idx",
"=",
"min",
"(",
"len",
"(",
"lower",
")",
",",
"len",
"(",
"upper",
")",
")",
"# Stack accelerometer count values for upper and lowe... | Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
Returns
-------
... | [
"Fit",
"acceleration",
"data",
"at",
"lower",
"and",
"upper",
"boundaries",
"of",
"gravity"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L103-L143 |
242,441 | robertchase/ergaleia | ergaleia/un_comment.py | un_comment | def un_comment(s, comment='#', strip=True):
"""Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (de... | python | def un_comment(s, comment='#', strip=True):
"""Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (de... | [
"def",
"un_comment",
"(",
"s",
",",
"comment",
"=",
"'#'",
",",
"strip",
"=",
"True",
")",
":",
"def",
"_un_comment",
"(",
"string",
")",
":",
"result",
"=",
"re",
".",
"split",
"(",
"r'(?<!\\\\)'",
"+",
"comment",
",",
"string",
",",
"maxsplit",
"="... | Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (default=#) (see Note 1)
strip - strip li... | [
"Uncomment",
"a",
"string",
"or",
"list",
"of",
"strings"
] | df8e9a4b18c563022a503faa27e822c9a5755490 | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/un_comment.py#L9-L36 |
242,442 | shaypal5/comath | comath/func/func.py | get_smooth_step_function | def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | python | def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | [
"def",
"get_smooth_step_function",
"(",
"min_val",
",",
"max_val",
",",
"switch_point",
",",
"smooth_factor",
")",
":",
"dif",
"=",
"max_val",
"-",
"min_val",
"def",
"_smooth_step",
"(",
"x",
")",
":",
"return",
"min_val",
"+",
"dif",
"*",
"tanh",
"(",
"("... | Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will return when x=switch_point.
min_val: float
The value the function will c... | [
"Returns",
"a",
"function",
"that",
"moves",
"smoothly",
"between",
"a",
"minimal",
"value",
"and",
"a",
"maximal",
"one",
"when",
"its",
"value",
"increases",
"from",
"a",
"given",
"witch",
"point",
"to",
"infinity",
"."
] | 1333e3b96242a5bad9d3e699ffd58a1597fdc89f | https://github.com/shaypal5/comath/blob/1333e3b96242a5bad9d3e699ffd58a1597fdc89f/comath/func/func.py#L10-L34 |
242,443 | jalanb/pysyte | pysyte/debuggers.py | stack_sources | def stack_sources():
"""A list of sources for frames above this"""
# lazy imports
import linecache
result = []
for frame_info in reversed(inspect.stack()):
_frame, filename, line_number, _function, _context, _index = frame_info
linecache.lazycache(filename, {})
_line = lineca... | python | def stack_sources():
"""A list of sources for frames above this"""
# lazy imports
import linecache
result = []
for frame_info in reversed(inspect.stack()):
_frame, filename, line_number, _function, _context, _index = frame_info
linecache.lazycache(filename, {})
_line = lineca... | [
"def",
"stack_sources",
"(",
")",
":",
"# lazy imports",
"import",
"linecache",
"result",
"=",
"[",
"]",
"for",
"frame_info",
"in",
"reversed",
"(",
"inspect",
".",
"stack",
"(",
")",
")",
":",
"_frame",
",",
"filename",
",",
"line_number",
",",
"_function... | A list of sources for frames above this | [
"A",
"list",
"of",
"sources",
"for",
"frames",
"above",
"this"
] | 4e278101943d1ceb1a6bcaf6ddc72052ecf13114 | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/debuggers.py#L151-L164 |
242,444 | KyleWpppd/css-audit | cssaudit/parser.py | extract_leftmost_selector | def extract_leftmost_selector(selector_list):
"""
Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree.
"... | python | def extract_leftmost_selector(selector_list):
"""
Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree.
"... | [
"def",
"extract_leftmost_selector",
"(",
"selector_list",
")",
":",
"classes",
"=",
"set",
"(",
")",
"ids",
"=",
"set",
"(",
")",
"elements",
"=",
"set",
"(",
")",
"# print \"Selector list: %s \\n\\n\\n\\n\\n\\n\" % selector_list",
"for",
"selector",
"in",
"selec... | Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree. | [
"Because",
"we",
"aren",
"t",
"building",
"a",
"DOM",
"tree",
"to",
"transverse",
"the",
"only",
"way",
"to",
"get",
"the",
"most",
"general",
"selectors",
"is",
"to",
"take",
"the",
"leftmost",
".",
"For",
"example",
"with",
"div",
".",
"outer",
"div",
... | cab4d4204cf30d54bc1881deee6ad92ae6aacc56 | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L213-L236 |
242,445 | KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.append_styles | def append_styles(self, tag, attrs):
"""
Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
... | python | def append_styles(self, tag, attrs):
"""
Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
... | [
"def",
"append_styles",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"dattrs",
"=",
"dict",
"(",
"attrs",
")",
"if",
"'class'",
"in",
"dattrs",
":",
"#print \"Found classes '%s'\" % dattrs['class']",
"class_names",
"=",
"dattrs",
"[",
"'class'",
"]",
".",
... | Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
A tuple of HTML element attributes such as 'class'... | [
"Append",
"classes",
"found",
"in",
"HTML",
"elements",
"to",
"the",
"list",
"of",
"styles",
"used",
".",
"Because",
"we",
"haven",
"t",
"built",
"the",
"tree",
"we",
"aren",
"t",
"using",
"the",
"tag",
"parameter",
"for",
"now",
"."
] | cab4d4204cf30d54bc1881deee6ad92ae6aacc56 | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L129-L151 |
242,446 | marcosgabarda/django-belt | belt/decorators.py | delete_after | def delete_after(filename):
"""Decorator to be sure the file given by parameter is deleted after the
execution of the method.
"""
def delete_after_decorator(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
finally:
... | python | def delete_after(filename):
"""Decorator to be sure the file given by parameter is deleted after the
execution of the method.
"""
def delete_after_decorator(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
finally:
... | [
"def",
"delete_after",
"(",
"filename",
")",
":",
"def",
"delete_after_decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"k... | Decorator to be sure the file given by parameter is deleted after the
execution of the method. | [
"Decorator",
"to",
"be",
"sure",
"the",
"file",
"given",
"by",
"parameter",
"is",
"deleted",
"after",
"the",
"execution",
"of",
"the",
"method",
"."
] | 81404604c4dff664b1520b01e1f638c9c6bab41b | https://github.com/marcosgabarda/django-belt/blob/81404604c4dff664b1520b01e1f638c9c6bab41b/belt/decorators.py#L8-L22 |
242,447 | tBaxter/tango-shared-core | build/lib/tango_shared/utils/maptools.py | get_geocode | def get_geocode(city, state, street_address="", zipcode=""):
"""
For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)... | python | def get_geocode(city, state, street_address="", zipcode=""):
"""
For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)... | [
"def",
"get_geocode",
"(",
"city",
",",
"state",
",",
"street_address",
"=",
"\"\"",
",",
"zipcode",
"=",
"\"\"",
")",
":",
"try",
":",
"key",
"=",
"settings",
".",
"GMAP_KEY",
"except",
"AttributeError",
":",
"return",
"\"You need to put GMAP_KEY in settings\""... | For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)
Most times you'll want to join the return. | [
"For",
"given",
"location",
"or",
"object",
"takes",
"address",
"data",
"and",
"returns",
"latitude",
"and",
"longitude",
"coordinates",
"from",
"Google",
"geocoding",
"service"
] | 35fc10aef1ceedcdb4d6d866d44a22efff718812 | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/maptools.py#L10-L50 |
242,448 | dicaso/leopard | leopard/__init__.py | Section.list | def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | python | def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | [
"def",
"list",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")"
] | List section titles. | [
"List",
"section",
"titles",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L129-L132 |
242,449 | dicaso/leopard | leopard/__init__.py | Section.listFigures | def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | python | def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | [
"def",
"listFigures",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")",
"if",
... | List section figures. | [
"List",
"section",
"figures",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L135-L145 |
242,450 | dicaso/leopard | leopard/__init__.py | Section.listTables | def listTables(self,walkTrace=tuple(),case=None,element=None):
"""List section tables.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'table':
caption,tab = element
try:
print(walkTrace,tab._leopardref,caption)
exc... | python | def listTables(self,walkTrace=tuple(),case=None,element=None):
"""List section tables.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'table':
caption,tab = element
try:
print(walkTrace,tab._leopardref,caption)
exc... | [
"def",
"listTables",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")",
"if",
... | List section tables. | [
"List",
"section",
"tables",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L148-L158 |
242,451 | dicaso/leopard | leopard/__init__.py | Section.sectionOutZip | def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'):
"""Prepares section for zip output
"""
from io import StringIO, BytesIO
text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n')
zipcontainer.writestr(
zipdir+'section.txt',
... | python | def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'):
"""Prepares section for zip output
"""
from io import StringIO, BytesIO
text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n')
zipcontainer.writestr(
zipdir+'section.txt',
... | [
"def",
"sectionOutZip",
"(",
"self",
",",
"zipcontainer",
",",
"zipdir",
"=",
"''",
",",
"figtype",
"=",
"'png'",
")",
":",
"from",
"io",
"import",
"StringIO",
",",
"BytesIO",
"text",
"=",
"self",
".",
"p",
"if",
"not",
"self",
".",
"settings",
"[",
... | Prepares section for zip output | [
"Prepares",
"section",
"for",
"zip",
"output"
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L160-L187 |
242,452 | dicaso/leopard | leopard/__init__.py | Section.sectionsPDF | def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for PDF output.
"""
import pylatex as pl
if case == 'sectionmain':
if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage'))
with doc.create(pl.Section(s... | python | def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for PDF output.
"""
import pylatex as pl
if case == 'sectionmain':
if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage'))
with doc.create(pl.Section(s... | [
"def",
"sectionsPDF",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"import",
"pylatex",
"as",
"pl",
"if",
"case",
"==",
"'sectionmain'",
":",
"if",
... | Prepares section for PDF output. | [
"Prepares",
"section",
"for",
"PDF",
"output",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L190-L240 |
242,453 | dicaso/leopard | leopard/__init__.py | Section.sectionsWord | def sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for word output.
"""
from docx.shared import Inches
from io import BytesIO
#p.add_run('italic.').italic = True
if case == 'sectionmain':
if self.sett... | python | def sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for word output.
"""
from docx.shared import Inches
from io import BytesIO
#p.add_run('italic.').italic = True
if case == 'sectionmain':
if self.sett... | [
"def",
"sectionsWord",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"from",
"docx",
".",
"shared",
"import",
"Inches",
"from",
"io",
"import",
"BytesI... | Prepares section for word output. | [
"Prepares",
"section",
"for",
"word",
"output",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L244-L286 |
242,454 | dicaso/leopard | leopard/__init__.py | Section.sectionFromFunction | def sectionFromFunction(function,*args,**kwargs):
"""
This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section... | python | def sectionFromFunction(function,*args,**kwargs):
"""
This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section... | [
"def",
"sectionFromFunction",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"figures",
",",
"tables",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"title",
"=",
"inspect",
".",
"getcomments",
"(",
"function",... | This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section text.
The function should return an ordered dict of figures a... | [
"This",
"staticmethod",
"executes",
"the",
"function",
"that",
"is",
"passed",
"with",
"the",
"provided",
"args",
"and",
"kwargs",
".",
"The",
"first",
"line",
"of",
"the",
"function",
"docstring",
"is",
"used",
"as",
"the",
"section",
"title",
"the",
"comme... | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L289-L316 |
242,455 | dicaso/leopard | leopard/__init__.py | Report.list | def list(self):
"""
Get an overview of the report content list
"""
for i in range(len(self.sections)):
self.sections[i].list(walkTrace=(i+1,)) | python | def list(self):
"""
Get an overview of the report content list
"""
for i in range(len(self.sections)):
self.sections[i].list(walkTrace=(i+1,)) | [
"def",
"list",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sections",
")",
")",
":",
"self",
".",
"sections",
"[",
"i",
"]",
".",
"list",
"(",
"walkTrace",
"=",
"(",
"i",
"+",
"1",
",",
")",
")"
] | Get an overview of the report content list | [
"Get",
"an",
"overview",
"of",
"the",
"report",
"content",
"list"
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L357-L362 |
242,456 | dicaso/leopard | leopard/__init__.py | Report.outputZip | def outputZip(self,figtype='png'):
"""
Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder.
"""
from zipfile import ZipFile
with ZipFile(self.outfile+'.zip', 'w') as zi... | python | def outputZip(self,figtype='png'):
"""
Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder.
"""
from zipfile import ZipFile
with ZipFile(self.outfile+'.zip', 'w') as zi... | [
"def",
"outputZip",
"(",
"self",
",",
"figtype",
"=",
"'png'",
")",
":",
"from",
"zipfile",
"import",
"ZipFile",
"with",
"ZipFile",
"(",
"self",
".",
"outfile",
"+",
"'.zip'",
",",
"'w'",
")",
"as",
"zipcontainer",
":",
"zipcontainer",
".",
"writestr",
"... | Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder. | [
"Outputs",
"the",
"report",
"in",
"a",
"zip",
"container",
".",
"Figs",
"and",
"tabs",
"as",
"pngs",
"and",
"excells",
"."
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L364-L385 |
242,457 | dicaso/leopard | leopard/__init__.py | Report.outputWord | def outputWord(self):
"""Output report to word docx
"""
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = docx.Document()
doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
doc.add_heading(self.title, level... | python | def outputWord(self):
"""Output report to word docx
"""
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = docx.Document()
doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
doc.add_heading(self.title, level... | [
"def",
"outputWord",
"(",
"self",
")",
":",
"import",
"docx",
"from",
"docx",
".",
"enum",
".",
"text",
"import",
"WD_ALIGN_PARAGRAPH",
"doc",
"=",
"docx",
".",
"Document",
"(",
")",
"doc",
".",
"styles",
"[",
"'Normal'",
"]",
".",
"paragraph_format",
".... | Output report to word docx | [
"Output",
"report",
"to",
"word",
"docx"
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L424-L459 |
242,458 | dicaso/leopard | leopard/__init__.py | Report.getReportTable | def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False):
"""Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
... | python | def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False):
"""Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
... | [
"def",
"getReportTable",
"(",
"reportzipfile",
",",
"tablefilename",
",",
"inReportsDir",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"zipfile",
",",
"io",
",",
"re",
"# zipfilename preparation",
"if",
"not",
"reportzipfile",
".",
"endswith",
... | Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
Can be provided as the filename within the zip folder, or a list of integers
... | [
"Get",
"a",
"pandas",
"table",
"from",
"a",
"previous",
"report"
] | ee9f45251aaacd1e453b135b419f4f0b50fb036e | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L462-L502 |
242,459 | cdeboever3/cdpybio | cdpybio/general.py | transform_standard_normal | def transform_standard_normal(df):
"""Transform a series or the rows of a dataframe to the values of a standard
normal based on rank."""
import pandas as pd
import scipy.stats as stats
if type(df) == pd.core.frame.DataFrame:
gc_ranks = df.rank(axis=1)
gc_ranks = gc_ranks / (gc_ranks.... | python | def transform_standard_normal(df):
"""Transform a series or the rows of a dataframe to the values of a standard
normal based on rank."""
import pandas as pd
import scipy.stats as stats
if type(df) == pd.core.frame.DataFrame:
gc_ranks = df.rank(axis=1)
gc_ranks = gc_ranks / (gc_ranks.... | [
"def",
"transform_standard_normal",
"(",
"df",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"scipy",
".",
"stats",
"as",
"stats",
"if",
"type",
"(",
"df",
")",
"==",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
":",
"gc_ranks",
"=",
"df",
... | Transform a series or the rows of a dataframe to the values of a standard
normal based on rank. | [
"Transform",
"a",
"series",
"or",
"the",
"rows",
"of",
"a",
"dataframe",
"to",
"the",
"values",
"of",
"a",
"standard",
"normal",
"based",
"on",
"rank",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L53-L69 |
242,460 | cdeboever3/cdpybio | cdpybio/general.py | read_gzipped_text_url | def read_gzipped_text_url(url):
"""Read a gzipped text file from a URL and return
contents as a string."""
import urllib2
import zlib
from StringIO import StringIO
opener = urllib2.build_opener()
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
respond ... | python | def read_gzipped_text_url(url):
"""Read a gzipped text file from a URL and return
contents as a string."""
import urllib2
import zlib
from StringIO import StringIO
opener = urllib2.build_opener()
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
respond ... | [
"def",
"read_gzipped_text_url",
"(",
"url",
")",
":",
"import",
"urllib2",
"import",
"zlib",
"from",
"StringIO",
"import",
"StringIO",
"opener",
"=",
"urllib2",
".",
"build_opener",
"(",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
")",
"reque... | Read a gzipped text file from a URL and return
contents as a string. | [
"Read",
"a",
"gzipped",
"text",
"file",
"from",
"a",
"URL",
"and",
"return",
"contents",
"as",
"a",
"string",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L71-L94 |
242,461 | OpenGov/carpenter | carpenter/blocks/flagable.py | Flagable.get_worst_flag_level | def get_worst_flag_level(self, flags):
'''
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
'''
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
... | python | def get_worst_flag_level(self, flags):
'''
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
'''
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
... | [
"def",
"get_worst_flag_level",
"(",
"self",
",",
"flags",
")",
":",
"worst_flag_level",
"=",
"0",
"for",
"flag_level_name",
"in",
"flags",
":",
"flag_level",
"=",
"self",
".",
"FLAG_LEVELS",
"[",
"flag_level_name",
"]",
"if",
"flag_level",
">",
"worst_flag_level... | Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned. | [
"Determines",
"the",
"worst",
"flag",
"present",
"in",
"the",
"provided",
"flags",
".",
"If",
"no",
"flags",
"are",
"given",
"then",
"a",
"minor",
"value",
"is",
"returned",
"."
] | 0ab3c54c05133b9b0468c63e834a7ce3a6fb575b | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/flagable.py#L76-L86 |
242,462 | skitazaki/python-clitool | clitool/accesslog.py | parse | def parse(line):
""" Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- que... | python | def parse(line):
""" Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- que... | [
"def",
"parse",
"(",
"line",
")",
":",
"m",
"=",
"LOG_FORMAT",
".",
"match",
"(",
"line",
")",
"if",
"m",
"is",
"None",
":",
"return",
"access",
"=",
"Access",
".",
"_make",
"(",
"m",
".",
"groups",
"(",
")",
")",
"entry",
"=",
"{",
"'host'",
"... | Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- query: HTTP requert query st... | [
"Parse",
"accesslog",
"line",
"to",
"map",
"Python",
"dictionary",
"."
] | 4971f8d093d51c6fd0e6cc536bbb597f78b570ab | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/accesslog.py#L60-L122 |
242,463 | skitazaki/python-clitool | clitool/accesslog.py | logparse | def logparse(*args, **kwargs):
""" Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report)
... | python | def logparse(*args, **kwargs):
""" Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report)
... | [
"def",
"logparse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"clitool",
".",
"cli",
"import",
"clistream",
"from",
"clitool",
".",
"processor",
"import",
"SimpleDictReporter",
"lst",
"=",
"[",
"parse",
"]",
"+",
"args",
"reporter",
"="... | Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report) | [
"Parse",
"access",
"log",
"on",
"the",
"terminal",
"application",
".",
"If",
"list",
"of",
"files",
"are",
"given",
"parse",
"each",
"file",
".",
"Otherwise",
"parse",
"standard",
"input",
"."
] | 4971f8d093d51c6fd0e6cc536bbb597f78b570ab | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/accesslog.py#L169-L184 |
242,464 | MacHu-GWU/angora-project | angora/math/outlier.py | std_filter | def std_filter(array, n_std=2.0, return_index=False):
"""Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance... | python | def std_filter(array, n_std=2.0, return_index=False):
"""Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance... | [
"def",
"std_filter",
"(",
"array",
",",
"n_std",
"=",
"2.0",
",",
"return_index",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"mean",
","... | Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index. | [
"Standard",
"deviation",
"outlier",
"detector",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/outlier.py#L47-L64 |
242,465 | MacHu-GWU/angora-project | angora/math/outlier.py | box_filter | def box_filter(array, n_iqr=1.5, return_index=False):
"""Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance(array, np.ndarray):
... | python | def box_filter(array, n_iqr=1.5, return_index=False):
"""Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance(array, np.ndarray):
... | [
"def",
"box_filter",
"(",
"array",
",",
"n_iqr",
"=",
"1.5",
",",
"return_index",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"Q3",
"=",
... | Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index. | [
"Box",
"plot",
"outlier",
"detector",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/outlier.py#L67-L87 |
242,466 | esterhui/pypu | pypu/pusher_utils.py | resize_compute_width_height | def resize_compute_width_height(fullfile,_megapixels):
"""Given image file and desired megapixels,
computes the new width and height"""
img = Image.open(fullfile)
width,height=img.size
current_megapixels=width*height/(2.0**20)
scale=sqrt(_megapixels/float(current_megapixels))
logger.debug... | python | def resize_compute_width_height(fullfile,_megapixels):
"""Given image file and desired megapixels,
computes the new width and height"""
img = Image.open(fullfile)
width,height=img.size
current_megapixels=width*height/(2.0**20)
scale=sqrt(_megapixels/float(current_megapixels))
logger.debug... | [
"def",
"resize_compute_width_height",
"(",
"fullfile",
",",
"_megapixels",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"fullfile",
")",
"width",
",",
"height",
"=",
"img",
".",
"size",
"current_megapixels",
"=",
"width",
"*",
"height",
"/",
"(",
"2.0"... | Given image file and desired megapixels,
computes the new width and height | [
"Given",
"image",
"file",
"and",
"desired",
"megapixels",
"computes",
"the",
"new",
"width",
"and",
"height"
] | cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L84-L104 |
242,467 | esterhui/pypu | pypu/pusher_utils.py | getexif_location | def getexif_location(directory,fn):
"""
directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None
"""
lat=None
lon=None
sign_lat=+1.0
sign_... | python | def getexif_location(directory,fn):
"""
directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None
"""
lat=None
lon=None
sign_lat=+1.0
sign_... | [
"def",
"getexif_location",
"(",
"directory",
",",
"fn",
")",
":",
"lat",
"=",
"None",
"lon",
"=",
"None",
"sign_lat",
"=",
"+",
"1.0",
"sign_lon",
"=",
"+",
"1.0",
"# Check if photo as geo info already",
"exif_tags",
"=",
"exifread",
".",
"process_file",
"(",
... | directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None | [
"directory",
"-",
"Dir",
"where",
"file",
"is",
"located",
"fn",
"-",
"filename",
"to",
"check",
"for",
"EXIF",
"GPS"
] | cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L107-L143 |
242,468 | CognitionGuidedSurgery/pyclictk | clictk/model.py | Executable.from_etree | def from_etree(tree):
"""Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable
"""
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.fi... | python | def from_etree(tree):
"""Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable
"""
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.fi... | [
"def",
"from_etree",
"(",
"tree",
")",
":",
"exe",
"=",
"Executable",
"(",
"tree",
")",
"exe",
".",
"category",
"=",
"tree",
".",
"findtext",
"(",
"'category'",
")",
"exe",
".",
"version",
"=",
"tree",
".",
"findtext",
"(",
"'version'",
")",
"exe",
"... | Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable | [
"Constructs",
"an",
"executable",
"form",
"a",
"given",
"ElementTree",
"structure",
"."
] | 74915098a24a33adb46d8738f9c4746d91ecc1dc | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/model.py#L501-L529 |
242,469 | edwards-lab/libGWAS | libgwas/snp_boundary_check.py | SnpBoundaryCheck.NoExclusions | def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | python | def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | [
"def",
"NoExclusions",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"start_bounds",
")",
"+",
"len",
"(",
"self",
".",
"target_rs",
")",
"+",
"len",
"(",
"self",
".",
"ignored_rs",
")",
"==",
"0",
":",
"return",
"BoundaryCheck",
".",
"chrom"... | Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive. | [
"Determine",
"that",
"there",
"are",
"no",
"exclusion",
"criterion",
"in",
"play"
] | d68c9a083d443dfa5d7c5112de29010909cfe23f | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/snp_boundary_check.py#L128-L138 |
242,470 | mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.set_address | def set_address(self, host, port):
"""Add host and port attributes"""
self.host = host
self.port = port | python | def set_address(self, host, port):
"""Add host and port attributes"""
self.host = host
self.port = port | [
"def",
"set_address",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"port"
] | Add host and port attributes | [
"Add",
"host",
"and",
"port",
"attributes"
] | b72ad622d9c94a879fe1085f0dbb52349892cd15 | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L32-L35 |
242,471 | mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.connect | def connect(self, host=None, port=None):
"""Connects to given host address and port."""
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) | python | def connect(self, host=None, port=None):
"""Connects to given host address and port."""
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) | [
"def",
"connect",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"host",
"=",
"self",
".",
"host",
"if",
"host",
"is",
"None",
"else",
"host",
"port",
"=",
"self",
".",
"port",
"if",
"port",
"is",
"None",
"else",
"port... | Connects to given host address and port. | [
"Connects",
"to",
"given",
"host",
"address",
"and",
"port",
"."
] | b72ad622d9c94a879fe1085f0dbb52349892cd15 | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L37-L41 |
242,472 | mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.send_file_message | def send_file_message(self, filename):
"""Send message inside the given file."""
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) | python | def send_file_message(self, filename):
"""Send message inside the given file."""
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) | [
"def",
"send_file_message",
"(",
"self",
",",
"filename",
")",
":",
"data",
"=",
"self",
".",
"_readFile",
"(",
"filename",
")",
"self",
".",
"print_debug_message",
"(",
"data",
")",
"self",
".",
"socket",
".",
"send",
"(",
"data",
")"
] | Send message inside the given file. | [
"Send",
"message",
"inside",
"the",
"given",
"file",
"."
] | b72ad622d9c94a879fe1085f0dbb52349892cd15 | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L54-L58 |
242,473 | mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.send_message | def send_message(self, message):
"""Send a given message to the remote host."""
self.print_debug_message(message)
self.socket.send(message) | python | def send_message(self, message):
"""Send a given message to the remote host."""
self.print_debug_message(message)
self.socket.send(message) | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"print_debug_message",
"(",
"message",
")",
"self",
".",
"socket",
".",
"send",
"(",
"message",
")"
] | Send a given message to the remote host. | [
"Send",
"a",
"given",
"message",
"to",
"the",
"remote",
"host",
"."
] | b72ad622d9c94a879fe1085f0dbb52349892cd15 | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L60-L63 |
242,474 | hsoft/xibless | xibless/util.py | modified_after | def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime."""
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except Environment... | python | def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime."""
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except Environment... | [
"def",
"modified_after",
"(",
"first_path",
",",
"second_path",
")",
":",
"try",
":",
"first_mtime",
"=",
"os",
".",
"stat",
"(",
"first_path",
")",
".",
"st_mtime",
"except",
"EnvironmentError",
":",
"return",
"False",
"try",
":",
"second_mtime",
"=",
"os",... | Returns True if first_path's mtime is higher than second_path's mtime. | [
"Returns",
"True",
"if",
"first_path",
"s",
"mtime",
"is",
"higher",
"than",
"second_path",
"s",
"mtime",
"."
] | a7393d28b4a31698869b2203d4d8b3398de1de7f | https://github.com/hsoft/xibless/blob/a7393d28b4a31698869b2203d4d8b3398de1de7f/xibless/util.py#L3-L13 |
242,475 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_packet | def _do_packet(self, packet, ip, port):
"""
React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: ... | python | def _do_packet(self, packet, ip, port):
"""
React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: ... | [
"def",
"_do_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"msg_type",
"=",
"packet",
".",
"header",
".",
"message_type",
"if",
"msg_type",
"==",
"MsgType",
".",
"JOIN",
":",
"self",
".",
"_do_join_packet",
"(",
"packet",
",",
"... | React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"incoming",
"packet"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L75-L94 |
242,476 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_join_packet | def _do_join_packet(self, packet, ip, port):
"""
React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: C... | python | def _do_join_packet(self, packet, ip, port):
"""
React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: C... | [
"def",
"_do_join_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"key",
"=",
"u\"{}:{}\"",
".",
"format",
"(",
"ip",
",",
"p... | React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"join",
"packet",
"-",
"add",
"a",
"client",
"to",
"this",
"server"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L96-L147 |
242,477 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_unjoin_packet | def _do_unjoin_packet(self, packet, ip, port):
"""
React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:para... | python | def _do_unjoin_packet(self, packet, ip, port):
"""
React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:para... | [
"def",
"_do_unjoin_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"if",
"device_id",
"<=",
"Id",
".",
"SERVER",
":",
"self",
... | React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"unjoin",
"packet",
"-",
"remove",
"a",
"client",
"from",
"this",
"server"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L149-L190 |
242,478 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._new_device_id | def _new_device_id(self, key):
"""
Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int
"""
device_id = Id.SERVER + 1
if key in self._key2deviceId:
... | python | def _new_device_id(self, key):
"""
Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int
"""
device_id = Id.SERVER + 1
if key in self._key2deviceId:
... | [
"def",
"_new_device_id",
"(",
"self",
",",
"key",
")",
":",
"device_id",
"=",
"Id",
".",
"SERVER",
"+",
"1",
"if",
"key",
"in",
"self",
".",
"_key2deviceId",
":",
"return",
"self",
".",
"_key2deviceId",
"[",
"key",
"]",
"while",
"device_id",
"in",
"sel... | Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int | [
"Generate",
"a",
"new",
"device",
"id",
"or",
"return",
"existing",
"device",
"id",
"for",
"key"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L253-L267 |
242,479 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._init_multicast_socket | def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | python | def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | [
"def",
"_init_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"# Create a UDP socket",
"self",
".",
"_multicast_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"... | Init multicast socket
:rtype: None | [
"Init",
"multicast",
"socket"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L269-L312 |
242,480 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._shutdown_multicast_socket | def _shutdown_multicast_socket(self):
"""
Shutdown multicast socket
:rtype: None
"""
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = N... | python | def _shutdown_multicast_socket(self):
"""
Shutdown multicast socket
:rtype: None
"""
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = N... | [
"def",
"_shutdown_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"self",
".",
"_drop_membership_multicast_socket",
"(",
")",
"self",
".",
"_listening",
".",
"remove",
"(",
"self",
".",
"_multicast_socket",
")",
"self",
".",... | Shutdown multicast socket
:rtype: None | [
"Shutdown",
"multicast",
"socket"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L314-L324 |
242,481 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._add_membership_multicast_socket | def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | python | def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | [
"def",
"_add_membership_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"_membership_request",
"=",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_group",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_ip",
")",
"# Send add... | Make membership request to multicast
:rtype: None | [
"Make",
"membership",
"request",
"to",
"multicast"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L326-L342 |
242,482 | the01/python-paps | paps/si/app/sensorServer.py | SensorServer._drop_membership_multicast_socket | def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
se... | python | def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
se... | [
"def",
"_drop_membership_multicast_socket",
"(",
"self",
")",
":",
"# Leave group",
"self",
".",
"_multicast_socket",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IP",
",",
"socket",
".",
"IP_DROP_MEMBERSHIP",
",",
"self",
".",
"_membership_request",
")",
"self",... | Drop membership to multicast
:rtype: None | [
"Drop",
"membership",
"to",
"multicast"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L344-L356 |
242,483 | racker/torment | torment/helpers.py | evert | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | python | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | [
"def",
"evert",
"(",
"iterable",
":",
"Iterable",
"[",
"Dict",
"[",
"str",
",",
"Tuple",
"]",
"]",
")",
"->",
"Iterable",
"[",
"Iterable",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"]",
":",
"keys",
"=",
"list",
"(",
"itertools",
".",
"chain... | Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]``
The resulting iterable contains the same number of tuples as the
initial iterable... | [
"Evert",
"dictionaries",
"with",
"tuples",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L32-L63 |
242,484 | racker/torment | torment/helpers.py | extend | def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... | python | def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... | [
"def",
"extend",
"(",
"base",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"extension",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"_",
"=",
"copy",
".",
"deepcopy",
"(",
"base",
")",
"_",... | Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from updating base with extension. | [
"Extend",
"base",
"by",
"updating",
"with",
"the",
"extension",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L66-L83 |
242,485 | racker/torment | torment/helpers.py | merge | def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... | python | def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... | [
"def",
"merge",
"(",
"base",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"extension",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"_",
"=",
"copy",
".",
"deepcopy",
"(",
"base",
")",
"for"... | Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extension on base. | [
"Merge",
"extension",
"into",
"base",
"recursively",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L86-L108 |
242,486 | racker/torment | torment/helpers.py | import_directory | def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... | python | def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... | [
"def",
"import_directory",
"(",
"module_basename",
":",
"str",
",",
"directory",
":",
"str",
",",
"sort_key",
"=",
"None",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"'loading submodules of %s'",
",",
"module_basename",
")",
"logger",
".",
"info",
"... | Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:``sort_key``: function to sort module names with before loading | [
"Load",
"all",
"python",
"modules",
"in",
"directory",
"and",
"directory",
"s",
"children",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L112-L137 |
242,487 | racker/torment | torment/helpers.py | _filenames_to_modulenames | def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | python | def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | [
"def",
"_filenames_to_modulenames",
"(",
"filenames",
":",
"Iterable",
"[",
"str",
"]",
",",
"modulename_prefix",
":",
"str",
",",
"filename_prefix",
":",
"str",
"=",
"''",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"modulenames",
"=",
"[",
"]",
"# type:... | Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
----------
:``filename_prefix``: a prefix to drop from all filenames (typically a
common directory); de... | [
"Convert",
"given",
"filenames",
"to",
"module",
"names",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L158-L208 |
242,488 | za-creature/gulpless | gulpless/proxy.py | Proxy.on_any_event | def on_any_event(self, event):
"""Called whenever a FS event occurs."""
self.updated = True
if self._changed:
self._changed() | python | def on_any_event(self, event):
"""Called whenever a FS event occurs."""
self.updated = True
if self._changed:
self._changed() | [
"def",
"on_any_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"updated",
"=",
"True",
"if",
"self",
".",
"_changed",
":",
"self",
".",
"_changed",
"(",
")"
] | Called whenever a FS event occurs. | [
"Called",
"whenever",
"a",
"FS",
"event",
"occurs",
"."
] | fd73907dbe86880086719816bb042233f85121f6 | https://github.com/za-creature/gulpless/blob/fd73907dbe86880086719816bb042233f85121f6/gulpless/proxy.py#L19-L23 |
242,489 | racker/torment | torment/decorators.py | log | def log(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wr... | python | def log(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wr... | [
"def",
"log",
"(",
"prefix",
"=",
"''",
")",
":",
"function",
"=",
"None",
"if",
"inspect",
".",
"isfunction",
"(",
"prefix",
")",
":",
"prefix",
",",
"function",
"=",
"''",
",",
"prefix",
"def",
"_",
"(",
"function",
")",
":",
"@",
"functools",
".... | Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional) | [
"Add",
"start",
"and",
"stop",
"logging",
"messages",
"to",
"the",
"function",
"."
] | bd5d2f978324bf9b7360edfae76d853b226c63e1 | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/decorators.py#L28-L77 |
242,490 | Metatab/tableintuit | tableintuit/rows.py | RowIntuiter.spec | def spec(self):
"""Return a dict with values that can be fed directly into SelectiveRowGenerator"""
return dict(
headers=self.header_lines,
start=self.start_line,
comments=self.comment_lines,
end=self.end_line
) | python | def spec(self):
"""Return a dict with values that can be fed directly into SelectiveRowGenerator"""
return dict(
headers=self.header_lines,
start=self.start_line,
comments=self.comment_lines,
end=self.end_line
) | [
"def",
"spec",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"headers",
"=",
"self",
".",
"header_lines",
",",
"start",
"=",
"self",
".",
"start_line",
",",
"comments",
"=",
"self",
".",
"comment_lines",
",",
"end",
"=",
"self",
".",
"end_line",
")"
] | Return a dict with values that can be fed directly into SelectiveRowGenerator | [
"Return",
"a",
"dict",
"with",
"values",
"that",
"can",
"be",
"fed",
"directly",
"into",
"SelectiveRowGenerator"
] | 9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c | https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/rows.py#L70-L77 |
242,491 | Metatab/tableintuit | tableintuit/rows.py | RowIntuiter.picture | def picture(self, row):
"""Create a simplified character representation of the data row, which can be pattern matched
with a regex """
template = '_Xn'
types = (type(None), binary_type, int)
def guess_type(v):
try:
v = text_type(v).strip()
... | python | def picture(self, row):
"""Create a simplified character representation of the data row, which can be pattern matched
with a regex """
template = '_Xn'
types = (type(None), binary_type, int)
def guess_type(v):
try:
v = text_type(v).strip()
... | [
"def",
"picture",
"(",
"self",
",",
"row",
")",
":",
"template",
"=",
"'_Xn'",
"types",
"=",
"(",
"type",
"(",
"None",
")",
",",
"binary_type",
",",
"int",
")",
"def",
"guess_type",
"(",
"v",
")",
":",
"try",
":",
"v",
"=",
"text_type",
"(",
"v",... | Create a simplified character representation of the data row, which can be pattern matched
with a regex | [
"Create",
"a",
"simplified",
"character",
"representation",
"of",
"the",
"data",
"row",
"which",
"can",
"be",
"pattern",
"matched",
"with",
"a",
"regex"
] | 9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c | https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/rows.py#L79-L113 |
242,492 | Metatab/tableintuit | tableintuit/rows.py | RowIntuiter.coalesce_headers | def coalesce_headers(cls, header_lines):
"""Collects headers that are spread across multiple lines into a single row"""
header_lines = [list(hl) for hl in header_lines if bool(hl)]
if len(header_lines) == 0:
return []
if len(header_lines) == 1:
return header_li... | python | def coalesce_headers(cls, header_lines):
"""Collects headers that are spread across multiple lines into a single row"""
header_lines = [list(hl) for hl in header_lines if bool(hl)]
if len(header_lines) == 0:
return []
if len(header_lines) == 1:
return header_li... | [
"def",
"coalesce_headers",
"(",
"cls",
",",
"header_lines",
")",
":",
"header_lines",
"=",
"[",
"list",
"(",
"hl",
")",
"for",
"hl",
"in",
"header_lines",
"if",
"bool",
"(",
"hl",
")",
"]",
"if",
"len",
"(",
"header_lines",
")",
"==",
"0",
":",
"retu... | Collects headers that are spread across multiple lines into a single row | [
"Collects",
"headers",
"that",
"are",
"spread",
"across",
"multiple",
"lines",
"into",
"a",
"single",
"row"
] | 9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c | https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/rows.py#L291-L318 |
242,493 | csaez/wishlib | wishlib/utils.py | map_recursive | def map_recursive(function, iterable):
"""
Apply function recursively to every item or value of iterable and returns a
new iterable object with the results.
"""
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
... | python | def map_recursive(function, iterable):
"""
Apply function recursively to every item or value of iterable and returns a
new iterable object with the results.
"""
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
... | [
"def",
"map_recursive",
"(",
"function",
",",
"iterable",
")",
":",
"if",
"isiterable",
"(",
"iterable",
")",
":",
"dataOut",
"=",
"iterable",
".",
"__class__",
"(",
")",
"for",
"i",
"in",
"iterable",
":",
"if",
"isinstance",
"(",
"dataOut",
",",
"dict",... | Apply function recursively to every item or value of iterable and returns a
new iterable object with the results. | [
"Apply",
"function",
"recursively",
"to",
"every",
"item",
"or",
"value",
"of",
"iterable",
"and",
"returns",
"a",
"new",
"iterable",
"object",
"with",
"the",
"results",
"."
] | c212fa7875006a332a4cefbf69885ced9647bc2f | https://github.com/csaez/wishlib/blob/c212fa7875006a332a4cefbf69885ced9647bc2f/wishlib/utils.py#L58-L74 |
242,494 | Nekroze/librarian | librarian/deck.py | Deck.get_card | def get_card(self, index=-1, cache=True, remove=True):
"""
Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrie... | python | def get_card(self, index=-1, cache=True, remove=True):
"""
Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrie... | [
"def",
"get_card",
"(",
"self",
",",
"index",
"=",
"-",
"1",
",",
"cache",
"=",
"True",
",",
"remove",
"=",
"True",
")",
":",
"if",
"len",
"(",
"self",
".",
"cards",
")",
"<",
"index",
":",
"return",
"None",
"retriever",
"=",
"self",
".",
"cards"... | Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrieved.
If cache is set to True (the default) it will tell the librar... | [
"Retrieve",
"a",
"card",
"any",
"number",
"of",
"cards",
"from",
"the",
"top",
".",
"Returns",
"a",
"Card",
"object",
"loaded",
"from",
"a",
"library",
"if",
"one",
"is",
"specified",
"otherwise",
"just",
"it",
"will",
"simply",
"return",
"its",
"code",
... | 5d3da2980d91a637f80ad7164fbf204a2dd2bd58 | https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/deck.py#L22-L45 |
242,495 | Nekroze/librarian | librarian/deck.py | Deck.top_cards | def top_cards(self, number=1, cache=True, remove=True):
"""
Retrieve the top number of cards as ``Librarian.Card`` objects in a
list in order of top to bottom most card. Uses the decks
``.get_card`` and passes along the cache and remove arguments.
"""
getter = partial(sel... | python | def top_cards(self, number=1, cache=True, remove=True):
"""
Retrieve the top number of cards as ``Librarian.Card`` objects in a
list in order of top to bottom most card. Uses the decks
``.get_card`` and passes along the cache and remove arguments.
"""
getter = partial(sel... | [
"def",
"top_cards",
"(",
"self",
",",
"number",
"=",
"1",
",",
"cache",
"=",
"True",
",",
"remove",
"=",
"True",
")",
":",
"getter",
"=",
"partial",
"(",
"self",
".",
"get_card",
"(",
"cache",
"=",
"cache",
",",
"remove",
"=",
"remove",
")",
")",
... | Retrieve the top number of cards as ``Librarian.Card`` objects in a
list in order of top to bottom most card. Uses the decks
``.get_card`` and passes along the cache and remove arguments. | [
"Retrieve",
"the",
"top",
"number",
"of",
"cards",
"as",
"Librarian",
".",
"Card",
"objects",
"in",
"a",
"list",
"in",
"order",
"of",
"top",
"to",
"bottom",
"most",
"card",
".",
"Uses",
"the",
"decks",
".",
"get_card",
"and",
"passes",
"along",
"the",
... | 5d3da2980d91a637f80ad7164fbf204a2dd2bd58 | https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/deck.py#L47-L54 |
242,496 | Nekroze/librarian | librarian/deck.py | Deck.move_top_cards | def move_top_cards(self, other, number=1):
"""
Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified.
"""
other.cards.append(reversed(self.cards[-number:])) | python | def move_top_cards(self, other, number=1):
"""
Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified.
"""
other.cards.append(reversed(self.cards[-number:])) | [
"def",
"move_top_cards",
"(",
"self",
",",
"other",
",",
"number",
"=",
"1",
")",
":",
"other",
".",
"cards",
".",
"append",
"(",
"reversed",
"(",
"self",
".",
"cards",
"[",
"-",
"number",
":",
"]",
")",
")"
] | Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified. | [
"Move",
"the",
"top",
"number",
"of",
"cards",
"to",
"the",
"top",
"of",
"some",
"other",
"deck",
"."
] | 5d3da2980d91a637f80ad7164fbf204a2dd2bd58 | https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/deck.py#L56-L62 |
242,497 | Nekroze/librarian | librarian/deck.py | Deck.contians_attribute | def contians_attribute(self, attribute):
"""
Returns how many cards in the deck have the specified attribute.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library.
"""
if self.library is None:
return 0... | python | def contians_attribute(self, attribute):
"""
Returns how many cards in the deck have the specified attribute.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library.
"""
if self.library is None:
return 0... | [
"def",
"contians_attribute",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"self",
".",
"library",
"is",
"None",
":",
"return",
"0",
"load",
"=",
"self",
".",
"library",
".",
"load_card",
"matches",
"=",
"0",
"for",
"code",
"in",
"self",
".",
"cards",... | Returns how many cards in the deck have the specified attribute.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library. | [
"Returns",
"how",
"many",
"cards",
"in",
"the",
"deck",
"have",
"the",
"specified",
"attribute",
"."
] | 5d3da2980d91a637f80ad7164fbf204a2dd2bd58 | https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/deck.py#L68-L84 |
242,498 | Nekroze/librarian | librarian/deck.py | Deck.contains_info | def contains_info(self, key, value):
"""
Returns how many cards in the deck have the specified value under the
specified key in their info data.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library.
"""
if... | python | def contains_info(self, key, value):
"""
Returns how many cards in the deck have the specified value under the
specified key in their info data.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library.
"""
if... | [
"def",
"contains_info",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"library",
"is",
"None",
":",
"return",
"0",
"load",
"=",
"self",
".",
"library",
".",
"load_card",
"matches",
"=",
"0",
"for",
"code",
"in",
"self",
".",
"... | Returns how many cards in the deck have the specified value under the
specified key in their info data.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library. | [
"Returns",
"how",
"many",
"cards",
"in",
"the",
"deck",
"have",
"the",
"specified",
"value",
"under",
"the",
"specified",
"key",
"in",
"their",
"info",
"data",
"."
] | 5d3da2980d91a637f80ad7164fbf204a2dd2bd58 | https://github.com/Nekroze/librarian/blob/5d3da2980d91a637f80ad7164fbf204a2dd2bd58/librarian/deck.py#L86-L103 |
242,499 | mgk/thingamon | thingamon/client.py | Client.connect | def connect(self):
"""Connect to MQTT server and wait for server to acknowledge"""
if not self.connect_attempted:
self.connect_attempted = True
self.client.connect(self.host, port=self.port)
self.client.loop_start()
while not self.connected:
... | python | def connect(self):
"""Connect to MQTT server and wait for server to acknowledge"""
if not self.connect_attempted:
self.connect_attempted = True
self.client.connect(self.host, port=self.port)
self.client.loop_start()
while not self.connected:
... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connect_attempted",
":",
"self",
".",
"connect_attempted",
"=",
"True",
"self",
".",
"client",
".",
"connect",
"(",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")",
"... | Connect to MQTT server and wait for server to acknowledge | [
"Connect",
"to",
"MQTT",
"server",
"and",
"wait",
"for",
"server",
"to",
"acknowledge"
] | 3f7d68dc2131c347473af15cd5f7d4b669407c6b | https://github.com/mgk/thingamon/blob/3f7d68dc2131c347473af15cd5f7d4b669407c6b/thingamon/client.py#L81-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.