repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.reset | def reset(self):
"""Reset the internal roast properties.
:returns: None
"""
self._roasting = False
self._roast_start = None
self._roast_end = None
self._roast = dict()
self._window = deque(list(), 5)
self._init_controls() | python | def reset(self):
"""Reset the internal roast properties.
:returns: None
"""
self._roasting = False
self._roast_start = None
self._roast_end = None
self._roast = dict()
self._window = deque(list(), 5)
self._init_controls() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_roasting",
"=",
"False",
"self",
".",
"_roast_start",
"=",
"None",
"self",
".",
"_roast_end",
"=",
"None",
"self",
".",
"_roast",
"=",
"dict",
"(",
")",
"self",
".",
"_window",
"=",
"deque",
"(",
... | Reset the internal roast properties.
:returns: None | [
"Reset",
"the",
"internal",
"roast",
"properties",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L656-L666 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.add_roast_event | def add_roast_event(self, event):
"""Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created e... | python | def add_roast_event(self, event):
"""Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created e... | [
"def",
"add_roast_event",
"(",
"self",
",",
"event",
")",
":",
"event_time",
"=",
"self",
".",
"get_roast_time",
"(",
")",
"def",
"get_valid_config",
"(",
")",
":",
"\"\"\"Keep grabbing configs until we have a valid one.\n\n In rare cases, the configuration will be... | Add an event to the roast log.
This method should be used for registering events that may be worth
tracking like first crack, second crack and the dropping of coffee.
Similar to the standard reading output from the roaster, manually
created events will include the current configuration ... | [
"Add",
"an",
"event",
"to",
"the",
"roast",
"log",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L668-L702 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_interval | def set_interval(self, interval):
"""Set the polling interval for the process thread.
:param interval: How often to poll the Hottop
:type interval: int or float
:returns: None
:raises: InvalidInput
"""
if type(interval) != float or type(interval) != int:
... | python | def set_interval(self, interval):
"""Set the polling interval for the process thread.
:param interval: How often to poll the Hottop
:type interval: int or float
:returns: None
:raises: InvalidInput
"""
if type(interval) != float or type(interval) != int:
... | [
"def",
"set_interval",
"(",
"self",
",",
"interval",
")",
":",
"if",
"type",
"(",
"interval",
")",
"!=",
"float",
"or",
"type",
"(",
"interval",
")",
"!=",
"int",
":",
"raise",
"InvalidInput",
"(",
"\"Interval value must be of float or int\"",
")",
"self",
"... | Set the polling interval for the process thread.
:param interval: How often to poll the Hottop
:type interval: int or float
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"polling",
"interval",
"for",
"the",
"process",
"thread",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L738-L748 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_roast_properties | def set_roast_properties(self, settings):
"""Set the properties of the roast.
:param settings: General settings for the roast setup
:type settings: dict
:returns: None
:raises: InvalidInput
"""
if type(settings) != dict:
raise InvalidInput("Properties... | python | def set_roast_properties(self, settings):
"""Set the properties of the roast.
:param settings: General settings for the roast setup
:type settings: dict
:returns: None
:raises: InvalidInput
"""
if type(settings) != dict:
raise InvalidInput("Properties... | [
"def",
"set_roast_properties",
"(",
"self",
",",
"settings",
")",
":",
"if",
"type",
"(",
"settings",
")",
"!=",
"dict",
":",
"raise",
"InvalidInput",
"(",
"\"Properties value must be of dict\"",
")",
"valid",
"=",
"[",
"'name'",
",",
"'input_weight'",
",",
"'... | Set the properties of the roast.
:param settings: General settings for the roast setup
:type settings: dict
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"properties",
"of",
"the",
"roast",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L757-L772 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_monitor | def set_monitor(self, monitor):
"""Set the monitor config.
This module assumes that users will connect to the roaster and get
reading information _before_ they want to begin collecting roast
details. This method is critical to enabling the collection of roast
information and ens... | python | def set_monitor(self, monitor):
"""Set the monitor config.
This module assumes that users will connect to the roaster and get
reading information _before_ they want to begin collecting roast
details. This method is critical to enabling the collection of roast
information and ens... | [
"def",
"set_monitor",
"(",
"self",
",",
"monitor",
")",
":",
"if",
"type",
"(",
"monitor",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Monitor value must be bool\"",
")",
"self",
".",
"_roast",
"[",
"'record'",
"]",
"=",
"bool2int",
"(",
"moni... | Set the monitor config.
This module assumes that users will connect to the roaster and get
reading information _before_ they want to begin collecting roast
details. This method is critical to enabling the collection of roast
information and ensuring it gets saved in memory.
:pa... | [
"Set",
"the",
"monitor",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L781-L809 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_heater | def set_heater(self, heater):
"""Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
"""
if type(heater) != int and heater not in range(0, 101):
raise InvalidInput("Heater value ... | python | def set_heater(self, heater):
"""Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
"""
if type(heater) != int and heater not in range(0, 101):
raise InvalidInput("Heater value ... | [
"def",
"set_heater",
"(",
"self",
",",
"heater",
")",
":",
"if",
"type",
"(",
"heater",
")",
"!=",
"int",
"and",
"heater",
"not",
"in",
"range",
"(",
"0",
",",
"101",
")",
":",
"raise",
"InvalidInput",
"(",
"\"Heater value must be int between 0-100\"",
")"... | Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"heater",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L818-L829 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_fan | def set_fan(self, fan):
"""Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(fan) != int and fan not in range(0, 11):
raise InvalidInput("Fan value must be int between 0-10")
... | python | def set_fan(self, fan):
"""Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(fan) != int and fan not in range(0, 11):
raise InvalidInput("Fan value must be int between 0-10")
... | [
"def",
"set_fan",
"(",
"self",
",",
"fan",
")",
":",
"if",
"type",
"(",
"fan",
")",
"!=",
"int",
"and",
"fan",
"not",
"in",
"range",
"(",
"0",
",",
"11",
")",
":",
"raise",
"InvalidInput",
"(",
"\"Fan value must be int between 0-10\"",
")",
"self",
"."... | Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"fan",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L838-L849 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_main_fan | def set_main_fan(self, main_fan):
"""Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(main_fan) != int and main_fan not in range(0, 11):
raise InvalidInput(... | python | def set_main_fan(self, main_fan):
"""Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(main_fan) != int and main_fan not in range(0, 11):
raise InvalidInput(... | [
"def",
"set_main_fan",
"(",
"self",
",",
"main_fan",
")",
":",
"if",
"type",
"(",
"main_fan",
")",
"!=",
"int",
"and",
"main_fan",
"not",
"in",
"range",
"(",
"0",
",",
"11",
")",
":",
"raise",
"InvalidInput",
"(",
"\"Main fan value must be int between 0-10\"... | Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"main",
"fan",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L858-L869 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_drum_motor | def set_drum_motor(self, drum_motor):
"""Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(drum_motor) != bool:
raise InvalidInput("Drum motor value must b... | python | def set_drum_motor(self, drum_motor):
"""Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(drum_motor) != bool:
raise InvalidInput("Drum motor value must b... | [
"def",
"set_drum_motor",
"(",
"self",
",",
"drum_motor",
")",
":",
"if",
"type",
"(",
"drum_motor",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Drum motor value must be bool\"",
")",
"self",
".",
"_config",
"[",
"'drum_motor'",
"]",
"=",
"bool2int... | Set the drum motor config.
:param drum_motor: Value to set the drum motor
:type drum_motor: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"drum",
"motor",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L878-L890 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_solenoid | def set_solenoid(self, solenoid):
"""Set the solenoid config.
:param solenoid: Value to set the solenoid
:type solenoid: bool
:returns: None
:raises: InvalidInput
"""
if type(solenoid) != bool:
raise InvalidInput("Solenoid value must be bool")
... | python | def set_solenoid(self, solenoid):
"""Set the solenoid config.
:param solenoid: Value to set the solenoid
:type solenoid: bool
:returns: None
:raises: InvalidInput
"""
if type(solenoid) != bool:
raise InvalidInput("Solenoid value must be bool")
... | [
"def",
"set_solenoid",
"(",
"self",
",",
"solenoid",
")",
":",
"if",
"type",
"(",
"solenoid",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Solenoid value must be bool\"",
")",
"self",
".",
"_config",
"[",
"'solenoid'",
"]",
"=",
"bool2int",
"(",
... | Set the solenoid config.
:param solenoid: Value to set the solenoid
:type solenoid: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"solenoid",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L899-L910 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_cooling_motor | def set_cooling_motor(self, cooling_motor):
"""Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(cooling_motor) != bool:
raise InvalidInput("Co... | python | def set_cooling_motor(self, cooling_motor):
"""Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(cooling_motor) != bool:
raise InvalidInput("Co... | [
"def",
"set_cooling_motor",
"(",
"self",
",",
"cooling_motor",
")",
":",
"if",
"type",
"(",
"cooling_motor",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Cooling motor value must be bool\"",
")",
"self",
".",
"_config",
"[",
"'cooling_motor'",
"]",
"... | Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"cooling",
"motor",
"config",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L919-L930 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | Hottop.set_simulate | def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... | python | def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... | [
"def",
"set_simulate",
"(",
"self",
",",
"status",
")",
":",
"if",
"type",
"(",
"status",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Status value must be bool\"",
")",
"self",
".",
"_simulate",
"=",
"bool2int",
"(",
"status",
")"
] | Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"simulation",
"status",
"."
] | train | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L939-L949 |
getfleety/coralillo | coralillo/queryset.py | QuerySet.make_filter | def make_filter(self, fieldname, query_func, expct_value):
''' makes a filter that will be appliead to an object's property based
on query_func '''
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
... | python | def make_filter(self, fieldname, query_func, expct_value):
''' makes a filter that will be appliead to an object's property based
on query_func '''
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
... | [
"def",
"make_filter",
"(",
"self",
",",
"fieldname",
",",
"query_func",
",",
"expct_value",
")",
":",
"def",
"actual_filter",
"(",
"item",
")",
":",
"value",
"=",
"getattr",
"(",
"item",
",",
"fieldname",
")",
"if",
"query_func",
"in",
"NULL_AFFECTED_FILTERS... | makes a filter that will be appliead to an object's property based
on query_func | [
"makes",
"a",
"filter",
"that",
"will",
"be",
"appliead",
"to",
"an",
"object",
"s",
"property",
"based",
"on",
"query_func"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/queryset.py#L35-L64 |
StyXman/ayrton | ayrton/parser/pyparser/pylexer.py | notChainStr | def notChainStr (states, s):
"""XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's.
"""
assert len(s)... | python | def notChainStr (states, s):
"""XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's.
"""
assert len(s)... | [
"def",
"notChainStr",
"(",
"states",
",",
"s",
")",
":",
"assert",
"len",
"(",
"s",
")",
">",
"0",
"arcs",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"newArcPair",
"(",
"states",
",",
"x",
")",
",",
"s",
")",
")",
"finish",
"=",
"len",
... | XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's. | [
"XXX",
"I",
"m",
"not",
"sure",
"this",
"is",
"how",
"it",
"should",
"be",
"done",
"but",
"I",
"m",
"going",
"to",
"try",
"it",
"anyway",
".",
"Note",
"that",
"for",
"this",
"case",
"I",
"require",
"only",
"single",
"character",
"arcs",
"since",
"I",... | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pylexer.py#L33-L48 |
StyXman/ayrton | ayrton/parser/pyparser/pylexer.py | notGroup | def notGroup (states, *stateIndexPairs):
"""Like group, but will add a DEFAULT transition to a new end state,
causing anything in the group to not match by going to a dead state.
XXX I think this is right...
"""
start, dead = group(states, *stateIndexPairs)
finish = len(states)
states.append... | python | def notGroup (states, *stateIndexPairs):
"""Like group, but will add a DEFAULT transition to a new end state,
causing anything in the group to not match by going to a dead state.
XXX I think this is right...
"""
start, dead = group(states, *stateIndexPairs)
finish = len(states)
states.append... | [
"def",
"notGroup",
"(",
"states",
",",
"*",
"stateIndexPairs",
")",
":",
"start",
",",
"dead",
"=",
"group",
"(",
"states",
",",
"*",
"stateIndexPairs",
")",
"finish",
"=",
"len",
"(",
"states",
")",
"states",
".",
"append",
"(",
"[",
"]",
")",
"stat... | Like group, but will add a DEFAULT transition to a new end state,
causing anything in the group to not match by going to a dead state.
XXX I think this is right... | [
"Like",
"group",
"but",
"will",
"add",
"a",
"DEFAULT",
"transition",
"to",
"a",
"new",
"end",
"state",
"causing",
"anything",
"in",
"the",
"group",
"to",
"not",
"match",
"by",
"going",
"to",
"a",
"dead",
"state",
".",
"XXX",
"I",
"think",
"this",
"is",... | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pylexer.py#L73-L82 |
StyXman/ayrton | ayrton/parser/pyparser/pylexer.py | sameState | def sameState (s1, s2):
"""sameState(s1, s2)
Note:
state := [ nfaclosure : Long, [ arc ], accept : Boolean ]
arc := [ label, arrow : Int, nfaClosure : Long ]
"""
if (len(s1[1]) != len(s2[1])) or (s1[2] != s2[2]):
return False
for arcIndex in range(0, len(s1[1])):
arc1 = s1[1]... | python | def sameState (s1, s2):
"""sameState(s1, s2)
Note:
state := [ nfaclosure : Long, [ arc ], accept : Boolean ]
arc := [ label, arrow : Int, nfaClosure : Long ]
"""
if (len(s1[1]) != len(s2[1])) or (s1[2] != s2[2]):
return False
for arcIndex in range(0, len(s1[1])):
arc1 = s1[1]... | [
"def",
"sameState",
"(",
"s1",
",",
"s2",
")",
":",
"if",
"(",
"len",
"(",
"s1",
"[",
"1",
"]",
")",
"!=",
"len",
"(",
"s2",
"[",
"1",
"]",
")",
")",
"or",
"(",
"s1",
"[",
"2",
"]",
"!=",
"s2",
"[",
"2",
"]",
")",
":",
"return",
"False"... | sameState(s1, s2)
Note:
state := [ nfaclosure : Long, [ arc ], accept : Boolean ]
arc := [ label, arrow : Int, nfaClosure : Long ] | [
"sameState",
"(",
"s1",
"s2",
")",
"Note",
":",
"state",
":",
"=",
"[",
"nfaclosure",
":",
"Long",
"[",
"arc",
"]",
"accept",
":",
"Boolean",
"]",
"arc",
":",
"=",
"[",
"label",
"arrow",
":",
"Int",
"nfaClosure",
":",
"Long",
"]"
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pylexer.py#L168-L181 |
StyXman/ayrton | ayrton/parser/pyparser/pylexer.py | simplifyTempDfa | def simplifyTempDfa (tempStates):
"""simplifyTempDfa (tempStates)
"""
changes = True
deletedStates = []
while changes:
changes = False
for i in range(1, len(tempStates)):
if i in deletedStates:
continue
for j in range(0, i):
if ... | python | def simplifyTempDfa (tempStates):
"""simplifyTempDfa (tempStates)
"""
changes = True
deletedStates = []
while changes:
changes = False
for i in range(1, len(tempStates)):
if i in deletedStates:
continue
for j in range(0, i):
if ... | [
"def",
"simplifyTempDfa",
"(",
"tempStates",
")",
":",
"changes",
"=",
"True",
"deletedStates",
"=",
"[",
"]",
"while",
"changes",
":",
"changes",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"tempStates",
")",
")",
":",
"if",
... | simplifyTempDfa (tempStates) | [
"simplifyTempDfa",
"(",
"tempStates",
")"
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pylexer.py#L185-L210 |
StyXman/ayrton | ayrton/parser/pyparser/pylexer.py | finalizeTempDfa | def finalizeTempDfa (tempStates):
"""finalizeTempDfa (tempStates)
Input domain:
tempState := [ nfaClosure : Long, [ tempArc ], accept : Boolean ]
tempArc := [ label, arrow, nfaClosure ]
Output domain:
state := [ arcMap, accept : Boolean ]
"""
states = []
accepts = []
stateMap =... | python | def finalizeTempDfa (tempStates):
"""finalizeTempDfa (tempStates)
Input domain:
tempState := [ nfaClosure : Long, [ tempArc ], accept : Boolean ]
tempArc := [ label, arrow, nfaClosure ]
Output domain:
state := [ arcMap, accept : Boolean ]
"""
states = []
accepts = []
stateMap =... | [
"def",
"finalizeTempDfa",
"(",
"tempStates",
")",
":",
"states",
"=",
"[",
"]",
"accepts",
"=",
"[",
"]",
"stateMap",
"=",
"{",
"}",
"tempIndex",
"=",
"0",
"for",
"tempIndex",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"tempStates",
")",
")",
":",
"... | finalizeTempDfa (tempStates)
Input domain:
tempState := [ nfaClosure : Long, [ tempArc ], accept : Boolean ]
tempArc := [ label, arrow, nfaClosure ]
Output domain:
state := [ arcMap, accept : Boolean ] | [
"finalizeTempDfa",
"(",
"tempStates",
")"
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/pyparser/pylexer.py#L213-L239 |
avinassh/prawoauth2 | prawoauth2/PrawOAuth2Mini.py | PrawOAuth2Mini.refresh | def refresh(self, force=False):
"""Refreshes the `access_token` and sets the praw instance `reddit_client`
with a valid one.
:param force: Boolean. Refresh will be done only when last refresh was
done before `EXPIRY_DURATION`, which is 3500 seconds. However
passing `forc... | python | def refresh(self, force=False):
"""Refreshes the `access_token` and sets the praw instance `reddit_client`
with a valid one.
:param force: Boolean. Refresh will be done only when last refresh was
done before `EXPIRY_DURATION`, which is 3500 seconds. However
passing `forc... | [
"def",
"refresh",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_is_token_expired",
"(",
")",
"or",
"force",
":",
"tokens",
"=",
"self",
".",
"_get_refresh_access",
"(",
")",
"self",
".",
"access_token",
"=",
"tokens",
"[",
"'a... | Refreshes the `access_token` and sets the praw instance `reddit_client`
with a valid one.
:param force: Boolean. Refresh will be done only when last refresh was
done before `EXPIRY_DURATION`, which is 3500 seconds. However
passing `force` will overrides this and refresh operatio... | [
"Refreshes",
"the",
"access_token",
"and",
"sets",
"the",
"praw",
"instance",
"reddit_client",
"with",
"a",
"valid",
"one",
"."
] | train | https://github.com/avinassh/prawoauth2/blob/a7c9ab5a93666d8468c6bf8455a4bdff6cda6583/prawoauth2/PrawOAuth2Mini.py#L86-L99 |
getfleety/coralillo | coralillo/datamodel.py | Location.distance | def distance(self, loc):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
assert type(loc) == type(self)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [
self.lon,
... | python | def distance(self, loc):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
assert type(loc) == type(self)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [
self.lon,
... | [
"def",
"distance",
"(",
"self",
",",
"loc",
")",
":",
"assert",
"type",
"(",
"loc",
")",
"==",
"type",
"(",
"self",
")",
"# convert decimal degrees to radians",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
"=",
"map",
"(",
"radians",
",",
"[",
"self"... | Calculate the great circle distance between two points
on the earth (specified in decimal degrees) | [
"Calculate",
"the",
"great",
"circle",
"distance",
"between",
"two",
"points",
"on",
"the",
"earth",
"(",
"specified",
"in",
"decimal",
"degrees",
")"
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/datamodel.py#L39-L60 |
ssato/python-anytemplate | anytemplate/engines/strtemplate.py | renders | def renders(template_content, context, **options):
"""
:param template_content: Template content
:param context:
A dict or dict-like object to instantiate given template file
:param options: Options such as:
- at_paths: Template search paths (common option)
- at_encoding: Templa... | python | def renders(template_content, context, **options):
"""
:param template_content: Template content
:param context:
A dict or dict-like object to instantiate given template file
:param options: Options such as:
- at_paths: Template search paths (common option)
- at_encoding: Templa... | [
"def",
"renders",
"(",
"template_content",
",",
"context",
",",
"*",
"*",
"options",
")",
":",
"if",
"options",
".",
"get",
"(",
"\"safe\"",
",",
"False",
")",
":",
"return",
"string",
".",
"Template",
"(",
"template_content",
")",
".",
"safe_substitute",
... | :param template_content: Template content
:param context:
A dict or dict-like object to instantiate given template file
:param options: Options such as:
- at_paths: Template search paths (common option)
- at_encoding: Template encoding (common option)
- safe: Safely substitute p... | [
":",
"param",
"template_content",
":",
"Template",
"content",
":",
"param",
"context",
":",
"A",
"dict",
"or",
"dict",
"-",
"like",
"object",
"to",
"instantiate",
"given",
"template",
"file",
":",
"param",
"options",
":",
"Options",
"such",
"as",
":"
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/strtemplate.py#L28-L49 |
ssato/python-anytemplate | anytemplate/engines/strtemplate.py | Engine.render_impl | def render_impl(self, template, context, **options):
"""
Inherited class must implement this!
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param options: Same options as :meth:`renders_impl`
... | python | def render_impl(self, template, context, **options):
"""
Inherited class must implement this!
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param options: Same options as :meth:`renders_impl`
... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"*",
"*",
"options",
")",
":",
"ropts",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"options",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"\"safe\... | Inherited class must implement this!
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param options: Same options as :meth:`renders_impl`
- at_paths: Template search paths (common option)
- at... | [
"Inherited",
"class",
"must",
"implement",
"this!"
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/strtemplate.py#L61-L80 |
ShenggaoZhu/midict | midict/__init__.py | cvt_iter | def cvt_iter(a):
'''
Convert an iterator/generator to a tuple so that it can be iterated again.
E.g., convert zip in PY3.
'''
if a is None:
return a
if not isinstance(a, (tuple, list)):
# convert iterator/generator to tuple
a = tuple(a)
return a | python | def cvt_iter(a):
'''
Convert an iterator/generator to a tuple so that it can be iterated again.
E.g., convert zip in PY3.
'''
if a is None:
return a
if not isinstance(a, (tuple, list)):
# convert iterator/generator to tuple
a = tuple(a)
return a | [
"def",
"cvt_iter",
"(",
"a",
")",
":",
"if",
"a",
"is",
"None",
":",
"return",
"a",
"if",
"not",
"isinstance",
"(",
"a",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"# convert iterator/generator to tuple",
"a",
"=",
"tuple",
"(",
"a",
")",
"return... | Convert an iterator/generator to a tuple so that it can be iterated again.
E.g., convert zip in PY3. | [
"Convert",
"an",
"iterator",
"/",
"generator",
"to",
"a",
"tuple",
"so",
"that",
"it",
"can",
"be",
"iterated",
"again",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L37-L49 |
ShenggaoZhu/midict | midict/__init__.py | convert_dict | def convert_dict(d, cls=AttrDict): # not used
'''
recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict)
'''
for k, v in d.items():
if isinstance(v, Mapping):
d[k] = convert_dict(v)
elif isinstance(v, list):
for i, ... | python | def convert_dict(d, cls=AttrDict): # not used
'''
recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict)
'''
for k, v in d.items():
if isinstance(v, Mapping):
d[k] = convert_dict(v)
elif isinstance(v, list):
for i, ... | [
"def",
"convert_dict",
"(",
"d",
",",
"cls",
"=",
"AttrDict",
")",
":",
"# not used",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Mapping",
")",
":",
"d",
"[",
"k",
"]",
"=",
"convert_dict",
... | recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict) | [
"recursively",
"convert",
"a",
"normal",
"Mapping",
"d",
"and",
"it",
"s",
"values",
"to",
"a",
"specified",
"type",
"(",
"defaults",
"to",
"AttrDict",
")"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L131-L143 |
ShenggaoZhu/midict | midict/__init__.py | _key_to_index | def _key_to_index(keys, key, single_only=False):
'convert ``key`` of various types to int or list of int'
if isinstance(key, int): # validate the int index
try:
keys[key]
except IndexError:
raise KeyError('Index out of range of keys: %s' % (key,))
if key < 0:
... | python | def _key_to_index(keys, key, single_only=False):
'convert ``key`` of various types to int or list of int'
if isinstance(key, int): # validate the int index
try:
keys[key]
except IndexError:
raise KeyError('Index out of range of keys: %s' % (key,))
if key < 0:
... | [
"def",
"_key_to_index",
"(",
"keys",
",",
"key",
",",
"single_only",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"# validate the int index",
"try",
":",
"keys",
"[",
"key",
"]",
"except",
"IndexError",
":",
"raise",
"Key... | convert ``key`` of various types to int or list of int | [
"convert",
"key",
"of",
"various",
"types",
"to",
"int",
"or",
"list",
"of",
"int"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L152-L185 |
ShenggaoZhu/midict | midict/__init__.py | convert_key_to_index | def convert_key_to_index(keys, key):
'''
convert ``key`` of various types to int or list of int
return index, single
'''
index = _key_to_index(keys, key)
single = isinstance(index, int)
return index, single | python | def convert_key_to_index(keys, key):
'''
convert ``key`` of various types to int or list of int
return index, single
'''
index = _key_to_index(keys, key)
single = isinstance(index, int)
return index, single | [
"def",
"convert_key_to_index",
"(",
"keys",
",",
"key",
")",
":",
"index",
"=",
"_key_to_index",
"(",
"keys",
",",
"key",
")",
"single",
"=",
"isinstance",
"(",
"index",
",",
"int",
")",
"return",
"index",
",",
"single"
] | convert ``key`` of various types to int or list of int
return index, single | [
"convert",
"key",
"of",
"various",
"types",
"to",
"int",
"or",
"list",
"of",
"int"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L192-L200 |
ShenggaoZhu/midict | midict/__init__.py | _int_to_key | def _int_to_key(keys, index):
'Convert int ``index`` to the corresponding key in ``keys``'
if isinstance(index, int):
try:
return keys[index]
except IndexError:
# use KeyError rather than IndexError for compatibility
raise KeyError('Index out of range of keys:... | python | def _int_to_key(keys, index):
'Convert int ``index`` to the corresponding key in ``keys``'
if isinstance(index, int):
try:
return keys[index]
except IndexError:
# use KeyError rather than IndexError for compatibility
raise KeyError('Index out of range of keys:... | [
"def",
"_int_to_key",
"(",
"keys",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"try",
":",
"return",
"keys",
"[",
"index",
"]",
"except",
"IndexError",
":",
"# use KeyError rather than IndexError for compatibility",
"raise",
... | Convert int ``index`` to the corresponding key in ``keys`` | [
"Convert",
"int",
"index",
"to",
"the",
"corresponding",
"key",
"in",
"keys"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L203-L211 |
ShenggaoZhu/midict | midict/__init__.py | convert_index_to_keys | def convert_index_to_keys(d, item):
# use a separate function rather than a method inside the class IndexDict
'''
Convert ``item`` in various types (int, tuple/list, slice, or a normal key)
to a single key or a list of keys.
'''
keys = force_list(d.keys())
# use KeyError for compatibility o... | python | def convert_index_to_keys(d, item):
# use a separate function rather than a method inside the class IndexDict
'''
Convert ``item`` in various types (int, tuple/list, slice, or a normal key)
to a single key or a list of keys.
'''
keys = force_list(d.keys())
# use KeyError for compatibility o... | [
"def",
"convert_index_to_keys",
"(",
"d",
",",
"item",
")",
":",
"# use a separate function rather than a method inside the class IndexDict",
"keys",
"=",
"force_list",
"(",
"d",
".",
"keys",
"(",
")",
")",
"# use KeyError for compatibility of normal use",
"# Warning: int ite... | Convert ``item`` in various types (int, tuple/list, slice, or a normal key)
to a single key or a list of keys. | [
"Convert",
"item",
"in",
"various",
"types",
"(",
"int",
"tuple",
"/",
"list",
"slice",
"or",
"a",
"normal",
"key",
")",
"to",
"a",
"single",
"key",
"or",
"a",
"list",
"of",
"keys",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L214-L257 |
ShenggaoZhu/midict | midict/__init__.py | get_unique_name | def get_unique_name(name='', collection=()):
'''
Generate a unique name (str type) by appending a sequence number to
the original name so that it is not contained in the collection.
``collection`` has a __contains__ method (tuple, list, dict, etc.)
'''
if name not in collection:
return n... | python | def get_unique_name(name='', collection=()):
'''
Generate a unique name (str type) by appending a sequence number to
the original name so that it is not contained in the collection.
``collection`` has a __contains__ method (tuple, list, dict, etc.)
'''
if name not in collection:
return n... | [
"def",
"get_unique_name",
"(",
"name",
"=",
"''",
",",
"collection",
"=",
"(",
")",
")",
":",
"if",
"name",
"not",
"in",
"collection",
":",
"return",
"name",
"i",
"=",
"1",
"while",
"True",
":",
"i",
"+=",
"1",
"name2",
"=",
"'%s_%s'",
"%",
"(",
... | Generate a unique name (str type) by appending a sequence number to
the original name so that it is not contained in the collection.
``collection`` has a __contains__ method (tuple, list, dict, etc.) | [
"Generate",
"a",
"unique",
"name",
"(",
"str",
"type",
")",
"by",
"appending",
"a",
"sequence",
"number",
"to",
"the",
"original",
"name",
"so",
"that",
"it",
"is",
"not",
"contained",
"in",
"the",
"collection",
".",
"collection",
"has",
"a",
"__contains__... | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L425-L438 |
ShenggaoZhu/midict | midict/__init__.py | get_value_len | def get_value_len(value):
'''
Get length of ``value``. If ``value`` (eg, iterator) has no len(), convert it to list first.
return both length and converted value.
'''
try:
Nvalue = len(value)
except TypeError:
# convert iterator/generator to list
value = list(value)
... | python | def get_value_len(value):
'''
Get length of ``value``. If ``value`` (eg, iterator) has no len(), convert it to list first.
return both length and converted value.
'''
try:
Nvalue = len(value)
except TypeError:
# convert iterator/generator to list
value = list(value)
... | [
"def",
"get_value_len",
"(",
"value",
")",
":",
"try",
":",
"Nvalue",
"=",
"len",
"(",
"value",
")",
"except",
"TypeError",
":",
"# convert iterator/generator to list",
"value",
"=",
"list",
"(",
"value",
")",
"Nvalue",
"=",
"len",
"(",
"value",
")",
"retu... | Get length of ``value``. If ``value`` (eg, iterator) has no len(), convert it to list first.
return both length and converted value. | [
"Get",
"length",
"of",
"value",
".",
"If",
"value",
"(",
"eg",
"iterator",
")",
"has",
"no",
"len",
"()",
"convert",
"it",
"to",
"list",
"first",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L441-L453 |
ShenggaoZhu/midict | midict/__init__.py | MI_parse_args | def MI_parse_args(self, args, ingore_index2=False, allow_new=False):
'''
Parse the arguments for indexing in MIDict.
Full syntax: ``d[index1:key, index2]``.
``index2`` can be flexible indexing (int, list, slice etc.) as in ``IndexDict``.
Short syntax:
* d[key] <==> d[key,] <==> d[first_index... | python | def MI_parse_args(self, args, ingore_index2=False, allow_new=False):
'''
Parse the arguments for indexing in MIDict.
Full syntax: ``d[index1:key, index2]``.
``index2`` can be flexible indexing (int, list, slice etc.) as in ``IndexDict``.
Short syntax:
* d[key] <==> d[key,] <==> d[first_index... | [
"def",
"MI_parse_args",
"(",
"self",
",",
"args",
",",
"ingore_index2",
"=",
"False",
",",
"allow_new",
"=",
"False",
")",
":",
"empty",
"=",
"len",
"(",
"self",
".",
"indices",
")",
"==",
"0",
"if",
"empty",
"and",
"not",
"allow_new",
":",
"raise",
... | Parse the arguments for indexing in MIDict.
Full syntax: ``d[index1:key, index2]``.
``index2`` can be flexible indexing (int, list, slice etc.) as in ``IndexDict``.
Short syntax:
* d[key] <==> d[key,] <==> d[first_index:key, all_indice_except_first]
* d[:key] <==> d[:key,] <==> d[None:key] <==> ... | [
"Parse",
"the",
"arguments",
"for",
"indexing",
"in",
"MIDict",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L456-L603 |
ShenggaoZhu/midict | midict/__init__.py | mget_list | def mget_list(item, index):
'get mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
return item[index]
else:
return map(item.__getitem__, index) | python | def mget_list(item, index):
'get mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
return item[index]
else:
return map(item.__getitem__, index) | [
"def",
"mget_list",
"(",
"item",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"(",
"int",
",",
"slice",
")",
")",
":",
"return",
"item",
"[",
"index",
"]",
"else",
":",
"return",
"map",
"(",
"item",
".",
"__getitem__",
",",
"index... | get mulitple items via index of int, slice or list | [
"get",
"mulitple",
"items",
"via",
"index",
"of",
"int",
"slice",
"or",
"list"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L606-L611 |
ShenggaoZhu/midict | midict/__init__.py | mset_list | def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | python | def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | [
"def",
"mset_list",
"(",
"item",
",",
"index",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"(",
"int",
",",
"slice",
")",
")",
":",
"item",
"[",
"index",
"]",
"=",
"value",
"else",
":",
"map",
"(",
"item",
".",
"__setitem__",
"... | set mulitple items via index of int, slice or list | [
"set",
"mulitple",
"items",
"via",
"index",
"of",
"int",
"slice",
"or",
"list"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L614-L619 |
ShenggaoZhu/midict | midict/__init__.py | MI_get_item | def MI_get_item(self, key, index=0):
'return list of item'
index = _key_to_index_single(force_list(self.indices.keys()), index)
if index != 0:
key = self.indices[index][key] # always use first index key
# key must exist
value = super(MIMapping, self).__getitem__(key)
N = len(self.indice... | python | def MI_get_item(self, key, index=0):
'return list of item'
index = _key_to_index_single(force_list(self.indices.keys()), index)
if index != 0:
key = self.indices[index][key] # always use first index key
# key must exist
value = super(MIMapping, self).__getitem__(key)
N = len(self.indice... | [
"def",
"MI_get_item",
"(",
"self",
",",
"key",
",",
"index",
"=",
"0",
")",
":",
"index",
"=",
"_key_to_index_single",
"(",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
",",
"index",
")",
"if",
"index",
"!=",
"0",
":",
"ke... | return list of item | [
"return",
"list",
"of",
"item"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L622-L635 |
ShenggaoZhu/midict | midict/__init__.py | od_replace_key | def od_replace_key(od, key, new_key, *args, **kw):
'''
Replace key(s) in OrderedDict ``od`` by new key(s) in-place (i.e.,
preserving the order(s) of the key(s))
Optional new value(s) for new key(s) can be provided as a positional
argument (otherwise the old value(s) will be used):
od_repla... | python | def od_replace_key(od, key, new_key, *args, **kw):
'''
Replace key(s) in OrderedDict ``od`` by new key(s) in-place (i.e.,
preserving the order(s) of the key(s))
Optional new value(s) for new key(s) can be provided as a positional
argument (otherwise the old value(s) will be used):
od_repla... | [
"def",
"od_replace_key",
"(",
"od",
",",
"key",
",",
"new_key",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"multi",
"=",
"kw",
".",
"get",
"(",
"'multi'",
",",
"False",
")",
"or",
"isinstance",
"(",
"key",
",",
"list",
")",
"if",
"multi",
... | Replace key(s) in OrderedDict ``od`` by new key(s) in-place (i.e.,
preserving the order(s) of the key(s))
Optional new value(s) for new key(s) can be provided as a positional
argument (otherwise the old value(s) will be used):
od_replace_key(od, key, new_key, new_value)
To replace multiple ke... | [
"Replace",
"key",
"(",
"s",
")",
"in",
"OrderedDict",
"od",
"by",
"new",
"key",
"(",
"s",
")",
"in",
"-",
"place",
"(",
"i",
".",
"e",
".",
"preserving",
"the",
"order",
"(",
"s",
")",
"of",
"the",
"key",
"(",
"s",
"))"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L639-L725 |
ShenggaoZhu/midict | midict/__init__.py | od_reorder_keys | def od_reorder_keys(od, keys_in_new_order): # not used
'''
Reorder the keys in an OrderedDict ``od`` in-place.
'''
if set(od.keys()) != set(keys_in_new_order):
raise KeyError('Keys in the new order do not match existing keys')
for key in keys_in_new_order:
od[key] = od.pop(key)
r... | python | def od_reorder_keys(od, keys_in_new_order): # not used
'''
Reorder the keys in an OrderedDict ``od`` in-place.
'''
if set(od.keys()) != set(keys_in_new_order):
raise KeyError('Keys in the new order do not match existing keys')
for key in keys_in_new_order:
od[key] = od.pop(key)
r... | [
"def",
"od_reorder_keys",
"(",
"od",
",",
"keys_in_new_order",
")",
":",
"# not used",
"if",
"set",
"(",
"od",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"keys_in_new_order",
")",
":",
"raise",
"KeyError",
"(",
"'Keys in the new order do not match existing ke... | Reorder the keys in an OrderedDict ``od`` in-place. | [
"Reorder",
"the",
"keys",
"in",
"an",
"OrderedDict",
"od",
"in",
"-",
"place",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L728-L736 |
ShenggaoZhu/midict | midict/__init__.py | _MI_setitem | def _MI_setitem(self, args, value):
'Separate __setitem__ function of MIMapping'
indices = self.indices
N = len(indices)
empty = N == 0
if empty: # init the dict
index1, key, index2, index1_last = MI_parse_args(self, args, allow_new=True)
exist_names = [index1]
item = [key]
... | python | def _MI_setitem(self, args, value):
'Separate __setitem__ function of MIMapping'
indices = self.indices
N = len(indices)
empty = N == 0
if empty: # init the dict
index1, key, index2, index1_last = MI_parse_args(self, args, allow_new=True)
exist_names = [index1]
item = [key]
... | [
"def",
"_MI_setitem",
"(",
"self",
",",
"args",
",",
"value",
")",
":",
"indices",
"=",
"self",
".",
"indices",
"N",
"=",
"len",
"(",
"indices",
")",
"empty",
"=",
"N",
"==",
"0",
"if",
"empty",
":",
"# init the dict",
"index1",
",",
"key",
",",
"i... | Separate __setitem__ function of MIMapping | [
"Separate",
"__setitem__",
"function",
"of",
"MIMapping"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L739-L830 |
ShenggaoZhu/midict | midict/__init__.py | _MI_init | def _MI_init(self, *args, **kw):
'''
Separate __init__ function of MIMapping
'''
items, names = [], None
n_args = len(args)
if n_args >= 1:
items = args[0]
if isinstance(items, Mapping): # copy from dict
if isinstance(items, MIMapping):
names = fo... | python | def _MI_init(self, *args, **kw):
'''
Separate __init__ function of MIMapping
'''
items, names = [], None
n_args = len(args)
if n_args >= 1:
items = args[0]
if isinstance(items, Mapping): # copy from dict
if isinstance(items, MIMapping):
names = fo... | [
"def",
"_MI_init",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"items",
",",
"names",
"=",
"[",
"]",
",",
"None",
"n_args",
"=",
"len",
"(",
"args",
")",
"if",
"n_args",
">=",
"1",
":",
"items",
"=",
"args",
"[",
"0",
"]",
... | Separate __init__ function of MIMapping | [
"Separate",
"__init__",
"function",
"of",
"MIMapping"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L833-L910 |
ShenggaoZhu/midict | midict/__init__.py | MI_method_PY3 | def MI_method_PY3(cls):
'''class decorator to change MIMapping method names for PY3 compatibility'''
nmspc = cls.__dict__.copy()
for m in ['__cmp__', 'has_key']:
nmspc.pop(m)
methods = ['keys', 'values', 'items']
for m in methods:
nmspc[m] = nmspc.pop('view' + m)
return type(cls... | python | def MI_method_PY3(cls):
'''class decorator to change MIMapping method names for PY3 compatibility'''
nmspc = cls.__dict__.copy()
for m in ['__cmp__', 'has_key']:
nmspc.pop(m)
methods = ['keys', 'values', 'items']
for m in methods:
nmspc[m] = nmspc.pop('view' + m)
return type(cls... | [
"def",
"MI_method_PY3",
"(",
"cls",
")",
":",
"nmspc",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"for",
"m",
"in",
"[",
"'__cmp__'",
",",
"'has_key'",
"]",
":",
"nmspc",
".",
"pop",
"(",
"m",
")",
"methods",
"=",
"[",
"'keys'",
",",
"'v... | class decorator to change MIMapping method names for PY3 compatibility | [
"class",
"decorator",
"to",
"change",
"MIMapping",
"method",
"names",
"for",
"PY3",
"compatibility"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L914-L923 |
ShenggaoZhu/midict | midict/__init__.py | MIMapping.fromkeys | def fromkeys(cls, keys, value=None, names=None):
'''
Create a new dictionary with keys from ``keys`` and values set to ``value``.
fromkeys() is a class method that returns a new dictionary. ``value`` defaults to None.
Length of ``keys`` must not exceed one because no duplicate values a... | python | def fromkeys(cls, keys, value=None, names=None):
'''
Create a new dictionary with keys from ``keys`` and values set to ``value``.
fromkeys() is a class method that returns a new dictionary. ``value`` defaults to None.
Length of ``keys`` must not exceed one because no duplicate values a... | [
"def",
"fromkeys",
"(",
"cls",
",",
"keys",
",",
"value",
"=",
"None",
",",
"names",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"keys",
")",
"if",
"N",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Length of keys (%s) must not exceed one because '",
"'n... | Create a new dictionary with keys from ``keys`` and values set to ``value``.
fromkeys() is a class method that returns a new dictionary. ``value`` defaults to None.
Length of ``keys`` must not exceed one because no duplicate values are allowed.
Optional ``names`` can be provided for index nam... | [
"Create",
"a",
"new",
"dictionary",
"with",
"keys",
"from",
"keys",
"and",
"values",
"set",
"to",
"value",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1131-L1146 |
ShenggaoZhu/midict | midict/__init__.py | MIMapping.itervalues | def itervalues(self, index=None):
'''
Iterate through values in the ``index`` (defaults to all indices
except the first index).
When ``index is None``, yielded values depend on the length of indices (``N``):
* if N <= 1: return
* if N == 2: yield values in the 2... | python | def itervalues(self, index=None):
'''
Iterate through values in the ``index`` (defaults to all indices
except the first index).
When ``index is None``, yielded values depend on the length of indices (``N``):
* if N <= 1: return
* if N == 2: yield values in the 2... | [
"def",
"itervalues",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"indices",
")",
"if",
"index",
"is",
"None",
":",
"if",
"N",
"<=",
"1",
":",
"return",
"elif",
"N",
"==",
"2",
":",
"index",
"=",
"1",
"... | Iterate through values in the ``index`` (defaults to all indices
except the first index).
When ``index is None``, yielded values depend on the length of indices (``N``):
* if N <= 1: return
* if N == 2: yield values in the 2nd index
* if N > 2: yield values in all i... | [
"Iterate",
"through",
"values",
"in",
"the",
"index",
"(",
"defaults",
"to",
"all",
"indices",
"except",
"the",
"first",
"index",
")",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1232-L1265 |
ShenggaoZhu/midict | midict/__init__.py | MIMapping.iteritems | def iteritems(self, indices=None):
'Iterate through items in the ``indices`` (defaults to all indices)'
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | python | def iteritems(self, indices=None):
'Iterate through items in the ``indices`` (defaults to all indices)'
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | [
"def",
"iteritems",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
"for",
"x",
"in",
"self",
".",
"itervalues",
"(",
"in... | Iterate through items in the ``indices`` (defaults to all indices) | [
"Iterate",
"through",
"items",
"in",
"the",
"indices",
"(",
"defaults",
"to",
"all",
"indices",
")"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1275-L1280 |
ShenggaoZhu/midict | midict/__init__.py | MIMapping.todict | def todict(self, dict_type=dict, index_key=0, index_value=-1):
'''convert to a specific type of dict using ``index_key`` as keys
and ``index_value`` as values (discarding index names)'''
if len(self):
return dict_type(self.items([index_key, index_value]))
else: # empty
... | python | def todict(self, dict_type=dict, index_key=0, index_value=-1):
'''convert to a specific type of dict using ``index_key`` as keys
and ``index_value`` as values (discarding index names)'''
if len(self):
return dict_type(self.items([index_key, index_value]))
else: # empty
... | [
"def",
"todict",
"(",
"self",
",",
"dict_type",
"=",
"dict",
",",
"index_key",
"=",
"0",
",",
"index_value",
"=",
"-",
"1",
")",
":",
"if",
"len",
"(",
"self",
")",
":",
"return",
"dict_type",
"(",
"self",
".",
"items",
"(",
"[",
"index_key",
",",
... | convert to a specific type of dict using ``index_key`` as keys
and ``index_value`` as values (discarding index names) | [
"convert",
"to",
"a",
"specific",
"type",
"of",
"dict",
"using",
"index_key",
"as",
"keys",
"and",
"index_value",
"as",
"values",
"(",
"discarding",
"index",
"names",
")"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1313-L1319 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.clear | def clear(self, clear_indices=False):
'Remove all items. index names are removed if ``clear_indices==True``.'
super(MIMapping, self).clear()
if clear_indices:
self.indices.clear()
else:
for index_d in self.indices[1:]:
index_d.clear() | python | def clear(self, clear_indices=False):
'Remove all items. index names are removed if ``clear_indices==True``.'
super(MIMapping, self).clear()
if clear_indices:
self.indices.clear()
else:
for index_d in self.indices[1:]:
index_d.clear() | [
"def",
"clear",
"(",
"self",
",",
"clear_indices",
"=",
"False",
")",
":",
"super",
"(",
"MIMapping",
",",
"self",
")",
".",
"clear",
"(",
")",
"if",
"clear_indices",
":",
"self",
".",
"indices",
".",
"clear",
"(",
")",
"else",
":",
"for",
"index_d",... | Remove all items. index names are removed if ``clear_indices==True``. | [
"Remove",
"all",
"items",
".",
"index",
"names",
"are",
"removed",
"if",
"clear_indices",
"==",
"True",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1403-L1410 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.update | def update(self, *args, **kw):
'''
Update the dictionary with items and names::
(items, names, **kw)
(dict, names, **kw)
(MIDict, names, **kw)
Optional positional argument ``names`` is only allowed when ``self.indices``
is empty (no indices are set y... | python | def update(self, *args, **kw):
'''
Update the dictionary with items and names::
(items, names, **kw)
(dict, names, **kw)
(MIDict, names, **kw)
Optional positional argument ``names`` is only allowed when ``self.indices``
is empty (no indices are set y... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"self",
".",
"indices",
":",
"raise",
"ValueError",
"(",
"'Only one positional argument is allowed when the'",
"'index names are al... | Update the dictionary with items and names::
(items, names, **kw)
(dict, names, **kw)
(MIDict, names, **kw)
Optional positional argument ``names`` is only allowed when ``self.indices``
is empty (no indices are set yet). | [
"Update",
"the",
"dictionary",
"with",
"items",
"and",
"names",
"::"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1412-L1444 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.rename_index | def rename_index(self, *args):
'''change the index name(s).
* call with one argument:
1. list of new index names (to replace all old names)
* call with two arguments:
1. old index name(s) (or index/indices)
2. new index name(s)
'''
if len(arg... | python | def rename_index(self, *args):
'''change the index name(s).
* call with one argument:
1. list of new index names (to replace all old names)
* call with two arguments:
1. old index name(s) (or index/indices)
2. new index name(s)
'''
if len(arg... | [
"def",
"rename_index",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"new_indices",
"=",
"args",
"[",
"0",
"]",
"old_indices",
"=",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
"... | change the index name(s).
* call with one argument:
1. list of new index names (to replace all old names)
* call with two arguments:
1. old index name(s) (or index/indices)
2. new index name(s) | [
"change",
"the",
"index",
"name",
"(",
"s",
")",
"."
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1450-L1479 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.reorder_indices | def reorder_indices(self, indices_order):
'reorder all the indices'
# allow mixed index syntax like int
indices_order, single = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices: # no changes
... | python | def reorder_indices(self, indices_order):
'reorder all the indices'
# allow mixed index syntax like int
indices_order, single = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices: # no changes
... | [
"def",
"reorder_indices",
"(",
"self",
",",
"indices_order",
")",
":",
"# allow mixed index syntax like int",
"indices_order",
",",
"single",
"=",
"convert_index_to_keys",
"(",
"self",
".",
"indices",
",",
"indices_order",
")",
"old_indices",
"=",
"force_list",
"(",
... | reorder all the indices | [
"reorder",
"all",
"the",
"indices"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1482-L1502 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.add_index | def add_index(self, values, name=None):
'add an index of ``name`` with the list of ``values``'
if len(values) != len(set(values)):
raise ValueError('Values in the new index are not unique')
d = self.indices
if len(values) != len(self) and len(values) and d:
raise... | python | def add_index(self, values, name=None):
'add an index of ``name`` with the list of ``values``'
if len(values) != len(set(values)):
raise ValueError('Values in the new index are not unique')
d = self.indices
if len(values) != len(self) and len(values) and d:
raise... | [
"def",
"add_index",
"(",
"self",
",",
"values",
",",
"name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"set",
"(",
"values",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Values in the new index are not unique'",
")",
"d",
... | add an index of ``name`` with the list of ``values`` | [
"add",
"an",
"index",
"of",
"name",
"with",
"the",
"list",
"of",
"values"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1505-L1531 |
ShenggaoZhu/midict | midict/__init__.py | MIDict.remove_index | def remove_index(self, index):
'remove one or more indices'
index_rm, single = convert_key_to_index(force_list(self.indices.keys()), index)
if single:
index_rm = [index_rm]
index_new = [i for i in range(len(self.indices)) if i not in index_rm]
if not index_new: # no... | python | def remove_index(self, index):
'remove one or more indices'
index_rm, single = convert_key_to_index(force_list(self.indices.keys()), index)
if single:
index_rm = [index_rm]
index_new = [i for i in range(len(self.indices)) if i not in index_rm]
if not index_new: # no... | [
"def",
"remove_index",
"(",
"self",
",",
"index",
")",
":",
"index_rm",
",",
"single",
"=",
"convert_key_to_index",
"(",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
",",
"index",
")",
"if",
"single",
":",
"index_rm",
"=",
"["... | remove one or more indices | [
"remove",
"one",
"or",
"more",
"indices"
] | train | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1534-L1549 |
KelSolaar/Foundations | foundations/core.py | exit | def exit(exit_code=0):
"""
Shuts down current process logging, associated handlers and then exits to system.
:param exit_code: System exit code.
:type exit_code: Integer or String or Object
:note: **exit_code** argument is passed to Python :func:`sys.exit` definition.
"""
LOGGER.debug("> ... | python | def exit(exit_code=0):
"""
Shuts down current process logging, associated handlers and then exits to system.
:param exit_code: System exit code.
:type exit_code: Integer or String or Object
:note: **exit_code** argument is passed to Python :func:`sys.exit` definition.
"""
LOGGER.debug("> ... | [
"def",
"exit",
"(",
"exit_code",
"=",
"0",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> {0} | Exiting current process!\"",
".",
"format",
"(",
"__name__",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Stopping logging handlers and logger!\"",
")",
"for",
"handler",
... | Shuts down current process logging, associated handlers and then exits to system.
:param exit_code: System exit code.
:type exit_code: Integer or String or Object
:note: **exit_code** argument is passed to Python :func:`sys.exit` definition. | [
"Shuts",
"down",
"current",
"process",
"logging",
"associated",
"handlers",
"and",
"then",
"exits",
"to",
"system",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/core.py#L38-L54 |
KelSolaar/Foundations | foundations/core.py | wait | def wait(wait_time):
"""
Halts current process exection for an user defined time.
:param wait_time: Current sleep time in seconds.
:type wait_time: float
:return: Definition success.
:rtype: bool
"""
LOGGER.debug("> Waiting '{0}' seconds!".format(wait_time))
time.sleep(wait_time)
... | python | def wait(wait_time):
"""
Halts current process exection for an user defined time.
:param wait_time: Current sleep time in seconds.
:type wait_time: float
:return: Definition success.
:rtype: bool
"""
LOGGER.debug("> Waiting '{0}' seconds!".format(wait_time))
time.sleep(wait_time)
... | [
"def",
"wait",
"(",
"wait_time",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Waiting '{0}' seconds!\"",
".",
"format",
"(",
"wait_time",
")",
")",
"time",
".",
"sleep",
"(",
"wait_time",
")",
"return",
"True"
] | Halts current process exection for an user defined time.
:param wait_time: Current sleep time in seconds.
:type wait_time: float
:return: Definition success.
:rtype: bool | [
"Halts",
"current",
"process",
"exection",
"for",
"an",
"user",
"defined",
"time",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/core.py#L57-L70 |
basilfx/flask-daapserver | daapserver/server.py | create_server_app | def create_server_app(provider, password=None, cache=True, cache_timeout=3600,
debug=False):
"""
Create a DAAP server, based around a Flask application. The server requires
a content provider, server name and optionally, a password. The content
provider should return raw object dat... | python | def create_server_app(provider, password=None, cache=True, cache_timeout=3600,
debug=False):
"""
Create a DAAP server, based around a Flask application. The server requires
a content provider, server name and optionally, a password. The content
provider should return raw object dat... | [
"def",
"create_server_app",
"(",
"provider",
",",
"password",
"=",
"None",
",",
"cache",
"=",
"True",
",",
"cache_timeout",
"=",
"3600",
",",
"debug",
"=",
"False",
")",
":",
"# Create Flask App",
"app",
"=",
"Flask",
"(",
"__name__",
",",
"static_folder",
... | Create a DAAP server, based around a Flask application. The server requires
a content provider, server name and optionally, a password. The content
provider should return raw object data.
Object responses can be cached. This may dramatically speed up connections
for multiple clients. However, this is o... | [
"Create",
"a",
"DAAP",
"server",
"based",
"around",
"a",
"Flask",
"application",
".",
"The",
"server",
"requires",
"a",
"content",
"provider",
"server",
"name",
"and",
"optionally",
"a",
"password",
".",
"The",
"content",
"provider",
"should",
"return",
"raw",... | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/daapserver/server.py#L49-L472 |
kurtbrose/ufork | ufork/ufork.py | spawn_daemon | def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
'causes run to be executed in a newly spawned daemon process'
global LAST_PGRP_PATH
fork = fork or os.fork
open(outfile, 'a').close() # TODO: configurable output file
if pgrpfile and os.path.exists(pgrpfile):
try:
cu... | python | def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
'causes run to be executed in a newly spawned daemon process'
global LAST_PGRP_PATH
fork = fork or os.fork
open(outfile, 'a').close() # TODO: configurable output file
if pgrpfile and os.path.exists(pgrpfile):
try:
cu... | [
"def",
"spawn_daemon",
"(",
"fork",
"=",
"None",
",",
"pgrpfile",
"=",
"None",
",",
"outfile",
"=",
"'out.txt'",
")",
":",
"global",
"LAST_PGRP_PATH",
"fork",
"=",
"fork",
"or",
"os",
".",
"fork",
"open",
"(",
"outfile",
",",
"'a'",
")",
".",
"close",
... | causes run to be executed in a newly spawned daemon process | [
"causes",
"run",
"to",
"be",
"executed",
"in",
"a",
"newly",
"spawned",
"daemon",
"process"
] | train | https://github.com/kurtbrose/ufork/blob/c9aadbb6a3531682fe8634e4e7f19c600a5cfb44/ufork/ufork.py#L406-L431 |
kurtbrose/ufork | ufork/ufork.py | wsgiref_thread_arbiter | def wsgiref_thread_arbiter(wsgi, host, port):
'probably not suitable for production use; example of threaded server'
import wsgiref.simple_server
httpd = wsgiref.simple_server.make_server(host, port, wsgi)
httpd.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start_server():
... | python | def wsgiref_thread_arbiter(wsgi, host, port):
'probably not suitable for production use; example of threaded server'
import wsgiref.simple_server
httpd = wsgiref.simple_server.make_server(host, port, wsgi)
httpd.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start_server():
... | [
"def",
"wsgiref_thread_arbiter",
"(",
"wsgi",
",",
"host",
",",
"port",
")",
":",
"import",
"wsgiref",
".",
"simple_server",
"httpd",
"=",
"wsgiref",
".",
"simple_server",
".",
"make_server",
"(",
"host",
",",
"port",
",",
"wsgi",
")",
"httpd",
".",
"socke... | probably not suitable for production use; example of threaded server | [
"probably",
"not",
"suitable",
"for",
"production",
"use",
";",
"example",
"of",
"threaded",
"server"
] | train | https://github.com/kurtbrose/ufork/blob/c9aadbb6a3531682fe8634e4e7f19c600a5cfb44/ufork/ufork.py#L544-L560 |
kurtbrose/ufork | ufork/ufork.py | Arbiter.spawn_thread | def spawn_thread(self):
'causes run to be executed in a thread'
self.thread = threading.Thread(target=self.run, args=(False,))
self.thread.daemon = True
self.thread.start() | python | def spawn_thread(self):
'causes run to be executed in a thread'
self.thread = threading.Thread(target=self.run, args=(False,))
self.thread.daemon = True
self.thread.start() | [
"def",
"spawn_thread",
"(",
"self",
")",
":",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"run",
",",
"args",
"=",
"(",
"False",
",",
")",
")",
"self",
".",
"thread",
".",
"daemon",
"=",
"True",
"self",
... | causes run to be executed in a thread | [
"causes",
"run",
"to",
"be",
"executed",
"in",
"a",
"thread"
] | train | https://github.com/kurtbrose/ufork/blob/c9aadbb6a3531682fe8634e4e7f19c600a5cfb44/ufork/ufork.py#L222-L226 |
kurtbrose/ufork | ufork/ufork.py | Arbiter.spawn_daemon | def spawn_daemon(self, pgrpfile=None, outfile="out.txt"):
'''
Causes this arbiters run() function to be executed in a newly spawned
daemon process.
Parameters
----------
pgrpfile : str, optional
Path at which to write a pgrpfile (file containing the process
... | python | def spawn_daemon(self, pgrpfile=None, outfile="out.txt"):
'''
Causes this arbiters run() function to be executed in a newly spawned
daemon process.
Parameters
----------
pgrpfile : str, optional
Path at which to write a pgrpfile (file containing the process
... | [
"def",
"spawn_daemon",
"(",
"self",
",",
"pgrpfile",
"=",
"None",
",",
"outfile",
"=",
"\"out.txt\"",
")",
":",
"if",
"spawn_daemon",
"(",
"self",
".",
"fork",
",",
"pgrpfile",
",",
"outfile",
")",
":",
"return",
"signal",
".",
"signal",
"(",
"signal",
... | Causes this arbiters run() function to be executed in a newly spawned
daemon process.
Parameters
----------
pgrpfile : str, optional
Path at which to write a pgrpfile (file containing the process
group id of the daemon process and its children).
outfile :... | [
"Causes",
"this",
"arbiters",
"run",
"()",
"function",
"to",
"be",
"executed",
"in",
"a",
"newly",
"spawned",
"daemon",
"process",
"."
] | train | https://github.com/kurtbrose/ufork/blob/c9aadbb6a3531682fe8634e4e7f19c600a5cfb44/ufork/ufork.py#L228-L246 |
kurtbrose/ufork | ufork/ufork.py | Arbiter._ensure_pgrp | def _ensure_pgrp(self):
"""Ensures that the pgrp file is present and up to date. There have
been production cases where the file was lost or not
immediately emitted due to disk space issues.
"""
if not LAST_PGRP_PATH: # global
return
try:
with ope... | python | def _ensure_pgrp(self):
"""Ensures that the pgrp file is present and up to date. There have
been production cases where the file was lost or not
immediately emitted due to disk space issues.
"""
if not LAST_PGRP_PATH: # global
return
try:
with ope... | [
"def",
"_ensure_pgrp",
"(",
"self",
")",
":",
"if",
"not",
"LAST_PGRP_PATH",
":",
"# global",
"return",
"try",
":",
"with",
"open",
"(",
"LAST_PGRP_PATH",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"os",
".",
"getpgrp",
"(",... | Ensures that the pgrp file is present and up to date. There have
been production cases where the file was lost or not
immediately emitted due to disk space issues. | [
"Ensures",
"that",
"the",
"pgrp",
"file",
"is",
"present",
"and",
"up",
"to",
"date",
".",
"There",
"have",
"been",
"production",
"cases",
"where",
"the",
"file",
"was",
"lost",
"or",
"not",
"immediately",
"emitted",
"due",
"to",
"disk",
"space",
"issues",... | train | https://github.com/kurtbrose/ufork/blob/c9aadbb6a3531682fe8634e4e7f19c600a5cfb44/ufork/ufork.py#L280-L292 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.setY | def setY(self,Y,standardize=False):
"""
Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance)
"""
assert Y.shape[0]==self.N, 'CVarianceDecomposition:: Incompat... | python | def setY(self,Y,standardize=False):
"""
Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance)
"""
assert Y.shape[0]==self.N, 'CVarianceDecomposition:: Incompat... | [
"def",
"setY",
"(",
"self",
",",
"Y",
",",
"standardize",
"=",
"False",
")",
":",
"assert",
"Y",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"N",
",",
"'CVarianceDecomposition:: Incompatible shape'",
"assert",
"Y",
".",
"shape",
"[",
"1",
"]",
"=="... | Set phenotype matrix
Args:
Y: phenotype matrix [N, P]
standardize: if True, phenotype is standardized (zero mean, unit variance) | [
"Set",
"phenotype",
"matrix",
"Args",
":",
"Y",
":",
"phenotype",
"matrix",
"[",
"N",
"P",
"]",
"standardize",
":",
"if",
"True",
"phenotype",
"is",
"standardized",
"(",
"zero",
"mean",
"unit",
"variance",
")"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L75-L101 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.addRandomEffect | def addRandomEffect(self,K=None,covar_type='freeform',is_noise=False,normalize=True,Ks=None,offset=1e-4,rank=1,covar_K0=None):
"""
Add random effect Term
depending on self.P=1 or >1 add single trait or multi trait random effect term
"""
if self.P==1: self.addSingleTraitTerm(K=K,i... | python | def addRandomEffect(self,K=None,covar_type='freeform',is_noise=False,normalize=True,Ks=None,offset=1e-4,rank=1,covar_K0=None):
"""
Add random effect Term
depending on self.P=1 or >1 add single trait or multi trait random effect term
"""
if self.P==1: self.addSingleTraitTerm(K=K,i... | [
"def",
"addRandomEffect",
"(",
"self",
",",
"K",
"=",
"None",
",",
"covar_type",
"=",
"'freeform'",
",",
"is_noise",
"=",
"False",
",",
"normalize",
"=",
"True",
",",
"Ks",
"=",
"None",
",",
"offset",
"=",
"1e-4",
",",
"rank",
"=",
"1",
",",
"covar_K... | Add random effect Term
depending on self.P=1 or >1 add single trait or multi trait random effect term | [
"Add",
"random",
"effect",
"Term",
"depending",
"on",
"self",
".",
"P",
"=",
"1",
"or",
">",
"1",
"add",
"single",
"trait",
"or",
"multi",
"trait",
"random",
"effect",
"term"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L103-L109 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.addSingleTraitTerm | def addSingleTraitTerm(self,K=None,is_noise=False,normalize=True,Ks=None):
"""
add random effects term for single trait models (no trait-trait covariance matrix)
Args:
K: NxN sample covariance matrix
is_noise: bool labeling the noise term (noise term has... | python | def addSingleTraitTerm(self,K=None,is_noise=False,normalize=True,Ks=None):
"""
add random effects term for single trait models (no trait-trait covariance matrix)
Args:
K: NxN sample covariance matrix
is_noise: bool labeling the noise term (noise term has... | [
"def",
"addSingleTraitTerm",
"(",
"self",
",",
"K",
"=",
"None",
",",
"is_noise",
"=",
"False",
",",
"normalize",
"=",
"True",
",",
"Ks",
"=",
"None",
")",
":",
"assert",
"self",
".",
"P",
"==",
"1",
",",
"'Incompatible number of traits'",
"assert",
"K",... | add random effects term for single trait models (no trait-trait covariance matrix)
Args:
K: NxN sample covariance matrix
is_noise: bool labeling the noise term (noise term has K=eye)
normalize: if True, K and Ks are scales such that K.diagonal().mean()==1
... | [
"add",
"random",
"effects",
"term",
"for",
"single",
"trait",
"models",
"(",
"no",
"trait",
"-",
"trait",
"covariance",
"matrix",
")",
"Args",
":",
"K",
":",
"NxN",
"sample",
"covariance",
"matrix",
"is_noise",
":",
"bool",
"labeling",
"the",
"noise",
"ter... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L112-L155 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.addMultiTraitTerm | def addMultiTraitTerm(self,K=None,covar_type='freeform',is_noise=False,normalize=True,Ks=None,offset=1e-4,rank=1,covar_K0=None):
"""
add multi trait random effects term.
The inter-trait covariance is parametrized by covar_type, where parameters are optimized.
Args:
K... | python | def addMultiTraitTerm(self,K=None,covar_type='freeform',is_noise=False,normalize=True,Ks=None,offset=1e-4,rank=1,covar_K0=None):
"""
add multi trait random effects term.
The inter-trait covariance is parametrized by covar_type, where parameters are optimized.
Args:
K... | [
"def",
"addMultiTraitTerm",
"(",
"self",
",",
"K",
"=",
"None",
",",
"covar_type",
"=",
"'freeform'",
",",
"is_noise",
"=",
"False",
",",
"normalize",
"=",
"True",
",",
"Ks",
"=",
"None",
",",
"offset",
"=",
"1e-4",
",",
"rank",
"=",
"1",
",",
"covar... | add multi trait random effects term.
The inter-trait covariance is parametrized by covar_type, where parameters are optimized.
Args:
K: Individual-individual (Intra-Trait) Covariance Matrix [N, N]
(K is normalised in the C++ code such that K.trace()=N)
... | [
"add",
"multi",
"trait",
"random",
"effects",
"term",
".",
"The",
"inter",
"-",
"trait",
"covariance",
"is",
"parametrized",
"by",
"covar_type",
"where",
"parameters",
"are",
"optimized",
".",
"Args",
":",
"K",
":",
"Individual",
"-",
"individual",
"(",
"Int... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L159-L264 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.addFixedEffect | def addFixedEffect(self,F=None,A=None):
"""
add fixed effect to the model
Args:
F: fixed effect matrix [N,1]
A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect)
"""
if A==None:
A = SP.eye(self.P)
if F==None... | python | def addFixedEffect(self,F=None,A=None):
"""
add fixed effect to the model
Args:
F: fixed effect matrix [N,1]
A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect)
"""
if A==None:
A = SP.eye(self.P)
if F==None... | [
"def",
"addFixedEffect",
"(",
"self",
",",
"F",
"=",
"None",
",",
"A",
"=",
"None",
")",
":",
"if",
"A",
"==",
"None",
":",
"A",
"=",
"SP",
".",
"eye",
"(",
"self",
".",
"P",
")",
"if",
"F",
"==",
"None",
":",
"F",
"=",
"SP",
".",
"ones",
... | add fixed effect to the model
Args:
F: fixed effect matrix [N,1]
A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect) | [
"add",
"fixed",
"effect",
"to",
"the",
"model"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L267-L298 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.initGP | def initGP(self,fast=False):
"""
Initialize GP objetct
Args:
fast: if fast==True initialize gpkronSum gp
"""
if fast:
assert self.n_terms==2, 'CVarianceDecomposition: for fast inference number of terms must be == 2'
assert self.P>1, ... | python | def initGP(self,fast=False):
"""
Initialize GP objetct
Args:
fast: if fast==True initialize gpkronSum gp
"""
if fast:
assert self.n_terms==2, 'CVarianceDecomposition: for fast inference number of terms must be == 2'
assert self.P>1, ... | [
"def",
"initGP",
"(",
"self",
",",
"fast",
"=",
"False",
")",
":",
"if",
"fast",
":",
"assert",
"self",
".",
"n_terms",
"==",
"2",
",",
"'CVarianceDecomposition: for fast inference number of terms must be == 2'",
"assert",
"self",
".",
"P",
">",
"1",
",",
"'CV... | Initialize GP objetct
Args:
fast: if fast==True initialize gpkronSum gp | [
"Initialize",
"GP",
"objetct",
"Args",
":",
"fast",
":",
"if",
"fast",
"==",
"True",
"initialize",
"gpkronSum",
"gp"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L302-L317 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition._getScalesDiag | def _getScalesDiag(self,termx=0):
"""
Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization
"""
assert self.P>1, 'CVarianceDecomposition:: diagonal init_method allowed onl... | python | def _getScalesDiag(self,termx=0):
"""
Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization
"""
assert self.P>1, 'CVarianceDecomposition:: diagonal init_method allowed onl... | [
"def",
"_getScalesDiag",
"(",
"self",
",",
"termx",
"=",
"0",
")",
":",
"assert",
"self",
".",
"P",
">",
"1",
",",
"'CVarianceDecomposition:: diagonal init_method allowed only for multi trait models'",
"assert",
"self",
".",
"noisPos",
"!=",
"None",
",",
"'CVariance... | Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization | [
"Uses",
"2",
"term",
"single",
"trait",
"model",
"to",
"get",
"covar",
"params",
"for",
"initialization",
"Args",
":",
"termx",
":",
"non",
"-",
"noise",
"term",
"terms",
"that",
"is",
"used",
"for",
"initialization"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L320-L346 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition._getScalesRand | def _getScalesRand(self):
"""
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP... | python | def _getScalesRand(self):
"""
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP... | [
"def",
"_getScalesRand",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
">",
"1",
":",
"scales",
"=",
"[",
"]",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_terms",
")",
":",
"_scales",
"=",
"SP",
".",
"randn",
"(",
"self",
".",
"diag",
... | Return a vector of random scales | [
"Return",
"a",
"vector",
"of",
"random",
"scales"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L348-L363 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition._perturbation | def _perturbation(self):
"""
Returns Gaussian perturbation
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP.co... | python | def _perturbation(self):
"""
Returns Gaussian perturbation
"""
if self.P>1:
scales = []
for term_i in range(self.n_terms):
_scales = SP.randn(self.diag[term_i].shape[0])
if self.offset[term_i]>0:
_scales = SP.co... | [
"def",
"_perturbation",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
">",
"1",
":",
"scales",
"=",
"[",
"]",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_terms",
")",
":",
"_scales",
"=",
"SP",
".",
"randn",
"(",
"self",
".",
"diag",
... | Returns Gaussian perturbation | [
"Returns",
"Gaussian",
"perturbation"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L365-L379 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.trainGP | def trainGP(self,fast=False,scales0=None,fixed0=None,lambd=None):
"""
Train the gp
Args:
fast: if true and the gp has not been initialized, initializes a kronSum gp
scales0: initial variance components params
fixed0: initial fixed effect para... | python | def trainGP(self,fast=False,scales0=None,fixed0=None,lambd=None):
"""
Train the gp
Args:
fast: if true and the gp has not been initialized, initializes a kronSum gp
scales0: initial variance components params
fixed0: initial fixed effect para... | [
"def",
"trainGP",
"(",
"self",
",",
"fast",
"=",
"False",
",",
"scales0",
"=",
"None",
",",
"fixed0",
"=",
"None",
",",
"lambd",
"=",
"None",
")",
":",
"assert",
"self",
".",
"n_terms",
">",
"0",
",",
"'CVarianceDecomposition:: No variance component terms'",... | Train the gp
Args:
fast: if true and the gp has not been initialized, initializes a kronSum gp
scales0: initial variance components params
fixed0: initial fixed effect params | [
"Train",
"the",
"gp",
"Args",
":",
"fast",
":",
"if",
"true",
"and",
"the",
"gp",
"has",
"not",
"been",
"initialized",
"initializes",
"a",
"kronSum",
"gp",
"scales0",
":",
"initial",
"variance",
"components",
"params",
"fixed0",
":",
"initial",
"fixed",
"e... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L381-L414 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.findLocalOptimum | def findLocalOptimum(self,fast=False,scales0=None,fixed0=None,init_method=None,termx=0,n_times=10,perturb=True,pertSize=1e-3,verbose=True,lambd=None):
"""
Train the model using the specified initialization strategy
Args:
fast: if true, fast gp is initialized
... | python | def findLocalOptimum(self,fast=False,scales0=None,fixed0=None,init_method=None,termx=0,n_times=10,perturb=True,pertSize=1e-3,verbose=True,lambd=None):
"""
Train the model using the specified initialization strategy
Args:
fast: if true, fast gp is initialized
... | [
"def",
"findLocalOptimum",
"(",
"self",
",",
"fast",
"=",
"False",
",",
"scales0",
"=",
"None",
",",
"fixed0",
"=",
"None",
",",
"init_method",
"=",
"None",
",",
"termx",
"=",
"0",
",",
"n_times",
"=",
"10",
",",
"perturb",
"=",
"True",
",",
"pertSiz... | Train the model using the specified initialization strategy
Args:
fast: if true, fast gp is initialized
scales0: if not None init_method is set to manual
fixed0: initial fixed effects
init_method: initialization method \in {random,d... | [
"Train",
"the",
"model",
"using",
"the",
"specified",
"initialization",
"strategy",
"Args",
":",
"fast",
":",
"if",
"true",
"fast",
"gp",
"is",
"initialized",
"scales0",
":",
"if",
"not",
"None",
"init_method",
"is",
"set",
"to",
"manual",
"fixed0",
":",
"... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L418-L470 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.findLocalOptima | def findLocalOptima(self,fast=False,verbose=True,n_times=10,lambd=None):
"""
Train the model repeadly up to a number specified by the users with random restarts and
return a list of all relative minima that have been found
Args:
fast: Boolean. if set to True i... | python | def findLocalOptima(self,fast=False,verbose=True,n_times=10,lambd=None):
"""
Train the model repeadly up to a number specified by the users with random restarts and
return a list of all relative minima that have been found
Args:
fast: Boolean. if set to True i... | [
"def",
"findLocalOptima",
"(",
"self",
",",
"fast",
"=",
"False",
",",
"verbose",
"=",
"True",
",",
"n_times",
"=",
"10",
",",
"lambd",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"init",
":",
"self",
".",
"initGP",
"(",
"fast",
")",
"opt_list... | Train the model repeadly up to a number specified by the users with random restarts and
return a list of all relative minima that have been found
Args:
fast: Boolean. if set to True initalize kronSumGP
verbose: Boolean. If set to True, verbose output is produce... | [
"Train",
"the",
"model",
"repeadly",
"up",
"to",
"a",
"number",
"specified",
"by",
"the",
"users",
"with",
"random",
"restarts",
"and",
"return",
"a",
"list",
"of",
"all",
"relative",
"minima",
"that",
"have",
"been",
"found",
"Args",
":",
"fast",
":",
"... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L476-L529 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.setScales | def setScales(self,scales=None,term_num=None):
"""
get random initialization of variances based on the empirical trait variance
Args:
scales: if scales==None: set them randomly,
else: set scales to term_num (if term_num==None: set to all terms)
... | python | def setScales(self,scales=None,term_num=None):
"""
get random initialization of variances based on the empirical trait variance
Args:
scales: if scales==None: set them randomly,
else: set scales to term_num (if term_num==None: set to all terms)
... | [
"def",
"setScales",
"(",
"self",
",",
"scales",
"=",
"None",
",",
"term_num",
"=",
"None",
")",
":",
"if",
"scales",
"==",
"None",
":",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_terms",
")",
":",
"n_scales",
"=",
"self",
".",
"vd",
".",
... | get random initialization of variances based on the empirical trait variance
Args:
scales: if scales==None: set them randomly,
else: set scales to term_num (if term_num==None: set to all terms)
term_num: set scales to term_num | [
"get",
"random",
"initialization",
"of",
"variances",
"based",
"on",
"the",
"empirical",
"trait",
"variance"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L549-L571 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getScales | def getScales(self,term_i=None):
"""
Returns the Parameters
Args:
term_i: index of the term we are interested in
if term_i==None returns the whole vector of parameters
"""
if term_i==None:
RV = self.vd.getScales()
... | python | def getScales(self,term_i=None):
"""
Returns the Parameters
Args:
term_i: index of the term we are interested in
if term_i==None returns the whole vector of parameters
"""
if term_i==None:
RV = self.vd.getScales()
... | [
"def",
"getScales",
"(",
"self",
",",
"term_i",
"=",
"None",
")",
":",
"if",
"term_i",
"==",
"None",
":",
"RV",
"=",
"self",
".",
"vd",
".",
"getScales",
"(",
")",
"else",
":",
"assert",
"term_i",
"<",
"self",
".",
"n_terms",
",",
"'Term index non va... | Returns the Parameters
Args:
term_i: index of the term we are interested in
if term_i==None returns the whole vector of parameters | [
"Returns",
"the",
"Parameters",
"Args",
":",
"term_i",
":",
"index",
"of",
"the",
"term",
"we",
"are",
"interested",
"in",
"if",
"term_i",
"==",
"None",
"returns",
"the",
"whole",
"vector",
"of",
"parameters"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L574-L587 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getEstTraitCovar | def getEstTraitCovar(self,term_i=None):
"""
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
"""
assert self.P>1, 'Trait covars not defined for single trait analysis'
if term_i==None:
... | python | def getEstTraitCovar(self,term_i=None):
"""
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
"""
assert self.P>1, 'Trait covars not defined for single trait analysis'
if term_i==None:
... | [
"def",
"getEstTraitCovar",
"(",
"self",
",",
"term_i",
"=",
"None",
")",
":",
"assert",
"self",
".",
"P",
">",
"1",
",",
"'Trait covars not defined for single trait analysis'",
"if",
"term_i",
"==",
"None",
":",
"RV",
"=",
"SP",
".",
"zeros",
"(",
"(",
"se... | Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in | [
"Returns",
"explicitly",
"the",
"estimated",
"trait",
"covariance",
"matrix"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L599-L614 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getEstTraitCorrCoef | def getEstTraitCorrCoef(self,term_i=None):
"""
Returns the estimated trait correlation matrix
Args:
term_i: index of the term we are interested in
"""
cov = self.getEstTraitCovar(term_i)
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/std... | python | def getEstTraitCorrCoef(self,term_i=None):
"""
Returns the estimated trait correlation matrix
Args:
term_i: index of the term we are interested in
"""
cov = self.getEstTraitCovar(term_i)
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/std... | [
"def",
"getEstTraitCorrCoef",
"(",
"self",
",",
"term_i",
"=",
"None",
")",
":",
"cov",
"=",
"self",
".",
"getEstTraitCovar",
"(",
"term_i",
")",
"stds",
"=",
"SP",
".",
"sqrt",
"(",
"cov",
".",
"diagonal",
"(",
")",
")",
"[",
":",
",",
"SP",
".",
... | Returns the estimated trait correlation matrix
Args:
term_i: index of the term we are interested in | [
"Returns",
"the",
"estimated",
"trait",
"correlation",
"matrix"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L619-L629 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getVariances | def getVariances(self):
"""
Returns the estimated variances as a n_terms x P matrix
each row of the output represents a term and its P values represent the variance corresponding variance in each trait
"""
if self.P>1:
RV=SP.zeros((self.n_terms,self.P))
fo... | python | def getVariances(self):
"""
Returns the estimated variances as a n_terms x P matrix
each row of the output represents a term and its P values represent the variance corresponding variance in each trait
"""
if self.P>1:
RV=SP.zeros((self.n_terms,self.P))
fo... | [
"def",
"getVariances",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
">",
"1",
":",
"RV",
"=",
"SP",
".",
"zeros",
"(",
"(",
"self",
".",
"n_terms",
",",
"self",
".",
"P",
")",
")",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_terms",
... | Returns the estimated variances as a n_terms x P matrix
each row of the output represents a term and its P values represent the variance corresponding variance in each trait | [
"Returns",
"the",
"estimated",
"variances",
"as",
"a",
"n_terms",
"x",
"P",
"matrix",
"each",
"row",
"of",
"the",
"output",
"represents",
"a",
"term",
"and",
"its",
"P",
"values",
"represent",
"the",
"variance",
"corresponding",
"variance",
"in",
"each",
"tr... | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L633-L644 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getHessian | def getHessian(self):
"""
COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y)
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Hessian']==None:
ParamMask=self.gp.ge... | python | def getHessian(self):
"""
COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y)
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Hessian']==None:
ParamMask=self.gp.ge... | [
"def",
"getHessian",
"(",
"self",
")",
":",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"assert",
"self",
".",
"fast",
"==",
"False",
",",
"'Not supported for fast implementation'",
"if",
"self",
".",
"cache",
"[",
"'Hessian'",
"]",
"==",
"None... | COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y) | [
"COMPUTES",
"OF",
"HESSIAN",
"OF",
"E",
"(",
"\\",
"theta",
")",
"=",
"-",
"log",
"L",
"(",
"\\",
"theta",
"|",
"X",
"y",
")"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L658-L672 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getLaplaceCovar | def getLaplaceCovar(self):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Sigma']==Non... | python | def getLaplaceCovar(self):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Sigma']==Non... | [
"def",
"getLaplaceCovar",
"(",
"self",
")",
":",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"assert",
"self",
".",
"fast",
"==",
"False",
",",
"'Not supported for fast implementation'",
"if",
"self",
".",
"cache",
"[",
"'Sigma'",
"]",
"==",
"N... | USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS | [
"USES",
"LAPLACE",
"APPROXIMATION",
"TO",
"CALCULATE",
"THE",
"COVARIANCE",
"MATRIX",
"OF",
"THE",
"OPTIMIZED",
"PARAMETERS"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L675-L684 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getFisher | def getFisher(self):
"""
Return the fisher information matrix over the parameters
TO CHECK: IT DOES NOT WORK PROPERLY
"""
Ctot = self.vd.getGP().getCovar()
Ki = SP.linalg.inv(Ctot.K())
n_scales = self.vd.getNumberScales()
out = SP.zeros((n_scales,n_scales)... | python | def getFisher(self):
"""
Return the fisher information matrix over the parameters
TO CHECK: IT DOES NOT WORK PROPERLY
"""
Ctot = self.vd.getGP().getCovar()
Ki = SP.linalg.inv(Ctot.K())
n_scales = self.vd.getNumberScales()
out = SP.zeros((n_scales,n_scales)... | [
"def",
"getFisher",
"(",
"self",
")",
":",
"Ctot",
"=",
"self",
".",
"vd",
".",
"getGP",
"(",
")",
".",
"getCovar",
"(",
")",
"Ki",
"=",
"SP",
".",
"linalg",
".",
"inv",
"(",
"Ctot",
".",
"K",
"(",
")",
")",
"n_scales",
"=",
"self",
".",
"vd"... | Return the fisher information matrix over the parameters
TO CHECK: IT DOES NOT WORK PROPERLY | [
"Return",
"the",
"fisher",
"information",
"matrix",
"over",
"the",
"parameters",
"TO",
"CHECK",
":",
"IT",
"DOES",
"NOT",
"WORK",
"PROPERLY"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L687-L701 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getModelPosterior | def getModelPosterior(self,min):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR
"""
Sigma = self.getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*SP.log(2*SP.pi)+0.5*SP.log(SP.linalg.det(Sigma))
RV = min['... | python | def getModelPosterior(self,min):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR
"""
Sigma = self.getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*SP.log(2*SP.pi)+0.5*SP.log(SP.linalg.det(Sigma))
RV = min['... | [
"def",
"getModelPosterior",
"(",
"self",
",",
"min",
")",
":",
"Sigma",
"=",
"self",
".",
"getLaplaceCovar",
"(",
"min",
")",
"n_params",
"=",
"self",
".",
"vd",
".",
"getNumberScales",
"(",
")",
"ModCompl",
"=",
"0.5",
"*",
"n_params",
"*",
"SP",
".",... | USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR | [
"USES",
"LAPLACE",
"APPROXIMATION",
"TO",
"CALCULATE",
"THE",
"BAYESIAN",
"MODEL",
"POSTERIOR"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L733-L741 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getEmpTraitCovar | def getEmpTraitCovar(self):
"""
Returns the empirical trait covariance matrix
"""
if self.P==1:
out=self.Y[self.Iok].var()
else:
out=SP.cov(self.Y[self.Iok].T)
return out | python | def getEmpTraitCovar(self):
"""
Returns the empirical trait covariance matrix
"""
if self.P==1:
out=self.Y[self.Iok].var()
else:
out=SP.cov(self.Y[self.Iok].T)
return out | [
"def",
"getEmpTraitCovar",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
"==",
"1",
":",
"out",
"=",
"self",
".",
"Y",
"[",
"self",
".",
"Iok",
"]",
".",
"var",
"(",
")",
"else",
":",
"out",
"=",
"SP",
".",
"cov",
"(",
"self",
".",
"Y",
"[... | Returns the empirical trait covariance matrix | [
"Returns",
"the",
"empirical",
"trait",
"covariance",
"matrix"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L745-L753 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.getEmpTraitCorrCoef | def getEmpTraitCorrCoef(self):
"""
Returns the empirical trait correlation matrix
"""
cov = self.getEmpTraitCovar()
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/stds.T
return RV | python | def getEmpTraitCorrCoef(self):
"""
Returns the empirical trait correlation matrix
"""
cov = self.getEmpTraitCovar()
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/stds.T
return RV | [
"def",
"getEmpTraitCorrCoef",
"(",
"self",
")",
":",
"cov",
"=",
"self",
".",
"getEmpTraitCovar",
"(",
")",
"stds",
"=",
"SP",
".",
"sqrt",
"(",
"cov",
".",
"diagonal",
"(",
")",
")",
"[",
":",
",",
"SP",
".",
"newaxis",
"]",
"RV",
"=",
"cov",
"/... | Returns the empirical trait correlation matrix | [
"Returns",
"the",
"empirical",
"trait",
"correlation",
"matrix"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L757-L764 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.estimateHeritabilities | def estimateHeritabilities(self, K, verbose=False):
"""
estimate variance components and fixed effects
from a single trait model having only two terms
"""
# Fit single trait model
varg = SP.zeros(self.P)
varn = SP.zeros(self.P)
fixed = SP.zeros(... | python | def estimateHeritabilities(self, K, verbose=False):
"""
estimate variance components and fixed effects
from a single trait model having only two terms
"""
# Fit single trait model
varg = SP.zeros(self.P)
varn = SP.zeros(self.P)
fixed = SP.zeros(... | [
"def",
"estimateHeritabilities",
"(",
"self",
",",
"K",
",",
"verbose",
"=",
"False",
")",
":",
"# Fit single trait model",
"varg",
"=",
"SP",
".",
"zeros",
"(",
"self",
".",
"P",
")",
"varn",
"=",
"SP",
".",
"zeros",
"(",
"self",
".",
"P",
")",
"fix... | estimate variance components and fixed effects
from a single trait model having only two terms | [
"estimate",
"variance",
"components",
"and",
"fixed",
"effects",
"from",
"a",
"single",
"trait",
"model",
"having",
"only",
"two",
"terms"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L768-L802 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.setKstar | def setKstar(self,term_i,Ks):
"""
Set the kernel for predictions
Args:
term_i: index of the term we are interested in
Ks: (TODO: is this the covariance between train and test or the covariance between test points?)
"""
assert Ks.shape[0]==self... | python | def setKstar(self,term_i,Ks):
"""
Set the kernel for predictions
Args:
term_i: index of the term we are interested in
Ks: (TODO: is this the covariance between train and test or the covariance between test points?)
"""
assert Ks.shape[0]==self... | [
"def",
"setKstar",
"(",
"self",
",",
"term_i",
",",
"Ks",
")",
":",
"assert",
"Ks",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"N",
"#if Kss!=None:",
"#assert Kss.shape[0]==Ks.shape[1]",
"#assert Kss.shape[1]==Ks.shape[1]",
"self",
".",
"vd",
".",
"getTer... | Set the kernel for predictions
Args:
term_i: index of the term we are interested in
Ks: (TODO: is this the covariance between train and test or the covariance between test points?) | [
"Set",
"the",
"kernel",
"for",
"predictions"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L809-L823 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | VarianceDecomposition.predictMean | def predictMean(self):
"""
predict the conditional mean (BLUP)
Returns:
predictions (BLUP)
"""
assert self.noisPos!=None, 'No noise element'
assert self.init, 'GP not initialised'
KiY = self.gp.agetKEffInvYCache()
... | python | def predictMean(self):
"""
predict the conditional mean (BLUP)
Returns:
predictions (BLUP)
"""
assert self.noisPos!=None, 'No noise element'
assert self.init, 'GP not initialised'
KiY = self.gp.agetKEffInvYCache()
... | [
"def",
"predictMean",
"(",
"self",
")",
":",
"assert",
"self",
".",
"noisPos",
"!=",
"None",
",",
"'No noise element'",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"KiY",
"=",
"self",
".",
"gp",
".",
"agetKEffInvYCache",
"(",
")",
"if",
"se... | predict the conditional mean (BLUP)
Returns:
predictions (BLUP) | [
"predict",
"the",
"conditional",
"mean",
"(",
"BLUP",
")"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L827-L856 |
vroomfonde1/basicmodem | example.py | callback | def callback(newstate):
"""Callback from modem, process based on new state"""
print('callback: ', newstate)
if newstate == modem.STATE_RING:
if state == modem.STATE_IDLE:
att = {"cid_time": modem.get_cidtime,
"cid_number": modem.get_cidnumber,
"cid_n... | python | def callback(newstate):
"""Callback from modem, process based on new state"""
print('callback: ', newstate)
if newstate == modem.STATE_RING:
if state == modem.STATE_IDLE:
att = {"cid_time": modem.get_cidtime,
"cid_number": modem.get_cidnumber,
"cid_n... | [
"def",
"callback",
"(",
"newstate",
")",
":",
"print",
"(",
"'callback: '",
",",
"newstate",
")",
"if",
"newstate",
"==",
"modem",
".",
"STATE_RING",
":",
"if",
"state",
"==",
"modem",
".",
"STATE_IDLE",
":",
"att",
"=",
"{",
"\"cid_time\"",
":",
"modem"... | Callback from modem, process based on new state | [
"Callback",
"from",
"modem",
"process",
"based",
"on",
"new",
"state"
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/example.py#L8-L24 |
vroomfonde1/basicmodem | example.py | main | def main():
global modem
modem = bm(port='/dev/ttyACM0', incomingcallback=callback)
if modem.state == modem.STATE_FAILED:
print('Unable to initialize modem, exiting.')
return
"""Print modem information."""
resp = modem.sendcmd('ATI3')
for line in resp:
if line:
... | python | def main():
global modem
modem = bm(port='/dev/ttyACM0', incomingcallback=callback)
if modem.state == modem.STATE_FAILED:
print('Unable to initialize modem, exiting.')
return
"""Print modem information."""
resp = modem.sendcmd('ATI3')
for line in resp:
if line:
... | [
"def",
"main",
"(",
")",
":",
"global",
"modem",
"modem",
"=",
"bm",
"(",
"port",
"=",
"'/dev/ttyACM0'",
",",
"incomingcallback",
"=",
"callback",
")",
"if",
"modem",
".",
"state",
"==",
"modem",
".",
"STATE_FAILED",
":",
"print",
"(",
"'Unable to initiali... | Print modem information. | [
"Print",
"modem",
"information",
"."
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/example.py#L27-L46 |
rags/pynt-contrib | pyntcontrib/__init__.py | safe_cd | def safe_cd(path):
"""
Changes to a directory, yields, and changes back.
Additionally any error will also change the directory back.
Usage:
>>> with safe_cd('some/repo'):
... call('git status')
"""
starting_directory = os.getcwd()
try:
os.chdir(path)
yield
fi... | python | def safe_cd(path):
"""
Changes to a directory, yields, and changes back.
Additionally any error will also change the directory back.
Usage:
>>> with safe_cd('some/repo'):
... call('git status')
"""
starting_directory = os.getcwd()
try:
os.chdir(path)
yield
fi... | [
"def",
"safe_cd",
"(",
"path",
")",
":",
"starting_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"os",
".",
"chdir",
"(",
"path",
")",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"starting_directory",
")"
] | Changes to a directory, yields, and changes back.
Additionally any error will also change the directory back.
Usage:
>>> with safe_cd('some/repo'):
... call('git status') | [
"Changes",
"to",
"a",
"directory",
"yields",
"and",
"changes",
"back",
".",
"Additionally",
"any",
"error",
"will",
"also",
"change",
"the",
"directory",
"back",
"."
] | train | https://github.com/rags/pynt-contrib/blob/912315f2df9ea9b4b61abc923cad8807eed54cba/pyntcontrib/__init__.py#L11-L25 |
rags/pynt-contrib | pyntcontrib/__init__.py | execute | def execute(script, *args, **kwargs):
"""
Executes a command through the shell. Spaces should breakup the args. Usage: execute('grep', 'TODO', '*')
NOTE: Any kwargs will be converted to args in the destination command.
E.g. execute('grep', 'TODO', '*', **{'--before-context': 5}) will be $grep todo * --b... | python | def execute(script, *args, **kwargs):
"""
Executes a command through the shell. Spaces should breakup the args. Usage: execute('grep', 'TODO', '*')
NOTE: Any kwargs will be converted to args in the destination command.
E.g. execute('grep', 'TODO', '*', **{'--before-context': 5}) will be $grep todo * --b... | [
"def",
"execute",
"(",
"script",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"popen_args",
"=",
"[",
"script",
"]",
"+",
"list",
"(",
"args",
")",
"if",
"kwargs",
":",
"popen_args",
".",
"extend",
"(",
"_kwargs_to_execute_args",
"(",
"kwargs",... | Executes a command through the shell. Spaces should breakup the args. Usage: execute('grep', 'TODO', '*')
NOTE: Any kwargs will be converted to args in the destination command.
E.g. execute('grep', 'TODO', '*', **{'--before-context': 5}) will be $grep todo * --before-context=5 | [
"Executes",
"a",
"command",
"through",
"the",
"shell",
".",
"Spaces",
"should",
"breakup",
"the",
"args",
".",
"Usage",
":",
"execute",
"(",
"grep",
"TODO",
"*",
")",
"NOTE",
":",
"Any",
"kwargs",
"will",
"be",
"converted",
"to",
"args",
"in",
"the",
"... | train | https://github.com/rags/pynt-contrib/blob/912315f2df9ea9b4b61abc923cad8807eed54cba/pyntcontrib/__init__.py#L29-L47 |
bretth/woven | woven/management/commands/patch.py | Command.parse_host_args | def parse_host_args(self, *args):
"""
Splits out the patch subcommand and returns a comma separated list of host_strings
"""
self.subcommand = None
new_args = args
try:
sub = args[0]
if sub in ['project','templates','static','media','wsgi','webconf... | python | def parse_host_args(self, *args):
"""
Splits out the patch subcommand and returns a comma separated list of host_strings
"""
self.subcommand = None
new_args = args
try:
sub = args[0]
if sub in ['project','templates','static','media','wsgi','webconf... | [
"def",
"parse_host_args",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"subcommand",
"=",
"None",
"new_args",
"=",
"args",
"try",
":",
"sub",
"=",
"args",
"[",
"0",
"]",
"if",
"sub",
"in",
"[",
"'project'",
",",
"'templates'",
",",
"'static'... | Splits out the patch subcommand and returns a comma separated list of host_strings | [
"Splits",
"out",
"the",
"patch",
"subcommand",
"and",
"returns",
"a",
"comma",
"separated",
"list",
"of",
"host_strings"
] | train | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/management/commands/patch.py#L33-L47 |
Jaza/url-for-s3 | url_for_s3.py | url_for_s3 | def url_for_s3(endpoint, bucket_name, bucket_domain=None, scheme='',
url_style='host', cdn_domain=None, filename=None):
"""
Generates an S3 URL to the given endpoint, using the
given bucket config.
Example:
url_for_s3('static', bucket_name='my-cool-foobar-bucket',
sche... | python | def url_for_s3(endpoint, bucket_name, bucket_domain=None, scheme='',
url_style='host', cdn_domain=None, filename=None):
"""
Generates an S3 URL to the given endpoint, using the
given bucket config.
Example:
url_for_s3('static', bucket_name='my-cool-foobar-bucket',
sche... | [
"def",
"url_for_s3",
"(",
"endpoint",
",",
"bucket_name",
",",
"bucket_domain",
"=",
"None",
",",
"scheme",
"=",
"''",
",",
"url_style",
"=",
"'host'",
",",
"cdn_domain",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"bucket_name",
":... | Generates an S3 URL to the given endpoint, using the
given bucket config.
Example:
url_for_s3('static', bucket_name='my-cool-foobar-bucket',
scheme='https', filename='pics/logo.png')
Will return:
https://my-cool-foobar-bucket.s3.amazonaws.com/static/pics/logo.png
Note: this fun... | [
"Generates",
"an",
"S3",
"URL",
"to",
"the",
"given",
"endpoint",
"using",
"the",
"given",
"bucket",
"config",
"."
] | train | https://github.com/Jaza/url-for-s3/blob/20c93437b9a22637de88ffe5cd251dede4b59ef6/url_for_s3.py#L4-L61 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | _put_text | def _put_text(irods_path, text):
"""Put raw text into iRODS."""
with tempfile.NamedTemporaryFile() as fh:
fpath = fh.name
try:
# Make Python2 compatible.
text = unicode(text, "utf-8")
except (NameError, TypeError):
# NameError: We are running Python3 ... | python | def _put_text(irods_path, text):
"""Put raw text into iRODS."""
with tempfile.NamedTemporaryFile() as fh:
fpath = fh.name
try:
# Make Python2 compatible.
text = unicode(text, "utf-8")
except (NameError, TypeError):
# NameError: We are running Python3 ... | [
"def",
"_put_text",
"(",
"irods_path",
",",
"text",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"fh",
":",
"fpath",
"=",
"fh",
".",
"name",
"try",
":",
"# Make Python2 compatible.",
"text",
"=",
"unicode",
"(",
"text",
",",
"... | Put raw text into iRODS. | [
"Put",
"raw",
"text",
"into",
"iRODS",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L91-L113 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | _put_obj | def _put_obj(irods_path, obj):
"""Put python object into iRODS as JSON text."""
text = json.dumps(obj, indent=2)
_put_text(irods_path, text) | python | def _put_obj(irods_path, obj):
"""Put python object into iRODS as JSON text."""
text = json.dumps(obj, indent=2)
_put_text(irods_path, text) | [
"def",
"_put_obj",
"(",
"irods_path",
",",
"obj",
")",
":",
"text",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"2",
")",
"_put_text",
"(",
"irods_path",
",",
"text",
")"
] | Put python object into iRODS as JSON text. | [
"Put",
"python",
"object",
"into",
"iRODS",
"as",
"JSON",
"text",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L121-L124 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.list_dataset_uris | def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs in base_uri."""
parsed_uri = generous_parse_uri(base_uri)
irods_path = parsed_uri.path
uri_list = []
logger.info("irods_path: '{}'".format(irods_path))
for dir_path in _ls_abspaths(irods_... | python | def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs in base_uri."""
parsed_uri = generous_parse_uri(base_uri)
irods_path = parsed_uri.path
uri_list = []
logger.info("irods_path: '{}'".format(irods_path))
for dir_path in _ls_abspaths(irods_... | [
"def",
"list_dataset_uris",
"(",
"cls",
",",
"base_uri",
",",
"config_path",
")",
":",
"parsed_uri",
"=",
"generous_parse_uri",
"(",
"base_uri",
")",
"irods_path",
"=",
"parsed_uri",
".",
"path",
"uri_list",
"=",
"[",
"]",
"logger",
".",
"info",
"(",
"\"irod... | Return list containing URIs in base_uri. | [
"Return",
"list",
"containing",
"URIs",
"in",
"base_uri",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L355-L381 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.list_overlay_names | def list_overlay_names(self):
"""Return list of overlay names."""
overlay_names = []
for fname in _ls(self._overlays_abspath):
name, ext = os.path.splitext(fname)
overlay_names.append(name)
return overlay_names | python | def list_overlay_names(self):
"""Return list of overlay names."""
overlay_names = []
for fname in _ls(self._overlays_abspath):
name, ext = os.path.splitext(fname)
overlay_names.append(name)
return overlay_names | [
"def",
"list_overlay_names",
"(",
"self",
")",
":",
"overlay_names",
"=",
"[",
"]",
"for",
"fname",
"in",
"_ls",
"(",
"self",
".",
"_overlays_abspath",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"overlay_n... | Return list of overlay names. | [
"Return",
"list",
"of",
"overlay",
"names",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L423-L429 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.get_item_abspath | def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metad... | python | def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metad... | [
"def",
"get_item_abspath",
"(",
"self",
",",
"identifier",
")",
":",
"admin_metadata",
"=",
"self",
".",
"get_admin_metadata",
"(",
")",
"uuid",
"=",
"admin_metadata",
"[",
"\"uuid\"",
"]",
"# Create directory for the specific dataset.",
"dataset_cache_abspath",
"=",
... | Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed | [
"Return",
"absolute",
"path",
"at",
"which",
"item",
"content",
"can",
"be",
"accessed",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L431-L457 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker._create_structure | def _create_structure(self):
"""Create necessary structure to hold a dataset."""
# Ensure that the specified path does not exist and create it.
if _path_exists(self._abspath):
raise(StorageBrokerOSError(
"Path already exists: {}".format(self._abspath)
))
... | python | def _create_structure(self):
"""Create necessary structure to hold a dataset."""
# Ensure that the specified path does not exist and create it.
if _path_exists(self._abspath):
raise(StorageBrokerOSError(
"Path already exists: {}".format(self._abspath)
))
... | [
"def",
"_create_structure",
"(",
"self",
")",
":",
"# Ensure that the specified path does not exist and create it.",
"if",
"_path_exists",
"(",
"self",
".",
"_abspath",
")",
":",
"raise",
"(",
"StorageBrokerOSError",
"(",
"\"Path already exists: {}\"",
".",
"format",
"(",... | Create necessary structure to hold a dataset. | [
"Create",
"necessary",
"structure",
"to",
"hold",
"a",
"dataset",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L459-L483 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.put_item | def put_item(self, fpath, relpath):
"""Put item with content from fpath at relpath in dataset.
Missing directories in relpath are created on the fly.
:param fpath: path to the item on local disk
:param relpath: relative path name given to the item in the dataset as
... | python | def put_item(self, fpath, relpath):
"""Put item with content from fpath at relpath in dataset.
Missing directories in relpath are created on the fly.
:param fpath: path to the item on local disk
:param relpath: relative path name given to the item in the dataset as
... | [
"def",
"put_item",
"(",
"self",
",",
"fpath",
",",
"relpath",
")",
":",
"# Put the file into iRODS.",
"fname",
"=",
"generate_identifier",
"(",
"relpath",
")",
"dest_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_abspath",
",",
"fname",... | Put item with content from fpath at relpath in dataset.
Missing directories in relpath are created on the fly.
:param fpath: path to the item on local disk
:param relpath: relative path name given to the item in the dataset as
a handle | [
"Put",
"item",
"with",
"content",
"from",
"fpath",
"at",
"relpath",
"in",
"dataset",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L485-L502 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.iter_item_handles | def iter_item_handles(self):
"""Return iterator over item handles."""
for abspath in self._ls_abspaths_with_cache(self._data_abspath):
try:
relpath = self._get_metadata_with_cache(abspath, "handle")
yield relpath
except IrodsNoMetaDataSetError:
... | python | def iter_item_handles(self):
"""Return iterator over item handles."""
for abspath in self._ls_abspaths_with_cache(self._data_abspath):
try:
relpath = self._get_metadata_with_cache(abspath, "handle")
yield relpath
except IrodsNoMetaDataSetError:
... | [
"def",
"iter_item_handles",
"(",
"self",
")",
":",
"for",
"abspath",
"in",
"self",
".",
"_ls_abspaths_with_cache",
"(",
"self",
".",
"_data_abspath",
")",
":",
"try",
":",
"relpath",
"=",
"self",
".",
"_get_metadata_with_cache",
"(",
"abspath",
",",
"\"handle\... | Return iterator over item handles. | [
"Return",
"iterator",
"over",
"item",
"handles",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L504-L511 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.add_item_metadata | def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
... | python | def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
... | [
"def",
"add_item_metadata",
"(",
"self",
",",
"handle",
",",
"key",
",",
"value",
")",
":",
"_mkdir_if_missing",
"(",
"self",
".",
"_metadata_fragments_abspath",
")",
"prefix",
"=",
"self",
".",
"_handle_to_fragment_absprefixpath",
"(",
"handle",
")",
"fpath",
"... | Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value | [
"Store",
"the",
"given",
"key",
":",
"value",
"pair",
"for",
"the",
"item",
"associated",
"with",
"handle",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L533-L546 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.get_item_metadata | def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
... | python | def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
... | [
"def",
"get_item_metadata",
"(",
"self",
",",
"handle",
")",
":",
"if",
"not",
"self",
".",
"_metadata_dir_exists",
"(",
")",
":",
"return",
"{",
"}",
"prefix",
"=",
"self",
".",
"_handle_to_fragment_absprefixpath",
"(",
"handle",
")",
"files",
"=",
"[",
"... | Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata | [
"Return",
"dictionary",
"containing",
"all",
"metadata",
"associated",
"with",
"handle",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L548-L573 |
jic-dtool/dtool-irods | dtool_irods/storagebroker.py | IrodsStorageBroker.post_freeze_hook | def post_freeze_hook(self):
"""Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions.
This method is called at the end of the
:meth:`dtoolcore.ProtoDataSet.freeze` method.
"""
self._use_cache = False
self._ls_abspath_cache = {}
self._metadata_cache = {}
... | python | def post_freeze_hook(self):
"""Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions.
This method is called at the end of the
:meth:`dtoolcore.ProtoDataSet.freeze` method.
"""
self._use_cache = False
self._ls_abspath_cache = {}
self._metadata_cache = {}
... | [
"def",
"post_freeze_hook",
"(",
"self",
")",
":",
"self",
".",
"_use_cache",
"=",
"False",
"self",
".",
"_ls_abspath_cache",
"=",
"{",
"}",
"self",
".",
"_metadata_cache",
"=",
"{",
"}",
"self",
".",
"_size_and_timestamp_cache",
"=",
"{",
"}",
"_rm_if_exists... | Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions.
This method is called at the end of the
:meth:`dtoolcore.ProtoDataSet.freeze` method. | [
"Post",
":",
"meth",
":",
"dtoolcore",
".",
"ProtoDataSet",
".",
"freeze",
"cleanup",
"actions",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/storagebroker.py#L587-L597 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.