nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/data.py
python
Makefile.finishparsing
(self)
Various activities, such as "eval", are not allowed after parsing is finished. In addition, various warnings and errors can only be issued after the parsing data model is complete. All dependency resolution and rule execution requires that parsing be finished.
Various activities, such as "eval", are not allowed after parsing is finished. In addition, various warnings and errors can only be issued after the parsing data model is complete. All dependency resolution and rule execution requires that parsing be finished.
[ "Various", "activities", "such", "as", "eval", "are", "not", "allowed", "after", "parsing", "is", "finished", ".", "In", "addition", "various", "warnings", "and", "errors", "can", "only", "be", "issued", "after", "the", "parsing", "data", "model", "is", "complete", ".", "All", "dependency", "resolution", "and", "rule", "execution", "requires", "that", "parsing", "be", "finished", "." ]
def finishparsing(self): """ Various activities, such as "eval", are not allowed after parsing is finished. In addition, various warnings and errors can only be issued after the parsing data model is complete. All dependency resolution and rule execution requires that parsing be finished. """ self.parsingfinished = True flavor, source, value = self.variables.get('GPATH') if value is not None and value.resolvestr(self, self.variables, ['GPATH']).strip() != '': raise DataError('GPATH was set: pymake does not support GPATH semantics') flavor, source, value = self.variables.get('VPATH') if value is None: self._vpath = [] else: self._vpath = filter(lambda e: e != '', re.split('[%s\s]+' % os.pathsep, value.resolvestr(self, self.variables, ['VPATH']))) targets = list(self._targets.itervalues()) for t in targets: t.explicit = True for r in t.rules: for p in r.prerequisites: self.gettarget(p).explicit = True np = self.gettarget('.NOTPARALLEL') if len(np.rules): self.context = process.getcontext(1) flavor, source, value = self.variables.get('.DEFAULT_GOAL') if value is not None: self.defaulttarget = value.resolvestr(self, self.variables, ['.DEFAULT_GOAL']).strip() self.error = False
[ "def", "finishparsing", "(", "self", ")", ":", "self", ".", "parsingfinished", "=", "True", "flavor", ",", "source", ",", "value", "=", "self", ".", "variables", ".", "get", "(", "'GPATH'", ")", "if", "value", "is", "not", "None", "and", "value", ".", "resolvestr", "(", "self", ",", "self", ".", "variables", ",", "[", "'GPATH'", "]", ")", ".", "strip", "(", ")", "!=", "''", ":", "raise", "DataError", "(", "'GPATH was set: pymake does not support GPATH semantics'", ")", "flavor", ",", "source", ",", "value", "=", "self", ".", "variables", ".", "get", "(", "'VPATH'", ")", "if", "value", "is", "None", ":", "self", ".", "_vpath", "=", "[", "]", "else", ":", "self", ".", "_vpath", "=", "filter", "(", "lambda", "e", ":", "e", "!=", "''", ",", "re", ".", "split", "(", "'[%s\\s]+'", "%", "os", ".", "pathsep", ",", "value", ".", "resolvestr", "(", "self", ",", "self", ".", "variables", ",", "[", "'VPATH'", "]", ")", ")", ")", "targets", "=", "list", "(", "self", ".", "_targets", ".", "itervalues", "(", ")", ")", "for", "t", "in", "targets", ":", "t", ".", "explicit", "=", "True", "for", "r", "in", "t", ".", "rules", ":", "for", "p", "in", "r", ".", "prerequisites", ":", "self", ".", "gettarget", "(", "p", ")", ".", "explicit", "=", "True", "np", "=", "self", ".", "gettarget", "(", "'.NOTPARALLEL'", ")", "if", "len", "(", "np", ".", "rules", ")", ":", "self", ".", "context", "=", "process", ".", "getcontext", "(", "1", ")", "flavor", ",", "source", ",", "value", "=", "self", ".", "variables", ".", "get", "(", "'.DEFAULT_GOAL'", ")", "if", "value", "is", "not", "None", ":", "self", ".", "defaulttarget", "=", "value", ".", "resolvestr", "(", "self", ",", "self", ".", "variables", ",", "[", "'.DEFAULT_GOAL'", "]", ")", ".", "strip", "(", ")", "self", ".", "error", "=", "False" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/data.py#L1736-L1772
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
_IncludeState.IsInAlphabeticalOrder
(self, clean_lines, linenum, header_path)
return True
Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order.
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and not Match(r'^\s*$', clean_lines.elided[linenum - 1])): return False return True
[ "def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "# If previous section is different from current section, _last_header will", "# be reset to empty string, so it's always less than current header.", "#", "# If previous line was a blank line, assume that the headers are", "# intentionally sorted the way they are.", "if", "(", "self", ".", "_last_header", ">", "header_path", "and", "not", "Match", "(", "r'^\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", ")", ":", "return", "False", "return", "True" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L677-L696
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/sandbox.py
python
SandboxedEnvironment.call_binop
(self, context, operator, left, right)
return self.binop_table[operator](left, right)
For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6
For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.
[ "For", "intercepted", "binary", "operator", "calls", "(", ":", "meth", ":", "intercepted_binops", ")", "this", "function", "is", "executed", "instead", "of", "the", "builtin", "operator", ".", "This", "can", "be", "used", "to", "fine", "tune", "the", "behavior", "of", "certain", "operators", "." ]
def call_binop(self, context, operator, left, right): """For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 """ return self.binop_table[operator](left, right)
[ "def", "call_binop", "(", "self", ",", "context", ",", "operator", ",", "left", ",", "right", ")", ":", "return", "self", ".", "binop_table", "[", "operator", "]", "(", "left", ",", "right", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/sandbox.py#L341-L348
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/futures.py
python
TransferCoordinator.status
(self)
return self._status
The status of the TransferFuture The currently supported states are: * not-started - Has yet to start. If in this state, a transfer can be canceled immediately and nothing will happen. * queued - SubmissionTask is about to submit tasks * running - Is inprogress. In-progress as of now means that the SubmissionTask that runs the transfer is being executed. So there is no guarantee any transfer requests had been made to S3 if this state is reached. * cancelled - Was cancelled * failed - An exception other than CancelledError was thrown * success - No exceptions were thrown and is done.
The status of the TransferFuture
[ "The", "status", "of", "the", "TransferFuture" ]
def status(self): """The status of the TransferFuture The currently supported states are: * not-started - Has yet to start. If in this state, a transfer can be canceled immediately and nothing will happen. * queued - SubmissionTask is about to submit tasks * running - Is inprogress. In-progress as of now means that the SubmissionTask that runs the transfer is being executed. So there is no guarantee any transfer requests had been made to S3 if this state is reached. * cancelled - Was cancelled * failed - An exception other than CancelledError was thrown * success - No exceptions were thrown and is done. """ return self._status
[ "def", "status", "(", "self", ")", ":", "return", "self", ".", "_status" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/futures.py#L204-L219
CGRU/cgru
1881a4128530e3d31ac6c25314c18314fc50c2c7
afanasy/python/af.py
python
Block.setFiles
(self, files, TransferToServer=True)
Missing DocString :param files: :param TransferToServer: :return:
Missing DocString
[ "Missing", "DocString" ]
def setFiles(self, files, TransferToServer=True): """Missing DocString :param files: :param TransferToServer: :return: """ if "files" not in self.data: self.data["files"] = [] for afile in files: if TransferToServer: afile = Pathmap.toServer(afile) self.data["files"].append(afile)
[ "def", "setFiles", "(", "self", ",", "files", ",", "TransferToServer", "=", "True", ")", ":", "if", "\"files\"", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "\"files\"", "]", "=", "[", "]", "for", "afile", "in", "files", ":", "if", "TransferToServer", ":", "afile", "=", "Pathmap", ".", "toServer", "(", "afile", ")", "self", ".", "data", "[", "\"files\"", "]", ".", "append", "(", "afile", ")" ]
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L277-L290
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Text.tag_names
(self, index=None)
return self.tk.splitlist( self.tk.call(self._w, 'tag', 'names', index))
Return a list of all tag names.
Return a list of all tag names.
[ "Return", "a", "list", "of", "all", "tag", "names", "." ]
def tag_names(self, index=None): """Return a list of all tag names.""" return self.tk.splitlist( self.tk.call(self._w, 'tag', 'names', index))
[ "def", "tag_names", "(", "self", ",", "index", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'tag'", ",", "'names'", ",", "index", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3379-L3382
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/call.py
python
ICall.Answer
(self)
Answers the call.
Answers the call.
[ "Answers", "the", "call", "." ]
def Answer(self): '''Answers the call. ''' self._Property('STATUS', 'INPROGRESS')
[ "def", "Answer", "(", "self", ")", ":", "self", ".", "_Property", "(", "'STATUS'", ",", "'INPROGRESS'", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/call.py#L25-L28
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucketlistresultset.py
python
bucket_lister
(bucket, prefix='', delimiter='', marker='', headers=None, encoding_type=None)
A generator function for listing keys in a bucket.
A generator function for listing keys in a bucket.
[ "A", "generator", "function", "for", "listing", "keys", "in", "a", "bucket", "." ]
def bucket_lister(bucket, prefix='', delimiter='', marker='', headers=None, encoding_type=None): """ A generator function for listing keys in a bucket. """ more_results = True k = None while more_results: rs = bucket.get_all_keys(prefix=prefix, marker=marker, delimiter=delimiter, headers=headers, encoding_type=encoding_type) for k in rs: yield k if k: marker = rs.next_marker or k.name if marker and encoding_type == "url": if isinstance(marker, six.text_type): marker = marker.encode('utf-8') marker = urllib.parse.unquote(marker) more_results= rs.is_truncated
[ "def", "bucket_lister", "(", "bucket", ",", "prefix", "=", "''", ",", "delimiter", "=", "''", ",", "marker", "=", "''", ",", "headers", "=", "None", ",", "encoding_type", "=", "None", ")", ":", "more_results", "=", "True", "k", "=", "None", "while", "more_results", ":", "rs", "=", "bucket", ".", "get_all_keys", "(", "prefix", "=", "prefix", ",", "marker", "=", "marker", ",", "delimiter", "=", "delimiter", ",", "headers", "=", "headers", ",", "encoding_type", "=", "encoding_type", ")", "for", "k", "in", "rs", ":", "yield", "k", "if", "k", ":", "marker", "=", "rs", ".", "next_marker", "or", "k", ".", "name", "if", "marker", "and", "encoding_type", "==", "\"url\"", ":", "if", "isinstance", "(", "marker", ",", "six", ".", "text_type", ")", ":", "marker", "=", "marker", ".", "encode", "(", "'utf-8'", ")", "marker", "=", "urllib", ".", "parse", ".", "unquote", "(", "marker", ")", "more_results", "=", "rs", ".", "is_truncated" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucketlistresultset.py#L24-L43
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/virtualpop.py
python
BikeStrategy.plan
(self, ids_person, logger=None, **kwargs)
return True
Generates a plan for these person according to this strategie. Overriden by specific strategy.
Generates a plan for these person according to this strategie. Overriden by specific strategy.
[ "Generates", "a", "plan", "for", "these", "person", "according", "to", "this", "strategie", ".", "Overriden", "by", "specific", "strategy", "." ]
def plan(self, ids_person, logger=None, **kwargs): """ Generates a plan for these person according to this strategie. Overriden by specific strategy. """ #make_plans_private(self, ids_person = None, mode = 'passenger') # routing necessary? virtualpop = self.get_virtualpop() plans = virtualpop.get_plans() # self._plans walkstages = plans.get_stagetable('walks') ridestages = plans.get_stagetable('bikerides') activitystages = plans.get_stagetable('activities') activities = virtualpop.get_activities() activitytypes = virtualpop.get_demand().activitytypes landuse = virtualpop.get_landuse() facilities = landuse.facilities #parking = landuse.parking scenario = virtualpop.get_scenario() edges = scenario.net.edges lanes = scenario.net.lanes modes = scenario.net.modes #times_est_plan = plans.times_est # here we can determine edge weights for different modes plans.prepare_stagetables(['walks', 'bikerides', 'activities']) # get initial travel times for persons. # initial travel times depend on the initial activity # landuse.parking.clear_booking() ids_person_act, ids_act_from, ids_act_to\ = virtualpop.get_activities_from_pattern(0, ids_person=ids_person) if len(ids_person_act) == 0: print 'WARNING in BikeStrategy.plan: no eligible persons found.' return False # ok # temporary maps from ids_person to other parameters nm = np.max(ids_person_act)+1 map_ids_plan = np.zeros(nm, dtype=np.int32) map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy()) map_times = np.zeros(nm, dtype=np.int32) map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit') # set start time to plans (important!) plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act] map_ids_fac_from = np.zeros(nm, dtype=np.int32) map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from] #map_ids_parking_from = np.zeros(nm, dtype = np.int32) # ids_parking_from, inds_vehparking = parking.get_closest_parkings( virtualpop.ids_iauto[ids_person_act], # facilities.centroids[activities.ids_facility[ids_act_from]]) # if len(ids_parking_from)==0: # return False # err #map_ids_parking_from[ids_person_act] = ids_parking_from n_plans = len(ids_person_act) print 'BikeStrategy.plan n_plans=', n_plans # print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape # set initial activity # this is because the following steps start with travel # and set the next activity #names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]] # for id_plan ind_act = 0 # make initial activity stage ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]] poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]] poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from) # this is the time when first activity starts # first activity is normally not simulated names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]] durations_act_from = activities.get_durations(ids_act_from) times_from = map_times[ids_person_act]-durations_act_from #times_from = activities.get_times_end(ids_act_from, pdf = 'unit') # do initial stage # could be common to all strategies for id_plan,\ time,\ id_act_from,\ name_acttype_from,\ duration_act_from,\ id_edge_from,\ pos_edge_from \ in zip(map_ids_plan[ids_person_act], times_from, ids_act_from, names_acttype_from, durations_act_from, ids_edge_from, poss_edge_from): id_stage_act, time = activitystages.append_stage( id_plan, time, ids_activity=id_act_from, names_activitytype=name_acttype_from, durations=duration_act_from, ids_lane=edges.ids_lanes[id_edge_from][0], positions=pos_edge_from, ) # main loop while there are persons performing # an activity at index ind_act while len(ids_person_act) > 0: ids_plan = map_ids_plan[ids_person_act] ids_veh = virtualpop.ids_ibike[ids_person_act] dists_walk_max = virtualpop.dists_walk_max[ids_person_act] times_from = map_times[ids_person_act] names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]] durations_act_to = activities.get_durations(ids_act_to) ids_fac_from = map_ids_fac_from[ids_person_act] ids_fac_to = activities.ids_facility[ids_act_to] # origin edge and position ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from] poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from] poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from) centroids_from = facilities.centroids[ids_fac_from] # this method will find and occupy parking space #ids_parking_from = map_ids_parking_from[ids_person_act] # print ' ids_veh.shape',ids_veh.shape # print ' centroids_to.shape',centroids_to.shape #ids_parking_to, inds_vehparking = parking.get_closest_parkings(ids_veh, centroids_to) #ids_lane_parking_from = parking.ids_lane[ids_parking_from] #ids_edge_parking_from = lanes.ids_edge[ids_lane_parking_from] #poss_edge_parking_from = parking.positions[ids_parking_from] # print ' ids_parking_to.shape',ids_parking_to.shape # print ' np.max(parking.get_ids()), np.max(ids_parking_to)',np.max(parking.get_ids()), np.max(ids_parking_to) #ids_lane_parking_to = parking.ids_lane[ids_parking_to] #ids_edge_parking_to = lanes.ids_edge[ids_lane_parking_to] #poss_edge_parking_to = parking.positions[ids_parking_to] # destination edge and position ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to] poss_edge_to1 = facilities.positions_roadedge_closest[ids_fac_to] poss_edge_to = self.clip_positions(poss_edge_to1, ids_edge_to) centroids_to = facilities.centroids[ids_fac_to] # debug poscorrection..OK # for id_edge, id_edge_sumo, length, pos_to1, pos in zip(ids_edge_to, edges.ids_sumo[ids_edge_to],edges.lengths[ids_edge_to],poss_edge_to1, poss_edge_to): # print ' ',id_edge, 'IDe%s'%id_edge_sumo, 'L=%.2fm'%length, '%.2fm'%pos_to1, '%.2fm'%pos dists_from_to = np.sqrt(np.sum((centroids_to - centroids_from)**2, 1)) i = 0.0 n_pers = len(ids_person_act) for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, dist_from_to, dist_walk_max\ in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, dists_from_to, dists_walk_max): if logger: logger.progress(i/n_pers*100) i += 1.0 print 79*'*' print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to] time = self.plan_bikeride(id_plan, time_from, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, dist_from_to, dist_walk_max, walkstages, ridestages) ################ # store time estimation for this plan # note that these are the travel times, no activity time plans.times_est[id_plan] += time-time_from # define current end time without last activity duration plans.times_end[id_plan] = time # finally add activity and respective duration id_stage_act, time = activitystages.append_stage( id_plan, time, ids_activity=id_act_to, names_activitytype=name_acttype_to, durations=duration_act_to, ids_lane=edges.ids_lanes[id_edge_to][0], positions=pos_edge_to, ) map_times[id_person] = time # return time ## # select persons and activities for next setp ind_act += 1 ids_person_act, ids_act_from, ids_act_to\ = virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act) # update timing with (random) activity duration!! return True
[ "def", "plan", "(", "self", ",", "ids_person", ",", "logger", "=", "None", ",", "*", "*", "kwargs", ")", ":", "#make_plans_private(self, ids_person = None, mode = 'passenger')", "# routing necessary?", "virtualpop", "=", "self", ".", "get_virtualpop", "(", ")", "plans", "=", "virtualpop", ".", "get_plans", "(", ")", "# self._plans", "walkstages", "=", "plans", ".", "get_stagetable", "(", "'walks'", ")", "ridestages", "=", "plans", ".", "get_stagetable", "(", "'bikerides'", ")", "activitystages", "=", "plans", ".", "get_stagetable", "(", "'activities'", ")", "activities", "=", "virtualpop", ".", "get_activities", "(", ")", "activitytypes", "=", "virtualpop", ".", "get_demand", "(", ")", ".", "activitytypes", "landuse", "=", "virtualpop", ".", "get_landuse", "(", ")", "facilities", "=", "landuse", ".", "facilities", "#parking = landuse.parking", "scenario", "=", "virtualpop", ".", "get_scenario", "(", ")", "edges", "=", "scenario", ".", "net", ".", "edges", "lanes", "=", "scenario", ".", "net", ".", "lanes", "modes", "=", "scenario", ".", "net", ".", "modes", "#times_est_plan = plans.times_est", "# here we can determine edge weights for different modes", "plans", ".", "prepare_stagetables", "(", "[", "'walks'", ",", "'bikerides'", ",", "'activities'", "]", ")", "# get initial travel times for persons.", "# initial travel times depend on the initial activity", "# landuse.parking.clear_booking()", "ids_person_act", ",", "ids_act_from", ",", "ids_act_to", "=", "virtualpop", ".", "get_activities_from_pattern", "(", "0", ",", "ids_person", "=", "ids_person", ")", "if", "len", "(", "ids_person_act", ")", "==", "0", ":", "print", "'WARNING in BikeStrategy.plan: no eligible persons found.'", "return", "False", "# ok", "# temporary maps from ids_person to other parameters", "nm", "=", "np", ".", "max", "(", "ids_person_act", ")", "+", "1", "map_ids_plan", "=", "np", ".", "zeros", "(", "nm", ",", "dtype", "=", "np", ".", "int32", ")", "map_ids_plan", "[", "ids_person_act", "]", "=", "virtualpop", ".", "add_plans", "(", "ids_person_act", ",", "id_strategy", "=", "self", ".", "get_id_strategy", "(", ")", ")", "map_times", "=", "np", ".", "zeros", "(", "nm", ",", "dtype", "=", "np", ".", "int32", ")", "map_times", "[", "ids_person_act", "]", "=", "activities", ".", "get_times_end", "(", "ids_act_from", ",", "pdf", "=", "'unit'", ")", "# set start time to plans (important!)", "plans", ".", "times_begin", "[", "map_ids_plan", "[", "ids_person_act", "]", "]", "=", "map_times", "[", "ids_person_act", "]", "map_ids_fac_from", "=", "np", ".", "zeros", "(", "nm", ",", "dtype", "=", "np", ".", "int32", ")", "map_ids_fac_from", "[", "ids_person_act", "]", "=", "activities", ".", "ids_facility", "[", "ids_act_from", "]", "#map_ids_parking_from = np.zeros(nm, dtype = np.int32)", "# ids_parking_from, inds_vehparking = parking.get_closest_parkings( virtualpop.ids_iauto[ids_person_act],", "# facilities.centroids[activities.ids_facility[ids_act_from]])", "# if len(ids_parking_from)==0:", "# return False", "# err", "#map_ids_parking_from[ids_person_act] = ids_parking_from", "n_plans", "=", "len", "(", "ids_person_act", ")", "print", "'BikeStrategy.plan n_plans='", ",", "n_plans", "# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape", "# set initial activity", "# this is because the following steps start with travel", "# and set the next activity", "#names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]", "# for id_plan", "ind_act", "=", "0", "# make initial activity stage", "ids_edge_from", "=", "facilities", ".", "ids_roadedge_closest", "[", "map_ids_fac_from", "[", "ids_person_act", "]", "]", "poss_edge_from", "=", "facilities", ".", "positions_roadedge_closest", "[", "map_ids_fac_from", "[", "ids_person_act", "]", "]", "poss_edge_from", "=", "self", ".", "clip_positions", "(", "poss_edge_from", ",", "ids_edge_from", ")", "# this is the time when first activity starts", "# first activity is normally not simulated", "names_acttype_from", "=", "activitytypes", ".", "names", "[", "activities", ".", "ids_activitytype", "[", "ids_act_from", "]", "]", "durations_act_from", "=", "activities", ".", "get_durations", "(", "ids_act_from", ")", "times_from", "=", "map_times", "[", "ids_person_act", "]", "-", "durations_act_from", "#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')", "# do initial stage", "# could be common to all strategies", "for", "id_plan", ",", "time", ",", "id_act_from", ",", "name_acttype_from", ",", "duration_act_from", ",", "id_edge_from", ",", "pos_edge_from", "in", "zip", "(", "map_ids_plan", "[", "ids_person_act", "]", ",", "times_from", ",", "ids_act_from", ",", "names_acttype_from", ",", "durations_act_from", ",", "ids_edge_from", ",", "poss_edge_from", ")", ":", "id_stage_act", ",", "time", "=", "activitystages", ".", "append_stage", "(", "id_plan", ",", "time", ",", "ids_activity", "=", "id_act_from", ",", "names_activitytype", "=", "name_acttype_from", ",", "durations", "=", "duration_act_from", ",", "ids_lane", "=", "edges", ".", "ids_lanes", "[", "id_edge_from", "]", "[", "0", "]", ",", "positions", "=", "pos_edge_from", ",", ")", "# main loop while there are persons performing", "# an activity at index ind_act", "while", "len", "(", "ids_person_act", ")", ">", "0", ":", "ids_plan", "=", "map_ids_plan", "[", "ids_person_act", "]", "ids_veh", "=", "virtualpop", ".", "ids_ibike", "[", "ids_person_act", "]", "dists_walk_max", "=", "virtualpop", ".", "dists_walk_max", "[", "ids_person_act", "]", "times_from", "=", "map_times", "[", "ids_person_act", "]", "names_acttype_to", "=", "activitytypes", ".", "names", "[", "activities", ".", "ids_activitytype", "[", "ids_act_to", "]", "]", "durations_act_to", "=", "activities", ".", "get_durations", "(", "ids_act_to", ")", "ids_fac_from", "=", "map_ids_fac_from", "[", "ids_person_act", "]", "ids_fac_to", "=", "activities", ".", "ids_facility", "[", "ids_act_to", "]", "# origin edge and position", "ids_edge_from", "=", "facilities", ".", "ids_roadedge_closest", "[", "ids_fac_from", "]", "poss_edge_from", "=", "facilities", ".", "positions_roadedge_closest", "[", "ids_fac_from", "]", "poss_edge_from", "=", "self", ".", "clip_positions", "(", "poss_edge_from", ",", "ids_edge_from", ")", "centroids_from", "=", "facilities", ".", "centroids", "[", "ids_fac_from", "]", "# this method will find and occupy parking space", "#ids_parking_from = map_ids_parking_from[ids_person_act]", "# print ' ids_veh.shape',ids_veh.shape", "# print ' centroids_to.shape',centroids_to.shape", "#ids_parking_to, inds_vehparking = parking.get_closest_parkings(ids_veh, centroids_to)", "#ids_lane_parking_from = parking.ids_lane[ids_parking_from]", "#ids_edge_parking_from = lanes.ids_edge[ids_lane_parking_from]", "#poss_edge_parking_from = parking.positions[ids_parking_from]", "# print ' ids_parking_to.shape',ids_parking_to.shape", "# print ' np.max(parking.get_ids()), np.max(ids_parking_to)',np.max(parking.get_ids()), np.max(ids_parking_to)", "#ids_lane_parking_to = parking.ids_lane[ids_parking_to]", "#ids_edge_parking_to = lanes.ids_edge[ids_lane_parking_to]", "#poss_edge_parking_to = parking.positions[ids_parking_to]", "# destination edge and position", "ids_edge_to", "=", "facilities", ".", "ids_roadedge_closest", "[", "ids_fac_to", "]", "poss_edge_to1", "=", "facilities", ".", "positions_roadedge_closest", "[", "ids_fac_to", "]", "poss_edge_to", "=", "self", ".", "clip_positions", "(", "poss_edge_to1", ",", "ids_edge_to", ")", "centroids_to", "=", "facilities", ".", "centroids", "[", "ids_fac_to", "]", "# debug poscorrection..OK", "# for id_edge, id_edge_sumo, length, pos_to1, pos in zip(ids_edge_to, edges.ids_sumo[ids_edge_to],edges.lengths[ids_edge_to],poss_edge_to1, poss_edge_to):", "# print ' ',id_edge, 'IDe%s'%id_edge_sumo, 'L=%.2fm'%length, '%.2fm'%pos_to1, '%.2fm'%pos", "dists_from_to", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "centroids_to", "-", "centroids_from", ")", "**", "2", ",", "1", ")", ")", "i", "=", "0.0", "n_pers", "=", "len", "(", "ids_person_act", ")", "for", "id_person", ",", "id_plan", ",", "time_from", ",", "id_act_from", ",", "id_act_to", ",", "name_acttype_to", ",", "duration_act_to", ",", "id_veh", ",", "id_edge_from", ",", "pos_edge_from", ",", "id_edge_to", ",", "pos_edge_to", ",", "dist_from_to", ",", "dist_walk_max", "in", "zip", "(", "ids_person_act", ",", "ids_plan", ",", "times_from", ",", "ids_act_from", ",", "ids_act_to", ",", "names_acttype_to", ",", "durations_act_to", ",", "ids_veh", ",", "ids_edge_from", ",", "poss_edge_from", ",", "ids_edge_to", ",", "poss_edge_to", ",", "dists_from_to", ",", "dists_walk_max", ")", ":", "if", "logger", ":", "logger", ".", "progress", "(", "i", "/", "n_pers", "*", "100", ")", "i", "+=", "1.0", "print", "79", "*", "'*'", "print", "' plan id_plan'", ",", "id_plan", ",", "'time_from'", ",", "time_from", ",", "'from'", ",", "id_edge_from", ",", "pos_edge_from", ",", "'to'", ",", "id_edge_to", ",", "pos_edge_to", "print", "' id_edge_from'", ",", "edges", ".", "ids_sumo", "[", "id_edge_from", "]", ",", "'id_edge_to'", ",", "edges", ".", "ids_sumo", "[", "id_edge_to", "]", "time", "=", "self", ".", "plan_bikeride", "(", "id_plan", ",", "time_from", ",", "id_veh", ",", "id_edge_from", ",", "pos_edge_from", ",", "id_edge_to", ",", "pos_edge_to", ",", "dist_from_to", ",", "dist_walk_max", ",", "walkstages", ",", "ridestages", ")", "################", "# store time estimation for this plan", "# note that these are the travel times, no activity time", "plans", ".", "times_est", "[", "id_plan", "]", "+=", "time", "-", "time_from", "# define current end time without last activity duration", "plans", ".", "times_end", "[", "id_plan", "]", "=", "time", "# finally add activity and respective duration", "id_stage_act", ",", "time", "=", "activitystages", ".", "append_stage", "(", "id_plan", ",", "time", ",", "ids_activity", "=", "id_act_to", ",", "names_activitytype", "=", "name_acttype_to", ",", "durations", "=", "duration_act_to", ",", "ids_lane", "=", "edges", ".", "ids_lanes", "[", "id_edge_to", "]", "[", "0", "]", ",", "positions", "=", "pos_edge_to", ",", ")", "map_times", "[", "id_person", "]", "=", "time", "# return time", "##", "# select persons and activities for next setp", "ind_act", "+=", "1", "ids_person_act", ",", "ids_act_from", ",", "ids_act_to", "=", "virtualpop", ".", "get_activities_from_pattern", "(", "ind_act", ",", "ids_person", "=", "ids_person_act", ")", "# update timing with (random) activity duration!!", "return", "True" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/virtualpop.py#L2140-L2356
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/servermanager.py
python
ArrayInformation.GetRange
(self, component=0)
return (range[0], range[1])
Given a component, returns its value range as a tuple of 2 values.
Given a component, returns its value range as a tuple of 2 values.
[ "Given", "a", "component", "returns", "its", "value", "range", "as", "a", "tuple", "of", "2", "values", "." ]
def GetRange(self, component=0): """Given a component, returns its value range as a tuple of 2 values.""" array = self.FieldData.GetFieldData().GetArrayInformation(self.Name) range = array.GetComponentRange(component) return (range[0], range[1])
[ "def", "GetRange", "(", "self", ",", "component", "=", "0", ")", ":", "array", "=", "self", ".", "FieldData", ".", "GetFieldData", "(", ")", ".", "GetArrayInformation", "(", "self", ".", "Name", ")", "range", "=", "array", ".", "GetComponentRange", "(", "component", ")", "return", "(", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1565-L1569
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py
python
KeysPage.var_changed_keybinding
(self, *params)
Store change to a keybinding.
Store change to a keybinding.
[ "Store", "change", "to", "a", "keybinding", "." ]
def var_changed_keybinding(self, *params): "Store change to a keybinding." value = self.keybinding.get() key_set = self.custom_name.get() event = self.bindingslist.get(ANCHOR).split()[0] if idleConf.IsCoreBinding(event): changes.add_option('keys', key_set, event, value) else: # Event is an extension binding. ext_name = idleConf.GetExtnNameForEvent(event) ext_keybind_section = ext_name + '_cfgBindings' changes.add_option('extensions', ext_keybind_section, event, value)
[ "def", "var_changed_keybinding", "(", "self", ",", "*", "params", ")", ":", "value", "=", "self", ".", "keybinding", ".", "get", "(", ")", "key_set", "=", "self", ".", "custom_name", ".", "get", "(", ")", "event", "=", "self", ".", "bindingslist", ".", "get", "(", "ANCHOR", ")", ".", "split", "(", ")", "[", "0", "]", "if", "idleConf", ".", "IsCoreBinding", "(", "event", ")", ":", "changes", ".", "add_option", "(", "'keys'", ",", "key_set", ",", "event", ",", "value", ")", "else", ":", "# Event is an extension binding.", "ext_name", "=", "idleConf", ".", "GetExtnNameForEvent", "(", "event", ")", "ext_keybind_section", "=", "ext_name", "+", "'_cfgBindings'", "changes", ".", "add_option", "(", "'extensions'", ",", "ext_keybind_section", ",", "event", ",", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L1580-L1590
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/poisson_lognormal.py
python
PoissonLogNormalQuadratureCompound.__init__
(self, loc, scale, quadrature_grid_and_probs=None, validate_args=False, allow_nan_stats=True, name="PoissonLogNormalQuadratureCompound")
Constructs the PoissonLogNormalQuadratureCompound on `R**k`. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (batch of) scalar `Tensor`; the scale parameter of the LogNormal prior. quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. When `None`, defaults to: `np.polynomial.hermite.hermgauss(deg=8)`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: TypeError: if `loc.dtype != scale[0].dtype`.
Constructs the PoissonLogNormalQuadratureCompound on `R**k`.
[ "Constructs", "the", "PoissonLogNormalQuadratureCompound", "on", "R", "**", "k", "." ]
def __init__(self, loc, scale, quadrature_grid_and_probs=None, validate_args=False, allow_nan_stats=True, name="PoissonLogNormalQuadratureCompound"): """Constructs the PoissonLogNormalQuadratureCompound on `R**k`. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `float`-like (batch of) scalar `Tensor`; the scale parameter of the LogNormal prior. quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. When `None`, defaults to: `np.polynomial.hermite.hermgauss(deg=8)`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: TypeError: if `loc.dtype != scale[0].dtype`. """ parameters = locals() with ops.name_scope(name, values=[loc, scale]): loc = ops.convert_to_tensor(loc, name="loc") self._loc = loc scale = ops.convert_to_tensor(scale, name="scale") self._scale = scale dtype = loc.dtype.base_dtype if dtype != scale.dtype.base_dtype: raise TypeError( "loc.dtype(\"{}\") does not match scale.dtype(\"{}\")".format( loc.dtype.name, scale.dtype.name)) grid, probs = distribution_util.process_quadrature_grid_and_probs( quadrature_grid_and_probs, dtype, validate_args) self._quadrature_grid = grid self._quadrature_probs = probs self._quadrature_size = distribution_util.dimension_size(probs, axis=0) self._mixture_distribution = categorical_lib.Categorical( logits=math_ops.log(self._quadrature_probs), validate_args=validate_args, allow_nan_stats=allow_nan_stats) # The following maps the broadcast of `loc` and `scale` to each grid # point, i.e., we are creating several log-rates that correspond to the # different Gauss-Hermite quadrature points and (possible) batches of # `loc` and `scale`. self._log_rate = (loc[..., array_ops.newaxis] + np.sqrt(2.) * scale[..., array_ops.newaxis] * grid) self._distribution = poisson_lib.Poisson( log_rate=self._log_rate, validate_args=validate_args, allow_nan_stats=allow_nan_stats) super(PoissonLogNormalQuadratureCompound, self).__init__( dtype=dtype, reparameterization_type=distribution_lib.NOT_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[loc, scale], name=name)
[ "def", "__init__", "(", "self", ",", "loc", ",", "scale", ",", "quadrature_grid_and_probs", "=", "None", ",", "validate_args", "=", "False", ",", "allow_nan_stats", "=", "True", ",", "name", "=", "\"PoissonLogNormalQuadratureCompound\"", ")", ":", "parameters", "=", "locals", "(", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "values", "=", "[", "loc", ",", "scale", "]", ")", ":", "loc", "=", "ops", ".", "convert_to_tensor", "(", "loc", ",", "name", "=", "\"loc\"", ")", "self", ".", "_loc", "=", "loc", "scale", "=", "ops", ".", "convert_to_tensor", "(", "scale", ",", "name", "=", "\"scale\"", ")", "self", ".", "_scale", "=", "scale", "dtype", "=", "loc", ".", "dtype", ".", "base_dtype", "if", "dtype", "!=", "scale", ".", "dtype", ".", "base_dtype", ":", "raise", "TypeError", "(", "\"loc.dtype(\\\"{}\\\") does not match scale.dtype(\\\"{}\\\")\"", ".", "format", "(", "loc", ".", "dtype", ".", "name", ",", "scale", ".", "dtype", ".", "name", ")", ")", "grid", ",", "probs", "=", "distribution_util", ".", "process_quadrature_grid_and_probs", "(", "quadrature_grid_and_probs", ",", "dtype", ",", "validate_args", ")", "self", ".", "_quadrature_grid", "=", "grid", "self", ".", "_quadrature_probs", "=", "probs", "self", ".", "_quadrature_size", "=", "distribution_util", ".", "dimension_size", "(", "probs", ",", "axis", "=", "0", ")", "self", ".", "_mixture_distribution", "=", "categorical_lib", ".", "Categorical", "(", "logits", "=", "math_ops", ".", "log", "(", "self", ".", "_quadrature_probs", ")", ",", "validate_args", "=", "validate_args", ",", "allow_nan_stats", "=", "allow_nan_stats", ")", "# The following maps the broadcast of `loc` and `scale` to each grid", "# point, i.e., we are creating several log-rates that correspond to the", "# different Gauss-Hermite quadrature points and (possible) batches of", "# `loc` and `scale`.", "self", ".", "_log_rate", "=", "(", "loc", "[", "...", ",", "array_ops", ".", "newaxis", "]", "+", "np", ".", "sqrt", "(", "2.", ")", "*", "scale", "[", "...", ",", "array_ops", ".", "newaxis", "]", "*", "grid", ")", "self", ".", "_distribution", "=", "poisson_lib", ".", "Poisson", "(", "log_rate", "=", "self", ".", "_log_rate", ",", "validate_args", "=", "validate_args", ",", "allow_nan_stats", "=", "allow_nan_stats", ")", "super", "(", "PoissonLogNormalQuadratureCompound", ",", "self", ")", ".", "__init__", "(", "dtype", "=", "dtype", ",", "reparameterization_type", "=", "distribution_lib", ".", "NOT_REPARAMETERIZED", ",", "validate_args", "=", "validate_args", ",", "allow_nan_stats", "=", "allow_nan_stats", ",", "parameters", "=", "parameters", ",", "graph_parents", "=", "[", "loc", ",", "scale", "]", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/poisson_lognormal.py#L121-L196
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py
python
visiblename
(name, all=None, obj=None)
Decide whether to show documentation on a variable.
Decide whether to show documentation on a variable.
[ "Decide", "whether", "to", "show", "documentation", "on", "a", "variable", "." ]
def visiblename(name, all=None, obj=None): """Decide whether to show documentation on a variable.""" # Certain special names are redundant or internal. # XXX Remove __initializing__? if name in {'__author__', '__builtins__', '__cached__', '__credits__', '__date__', '__doc__', '__file__', '__spec__', '__loader__', '__module__', '__name__', '__package__', '__path__', '__qualname__', '__slots__', '__version__'}: return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 # Namedtuples have public fields and methods with a single leading underscore if name.startswith('_') and hasattr(obj, '_fields'): return True if all is not None: # only document that which the programmer exported in __all__ return name in all else: return not name.startswith('_')
[ "def", "visiblename", "(", "name", ",", "all", "=", "None", ",", "obj", "=", "None", ")", ":", "# Certain special names are redundant or internal.", "# XXX Remove __initializing__?", "if", "name", "in", "{", "'__author__'", ",", "'__builtins__'", ",", "'__cached__'", ",", "'__credits__'", ",", "'__date__'", ",", "'__doc__'", ",", "'__file__'", ",", "'__spec__'", ",", "'__loader__'", ",", "'__module__'", ",", "'__name__'", ",", "'__package__'", ",", "'__path__'", ",", "'__qualname__'", ",", "'__slots__'", ",", "'__version__'", "}", ":", "return", "0", "# Private names are hidden, but special names are displayed.", "if", "name", ".", "startswith", "(", "'__'", ")", "and", "name", ".", "endswith", "(", "'__'", ")", ":", "return", "1", "# Namedtuples have public fields and methods with a single leading underscore", "if", "name", ".", "startswith", "(", "'_'", ")", "and", "hasattr", "(", "obj", ",", "'_fields'", ")", ":", "return", "True", "if", "all", "is", "not", "None", ":", "# only document that which the programmer exported in __all__", "return", "name", "in", "all", "else", ":", "return", "not", "name", ".", "startswith", "(", "'_'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L187-L205
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/directives/__init__.py
python
positive_int
(argument)
return value
Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.)
Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.)
[ "Converts", "the", "argument", "into", "an", "integer", ".", "Raises", "ValueError", "for", "negative", "zero", "or", "non", "-", "integer", "values", ".", "(", "Directive", "option", "conversion", "function", ".", ")" ]
def positive_int(argument): """ Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.) """ value = int(argument) if value < 1: raise ValueError('negative or zero value; must be positive') return value
[ "def", "positive_int", "(", "argument", ")", ":", "value", "=", "int", "(", "argument", ")", "if", "value", "<", "1", ":", "raise", "ValueError", "(", "'negative or zero value; must be positive'", ")", "return", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/directives/__init__.py#L341-L349
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/common/option_tools.py
python
_get_preset_default_ai_options
()
return odict( [ ( TIMER_SECTION, odict([(TIMERS_USE_TIMERS, False)]), ), ("main", odict([(HANDLERS, "")])), # module names in handler directory, joined by space ] )
returns preset default options for AI; an ordered dict of dicts. each sub-dict corresponds to a config file section :return:
returns preset default options for AI; an ordered dict of dicts. each sub-dict corresponds to a config file section :return:
[ "returns", "preset", "default", "options", "for", "AI", ";", "an", "ordered", "dict", "of", "dicts", ".", "each", "sub", "-", "dict", "corresponds", "to", "a", "config", "file", "section", ":", "return", ":" ]
def _get_preset_default_ai_options(): """ returns preset default options for AI; an ordered dict of dicts. each sub-dict corresponds to a config file section :return: """ return odict( [ ( TIMER_SECTION, odict([(TIMERS_USE_TIMERS, False)]), ), ("main", odict([(HANDLERS, "")])), # module names in handler directory, joined by space ] )
[ "def", "_get_preset_default_ai_options", "(", ")", ":", "return", "odict", "(", "[", "(", "TIMER_SECTION", ",", "odict", "(", "[", "(", "TIMERS_USE_TIMERS", ",", "False", ")", "]", ")", ",", ")", ",", "(", "\"main\"", ",", "odict", "(", "[", "(", "HANDLERS", ",", "\"\"", ")", "]", ")", ")", ",", "# module names in handler directory, joined by space", "]", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/common/option_tools.py#L42-L56
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
Document.DeleteAllViews
(self)
return True
Calls wxView.Close and deletes each view. Deleting the final view will implicitly delete the document itself, because the wxView destructor calls RemoveView. This in turns calls wxDocument::OnChangedViewList, whose default implemention is to save and delete the document if no views exist.
Calls wxView.Close and deletes each view. Deleting the final view will implicitly delete the document itself, because the wxView destructor calls RemoveView. This in turns calls wxDocument::OnChangedViewList, whose default implemention is to save and delete the document if no views exist.
[ "Calls", "wxView", ".", "Close", "and", "deletes", "each", "view", ".", "Deleting", "the", "final", "view", "will", "implicitly", "delete", "the", "document", "itself", "because", "the", "wxView", "destructor", "calls", "RemoveView", ".", "This", "in", "turns", "calls", "wxDocument", "::", "OnChangedViewList", "whose", "default", "implemention", "is", "to", "save", "and", "delete", "the", "document", "if", "no", "views", "exist", "." ]
def DeleteAllViews(self): """ Calls wxView.Close and deletes each view. Deleting the final view will implicitly delete the document itself, because the wxView destructor calls RemoveView. This in turns calls wxDocument::OnChangedViewList, whose default implemention is to save and delete the document if no views exist. """ manager = self.GetDocumentManager() for view in self._documentViews: if not view.Close(): return False if self in manager.GetDocuments(): self.Destroy() return True
[ "def", "DeleteAllViews", "(", "self", ")", ":", "manager", "=", "self", ".", "GetDocumentManager", "(", ")", "for", "view", "in", "self", ".", "_documentViews", ":", "if", "not", "view", ".", "Close", "(", ")", ":", "return", "False", "if", "self", "in", "manager", ".", "GetDocuments", "(", ")", ":", "self", ".", "Destroy", "(", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L319-L333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/common.py
python
stringify_path
( filepath_or_buffer: FilePathOrBuffer[AnyStr], )
return _expand_user(filepath_or_buffer)
Attempt to convert a path-like object to a string. Parameters ---------- filepath_or_buffer : object to be converted Returns ------- str_filepath_or_buffer : maybe a string version of the object Notes ----- Objects supporting the fspath protocol (python 3.6+) are coerced according to its __fspath__ method. For backwards compatibility with older pythons, pathlib.Path and py.path objects are specially coerced. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like.
Attempt to convert a path-like object to a string.
[ "Attempt", "to", "convert", "a", "path", "-", "like", "object", "to", "a", "string", "." ]
def stringify_path( filepath_or_buffer: FilePathOrBuffer[AnyStr], ) -> FilePathOrBuffer[AnyStr]: """Attempt to convert a path-like object to a string. Parameters ---------- filepath_or_buffer : object to be converted Returns ------- str_filepath_or_buffer : maybe a string version of the object Notes ----- Objects supporting the fspath protocol (python 3.6+) are coerced according to its __fspath__ method. For backwards compatibility with older pythons, pathlib.Path and py.path objects are specially coerced. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. """ if hasattr(filepath_or_buffer, "__fspath__"): # https://github.com/python/mypy/issues/1424 return filepath_or_buffer.__fspath__() # type: ignore elif isinstance(filepath_or_buffer, pathlib.Path): return str(filepath_or_buffer) return _expand_user(filepath_or_buffer)
[ "def", "stringify_path", "(", "filepath_or_buffer", ":", "FilePathOrBuffer", "[", "AnyStr", "]", ",", ")", "->", "FilePathOrBuffer", "[", "AnyStr", "]", ":", "if", "hasattr", "(", "filepath_or_buffer", ",", "\"__fspath__\"", ")", ":", "# https://github.com/python/mypy/issues/1424", "return", "filepath_or_buffer", ".", "__fspath__", "(", ")", "# type: ignore", "elif", "isinstance", "(", "filepath_or_buffer", ",", "pathlib", ".", "Path", ")", ":", "return", "str", "(", "filepath_or_buffer", ")", "return", "_expand_user", "(", "filepath_or_buffer", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/common.py#L88-L117
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_java.py
python
SyntaxData.GetSyntaxSpec
(self)
return SYNTAX_ITEMS
Syntax Specifications
Syntax Specifications
[ "Syntax", "Specifications" ]
def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS
[ "def", "GetSyntaxSpec", "(", "self", ")", ":", "return", "SYNTAX_ITEMS" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_java.py#L110-L112
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/factorization/python/ops/factorization_ops.py
python
WALSModel.col_weights
(self)
return self._col_weights
Returns a list of tensors corresponding to col weight shards.
Returns a list of tensors corresponding to col weight shards.
[ "Returns", "a", "list", "of", "tensors", "corresponding", "to", "col", "weight", "shards", "." ]
def col_weights(self): """Returns a list of tensors corresponding to col weight shards.""" return self._col_weights
[ "def", "col_weights", "(", "self", ")", ":", "return", "self", ".", "_col_weights" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L259-L261
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/distutils/fcompiler/__init__.py
python
FCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compile 'src' to product 'obj'.
Compile 'src' to product 'obj'.
[ "Compile", "src", "to", "product", "obj", "." ]
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" src_flags = {} if is_f_file(src) and not has_f90_header(src): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) elif is_free_format(src): flavor = ':f90' compiler = self.compiler_f90 if compiler is None: raise DistutilsExecError('f90 not supported by %s needed for %s'\ % (self.__class__.__name__,src)) else: flavor = ':fix' compiler = self.compiler_fix if compiler is None: raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\ % (self.__class__.__name__,src)) if self.object_switch[-1]==' ': o_args = [self.object_switch.strip(),obj] else: o_args = [self.object_switch.strip()+obj] assert self.compile_switch.strip() s_args = [self.compile_switch, src] extra_flags = src_flags.get(self.compiler_type,[]) if extra_flags: log.info('using compile options from source: %r' \ % ' '.join(extra_flags)) command = compiler + cc_args + extra_flags + s_args + o_args \ + extra_postargs display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) try: self.spawn(command,display=display) except DistutilsExecError: msg = str(get_exception()) raise CompileError(msg)
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "src_flags", "=", "{", "}", "if", "is_f_file", "(", "src", ")", "and", "not", "has_f90_header", "(", "src", ")", ":", "flavor", "=", "':f77'", "compiler", "=", "self", ".", "compiler_f77", "src_flags", "=", "get_f77flags", "(", "src", ")", "elif", "is_free_format", "(", "src", ")", ":", "flavor", "=", "':f90'", "compiler", "=", "self", ".", "compiler_f90", "if", "compiler", "is", "None", ":", "raise", "DistutilsExecError", "(", "'f90 not supported by %s needed for %s'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "src", ")", ")", "else", ":", "flavor", "=", "':fix'", "compiler", "=", "self", ".", "compiler_fix", "if", "compiler", "is", "None", ":", "raise", "DistutilsExecError", "(", "'f90 (fixed) not supported by %s needed for %s'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "src", ")", ")", "if", "self", ".", "object_switch", "[", "-", "1", "]", "==", "' '", ":", "o_args", "=", "[", "self", ".", "object_switch", ".", "strip", "(", ")", ",", "obj", "]", "else", ":", "o_args", "=", "[", "self", ".", "object_switch", ".", "strip", "(", ")", "+", "obj", "]", "assert", "self", ".", "compile_switch", ".", "strip", "(", ")", "s_args", "=", "[", "self", ".", "compile_switch", ",", "src", "]", "extra_flags", "=", "src_flags", ".", "get", "(", "self", ".", "compiler_type", ",", "[", "]", ")", "if", "extra_flags", ":", "log", ".", "info", "(", "'using compile options from source: %r'", "%", "' '", ".", "join", "(", "extra_flags", ")", ")", "command", "=", "compiler", "+", "cc_args", "+", "extra_flags", "+", "s_args", "+", "o_args", "+", "extra_postargs", "display", "=", "'%s: %s'", "%", "(", "os", ".", "path", ".", "basename", "(", "compiler", "[", "0", "]", ")", "+", "flavor", ",", "src", ")", "try", ":", "self", ".", "spawn", "(", "command", ",", "display", "=", "display", ")", "except", "DistutilsExecError", ":", "msg", "=", "str", "(", "get_exception", "(", ")", ")", "raise", "CompileError", "(", "msg", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/fcompiler/__init__.py#L557-L598
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/boringssl/src/util/generate_build_files.py
python
WriteAsmFiles
(perlasms)
return asmfiles
Generates asm files from perlasm directives for each supported OS x platform combination.
Generates asm files from perlasm directives for each supported OS x platform combination.
[ "Generates", "asm", "files", "from", "perlasm", "directives", "for", "each", "supported", "OS", "x", "platform", "combination", "." ]
def WriteAsmFiles(perlasms): """Generates asm files from perlasm directives for each supported OS x platform combination.""" asmfiles = {} for osarch in OS_ARCH_COMBOS: (osname, arch, perlasm_style, extra_args, asm_ext) = osarch key = (osname, arch) outDir = '%s-%s' % key for perlasm in perlasms: filename = os.path.basename(perlasm['input']) output = perlasm['output'] if not output.startswith('src'): raise ValueError('output missing src: %s' % output) output = os.path.join(outDir, output[4:]) if output.endswith('-armx.${ASM_EXT}'): output = output.replace('-armx', '-armx64' if arch == 'aarch64' else '-armx32') output = output.replace('${ASM_EXT}', asm_ext) if arch in ArchForAsmFilename(filename): PerlAsm(output, perlasm['input'], perlasm_style, perlasm['extra_args'] + extra_args) asmfiles.setdefault(key, []).append(output) for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems(): asmfiles.setdefault(key, []).extend(non_perl_asm_files) return asmfiles
[ "def", "WriteAsmFiles", "(", "perlasms", ")", ":", "asmfiles", "=", "{", "}", "for", "osarch", "in", "OS_ARCH_COMBOS", ":", "(", "osname", ",", "arch", ",", "perlasm_style", ",", "extra_args", ",", "asm_ext", ")", "=", "osarch", "key", "=", "(", "osname", ",", "arch", ")", "outDir", "=", "'%s-%s'", "%", "key", "for", "perlasm", "in", "perlasms", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "perlasm", "[", "'input'", "]", ")", "output", "=", "perlasm", "[", "'output'", "]", "if", "not", "output", ".", "startswith", "(", "'src'", ")", ":", "raise", "ValueError", "(", "'output missing src: %s'", "%", "output", ")", "output", "=", "os", ".", "path", ".", "join", "(", "outDir", ",", "output", "[", "4", ":", "]", ")", "if", "output", ".", "endswith", "(", "'-armx.${ASM_EXT}'", ")", ":", "output", "=", "output", ".", "replace", "(", "'-armx'", ",", "'-armx64'", "if", "arch", "==", "'aarch64'", "else", "'-armx32'", ")", "output", "=", "output", ".", "replace", "(", "'${ASM_EXT}'", ",", "asm_ext", ")", "if", "arch", "in", "ArchForAsmFilename", "(", "filename", ")", ":", "PerlAsm", "(", "output", ",", "perlasm", "[", "'input'", "]", ",", "perlasm_style", ",", "perlasm", "[", "'extra_args'", "]", "+", "extra_args", ")", "asmfiles", ".", "setdefault", "(", "key", ",", "[", "]", ")", ".", "append", "(", "output", ")", "for", "(", "key", ",", "non_perl_asm_files", ")", "in", "NON_PERL_FILES", ".", "iteritems", "(", ")", ":", "asmfiles", ".", "setdefault", "(", "key", ",", "[", "]", ")", ".", "extend", "(", "non_perl_asm_files", ")", "return", "asmfiles" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/boringssl/src/util/generate_build_files.py#L584-L613
ducha-aiki/LSUVinit
a42ecdc0d44c217a29b65e98748d80b90d5c6279
scripts/cpp_lint.py
python
_VerboseLevel
()
return _cpplint_state.verbose_level
Returns the module's verbosity setting.
Returns the module's verbosity setting.
[ "Returns", "the", "module", "s", "verbosity", "setting", "." ]
def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level
[ "def", "_VerboseLevel", "(", ")", ":", "return", "_cpplint_state", ".", "verbose_level" ]
https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/scripts/cpp_lint.py#L777-L779
LeoSirius/leetcode_solutions
9bbbaaba704862a3e0cec4ae715daf1ee4752c7b
mst10.01_Sorted_Merge_LCCI/Solution1.py
python
Solution.merge
(self, A: List[int], m: int, B: List[int], n: int)
Do not return anything, modify A in-place instead.
Do not return anything, modify A in-place instead.
[ "Do", "not", "return", "anything", "modify", "A", "in", "-", "place", "instead", "." ]
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None: """ Do not return anything, modify A in-place instead. """ pa, pb = m - 1, n - 1 tail = m + n - 1 while pa >= 0 and pb >= 0: if A[pa] > B[pb]: A[tail] = A[pa] pa -= 1 else: A[tail] = B[pb] pb -= 1 tail -= 1 # 我们以A为基准,这个不用判断,若pb = -1, 则tail 必然等于pa # while pa >= 0: # A[tail] = A[pa] # tail -= 1 # pa -= 1 while pb >= 0: A[tail] = B[pb] tail -= 1 pb -= 1
[ "def", "merge", "(", "self", ",", "A", ":", "List", "[", "int", "]", ",", "m", ":", "int", ",", "B", ":", "List", "[", "int", "]", ",", "n", ":", "int", ")", "->", "None", ":", "pa", ",", "pb", "=", "m", "-", "1", ",", "n", "-", "1", "tail", "=", "m", "+", "n", "-", "1", "while", "pa", ">=", "0", "and", "pb", ">=", "0", ":", "if", "A", "[", "pa", "]", ">", "B", "[", "pb", "]", ":", "A", "[", "tail", "]", "=", "A", "[", "pa", "]", "pa", "-=", "1", "else", ":", "A", "[", "tail", "]", "=", "B", "[", "pb", "]", "pb", "-=", "1", "tail", "-=", "1", "# 我们以A为基准,这个不用判断,若pb = -1, 则tail 必然等于pa", "# while pa >= 0:", "# A[tail] = A[pa]", "# tail -= 1", "# pa -= 1", "while", "pb", ">=", "0", ":", "A", "[", "tail", "]", "=", "B", "[", "pb", "]", "tail", "-=", "1", "pb", "-=", "1" ]
https://github.com/LeoSirius/leetcode_solutions/blob/9bbbaaba704862a3e0cec4ae715daf1ee4752c7b/mst10.01_Sorted_Merge_LCCI/Solution1.py#L4-L29
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/polybond/lmpsdata.py
python
particlesurface.extractparticle
(self)
return self.particle
deletesatoms from particle from the list of deletedatoms and than returns the particle.
deletesatoms from particle from the list of deletedatoms and than returns the particle.
[ "deletesatoms", "from", "particle", "from", "the", "list", "of", "deletedatoms", "and", "than", "returns", "the", "particle", "." ]
def extractparticle(self): """"deletesatoms from particle from the list of deletedatoms and than returns the particle.""" self.particle=self.deleteatoms(self.particle,self.deletedatoms) return self.particle
[ "def", "extractparticle", "(", "self", ")", ":", "self", ".", "particle", "=", "self", ".", "deleteatoms", "(", "self", ".", "particle", ",", "self", ".", "deletedatoms", ")", "return", "self", ".", "particle" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/polybond/lmpsdata.py#L1020-L1024
lilypond/lilypond
2a14759372979f5b796ee802b0ee3bc15d28b06b
release/binaries/lib/build.py
python
Package.install_directory
(self, c: Config)
return os.path.join(c.dependencies_install_dir, self.directory)
Return the temporary install directory for this package
Return the temporary install directory for this package
[ "Return", "the", "temporary", "install", "directory", "for", "this", "package" ]
def install_directory(self, c: Config) -> str: """Return the temporary install directory for this package""" return os.path.join(c.dependencies_install_dir, self.directory)
[ "def", "install_directory", "(", "self", ",", "c", ":", "Config", ")", "->", "str", ":", "return", "os", ".", "path", ".", "join", "(", "c", ".", "dependencies_install_dir", ",", "self", ".", "directory", ")" ]
https://github.com/lilypond/lilypond/blob/2a14759372979f5b796ee802b0ee3bc15d28b06b/release/binaries/lib/build.py#L70-L72
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/pretty_printers.py
python
register_pretty_printer_commands
()
Call from a top level script to install the pretty-printer commands.
Call from a top level script to install the pretty-printer commands.
[ "Call", "from", "a", "top", "level", "script", "to", "install", "the", "pretty", "-", "printer", "commands", "." ]
def register_pretty_printer_commands(): """Call from a top level script to install the pretty-printer commands.""" InfoPrettyPrinter() EnablePrettyPrinter() DisablePrettyPrinter()
[ "def", "register_pretty_printer_commands", "(", ")", ":", "InfoPrettyPrinter", "(", ")", "EnablePrettyPrinter", "(", ")", "DisablePrettyPrinter", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/pretty_printers.py#L362-L366
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/parallel.py
python
threading_layer
()
Get the name of the threading layer in use for parallel CPU targets
Get the name of the threading layer in use for parallel CPU targets
[ "Get", "the", "name", "of", "the", "threading", "layer", "in", "use", "for", "parallel", "CPU", "targets" ]
def threading_layer(): """ Get the name of the threading layer in use for parallel CPU targets """ if _threading_layer is None: raise ValueError("Threading layer is not initialized.") else: return _threading_layer
[ "def", "threading_layer", "(", ")", ":", "if", "_threading_layer", "is", "None", ":", "raise", "ValueError", "(", "\"Threading layer is not initialized.\"", ")", "else", ":", "return", "_threading_layer" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/parallel.py#L310-L317
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config_key.py
python
GetKeysDialog.__init__
(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False)
parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest
parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest
[ "parent", "-", "parent", "of", "this", "dialog", "title", "-", "string", "which", "is", "the", "title", "of", "the", "popup", "dialog", "action", "-", "string", "the", "name", "of", "the", "virtual", "event", "these", "keys", "will", "be", "mapped", "to", "current_key_sequences", "-", "list", "a", "list", "of", "all", "key", "sequence", "lists", "currently", "mapped", "to", "virtual", "events", "for", "overlap", "checking", "_htest", "-", "bool", "change", "box", "location", "when", "running", "htest", "_utest", "-", "bool", "do", "not", "wait", "when", "running", "unittest" ]
def __init__(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False): """ parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest """ Toplevel.__init__(self, parent) self.withdraw() # Hide while setting geometry. self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.action = action self.current_key_sequences = current_key_sequences self.result = '' self.key_string = StringVar(self) self.key_string.set('') # Set self.modifiers, self.modifier_label. self.set_modifiers_for_platform() self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.create_widgets() self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) # Center dialog over parent (or below htest box). if not _utest: self.deiconify() # Geometry set, unhide. self.wait_window()
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ",", "action", ",", "current_key_sequences", ",", "*", ",", "_htest", "=", "False", ",", "_utest", "=", "False", ")", ":", "Toplevel", ".", "__init__", "(", "self", ",", "parent", ")", "self", ".", "withdraw", "(", ")", "# Hide while setting geometry.", "self", ".", "configure", "(", "borderwidth", "=", "5", ")", "self", ".", "resizable", "(", "height", "=", "False", ",", "width", "=", "False", ")", "self", ".", "title", "(", "title", ")", "self", ".", "transient", "(", "parent", ")", "self", ".", "grab_set", "(", ")", "self", ".", "protocol", "(", "\"WM_DELETE_WINDOW\"", ",", "self", ".", "cancel", ")", "self", ".", "parent", "=", "parent", "self", ".", "action", "=", "action", "self", ".", "current_key_sequences", "=", "current_key_sequences", "self", ".", "result", "=", "''", "self", ".", "key_string", "=", "StringVar", "(", "self", ")", "self", ".", "key_string", ".", "set", "(", "''", ")", "# Set self.modifiers, self.modifier_label.", "self", ".", "set_modifiers_for_platform", "(", ")", "self", ".", "modifier_vars", "=", "[", "]", "for", "modifier", "in", "self", ".", "modifiers", ":", "variable", "=", "StringVar", "(", "self", ")", "variable", ".", "set", "(", "''", ")", "self", ".", "modifier_vars", ".", "append", "(", "variable", ")", "self", ".", "advanced", "=", "False", "self", ".", "create_widgets", "(", ")", "self", ".", "update_idletasks", "(", ")", "self", ".", "geometry", "(", "\"+%d+%d\"", "%", "(", "parent", ".", "winfo_rootx", "(", ")", "+", "(", "parent", ".", "winfo_width", "(", ")", "/", "2", "-", "self", ".", "winfo_reqwidth", "(", ")", "/", "2", ")", ",", "parent", ".", "winfo_rooty", "(", ")", "+", "(", "(", "parent", ".", "winfo_height", "(", ")", "/", "2", "-", "self", ".", "winfo_reqheight", "(", ")", "/", "2", ")", "if", "not", "_htest", "else", "150", ")", ")", ")", "# Center dialog over parent (or below htest box).", "if", "not", "_utest", ":", "self", ".", "deiconify", "(", ")", "# Geometry set, unhide.", "self", ".", "wait_window", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config_key.py#L48-L94
alexsax/2D-3D-Semantics
54a532959b20203ea4c3fcc26f5c8bf678d6fdb4
assets/utils.py
python
read_exr
( image_fpath )
return im
Reads an openEXR file into an RGB matrix with floats
Reads an openEXR file into an RGB matrix with floats
[ "Reads", "an", "openEXR", "file", "into", "an", "RGB", "matrix", "with", "floats" ]
def read_exr( image_fpath ): """ Reads an openEXR file into an RGB matrix with floats """ f = OpenEXR.InputFile( image_fpath ) dw = f.header()['dataWindow'] w, h = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1) im = np.empty( (h, w, 3) ) # Read in the EXR FLOAT = Imath.PixelType(Imath.PixelType.FLOAT) channels = f.channels( ["R", "G", "B"], FLOAT ) for i, channel in enumerate( channels ): im[:,:,i] = np.reshape( array.array( 'f', channel ), (h, w) ) return im
[ "def", "read_exr", "(", "image_fpath", ")", ":", "f", "=", "OpenEXR", ".", "InputFile", "(", "image_fpath", ")", "dw", "=", "f", ".", "header", "(", ")", "[", "'dataWindow'", "]", "w", ",", "h", "=", "(", "dw", ".", "max", ".", "x", "-", "dw", ".", "min", ".", "x", "+", "1", ",", "dw", ".", "max", ".", "y", "-", "dw", ".", "min", ".", "y", "+", "1", ")", "im", "=", "np", ".", "empty", "(", "(", "h", ",", "w", ",", "3", ")", ")", "# Read in the EXR", "FLOAT", "=", "Imath", ".", "PixelType", "(", "Imath", ".", "PixelType", ".", "FLOAT", ")", "channels", "=", "f", ".", "channels", "(", "[", "\"R\"", ",", "\"G\"", ",", "\"B\"", "]", ",", "FLOAT", ")", "for", "i", ",", "channel", "in", "enumerate", "(", "channels", ")", ":", "im", "[", ":", ",", ":", ",", "i", "]", "=", "np", ".", "reshape", "(", "array", ".", "array", "(", "'f'", ",", "channel", ")", ",", "(", "h", ",", "w", ")", ")", "return", "im" ]
https://github.com/alexsax/2D-3D-Semantics/blob/54a532959b20203ea4c3fcc26f5c8bf678d6fdb4/assets/utils.py#L72-L84
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py
python
Normal.mode
(self, name="mode")
return self.mean(name="mode")
Mode of this distribution.
Mode of this distribution.
[ "Mode", "of", "this", "distribution", "." ]
def mode(self, name="mode"): """Mode of this distribution.""" return self.mean(name="mode")
[ "def", "mode", "(", "self", ",", "name", "=", "\"mode\"", ")", ":", "return", "self", ".", "mean", "(", "name", "=", "\"mode\"", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py#L207-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/excel.py
python
_OpenpyxlWriter._convert_to_stop
(cls, stop_seq)
return map(cls._convert_to_color, stop_seq)
Convert ``stop_seq`` to a list of openpyxl v2 Color objects, suitable for initializing the ``GradientFill`` ``stop`` parameter. Parameters ---------- stop_seq : iterable An iterable that yields objects suitable for consumption by ``_convert_to_color``. Returns ------- stop : list of openpyxl.styles.Color
Convert ``stop_seq`` to a list of openpyxl v2 Color objects, suitable for initializing the ``GradientFill`` ``stop`` parameter. Parameters ---------- stop_seq : iterable An iterable that yields objects suitable for consumption by ``_convert_to_color``. Returns ------- stop : list of openpyxl.styles.Color
[ "Convert", "stop_seq", "to", "a", "list", "of", "openpyxl", "v2", "Color", "objects", "suitable", "for", "initializing", "the", "GradientFill", "stop", "parameter", ".", "Parameters", "----------", "stop_seq", ":", "iterable", "An", "iterable", "that", "yields", "objects", "suitable", "for", "consumption", "by", "_convert_to_color", ".", "Returns", "-------", "stop", ":", "list", "of", "openpyxl", ".", "styles", ".", "Color" ]
def _convert_to_stop(cls, stop_seq): """ Convert ``stop_seq`` to a list of openpyxl v2 Color objects, suitable for initializing the ``GradientFill`` ``stop`` parameter. Parameters ---------- stop_seq : iterable An iterable that yields objects suitable for consumption by ``_convert_to_color``. Returns ------- stop : list of openpyxl.styles.Color """ return map(cls._convert_to_color, stop_seq)
[ "def", "_convert_to_stop", "(", "cls", ",", "stop_seq", ")", ":", "return", "map", "(", "cls", ".", "_convert_to_color", ",", "stop_seq", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/excel.py#L1367-L1381
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/input/crystalloader.py
python
CRYSTALLoader._inside_k_block
(self, file_obj=None)
return any([key in line for key in allowed_keywords])
Checks if end of k-points block. :param file_obj: file object from which we read :returns: True if end of block otherwise False
Checks if end of k-points block. :param file_obj: file object from which we read :returns: True if end of block otherwise False
[ "Checks", "if", "end", "of", "k", "-", "points", "block", ".", ":", "param", "file_obj", ":", "file", "object", "from", "which", "we", "read", ":", "returns", ":", "True", "if", "end", "of", "block", "otherwise", "False" ]
def _inside_k_block(self, file_obj=None): """ Checks if end of k-points block. :param file_obj: file object from which we read :returns: True if end of block otherwise False """ allowed_keywords = [b" X ", b" Y ", b" Z ", b"-", b"REAL", b"IMAGINARY", b"MODES", b"DISPERSION"] # remove empty lines: pos = None while not self._parser.file_end(file_obj=file_obj): pos = file_obj.tell() line = file_obj.readline() if line.strip(): break file_obj.seek(pos) # non empty line to check pos = file_obj.tell() line = file_obj.readline() file_obj.seek(pos) # if there isn't any keyword from set "allowed_keywords" it means that we reached end of k-block # if any keyword in line we are still in k-block return any([key in line for key in allowed_keywords])
[ "def", "_inside_k_block", "(", "self", ",", "file_obj", "=", "None", ")", ":", "allowed_keywords", "=", "[", "b\" X \"", ",", "b\" Y \"", ",", "b\" Z \"", ",", "b\"-\"", ",", "b\"REAL\"", ",", "b\"IMAGINARY\"", ",", "b\"MODES\"", ",", "b\"DISPERSION\"", "]", "# remove empty lines:", "pos", "=", "None", "while", "not", "self", ".", "_parser", ".", "file_end", "(", "file_obj", "=", "file_obj", ")", ":", "pos", "=", "file_obj", ".", "tell", "(", ")", "line", "=", "file_obj", ".", "readline", "(", ")", "if", "line", ".", "strip", "(", ")", ":", "break", "file_obj", ".", "seek", "(", "pos", ")", "# non empty line to check", "pos", "=", "file_obj", ".", "tell", "(", ")", "line", "=", "file_obj", ".", "readline", "(", ")", "file_obj", ".", "seek", "(", "pos", ")", "# if there isn't any keyword from set \"allowed_keywords\" it means that we reached end of k-block", "# if any keyword in line we are still in k-block", "return", "any", "(", "[", "key", "in", "line", "for", "key", "in", "allowed_keywords", "]", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/crystalloader.py#L346-L370
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/model.py
python
MapreduceState.get_processed
(self)
return self.counters_map.get(context.COUNTER_MAPPER_CALLS)
Number of processed entities. Returns: The total number of processed entities as int.
Number of processed entities.
[ "Number", "of", "processed", "entities", "." ]
def get_processed(self): """Number of processed entities. Returns: The total number of processed entities as int. """ return self.counters_map.get(context.COUNTER_MAPPER_CALLS)
[ "def", "get_processed", "(", "self", ")", ":", "return", "self", ".", "counters_map", ".", "get", "(", "context", ".", "COUNTER_MAPPER_CALLS", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/model.py#L692-L698
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Locale.GetLocale
(*args, **kwargs)
return _gdi_.Locale_GetLocale(*args, **kwargs)
GetLocale(self) -> String
GetLocale(self) -> String
[ "GetLocale", "(", "self", ")", "-", ">", "String" ]
def GetLocale(*args, **kwargs): """GetLocale(self) -> String""" return _gdi_.Locale_GetLocale(*args, **kwargs)
[ "def", "GetLocale", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_GetLocale", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L3114-L3116
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/lib/workflowUtil.py
python
getGenomeSegmentGroups
(genomeSegmentIterator, contigsExcludedFromGrouping = None)
Iterate segment groups and 'clump' small contigs together @param genomeSegmentIterator any object which will iterate through ungrouped genome segments) @param contigsExcludedFromGrouping defines a set of contigs which are excluded from grouping (useful when a particular contig, eg. chrM, is called with contig-specific parameters) @return yields a series of segment group lists Note this function will not reorder segments. This means that grouping will be suboptimal if small segments are sparsely distributed among larger ones.
Iterate segment groups and 'clump' small contigs together
[ "Iterate", "segment", "groups", "and", "clump", "small", "contigs", "together" ]
def getGenomeSegmentGroups(genomeSegmentIterator, contigsExcludedFromGrouping = None) : """ Iterate segment groups and 'clump' small contigs together @param genomeSegmentIterator any object which will iterate through ungrouped genome segments) @param contigsExcludedFromGrouping defines a set of contigs which are excluded from grouping (useful when a particular contig, eg. chrM, is called with contig-specific parameters) @return yields a series of segment group lists Note this function will not reorder segments. This means that grouping will be suboptimal if small segments are sparsely distributed among larger ones. """ def isGroupEligible(gseg) : if contigsExcludedFromGrouping is None : return True return (gseg.chromLabel not in contigsExcludedFromGrouping) minSegmentGroupSize=200000 group = [] headSize = 0 isLastSegmentGroupEligible = True for gseg in genomeSegmentIterator : isSegmentGroupEligible = isGroupEligible(gseg) if (isSegmentGroupEligible and isLastSegmentGroupEligible) and (headSize+gseg.size() <= minSegmentGroupSize) : group.append(gseg) headSize += gseg.size() else : if len(group) != 0 : yield(group) group = [gseg] headSize = gseg.size() isLastSegmentGroupEligible = isSegmentGroupEligible if len(group) != 0 : yield(group)
[ "def", "getGenomeSegmentGroups", "(", "genomeSegmentIterator", ",", "contigsExcludedFromGrouping", "=", "None", ")", ":", "def", "isGroupEligible", "(", "gseg", ")", ":", "if", "contigsExcludedFromGrouping", "is", "None", ":", "return", "True", "return", "(", "gseg", ".", "chromLabel", "not", "in", "contigsExcludedFromGrouping", ")", "minSegmentGroupSize", "=", "200000", "group", "=", "[", "]", "headSize", "=", "0", "isLastSegmentGroupEligible", "=", "True", "for", "gseg", "in", "genomeSegmentIterator", ":", "isSegmentGroupEligible", "=", "isGroupEligible", "(", "gseg", ")", "if", "(", "isSegmentGroupEligible", "and", "isLastSegmentGroupEligible", ")", "and", "(", "headSize", "+", "gseg", ".", "size", "(", ")", "<=", "minSegmentGroupSize", ")", ":", "group", ".", "append", "(", "gseg", ")", "headSize", "+=", "gseg", ".", "size", "(", ")", "else", ":", "if", "len", "(", "group", ")", "!=", "0", ":", "yield", "(", "group", ")", "group", "=", "[", "gseg", "]", "headSize", "=", "gseg", ".", "size", "(", ")", "isLastSegmentGroupEligible", "=", "isSegmentGroupEligible", "if", "len", "(", "group", ")", "!=", "0", ":", "yield", "(", "group", ")" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/workflowUtil.py#L335-L366
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/core.py
python
CatBoostRanker.fit
(self, X, y=None, group_id=None, cat_features=None, text_features=None, embedding_features=None, pairs=None, sample_weight=None, group_weight=None, subgroup_id=None, pairs_weight=None, baseline=None, use_best_model=None, eval_set=None, verbose=None, logging_level=None, plot=False, column_description=None, verbose_eval=None, metric_period=None, silent=None, early_stopping_rounds=None, save_snapshot=None, snapshot_file=None, snapshot_interval=None, init_model=None, callbacks=None, log_cout=sys.stdout, log_cerr=sys.stderr)
return self
Fit the CatBoostRanker model. Parameters ---------- X : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series If not catboost.Pool, 2 dimensional Feature matrix or string - file with dataset. y : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Labels, 1 dimensional array like. Use only if X is not catboost.Pool. group_id : numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Ranking groups, 1 dimensional array like. Use only if X is not catboost.Pool. cat_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Categ columns indices. Use only if X is not catboost.Pool. text_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Text columns indices. Use only if X is not catboost.Pool. embedding_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Embedding columns indices. Use only if X is not catboost.Pool. pairs : list or numpy.ndarray or pandas.DataFrame, optional (default=None) The pairs description in the form of a two-dimensional matrix of shape N by 2: N is the number of pairs. The first element of the pair is the zero-based index of the winner object from the input dataset for pairwise comparison. The second element of the pair is the zero-based index of the loser object from the input dataset for pairwise comparison. sample_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Instance weights, 1 dimensional array like. group_weight : list or numpy.ndarray (default=None) The weights of all objects within the defined groups from the input data in the form of one-dimensional array-like data. Used for calculating the final values of trees. By default, it is set to 1 for all objects in all groups. Only a weight or group_weight parameter can be used at a time subgroup_id : list or numpy.ndarray (default=None) Subgroup identifiers for all input objects. Supported identifier types are: int string types (string or unicode for Python 2 and bytes or string for Python 3). pairs_weight : list or numpy.ndarray (default=None) The weight of each input pair of objects in the form of one-dimensional array-like pairs. The number of given values must match the number of specified pairs. This information is used for calculation and optimization of Pairwise metrics . By default, it is set to 1 for all pairs. baseline : list or numpy.ndarray, optional (default=None) If not None, giving 2 dimensional array like data. Use only if X is not catboost.Pool. use_best_model : bool, optional (default=None) Flag to use best model eval_set : catboost.Pool or list, optional (default=None) A list of (X, y) tuple pairs to use as a validation set for early-stopping verbose : bool or int If verbose is bool, then if set to True, logging_level is set to Verbose, if set to False, logging_level is set to Silent. If verbose is int, it determines the frequency of writing metrics to output and logging_level is set to Verbose. logging_level : string, optional (default=None) Possible values: - 'Silent' - 'Verbose' - 'Info' - 'Debug' plot : bool, optional (default=False) If True, draw train and eval error in Jupyter notebook verbose_eval : bool or int Synonym for verbose. Only one of these parameters should be set. metric_period : int Frequency of evaluating metrics. silent : bool If silent is True, logging_level is set to Silent. If silent is False, logging_level is set to Verbose. early_stopping_rounds : int Activates Iter overfitting detector with od_wait set to early_stopping_rounds. save_snapshot : bool, [default=None] Enable progress snapshotting for restoring progress after crashes or interruptions snapshot_file : string or pathlib.Path, [default=None] Learn progress snapshot file path, if None will use default filename snapshot_interval: int, [default=600] Interval between saving snapshots (seconds) init_model : CatBoost class or string or pathlib.Path, [default=None] Continue training starting from the existing model. If this parameter is a string or pathlib.Path, load initial model from the path specified by this string. callbacks : list, optional (default=None) List of callback objects that are applied at end of each iteration. log_cout: output stream or callback for logging log_cerr: error stream or callback for logging Returns ------- model : CatBoost
Fit the CatBoostRanker model. Parameters ---------- X : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series If not catboost.Pool, 2 dimensional Feature matrix or string - file with dataset. y : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Labels, 1 dimensional array like. Use only if X is not catboost.Pool. group_id : numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Ranking groups, 1 dimensional array like. Use only if X is not catboost.Pool. cat_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Categ columns indices. Use only if X is not catboost.Pool. text_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Text columns indices. Use only if X is not catboost.Pool. embedding_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Embedding columns indices. Use only if X is not catboost.Pool. pairs : list or numpy.ndarray or pandas.DataFrame, optional (default=None) The pairs description in the form of a two-dimensional matrix of shape N by 2: N is the number of pairs. The first element of the pair is the zero-based index of the winner object from the input dataset for pairwise comparison. The second element of the pair is the zero-based index of the loser object from the input dataset for pairwise comparison. sample_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Instance weights, 1 dimensional array like. group_weight : list or numpy.ndarray (default=None) The weights of all objects within the defined groups from the input data in the form of one-dimensional array-like data. Used for calculating the final values of trees. By default, it is set to 1 for all objects in all groups. Only a weight or group_weight parameter can be used at a time subgroup_id : list or numpy.ndarray (default=None) Subgroup identifiers for all input objects. Supported identifier types are: int string types (string or unicode for Python 2 and bytes or string for Python 3). pairs_weight : list or numpy.ndarray (default=None) The weight of each input pair of objects in the form of one-dimensional array-like pairs. The number of given values must match the number of specified pairs. This information is used for calculation and optimization of Pairwise metrics . By default, it is set to 1 for all pairs. baseline : list or numpy.ndarray, optional (default=None) If not None, giving 2 dimensional array like data. Use only if X is not catboost.Pool. use_best_model : bool, optional (default=None) Flag to use best model eval_set : catboost.Pool or list, optional (default=None) A list of (X, y) tuple pairs to use as a validation set for early-stopping verbose : bool or int If verbose is bool, then if set to True, logging_level is set to Verbose, if set to False, logging_level is set to Silent. If verbose is int, it determines the frequency of writing metrics to output and logging_level is set to Verbose. logging_level : string, optional (default=None) Possible values: - 'Silent' - 'Verbose' - 'Info' - 'Debug' plot : bool, optional (default=False) If True, draw train and eval error in Jupyter notebook verbose_eval : bool or int Synonym for verbose. Only one of these parameters should be set. metric_period : int Frequency of evaluating metrics. silent : bool If silent is True, logging_level is set to Silent. If silent is False, logging_level is set to Verbose. early_stopping_rounds : int Activates Iter overfitting detector with od_wait set to early_stopping_rounds. save_snapshot : bool, [default=None] Enable progress snapshotting for restoring progress after crashes or interruptions snapshot_file : string or pathlib.Path, [default=None] Learn progress snapshot file path, if None will use default filename snapshot_interval: int, [default=600] Interval between saving snapshots (seconds) init_model : CatBoost class or string or pathlib.Path, [default=None] Continue training starting from the existing model. If this parameter is a string or pathlib.Path, load initial model from the path specified by this string. callbacks : list, optional (default=None) List of callback objects that are applied at end of each iteration.
[ "Fit", "the", "CatBoostRanker", "model", ".", "Parameters", "----------", "X", ":", "catboost", ".", "Pool", "or", "list", "or", "numpy", ".", "ndarray", "or", "pandas", ".", "DataFrame", "or", "pandas", ".", "Series", "If", "not", "catboost", ".", "Pool", "2", "dimensional", "Feature", "matrix", "or", "string", "-", "file", "with", "dataset", ".", "y", ":", "list", "or", "numpy", ".", "ndarray", "or", "pandas", ".", "DataFrame", "or", "pandas", ".", "Series", "optional", "(", "default", "=", "None", ")", "Labels", "1", "dimensional", "array", "like", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "group_id", ":", "numpy", ".", "ndarray", "or", "pandas", ".", "DataFrame", "or", "pandas", ".", "Series", "optional", "(", "default", "=", "None", ")", "Ranking", "groups", "1", "dimensional", "array", "like", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "cat_features", ":", "list", "or", "numpy", ".", "ndarray", "optional", "(", "default", "=", "None", ")", "If", "not", "None", "giving", "the", "list", "of", "Categ", "columns", "indices", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "text_features", ":", "list", "or", "numpy", ".", "ndarray", "optional", "(", "default", "=", "None", ")", "If", "not", "None", "giving", "the", "list", "of", "Text", "columns", "indices", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "embedding_features", ":", "list", "or", "numpy", ".", "ndarray", "optional", "(", "default", "=", "None", ")", "If", "not", "None", "giving", "the", "list", "of", "Embedding", "columns", "indices", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "pairs", ":", "list", "or", "numpy", ".", "ndarray", "or", "pandas", ".", "DataFrame", "optional", "(", "default", "=", "None", ")", "The", "pairs", "description", "in", "the", "form", "of", "a", "two", "-", "dimensional", "matrix", "of", "shape", "N", "by", "2", ":", "N", "is", "the", "number", "of", "pairs", ".", "The", "first", "element", "of", "the", "pair", "is", "the", "zero", "-", "based", "index", "of", "the", "winner", "object", "from", "the", "input", "dataset", "for", "pairwise", "comparison", ".", "The", "second", "element", "of", "the", "pair", "is", "the", "zero", "-", "based", "index", "of", "the", "loser", "object", "from", "the", "input", "dataset", "for", "pairwise", "comparison", ".", "sample_weight", ":", "list", "or", "numpy", ".", "ndarray", "or", "pandas", ".", "DataFrame", "or", "pandas", ".", "Series", "optional", "(", "default", "=", "None", ")", "Instance", "weights", "1", "dimensional", "array", "like", ".", "group_weight", ":", "list", "or", "numpy", ".", "ndarray", "(", "default", "=", "None", ")", "The", "weights", "of", "all", "objects", "within", "the", "defined", "groups", "from", "the", "input", "data", "in", "the", "form", "of", "one", "-", "dimensional", "array", "-", "like", "data", ".", "Used", "for", "calculating", "the", "final", "values", "of", "trees", ".", "By", "default", "it", "is", "set", "to", "1", "for", "all", "objects", "in", "all", "groups", ".", "Only", "a", "weight", "or", "group_weight", "parameter", "can", "be", "used", "at", "a", "time", "subgroup_id", ":", "list", "or", "numpy", ".", "ndarray", "(", "default", "=", "None", ")", "Subgroup", "identifiers", "for", "all", "input", "objects", ".", "Supported", "identifier", "types", "are", ":", "int", "string", "types", "(", "string", "or", "unicode", "for", "Python", "2", "and", "bytes", "or", "string", "for", "Python", "3", ")", ".", "pairs_weight", ":", "list", "or", "numpy", ".", "ndarray", "(", "default", "=", "None", ")", "The", "weight", "of", "each", "input", "pair", "of", "objects", "in", "the", "form", "of", "one", "-", "dimensional", "array", "-", "like", "pairs", ".", "The", "number", "of", "given", "values", "must", "match", "the", "number", "of", "specified", "pairs", ".", "This", "information", "is", "used", "for", "calculation", "and", "optimization", "of", "Pairwise", "metrics", ".", "By", "default", "it", "is", "set", "to", "1", "for", "all", "pairs", ".", "baseline", ":", "list", "or", "numpy", ".", "ndarray", "optional", "(", "default", "=", "None", ")", "If", "not", "None", "giving", "2", "dimensional", "array", "like", "data", ".", "Use", "only", "if", "X", "is", "not", "catboost", ".", "Pool", ".", "use_best_model", ":", "bool", "optional", "(", "default", "=", "None", ")", "Flag", "to", "use", "best", "model", "eval_set", ":", "catboost", ".", "Pool", "or", "list", "optional", "(", "default", "=", "None", ")", "A", "list", "of", "(", "X", "y", ")", "tuple", "pairs", "to", "use", "as", "a", "validation", "set", "for", "early", "-", "stopping", "verbose", ":", "bool", "or", "int", "If", "verbose", "is", "bool", "then", "if", "set", "to", "True", "logging_level", "is", "set", "to", "Verbose", "if", "set", "to", "False", "logging_level", "is", "set", "to", "Silent", ".", "If", "verbose", "is", "int", "it", "determines", "the", "frequency", "of", "writing", "metrics", "to", "output", "and", "logging_level", "is", "set", "to", "Verbose", ".", "logging_level", ":", "string", "optional", "(", "default", "=", "None", ")", "Possible", "values", ":", "-", "Silent", "-", "Verbose", "-", "Info", "-", "Debug", "plot", ":", "bool", "optional", "(", "default", "=", "False", ")", "If", "True", "draw", "train", "and", "eval", "error", "in", "Jupyter", "notebook", "verbose_eval", ":", "bool", "or", "int", "Synonym", "for", "verbose", ".", "Only", "one", "of", "these", "parameters", "should", "be", "set", ".", "metric_period", ":", "int", "Frequency", "of", "evaluating", "metrics", ".", "silent", ":", "bool", "If", "silent", "is", "True", "logging_level", "is", "set", "to", "Silent", ".", "If", "silent", "is", "False", "logging_level", "is", "set", "to", "Verbose", ".", "early_stopping_rounds", ":", "int", "Activates", "Iter", "overfitting", "detector", "with", "od_wait", "set", "to", "early_stopping_rounds", ".", "save_snapshot", ":", "bool", "[", "default", "=", "None", "]", "Enable", "progress", "snapshotting", "for", "restoring", "progress", "after", "crashes", "or", "interruptions", "snapshot_file", ":", "string", "or", "pathlib", ".", "Path", "[", "default", "=", "None", "]", "Learn", "progress", "snapshot", "file", "path", "if", "None", "will", "use", "default", "filename", "snapshot_interval", ":", "int", "[", "default", "=", "600", "]", "Interval", "between", "saving", "snapshots", "(", "seconds", ")", "init_model", ":", "CatBoost", "class", "or", "string", "or", "pathlib", ".", "Path", "[", "default", "=", "None", "]", "Continue", "training", "starting", "from", "the", "existing", "model", ".", "If", "this", "parameter", "is", "a", "string", "or", "pathlib", ".", "Path", "load", "initial", "model", "from", "the", "path", "specified", "by", "this", "string", ".", "callbacks", ":", "list", "optional", "(", "default", "=", "None", ")", "List", "of", "callback", "objects", "that", "are", "applied", "at", "end", "of", "each", "iteration", "." ]
def fit(self, X, y=None, group_id=None, cat_features=None, text_features=None, embedding_features=None, pairs=None, sample_weight=None, group_weight=None, subgroup_id=None, pairs_weight=None, baseline=None, use_best_model=None, eval_set=None, verbose=None, logging_level=None, plot=False, column_description=None, verbose_eval=None, metric_period=None, silent=None, early_stopping_rounds=None, save_snapshot=None, snapshot_file=None, snapshot_interval=None, init_model=None, callbacks=None, log_cout=sys.stdout, log_cerr=sys.stderr): """ Fit the CatBoostRanker model. Parameters ---------- X : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series If not catboost.Pool, 2 dimensional Feature matrix or string - file with dataset. y : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Labels, 1 dimensional array like. Use only if X is not catboost.Pool. group_id : numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Ranking groups, 1 dimensional array like. Use only if X is not catboost.Pool. cat_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Categ columns indices. Use only if X is not catboost.Pool. text_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Text columns indices. Use only if X is not catboost.Pool. embedding_features : list or numpy.ndarray, optional (default=None) If not None, giving the list of Embedding columns indices. Use only if X is not catboost.Pool. pairs : list or numpy.ndarray or pandas.DataFrame, optional (default=None) The pairs description in the form of a two-dimensional matrix of shape N by 2: N is the number of pairs. The first element of the pair is the zero-based index of the winner object from the input dataset for pairwise comparison. The second element of the pair is the zero-based index of the loser object from the input dataset for pairwise comparison. sample_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Instance weights, 1 dimensional array like. group_weight : list or numpy.ndarray (default=None) The weights of all objects within the defined groups from the input data in the form of one-dimensional array-like data. Used for calculating the final values of trees. By default, it is set to 1 for all objects in all groups. Only a weight or group_weight parameter can be used at a time subgroup_id : list or numpy.ndarray (default=None) Subgroup identifiers for all input objects. Supported identifier types are: int string types (string or unicode for Python 2 and bytes or string for Python 3). pairs_weight : list or numpy.ndarray (default=None) The weight of each input pair of objects in the form of one-dimensional array-like pairs. The number of given values must match the number of specified pairs. This information is used for calculation and optimization of Pairwise metrics . By default, it is set to 1 for all pairs. baseline : list or numpy.ndarray, optional (default=None) If not None, giving 2 dimensional array like data. Use only if X is not catboost.Pool. use_best_model : bool, optional (default=None) Flag to use best model eval_set : catboost.Pool or list, optional (default=None) A list of (X, y) tuple pairs to use as a validation set for early-stopping verbose : bool or int If verbose is bool, then if set to True, logging_level is set to Verbose, if set to False, logging_level is set to Silent. If verbose is int, it determines the frequency of writing metrics to output and logging_level is set to Verbose. logging_level : string, optional (default=None) Possible values: - 'Silent' - 'Verbose' - 'Info' - 'Debug' plot : bool, optional (default=False) If True, draw train and eval error in Jupyter notebook verbose_eval : bool or int Synonym for verbose. Only one of these parameters should be set. metric_period : int Frequency of evaluating metrics. silent : bool If silent is True, logging_level is set to Silent. If silent is False, logging_level is set to Verbose. early_stopping_rounds : int Activates Iter overfitting detector with od_wait set to early_stopping_rounds. save_snapshot : bool, [default=None] Enable progress snapshotting for restoring progress after crashes or interruptions snapshot_file : string or pathlib.Path, [default=None] Learn progress snapshot file path, if None will use default filename snapshot_interval: int, [default=600] Interval between saving snapshots (seconds) init_model : CatBoost class or string or pathlib.Path, [default=None] Continue training starting from the existing model. If this parameter is a string or pathlib.Path, load initial model from the path specified by this string. callbacks : list, optional (default=None) List of callback objects that are applied at end of each iteration. log_cout: output stream or callback for logging log_cerr: error stream or callback for logging Returns ------- model : CatBoost """ params = deepcopy(self._init_params) _process_synonyms(params) if 'loss_function' in params: CatBoostRanker._check_is_compatible_loss(params['loss_function']) self._fit(X, y, cat_features, text_features, embedding_features, pairs, sample_weight, group_id, group_weight, subgroup_id, pairs_weight, baseline, use_best_model, eval_set, verbose, logging_level, plot, column_description, verbose_eval, metric_period, silent, early_stopping_rounds, save_snapshot, snapshot_file, snapshot_interval, init_model, callbacks, log_cout, log_cerr) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "group_id", "=", "None", ",", "cat_features", "=", "None", ",", "text_features", "=", "None", ",", "embedding_features", "=", "None", ",", "pairs", "=", "None", ",", "sample_weight", "=", "None", ",", "group_weight", "=", "None", ",", "subgroup_id", "=", "None", ",", "pairs_weight", "=", "None", ",", "baseline", "=", "None", ",", "use_best_model", "=", "None", ",", "eval_set", "=", "None", ",", "verbose", "=", "None", ",", "logging_level", "=", "None", ",", "plot", "=", "False", ",", "column_description", "=", "None", ",", "verbose_eval", "=", "None", ",", "metric_period", "=", "None", ",", "silent", "=", "None", ",", "early_stopping_rounds", "=", "None", ",", "save_snapshot", "=", "None", ",", "snapshot_file", "=", "None", ",", "snapshot_interval", "=", "None", ",", "init_model", "=", "None", ",", "callbacks", "=", "None", ",", "log_cout", "=", "sys", ".", "stdout", ",", "log_cerr", "=", "sys", ".", "stderr", ")", ":", "params", "=", "deepcopy", "(", "self", ".", "_init_params", ")", "_process_synonyms", "(", "params", ")", "if", "'loss_function'", "in", "params", ":", "CatBoostRanker", ".", "_check_is_compatible_loss", "(", "params", "[", "'loss_function'", "]", ")", "self", ".", "_fit", "(", "X", ",", "y", ",", "cat_features", ",", "text_features", ",", "embedding_features", ",", "pairs", ",", "sample_weight", ",", "group_id", ",", "group_weight", ",", "subgroup_id", ",", "pairs_weight", ",", "baseline", ",", "use_best_model", ",", "eval_set", ",", "verbose", ",", "logging_level", ",", "plot", ",", "column_description", ",", "verbose_eval", ",", "metric_period", ",", "silent", ",", "early_stopping_rounds", ",", "save_snapshot", ",", "snapshot_file", ",", "snapshot_interval", ",", "init_model", ",", "callbacks", ",", "log_cout", ",", "log_cerr", ")", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/core.py#L5788-L5895
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/function.py
python
_TapeGradientFunctions.record
(self, flat_outputs, inference_args, input_tangents)
Record the function call operation. For backprop, indicates the backward function to use and which new Tensors must be watched. For forwardprop from eager, the function call itself will have produced tangents which need to be recorded. Args: flat_outputs: The result of running `forward`. inference_args: A flat list of Tensors with inference inputs to the operation. input_tangents: A flat list of Tensors with input tangents consumed by the operation.
Record the function call operation.
[ "Record", "the", "function", "call", "operation", "." ]
def record(self, flat_outputs, inference_args, input_tangents): """Record the function call operation. For backprop, indicates the backward function to use and which new Tensors must be watched. For forwardprop from eager, the function call itself will have produced tangents which need to be recorded. Args: flat_outputs: The result of running `forward`. inference_args: A flat list of Tensors with inference inputs to the operation. input_tangents: A flat list of Tensors with input tangents consumed by the operation. """ backward_function, to_record = self._wrap_backward_function( self._forward_graph, self._backward, flat_outputs) if self._forwardprop_output_indices: tape.record_operation_backprop_only( self._forward.signature.name, to_record, inference_args, backward_function) tape.record_operation_forwardprop_only( self._forward.signature.name, flat_outputs, inference_args + input_tangents, backward_function, self._forwardprop_output_indices) else: tape.record_operation(self._forward.signature.name, to_record, inference_args + input_tangents, backward_function)
[ "def", "record", "(", "self", ",", "flat_outputs", ",", "inference_args", ",", "input_tangents", ")", ":", "backward_function", ",", "to_record", "=", "self", ".", "_wrap_backward_function", "(", "self", ".", "_forward_graph", ",", "self", ".", "_backward", ",", "flat_outputs", ")", "if", "self", ".", "_forwardprop_output_indices", ":", "tape", ".", "record_operation_backprop_only", "(", "self", ".", "_forward", ".", "signature", ".", "name", ",", "to_record", ",", "inference_args", ",", "backward_function", ")", "tape", ".", "record_operation_forwardprop_only", "(", "self", ".", "_forward", ".", "signature", ".", "name", ",", "flat_outputs", ",", "inference_args", "+", "input_tangents", ",", "backward_function", ",", "self", ".", "_forwardprop_output_indices", ")", "else", ":", "tape", ".", "record_operation", "(", "self", ".", "_forward", ".", "signature", ".", "name", ",", "to_record", ",", "inference_args", "+", "input_tangents", ",", "backward_function", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L1211-L1240
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distribution/kl.py
python
kl_divergence
(p, q)
return _dispatch(type(p), type(q))(p, q)
r""" Kullback-Leibler divergence between distribution p and q. .. math:: KL(p||q) = \int p(x)log\frac{p(x)}{q(x)} \mathrm{d}x Args: p (Distribution): ``Distribution`` object. q (Distribution): ``Distribution`` object. Returns: Tensor: Batchwise KL-divergence between distribution p and q. Examples: .. code-block:: python import paddle p = paddle.distribution.Beta(alpha=0.5, beta=0.5) q = paddle.distribution.Beta(alpha=0.3, beta=0.7) print(paddle.distribution.kl_divergence(p, q)) # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [0.21193528])
r""" Kullback-Leibler divergence between distribution p and q.
[ "r", "Kullback", "-", "Leibler", "divergence", "between", "distribution", "p", "and", "q", "." ]
def kl_divergence(p, q): r""" Kullback-Leibler divergence between distribution p and q. .. math:: KL(p||q) = \int p(x)log\frac{p(x)}{q(x)} \mathrm{d}x Args: p (Distribution): ``Distribution`` object. q (Distribution): ``Distribution`` object. Returns: Tensor: Batchwise KL-divergence between distribution p and q. Examples: .. code-block:: python import paddle p = paddle.distribution.Beta(alpha=0.5, beta=0.5) q = paddle.distribution.Beta(alpha=0.3, beta=0.7) print(paddle.distribution.kl_divergence(p, q)) # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [0.21193528]) """ return _dispatch(type(p), type(q))(p, q)
[ "def", "kl_divergence", "(", "p", ",", "q", ")", ":", "return", "_dispatch", "(", "type", "(", "p", ")", ",", "type", "(", "q", ")", ")", "(", "p", ",", "q", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distribution/kl.py#L33-L62
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._get_local_index
(self, this_id, id_list, entity='entity')
return id_list.index(this_id)
Return the local index corresponding to the given id. If an entity is not present, throw an error. Example: >>> model._get_local_index(10, [10, 20, 30]) 0 >>> model._get_local_index('first', [10, 20, 30]) 10
Return the local index corresponding to the given id.
[ "Return", "the", "local", "index", "corresponding", "to", "the", "given", "id", "." ]
def _get_local_index(self, this_id, id_list, entity='entity'): """ Return the local index corresponding to the given id. If an entity is not present, throw an error. Example: >>> model._get_local_index(10, [10, 20, 30]) 0 >>> model._get_local_index('first', [10, 20, 30]) 10 """ if this_id == 'first': if not id_list: self._error( 'Undefined %s reference.' % entity, 'A reference to the first %s was encountered but ' 'no %ss are defined.' % (entity, entity)) return 0 if this_id == 'last': if not id_list: self._error( 'Undefined %s reference.' % entity, 'A reference to the last %s was encountered but ' 'no %ss are defined.' % (entity, entity)) return len(id_list) - 1 if this_id not in id_list: entity_list = ', '.join([str(x) for x in id_list]) self._error( 'Reference to undefined %s.' % entity, 'A reference to %s "%s" was encountered but is not ' 'defined in the model. There are %d defined %ss: %s' % (entity, str(this_id), len(id_list), entity, entity_list)) return id_list.index(this_id)
[ "def", "_get_local_index", "(", "self", ",", "this_id", ",", "id_list", ",", "entity", "=", "'entity'", ")", ":", "if", "this_id", "==", "'first'", ":", "if", "not", "id_list", ":", "self", ".", "_error", "(", "'Undefined %s reference.'", "%", "entity", ",", "'A reference to the first %s was encountered but '", "'no %ss are defined.'", "%", "(", "entity", ",", "entity", ")", ")", "return", "0", "if", "this_id", "==", "'last'", ":", "if", "not", "id_list", ":", "self", ".", "_error", "(", "'Undefined %s reference.'", "%", "entity", ",", "'A reference to the last %s was encountered but '", "'no %ss are defined.'", "%", "(", "entity", ",", "entity", ")", ")", "return", "len", "(", "id_list", ")", "-", "1", "if", "this_id", "not", "in", "id_list", ":", "entity_list", "=", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "id_list", "]", ")", "self", ".", "_error", "(", "'Reference to undefined %s.'", "%", "entity", ",", "'A reference to %s \"%s\" was encountered but is not '", "'defined in the model. There are %d defined %ss: %s'", "%", "(", "entity", ",", "str", "(", "this_id", ")", ",", "len", "(", "id_list", ")", ",", "entity", ",", "entity_list", ")", ")", "return", "id_list", ".", "index", "(", "this_id", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L3028-L3062
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler_machinery.py
python
PassManager.dependency_analysis
(self)
return dep_chain
Computes dependency analysis
Computes dependency analysis
[ "Computes", "dependency", "analysis" ]
def dependency_analysis(self): """ Computes dependency analysis """ deps = dict() for (pss, _) in self.passes: x = _pass_registry.get(pss).pass_inst au = AnalysisUsage() x.get_analysis_usage(au) deps[type(x)] = au requires_map = dict() for k, v in deps.items(): requires_map[k] = v.get_required_set() def resolve_requires(key, rmap): def walk(lkey, rmap): dep_set = set(rmap[lkey]) if dep_set: for x in dep_set: dep_set |= (walk(x, rmap)) return dep_set else: return set() ret = set() for k in key: ret |= walk(k, rmap) return ret dep_chain = dict() for k, v in requires_map.items(): dep_chain[k] = set(v) | (resolve_requires(v, requires_map)) return dep_chain
[ "def", "dependency_analysis", "(", "self", ")", ":", "deps", "=", "dict", "(", ")", "for", "(", "pss", ",", "_", ")", "in", "self", ".", "passes", ":", "x", "=", "_pass_registry", ".", "get", "(", "pss", ")", ".", "pass_inst", "au", "=", "AnalysisUsage", "(", ")", "x", ".", "get_analysis_usage", "(", "au", ")", "deps", "[", "type", "(", "x", ")", "]", "=", "au", "requires_map", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "deps", ".", "items", "(", ")", ":", "requires_map", "[", "k", "]", "=", "v", ".", "get_required_set", "(", ")", "def", "resolve_requires", "(", "key", ",", "rmap", ")", ":", "def", "walk", "(", "lkey", ",", "rmap", ")", ":", "dep_set", "=", "set", "(", "rmap", "[", "lkey", "]", ")", "if", "dep_set", ":", "for", "x", "in", "dep_set", ":", "dep_set", "|=", "(", "walk", "(", "x", ",", "rmap", ")", ")", "return", "dep_set", "else", ":", "return", "set", "(", ")", "ret", "=", "set", "(", ")", "for", "k", "in", "key", ":", "ret", "|=", "walk", "(", "k", ",", "rmap", ")", "return", "ret", "dep_chain", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "requires_map", ".", "items", "(", ")", ":", "dep_chain", "[", "k", "]", "=", "set", "(", "v", ")", "|", "(", "resolve_requires", "(", "v", ",", "requires_map", ")", ")", "return", "dep_chain" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler_machinery.py#L349-L382
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiPaneInfo.FloatingSize
(*args, **kwargs)
return _aui.AuiPaneInfo_FloatingSize(*args, **kwargs)
FloatingSize(self, Size size) -> AuiPaneInfo
FloatingSize(self, Size size) -> AuiPaneInfo
[ "FloatingSize", "(", "self", "Size", "size", ")", "-", ">", "AuiPaneInfo" ]
def FloatingSize(*args, **kwargs): """FloatingSize(self, Size size) -> AuiPaneInfo""" return _aui.AuiPaneInfo_FloatingSize(*args, **kwargs)
[ "def", "FloatingSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_FloatingSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L405-L407
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/appdirs.py
python
user_state_dir
(appname=None, appauthor=None, version=None, roaming=False)
return path
r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>".
r"""Return full path to the user-specific state dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "state", "dir", "for", "this", "application", "." ]
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
[ "def", "user_state_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "user_data_dir", "(", "appname", ",", "appauthor", ",", "None", ",", "roaming", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_STATE_HOME'", ",", "os", ".", "path", ".", "expanduser", "(", "\"~/.local/state\"", ")", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/appdirs.py#L325-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/sched.py
python
scheduler.empty
(self)
Check whether the queue is empty.
Check whether the queue is empty.
[ "Check", "whether", "the", "queue", "is", "empty", "." ]
def empty(self): """Check whether the queue is empty.""" with self._lock: return not self._queue
[ "def", "empty", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "return", "not", "self", ".", "_queue" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/sched.py#L99-L102
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Tools/CryVersionSelector/release_project.py
python
get_available_configurations
(engine_path)
return available_configurations
Returns the configurations that are available for this engine.
Returns the configurations that are available for this engine.
[ "Returns", "the", "configurations", "that", "are", "available", "for", "this", "engine", "." ]
def get_available_configurations(engine_path): """ Returns the configurations that are available for this engine. """ available_configurations = [] for key, value in DEFAULT_CONFIGURATIONS: win_path = os.path.join(engine_path, value, "GameLauncher.exe") linux_path = os.path.join(engine_path, value, "GameLauncher") if os.path.isfile(win_path) or os.path.isfile(linux_path): available_configurations.append((key, value)) return available_configurations
[ "def", "get_available_configurations", "(", "engine_path", ")", ":", "available_configurations", "=", "[", "]", "for", "key", ",", "value", "in", "DEFAULT_CONFIGURATIONS", ":", "win_path", "=", "os", ".", "path", ".", "join", "(", "engine_path", ",", "value", ",", "\"GameLauncher.exe\"", ")", "linux_path", "=", "os", ".", "path", ".", "join", "(", "engine_path", ",", "value", ",", "\"GameLauncher\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "win_path", ")", "or", "os", ".", "path", ".", "isfile", "(", "linux_path", ")", ":", "available_configurations", ".", "append", "(", "(", "key", ",", "value", ")", ")", "return", "available_configurations" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/release_project.py#L177-L188
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/subprocess.py
python
check_call
(*popenargs, **kwargs)
return 0
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the call function. Example: check_call(["ls", "-l"])
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.
[ "Run", "command", "with", "arguments", ".", "Wait", "for", "command", "to", "complete", ".", "If", "the", "exit", "code", "was", "zero", "then", "return", "otherwise", "raise", "CalledProcessError", ".", "The", "CalledProcessError", "object", "will", "have", "the", "return", "code", "in", "the", "returncode", "attribute", "." ]
def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the call function. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
[ "def", "check_call", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "retcode", "=", "call", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", "if", "retcode", ":", "cmd", "=", "kwargs", ".", "get", "(", "\"args\"", ")", "if", "cmd", "is", "None", ":", "cmd", "=", "popenargs", "[", "0", "]", "raise", "CalledProcessError", "(", "retcode", ",", "cmd", ")", "return", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/subprocess.py#L358-L374
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
EventFilter/L1TXRawToDigi/python/util/rrapi.py
python
RRApi.tables
(self, workspace)
return self.get([workspace, "tables"])
Get tables for workspace (all apps)
Get tables for workspace (all apps)
[ "Get", "tables", "for", "workspace", "(", "all", "apps", ")" ]
def tables(self, workspace): """ Get tables for workspace (all apps) """ return self.get([workspace, "tables"])
[ "def", "tables", "(", "self", ",", "workspace", ")", ":", "return", "self", ".", "get", "(", "[", "workspace", ",", "\"tables\"", "]", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/EventFilter/L1TXRawToDigi/python/util/rrapi.py#L134-L138
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/plan/cspaceutils.py
python
EmbeddedCSpace.project
(self,xamb)
return [xamb[i] for i in self.mapping]
Ambient space -> embedded space
Ambient space -> embedded space
[ "Ambient", "space", "-", ">", "embedded", "space" ]
def project(self,xamb): """Ambient space -> embedded space""" if len(xamb) != len(self.xinit): raise ValueError("Invalid length of ambient space vector: %d should be %d"%(len(xamb),len(self.xinit))) return [xamb[i] for i in self.mapping]
[ "def", "project", "(", "self", ",", "xamb", ")", ":", "if", "len", "(", "xamb", ")", "!=", "len", "(", "self", ".", "xinit", ")", ":", "raise", "ValueError", "(", "\"Invalid length of ambient space vector: %d should be %d\"", "%", "(", "len", "(", "xamb", ")", ",", "len", "(", "self", ".", "xinit", ")", ")", ")", "return", "[", "xamb", "[", "i", "]", "for", "i", "in", "self", ".", "mapping", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/cspaceutils.py#L172-L176
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/neighbors/base.py
python
UnsupervisedMixin.fit
(self, X, y=None)
return self._fit(X)
Fit the model using X as training data Parameters ---------- X : {array-like, sparse matrix, BallTree, KDTree} Training data. If array or matrix, shape [n_samples, n_features], or [n_samples, n_samples] if metric='precomputed'.
Fit the model using X as training data
[ "Fit", "the", "model", "using", "X", "as", "training", "data" ]
def fit(self, X, y=None): """Fit the model using X as training data Parameters ---------- X : {array-like, sparse matrix, BallTree, KDTree} Training data. If array or matrix, shape [n_samples, n_features], or [n_samples, n_samples] if metric='precomputed'. """ return self._fit(X)
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "return", "self", ".", "_fit", "(", "X", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/neighbors/base.py#L790-L799
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/glibc.py
python
glibc_version_string_confstr
()
return version
Primary implementation of glibc_version_string using os.confstr.
Primary implementation of glibc_version_string using os.confstr.
[ "Primary", "implementation", "of", "glibc_version_string", "using", "os", ".", "confstr", "." ]
def glibc_version_string_confstr(): # type: () -> Optional[str] "Primary implementation of glibc_version_string using os.confstr." # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module: # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183 if sys.platform == "win32": return None try: # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17": _, version = os.confstr("CS_GNU_LIBC_VERSION").split() except (AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version
[ "def", "glibc_version_string_confstr", "(", ")", ":", "# type: () -> Optional[str]", "# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely", "# to be broken or missing. This strategy is used in the standard library", "# platform module:", "# https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "return", "None", "try", ":", "# os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\":", "_", ",", "version", "=", "os", ".", "confstr", "(", "\"CS_GNU_LIBC_VERSION\"", ")", ".", "split", "(", ")", "except", "(", "AttributeError", ",", "OSError", ",", "ValueError", ")", ":", "# os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...", "return", "None", "return", "version" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/glibc.py#L37-L67
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/configs/config.py
python
Config._configure_engine_params
(self)
Converts engine config section into engine params dict
Converts engine config section into engine params dict
[ "Converts", "engine", "config", "section", "into", "engine", "params", "dict" ]
def _configure_engine_params(self): """ Converts engine config section into engine params dict """ engine = self.engine if 'type' not in engine or engine.type == 'accuracy_checker': self._configure_ac_params() self.engine.type = 'accuracy_checker' elif engine.type == 'simplified' or engine.type == 'data_free': if engine.data_source is None: raise KeyError(f'Missed data dir for {engine.type} engine') self.engine.device = engine.device if engine.device else 'CPU' engine.data_source = Path(engine.data_source) else: raise KeyError('Unsupported engine type')
[ "def", "_configure_engine_params", "(", "self", ")", ":", "engine", "=", "self", ".", "engine", "if", "'type'", "not", "in", "engine", "or", "engine", ".", "type", "==", "'accuracy_checker'", ":", "self", ".", "_configure_ac_params", "(", ")", "self", ".", "engine", ".", "type", "=", "'accuracy_checker'", "elif", "engine", ".", "type", "==", "'simplified'", "or", "engine", ".", "type", "==", "'data_free'", ":", "if", "engine", ".", "data_source", "is", "None", ":", "raise", "KeyError", "(", "f'Missed data dir for {engine.type} engine'", ")", "self", ".", "engine", ".", "device", "=", "engine", ".", "device", "if", "engine", ".", "device", "else", "'CPU'", "engine", ".", "data_source", "=", "Path", "(", "engine", ".", "data_source", ")", "else", ":", "raise", "KeyError", "(", "'Unsupported engine type'", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/configs/config.py#L305-L318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py
python
KeyBindings.get_bindings_for_keys
(self, keys: KeysTuple)
return self._get_bindings_for_keys_cache.get(keys, get)
Return a list of key bindings that can handle this key. (This return also inactive bindings, so the `filter` still has to be called, for checking it.) :param keys: tuple of keys.
Return a list of key bindings that can handle this key. (This return also inactive bindings, so the `filter` still has to be called, for checking it.)
[ "Return", "a", "list", "of", "key", "bindings", "that", "can", "handle", "this", "key", ".", "(", "This", "return", "also", "inactive", "bindings", "so", "the", "filter", "still", "has", "to", "be", "called", "for", "checking", "it", ".", ")" ]
def get_bindings_for_keys(self, keys: KeysTuple) -> List[Binding]: """ Return a list of key bindings that can handle this key. (This return also inactive bindings, so the `filter` still has to be called, for checking it.) :param keys: tuple of keys. """ def get() -> List[Binding]: result: List[Tuple[int, Binding]] = [] for b in self.bindings: if len(keys) == len(b.keys): match = True any_count = 0 for i, j in zip(b.keys, keys): if i != j and i != Keys.Any: match = False break if i == Keys.Any: any_count += 1 if match: result.append((any_count, b)) # Place bindings that have more 'Any' occurrences in them at the end. result = sorted(result, key=lambda item: -item[0]) return [item[1] for item in result] return self._get_bindings_for_keys_cache.get(keys, get)
[ "def", "get_bindings_for_keys", "(", "self", ",", "keys", ":", "KeysTuple", ")", "->", "List", "[", "Binding", "]", ":", "def", "get", "(", ")", "->", "List", "[", "Binding", "]", ":", "result", ":", "List", "[", "Tuple", "[", "int", ",", "Binding", "]", "]", "=", "[", "]", "for", "b", "in", "self", ".", "bindings", ":", "if", "len", "(", "keys", ")", "==", "len", "(", "b", ".", "keys", ")", ":", "match", "=", "True", "any_count", "=", "0", "for", "i", ",", "j", "in", "zip", "(", "b", ".", "keys", ",", "keys", ")", ":", "if", "i", "!=", "j", "and", "i", "!=", "Keys", ".", "Any", ":", "match", "=", "False", "break", "if", "i", "==", "Keys", ".", "Any", ":", "any_count", "+=", "1", "if", "match", ":", "result", ".", "append", "(", "(", "any_count", ",", "b", ")", ")", "# Place bindings that have more 'Any' occurrences in them at the end.", "result", "=", "sorted", "(", "result", ",", "key", "=", "lambda", "item", ":", "-", "item", "[", "0", "]", ")", "return", "[", "item", "[", "1", "]", "for", "item", "in", "result", "]", "return", "self", ".", "_get_bindings_for_keys_cache", ".", "get", "(", "keys", ",", "get", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py#L368-L401
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/operators/slices.py
python
_tf_tensor_get_item
(target, i)
return target[i]
Overload of get_item that stages a Tensor (not Tensor list) read.
Overload of get_item that stages a Tensor (not Tensor list) read.
[ "Overload", "of", "get_item", "that", "stages", "a", "Tensor", "(", "not", "Tensor", "list", ")", "read", "." ]
def _tf_tensor_get_item(target, i): """Overload of get_item that stages a Tensor (not Tensor list) read.""" return target[i]
[ "def", "_tf_tensor_get_item", "(", "target", ",", "i", ")", ":", "return", "target", "[", "i", "]" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/slices.py#L80-L82
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
RobotModel.getCoriolisForces
(self)
return _robotsim.RobotModel_getCoriolisForces(self)
getCoriolisForces(RobotModel self) Returns the Coriolis forces C(q,dq)*dq for current config and velocity. Takes O(n) time, which is faster than computing matrix and doing product. ("Forces" is somewhat of a misnomer; the result is a joint torque vector)
getCoriolisForces(RobotModel self)
[ "getCoriolisForces", "(", "RobotModel", "self", ")" ]
def getCoriolisForces(self): """ getCoriolisForces(RobotModel self) Returns the Coriolis forces C(q,dq)*dq for current config and velocity. Takes O(n) time, which is faster than computing matrix and doing product. ("Forces" is somewhat of a misnomer; the result is a joint torque vector) """ return _robotsim.RobotModel_getCoriolisForces(self)
[ "def", "getCoriolisForces", "(", "self", ")", ":", "return", "_robotsim", ".", "RobotModel_getCoriolisForces", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L4971-L4982
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__setitem__
(self, key, value)
Sets the item on the specified position.
Sets the item on the specified position.
[ "Sets", "the", "item", "on", "the", "specified", "position", "." ]
def __setitem__(self, key, value): """Sets the item on the specified position.""" if isinstance(key, slice): # PY3 if key.step is not None: raise ValueError('Extended slices not supported') self.__setslice__(key.start, key.stop, value) else: self._values[key] = self._type_checker.CheckValue(value) self._message_listener.Modified()
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "isinstance", "(", "key", ",", "slice", ")", ":", "# PY3", "if", "key", ".", "step", "is", "not", "None", ":", "raise", "ValueError", "(", "'Extended slices not supported'", ")", "self", ".", "__setslice__", "(", "key", ".", "start", ",", "key", ".", "stop", ",", "value", ")", "else", ":", "self", ".", "_values", "[", "key", "]", "=", "self", ".", "_type_checker", ".", "CheckValue", "(", "value", ")", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/containers.py#L298-L306
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/matlab/mio.py
python
mat_reader_factory
(file_name, appendmat=True, **kwargs)
Create reader for matlab .mat format files. Parameters ---------- %(file_arg)s %(append_arg)s %(load_args)s %(struct_arg)s Returns ------- matreader : MatFileReader object Initialized instance of MatFileReader class matching the mat file type detected in `filename`. file_opened : bool Whether the file was opened by this routine.
Create reader for matlab .mat format files.
[ "Create", "reader", "for", "matlab", ".", "mat", "format", "files", "." ]
def mat_reader_factory(file_name, appendmat=True, **kwargs): """ Create reader for matlab .mat format files. Parameters ---------- %(file_arg)s %(append_arg)s %(load_args)s %(struct_arg)s Returns ------- matreader : MatFileReader object Initialized instance of MatFileReader class matching the mat file type detected in `filename`. file_opened : bool Whether the file was opened by this routine. """ byte_stream, file_opened = _open_file(file_name, appendmat) mjv, mnv = get_matfile_version(byte_stream) if mjv == 0: return MatFile4Reader(byte_stream, **kwargs), file_opened elif mjv == 1: return MatFile5Reader(byte_stream, **kwargs), file_opened elif mjv == 2: raise NotImplementedError('Please use HDF reader for matlab v7.3 files') else: raise TypeError('Did not recognize version %s' % mjv)
[ "def", "mat_reader_factory", "(", "file_name", ",", "appendmat", "=", "True", ",", "*", "*", "kwargs", ")", ":", "byte_stream", ",", "file_opened", "=", "_open_file", "(", "file_name", ",", "appendmat", ")", "mjv", ",", "mnv", "=", "get_matfile_version", "(", "byte_stream", ")", "if", "mjv", "==", "0", ":", "return", "MatFile4Reader", "(", "byte_stream", ",", "*", "*", "kwargs", ")", ",", "file_opened", "elif", "mjv", "==", "1", ":", "return", "MatFile5Reader", "(", "byte_stream", ",", "*", "*", "kwargs", ")", ",", "file_opened", "elif", "mjv", "==", "2", ":", "raise", "NotImplementedError", "(", "'Please use HDF reader for matlab v7.3 files'", ")", "else", ":", "raise", "TypeError", "(", "'Did not recognize version %s'", "%", "mjv", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/mio.py#L42-L71
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
clang/utils/check_cfc/check_cfc.py
python
set_output_file
(args, output_file)
return args
Set the output file within the arguments. Appends or replaces as appropriate.
Set the output file within the arguments. Appends or replaces as appropriate.
[ "Set", "the", "output", "file", "within", "the", "arguments", ".", "Appends", "or", "replaces", "as", "appropriate", "." ]
def set_output_file(args, output_file): """Set the output file within the arguments. Appends or replaces as appropriate.""" if is_output_specified(args): args = replace_output_file(args, output_file) else: args = add_output_file(args, output_file) return args
[ "def", "set_output_file", "(", "args", ",", "output_file", ")", ":", "if", "is_output_specified", "(", "args", ")", ":", "args", "=", "replace_output_file", "(", "args", ",", "output_file", ")", "else", ":", "args", "=", "add_output_file", "(", "args", ",", "output_file", ")", "return", "args" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/utils/check_cfc/check_cfc.py#L176-L183
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/random.py
python
Random.gauss
(self, mu, sigma)
return mu + z*sigma
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.
Gaussian distribution.
[ "Gaussian", "distribution", "." ]
def gauss(self, mu, sigma): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z*sigma
[ "def", "gauss", "(", "self", ",", "mu", ",", "sigma", ")", ":", "# When x and y are two variables from [0, 1), uniformly", "# distributed, then", "#", "# cos(2*pi*x)*sqrt(-2*log(1-y))", "# sin(2*pi*x)*sqrt(-2*log(1-y))", "#", "# are two *independent* variables with normal distribution", "# (mu = 0, sigma = 1).", "# (Lambert Meertens)", "# (corrected version; bug discovered by Mike Miller, fixed by LM)", "# Multithreading note: When two threads call this function", "# simultaneously, it is possible that they will receive the", "# same return value. The window is very small though. To", "# avoid this, you have to use a lock around all calls. (I", "# didn't want to slow this down in the serial case by using a", "# lock here.)", "random", "=", "self", ".", "random", "z", "=", "self", ".", "gauss_next", "self", ".", "gauss_next", "=", "None", "if", "z", "is", "None", ":", "x2pi", "=", "random", "(", ")", "*", "TWOPI", "g2rad", "=", "_sqrt", "(", "-", "2.0", "*", "_log", "(", "1.0", "-", "random", "(", ")", ")", ")", "z", "=", "_cos", "(", "x2pi", ")", "*", "g2rad", "self", ".", "gauss_next", "=", "_sin", "(", "x2pi", ")", "*", "g2rad", "return", "mu", "+", "z", "*", "sigma" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/random.py#L556-L593
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/ikfast_generator_cpp.py
python
CodeGenerator.generateSolution
(self, node,declarearray=True,acceptfreevars=True)
return code.getvalue()
writes the solution of one variable :param declarearray: if False, will return the equations to be written without evaluating them. Used for conditioned solutions.
writes the solution of one variable :param declarearray: if False, will return the equations to be written without evaluating them. Used for conditioned solutions.
[ "writes", "the", "solution", "of", "one", "variable", ":", "param", "declarearray", ":", "if", "False", "will", "return", "the", "equations", "to", "be", "written", "without", "evaluating", "them", ".", "Used", "for", "conditioned", "solutions", "." ]
def generateSolution(self, node,declarearray=True,acceptfreevars=True): """writes the solution of one variable :param declarearray: if False, will return the equations to be written without evaluating them. Used for conditioned solutions. """ code = StringIO() numsolutions = 0 eqcode = StringIO() name = node.jointname self._solutioncounter += 1 log.info('c=%d var=%s', self._solutioncounter, name) node.HasFreeVar = False allnumsolutions = 0 #log.info('generateSolution %s (%d)', name, len(node.dictequations)) self.WriteDictEquations(node.dictequations, code=eqcode) # for var,value in node.dictequations: # eqcode.write('IkReal %s;\n'%var) # self.WriteEquations2(lambda k: var,value,code=eqcode) if node.jointeval is not None: numsolutions = len(node.jointeval) equations = [] names = [] for i,expr in enumerate(node.jointeval): if acceptfreevars and self.freevars is not None: m = None for freevar in self.freevars: if expr.has(Symbol(freevar)): # has free variables, so have to look for a*freevar+b form a = Wild('a',exclude=[Symbol(freevar)]) b = Wild('b',exclude=[Symbol(freevar)]) m = expr.match(a*Symbol(freevar)+b) if m is not None: self.freevardependencies.append((freevar,name)) assert(len(node.jointeval)==1) self.WriteEquations2(lambda i: '%smul'%name, m[a], code=code) self.WriteEquations2(lambda i: name, m[b],code=code) node.HasFreeVar = True return code.getvalue() else: log.error('failed to extract free variable %s for %s from: eq=%s', freevar,node.jointname, expr) # m = dict() # m[a] = Float(-1,30) # m[b] = Float(0,30) equations.append(expr) names.append('%sarray[%d]'%(name,allnumsolutions+i)) equations.append(sin(Symbol('%sarray[%d]'%(name,allnumsolutions+i)))) names.append('s%sarray[%d]'%(name,allnumsolutions+i)) equations.append(cos(Symbol('%sarray[%d]'%(name,allnumsolutions+i)))) names.append('c%sarray[%d]'%(name,allnumsolutions+i)) self.WriteEquations2(lambda i: names[i], equations,code=eqcode) if node.AddPiIfNegativeEq: for i in range(numsolutions): eqcode.write('%sarray[%d] = %sarray[%d] > 0 ? %sarray[%d]-IKPI : %sarray[%d]+IKPI;\n'%(name,allnumsolutions+numsolutions+i,name,allnumsolutions+i,name,allnumsolutions+i,name,allnumsolutions+i)) eqcode.write('s%sarray[%d] = -s%sarray[%d];\n'%(name,allnumsolutions+numsolutions+i,name,allnumsolutions+i)) eqcode.write('c%sarray[%d] = -c%sarray[%d];\n'%(name,allnumsolutions+numsolutions+i,name,allnumsolutions+i)) numsolutions *= 2 for i in range(numsolutions): if node.isHinge: eqcode.write('if( %sarray[%d] > IKPI )\n{\n %sarray[%d]-=IK2PI;\n}\nelse if( %sarray[%d] < -IKPI )\n{ %sarray[%d]+=IK2PI;\n}\n'%(name,allnumsolutions+i,name,allnumsolutions+i,name,allnumsolutions+i,name,allnumsolutions+i)) eqcode.write('%svalid[%d] = true;\n'%(name,allnumsolutions+i)) allnumsolutions += numsolutions # might also have cos solutions ... if node.jointevalcos is not None: numsolutions = 2*len(node.jointevalcos) self.WriteEquations2(lambda i: 'c%sarray[%d]'%(name,allnumsolutions+2*i),node.jointevalcos,code=eqcode) for i in range(len(node.jointevalcos)): eqcode.write('if( c%sarray[%d] >= -1-IKFAST_SINCOS_THRESH && c%sarray[%d] <= 1+IKFAST_SINCOS_THRESH )\n{\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write(' %svalid[%d] = %svalid[%d] = true;\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i+1)) eqcode.write(' %sarray[%d] = IKacos(c%sarray[%d]);\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write(' s%sarray[%d] = IKsin(%sarray[%d]);\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) # second solution eqcode.write(' c%sarray[%d] = c%sarray[%d];\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i)) eqcode.write(' %sarray[%d] = -%sarray[%d];\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i)) eqcode.write(' s%sarray[%d] = -s%sarray[%d];\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i)) eqcode.write('}\n') eqcode.write('else if( isnan(c%sarray[%d]) )\n{\n'%(name,allnumsolutions+2*i)) eqcode.write(' // probably any value will work\n') eqcode.write(' %svalid[%d] = true;\n'%(name,allnumsolutions+2*i)) eqcode.write(' c%sarray[%d] = 1; s%sarray[%d] = 0; %sarray[%d] = 0;\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write('}\n') allnumsolutions += numsolutions if node.jointevalsin is not None: numsolutions = 2*len(node.jointevalsin) self.WriteEquations2(lambda i: 's%sarray[%d]'%(name,allnumsolutions+2*i),node.jointevalsin,code=eqcode) for i in range(len(node.jointevalsin)): eqcode.write('if( s%sarray[%d] >= -1-IKFAST_SINCOS_THRESH && s%sarray[%d] <= 1+IKFAST_SINCOS_THRESH )\n{\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write(' %svalid[%d] = %svalid[%d] = true;\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i+1)) eqcode.write(' %sarray[%d] = IKasin(s%sarray[%d]);\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write(' c%sarray[%d] = IKcos(%sarray[%d]);\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i)) # second solution eqcode.write(' s%sarray[%d] = s%sarray[%d];\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i)) eqcode.write(' %sarray[%d] = %sarray[%d] > 0 ? (IKPI-%sarray[%d]) : (-IKPI-%sarray[%d]);\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i,name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write(' c%sarray[%d] = -c%sarray[%d];\n'%(name,allnumsolutions+2*i+1,name,allnumsolutions+2*i)) eqcode.write('}\n') eqcode.write('else if( isnan(s%sarray[%d]) )\n{\n'%(name,allnumsolutions+2*i)) eqcode.write(' // probably any value will work\n') eqcode.write(' %svalid[%d] = true;\n'%(name,allnumsolutions+2*i)) eqcode.write(' c%sarray[%d] = 1; s%sarray[%d] = 0; %sarray[%d] = 0;\n'%(name,allnumsolutions+2*i,name,allnumsolutions+2*i,name,allnumsolutions+2*i)) eqcode.write('}\n') allnumsolutions += numsolutions if not declarearray: return eqcode.getvalue(),allnumsolutions code.write('{\nIkReal %sarray[%d], c%sarray[%d], s%sarray[%d];\n'%(name,allnumsolutions,name,allnumsolutions,name,allnumsolutions)) code.write('bool %svalid[%d]={false};\n'%(name,allnumsolutions)) code.write('_n%s = %d;\n'%(name,allnumsolutions)) code.write(eqcode.getvalue()) if allnumsolutions > 1: if allnumsolutions >= 256: log.error('num solutions is %d>=256, which exceeds unsigned char',allnumsolutions) code.write('for(int i%s = 0; i%s < %d; ++i%s)\n{\n'%(name,name,allnumsolutions,name)) code.write('if( !%svalid[i%s] )\n{\n continue;\n}\n'%(name,name)) code.write('_i%s[0] = i%s; _i%s[1] = -1;\n'%(name,name,name)) # check for a similar solution code.write('for(int ii%s = i%s+1; ii%s < %d; ++ii%s)\n{\n'%(name,name,name,allnumsolutions,name)) code.write('if( %svalid[ii%s] && IKabs(c%sarray[i%s]-c%sarray[ii%s]) < IKFAST_SOLUTION_THRESH && IKabs(s%sarray[i%s]-s%sarray[ii%s]) < IKFAST_SOLUTION_THRESH )\n{\n %svalid[ii%s]=false; _i%s[1] = ii%s; break; \n}\n'%(name,name,name,name,name,name,name,name,name,name,name,name,name,name)) code.write('}\n') code.write('%s = %sarray[i%s]; c%s = c%sarray[i%s]; s%s = s%sarray[i%s];\n'%(name,name,name,name,name,name,name,name,name)) if node.AddHalfTanValue: code.write('ht%s = IKtan(%s/2);\n'%(name,name)) if node.getEquationsUsed() is not None and len(node.getEquationsUsed()) > 0: code.write('{\nIkReal evalcond[%d];\n'%len(node.getEquationsUsed())) self.WriteEquations2(lambda i: 'evalcond[%d]'%(i),node.getEquationsUsed(),code=code) code.write('if( ') for i in range(len(node.getEquationsUsed())): if i != 0: code.write(' || ') # using smaller node.thresh increases the missing solution rate, really not sure whether the solutions themselves # are bad due to double precision arithmetic, or due to singularities code.write('IKabs(evalcond[%d]) > IKFAST_EVALCOND_THRESH '%(i)) code.write(' )\n{\n') #code += 'cout <<' #code += '<<'.join(['evalcond[%d]'%i for i in range(len(node.getEquationsUsed()))]) #code += '<< endl;' code.write('continue;\n}\n') code.write('}\n') code.write('\n') return code.getvalue()
[ "def", "generateSolution", "(", "self", ",", "node", ",", "declarearray", "=", "True", ",", "acceptfreevars", "=", "True", ")", ":", "code", "=", "StringIO", "(", ")", "numsolutions", "=", "0", "eqcode", "=", "StringIO", "(", ")", "name", "=", "node", ".", "jointname", "self", ".", "_solutioncounter", "+=", "1", "log", ".", "info", "(", "'c=%d var=%s'", ",", "self", ".", "_solutioncounter", ",", "name", ")", "node", ".", "HasFreeVar", "=", "False", "allnumsolutions", "=", "0", "#log.info('generateSolution %s (%d)', name, len(node.dictequations))", "self", ".", "WriteDictEquations", "(", "node", ".", "dictequations", ",", "code", "=", "eqcode", ")", "# for var,value in node.dictequations:", "# eqcode.write('IkReal %s;\\n'%var)", "# self.WriteEquations2(lambda k: var,value,code=eqcode)", "if", "node", ".", "jointeval", "is", "not", "None", ":", "numsolutions", "=", "len", "(", "node", ".", "jointeval", ")", "equations", "=", "[", "]", "names", "=", "[", "]", "for", "i", ",", "expr", "in", "enumerate", "(", "node", ".", "jointeval", ")", ":", "if", "acceptfreevars", "and", "self", ".", "freevars", "is", "not", "None", ":", "m", "=", "None", "for", "freevar", "in", "self", ".", "freevars", ":", "if", "expr", ".", "has", "(", "Symbol", "(", "freevar", ")", ")", ":", "# has free variables, so have to look for a*freevar+b form", "a", "=", "Wild", "(", "'a'", ",", "exclude", "=", "[", "Symbol", "(", "freevar", ")", "]", ")", "b", "=", "Wild", "(", "'b'", ",", "exclude", "=", "[", "Symbol", "(", "freevar", ")", "]", ")", "m", "=", "expr", ".", "match", "(", "a", "*", "Symbol", "(", "freevar", ")", "+", "b", ")", "if", "m", "is", "not", "None", ":", "self", ".", "freevardependencies", ".", "append", "(", "(", "freevar", ",", "name", ")", ")", "assert", "(", "len", "(", "node", ".", "jointeval", ")", "==", "1", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "'%smul'", "%", "name", ",", "m", "[", "a", "]", ",", "code", "=", "code", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "name", ",", "m", "[", "b", "]", ",", "code", "=", "code", ")", "node", ".", "HasFreeVar", "=", "True", "return", "code", ".", "getvalue", "(", ")", "else", ":", "log", ".", "error", "(", "'failed to extract free variable %s for %s from: eq=%s'", ",", "freevar", ",", "node", ".", "jointname", ",", "expr", ")", "# m = dict()", "# m[a] = Float(-1,30)", "# m[b] = Float(0,30)", "equations", ".", "append", "(", "expr", ")", "names", ".", "append", "(", "'%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", "equations", ".", "append", "(", "sin", "(", "Symbol", "(", "'%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", ")", ")", "names", ".", "append", "(", "'s%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", "equations", ".", "append", "(", "cos", "(", "Symbol", "(", "'%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", ")", ")", "names", ".", "append", "(", "'c%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "names", "[", "i", "]", ",", "equations", ",", "code", "=", "eqcode", ")", "if", "node", ".", "AddPiIfNegativeEq", ":", "for", "i", "in", "range", "(", "numsolutions", ")", ":", "eqcode", ".", "write", "(", "'%sarray[%d] = %sarray[%d] > 0 ? %sarray[%d]-IKPI : %sarray[%d]+IKPI;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "numsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ")", ")", "eqcode", ".", "write", "(", "'s%sarray[%d] = -s%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "numsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ")", ")", "eqcode", ".", "write", "(", "'c%sarray[%d] = -c%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "numsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ")", ")", "numsolutions", "*=", "2", "for", "i", "in", "range", "(", "numsolutions", ")", ":", "if", "node", ".", "isHinge", ":", "eqcode", ".", "write", "(", "'if( %sarray[%d] > IKPI )\\n{\\n %sarray[%d]-=IK2PI;\\n}\\nelse if( %sarray[%d] < -IKPI )\\n{ %sarray[%d]+=IK2PI;\\n}\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ",", "name", ",", "allnumsolutions", "+", "i", ")", ")", "eqcode", ".", "write", "(", "'%svalid[%d] = true;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "i", ")", ")", "allnumsolutions", "+=", "numsolutions", "# might also have cos solutions ...", "if", "node", ".", "jointevalcos", "is", "not", "None", ":", "numsolutions", "=", "2", "*", "len", "(", "node", ".", "jointevalcos", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "'c%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ",", "node", ".", "jointevalcos", ",", "code", "=", "eqcode", ")", "for", "i", "in", "range", "(", "len", "(", "node", ".", "jointevalcos", ")", ")", ":", "eqcode", ".", "write", "(", "'if( c%sarray[%d] >= -1-IKFAST_SINCOS_THRESH && c%sarray[%d] <= 1+IKFAST_SINCOS_THRESH )\\n{\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' %svalid[%d] = %svalid[%d] = true;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ")", ")", "eqcode", ".", "write", "(", "' %sarray[%d] = IKacos(c%sarray[%d]);\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' s%sarray[%d] = IKsin(%sarray[%d]);\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "# second solution", "eqcode", ".", "write", "(", "' c%sarray[%d] = c%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' %sarray[%d] = -%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' s%sarray[%d] = -s%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "'}\\n'", ")", "eqcode", ".", "write", "(", "'else if( isnan(c%sarray[%d]) )\\n{\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' // probably any value will work\\n'", ")", "eqcode", ".", "write", "(", "' %svalid[%d] = true;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' c%sarray[%d] = 1; s%sarray[%d] = 0; %sarray[%d] = 0;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "'}\\n'", ")", "allnumsolutions", "+=", "numsolutions", "if", "node", ".", "jointevalsin", "is", "not", "None", ":", "numsolutions", "=", "2", "*", "len", "(", "node", ".", "jointevalsin", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "'s%sarray[%d]'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ",", "node", ".", "jointevalsin", ",", "code", "=", "eqcode", ")", "for", "i", "in", "range", "(", "len", "(", "node", ".", "jointevalsin", ")", ")", ":", "eqcode", ".", "write", "(", "'if( s%sarray[%d] >= -1-IKFAST_SINCOS_THRESH && s%sarray[%d] <= 1+IKFAST_SINCOS_THRESH )\\n{\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' %svalid[%d] = %svalid[%d] = true;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ")", ")", "eqcode", ".", "write", "(", "' %sarray[%d] = IKasin(s%sarray[%d]);\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' c%sarray[%d] = IKcos(%sarray[%d]);\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "# second solution", "eqcode", ".", "write", "(", "' s%sarray[%d] = s%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' %sarray[%d] = %sarray[%d] > 0 ? (IKPI-%sarray[%d]) : (-IKPI-%sarray[%d]);\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' c%sarray[%d] = -c%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", "+", "1", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "'}\\n'", ")", "eqcode", ".", "write", "(", "'else if( isnan(s%sarray[%d]) )\\n{\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' // probably any value will work\\n'", ")", "eqcode", ".", "write", "(", "' %svalid[%d] = true;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "' c%sarray[%d] = 1; s%sarray[%d] = 0; %sarray[%d] = 0;\\n'", "%", "(", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ",", "name", ",", "allnumsolutions", "+", "2", "*", "i", ")", ")", "eqcode", ".", "write", "(", "'}\\n'", ")", "allnumsolutions", "+=", "numsolutions", "if", "not", "declarearray", ":", "return", "eqcode", ".", "getvalue", "(", ")", ",", "allnumsolutions", "code", ".", "write", "(", "'{\\nIkReal %sarray[%d], c%sarray[%d], s%sarray[%d];\\n'", "%", "(", "name", ",", "allnumsolutions", ",", "name", ",", "allnumsolutions", ",", "name", ",", "allnumsolutions", ")", ")", "code", ".", "write", "(", "'bool %svalid[%d]={false};\\n'", "%", "(", "name", ",", "allnumsolutions", ")", ")", "code", ".", "write", "(", "'_n%s = %d;\\n'", "%", "(", "name", ",", "allnumsolutions", ")", ")", "code", ".", "write", "(", "eqcode", ".", "getvalue", "(", ")", ")", "if", "allnumsolutions", ">", "1", ":", "if", "allnumsolutions", ">=", "256", ":", "log", ".", "error", "(", "'num solutions is %d>=256, which exceeds unsigned char'", ",", "allnumsolutions", ")", "code", ".", "write", "(", "'for(int i%s = 0; i%s < %d; ++i%s)\\n{\\n'", "%", "(", "name", ",", "name", ",", "allnumsolutions", ",", "name", ")", ")", "code", ".", "write", "(", "'if( !%svalid[i%s] )\\n{\\n continue;\\n}\\n'", "%", "(", "name", ",", "name", ")", ")", "code", ".", "write", "(", "'_i%s[0] = i%s; _i%s[1] = -1;\\n'", "%", "(", "name", ",", "name", ",", "name", ")", ")", "# check for a similar solution", "code", ".", "write", "(", "'for(int ii%s = i%s+1; ii%s < %d; ++ii%s)\\n{\\n'", "%", "(", "name", ",", "name", ",", "name", ",", "allnumsolutions", ",", "name", ")", ")", "code", ".", "write", "(", "'if( %svalid[ii%s] && IKabs(c%sarray[i%s]-c%sarray[ii%s]) < IKFAST_SOLUTION_THRESH && IKabs(s%sarray[i%s]-s%sarray[ii%s]) < IKFAST_SOLUTION_THRESH )\\n{\\n %svalid[ii%s]=false; _i%s[1] = ii%s; break; \\n}\\n'", "%", "(", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ")", ")", "code", ".", "write", "(", "'}\\n'", ")", "code", ".", "write", "(", "'%s = %sarray[i%s]; c%s = c%sarray[i%s]; s%s = s%sarray[i%s];\\n'", "%", "(", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ",", "name", ")", ")", "if", "node", ".", "AddHalfTanValue", ":", "code", ".", "write", "(", "'ht%s = IKtan(%s/2);\\n'", "%", "(", "name", ",", "name", ")", ")", "if", "node", ".", "getEquationsUsed", "(", ")", "is", "not", "None", "and", "len", "(", "node", ".", "getEquationsUsed", "(", ")", ")", ">", "0", ":", "code", ".", "write", "(", "'{\\nIkReal evalcond[%d];\\n'", "%", "len", "(", "node", ".", "getEquationsUsed", "(", ")", ")", ")", "self", ".", "WriteEquations2", "(", "lambda", "i", ":", "'evalcond[%d]'", "%", "(", "i", ")", ",", "node", ".", "getEquationsUsed", "(", ")", ",", "code", "=", "code", ")", "code", ".", "write", "(", "'if( '", ")", "for", "i", "in", "range", "(", "len", "(", "node", ".", "getEquationsUsed", "(", ")", ")", ")", ":", "if", "i", "!=", "0", ":", "code", ".", "write", "(", "' || '", ")", "# using smaller node.thresh increases the missing solution rate, really not sure whether the solutions themselves", "# are bad due to double precision arithmetic, or due to singularities", "code", ".", "write", "(", "'IKabs(evalcond[%d]) > IKFAST_EVALCOND_THRESH '", "%", "(", "i", ")", ")", "code", ".", "write", "(", "' )\\n{\\n'", ")", "#code += 'cout <<'", "#code += '<<'.join(['evalcond[%d]'%i for i in range(len(node.getEquationsUsed()))])", "#code += '<< endl;'", "code", ".", "write", "(", "'continue;\\n}\\n'", ")", "code", ".", "write", "(", "'}\\n'", ")", "code", ".", "write", "(", "'\\n'", ")", "return", "code", ".", "getvalue", "(", ")" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast_generator_cpp.py#L1134-L1274
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/template.py
python
Template.local_variables
(self)
Returns the list of global variables created by the Template.
Returns the list of global variables created by the Template.
[ "Returns", "the", "list", "of", "global", "variables", "created", "by", "the", "Template", "." ]
def local_variables(self): """Returns the list of global variables created by the Template.""" if self._variables_created: return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, self.variable_scope_name) else: return []
[ "def", "local_variables", "(", "self", ")", ":", "if", "self", ".", "_variables_created", ":", "return", "ops", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "LOCAL_VARIABLES", ",", "self", ".", "variable_scope_name", ")", "else", ":", "return", "[", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/template.py#L453-L459
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/boost/1.78.0/libs/metaparse/tools/benchmark/benchmark.py
python
plot_temp_diagrams
(config, results, temp_dir)
return img_files
Plot temporary diagrams
Plot temporary diagrams
[ "Plot", "temporary", "diagrams" ]
def plot_temp_diagrams(config, results, temp_dir): """Plot temporary diagrams""" display_name = { 'time': 'Compilation time (s)', 'memory': 'Compiler memory usage (MB)', } files = config['files'] img_files = [] if any('slt' in result for result in results) and 'bmp' in files.values()[0]: config['modes']['slt'] = 'Using BOOST_METAPARSE_STRING with string literal templates' for f in files.values(): f['slt'] = f['bmp'].replace('bmp', 'slt') for measured in ['time', 'memory']: mpts = sorted(int(k) for k in files.keys()) img_files.append(os.path.join(temp_dir, '_{0}.png'.format(measured))) plot( { m: [(x, results[files[str(x)][m]][measured]) for x in mpts] for m in config['modes'].keys() }, config['modes'], display_name[measured], (config['x_axis_label'], display_name[measured]), img_files[-1] ) return img_files
[ "def", "plot_temp_diagrams", "(", "config", ",", "results", ",", "temp_dir", ")", ":", "display_name", "=", "{", "'time'", ":", "'Compilation time (s)'", ",", "'memory'", ":", "'Compiler memory usage (MB)'", ",", "}", "files", "=", "config", "[", "'files'", "]", "img_files", "=", "[", "]", "if", "any", "(", "'slt'", "in", "result", "for", "result", "in", "results", ")", "and", "'bmp'", "in", "files", ".", "values", "(", ")", "[", "0", "]", ":", "config", "[", "'modes'", "]", "[", "'slt'", "]", "=", "'Using BOOST_METAPARSE_STRING with string literal templates'", "for", "f", "in", "files", ".", "values", "(", ")", ":", "f", "[", "'slt'", "]", "=", "f", "[", "'bmp'", "]", ".", "replace", "(", "'bmp'", ",", "'slt'", ")", "for", "measured", "in", "[", "'time'", ",", "'memory'", "]", ":", "mpts", "=", "sorted", "(", "int", "(", "k", ")", "for", "k", "in", "files", ".", "keys", "(", ")", ")", "img_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "'_{0}.png'", ".", "format", "(", "measured", ")", ")", ")", "plot", "(", "{", "m", ":", "[", "(", "x", ",", "results", "[", "files", "[", "str", "(", "x", ")", "]", "[", "m", "]", "]", "[", "measured", "]", ")", "for", "x", "in", "mpts", "]", "for", "m", "in", "config", "[", "'modes'", "]", ".", "keys", "(", ")", "}", ",", "config", "[", "'modes'", "]", ",", "display_name", "[", "measured", "]", ",", "(", "config", "[", "'x_axis_label'", "]", ",", "display_name", "[", "measured", "]", ")", ",", "img_files", "[", "-", "1", "]", ")", "return", "img_files" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/boost/1.78.0/libs/metaparse/tools/benchmark/benchmark.py#L229-L257
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py
python
connect_cognito_identity
(aws_access_key_id=None, aws_secret_access_key=None, **kwargs)
return CognitoIdentityConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs )
Connect to Amazon Cognito Identity :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key rtype: :class:`boto.cognito.identity.layer1.CognitoIdentityConnection` :return: A connection to the Amazon Cognito Identity service
Connect to Amazon Cognito Identity
[ "Connect", "to", "Amazon", "Cognito", "Identity" ]
def connect_cognito_identity(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ Connect to Amazon Cognito Identity :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key rtype: :class:`boto.cognito.identity.layer1.CognitoIdentityConnection` :return: A connection to the Amazon Cognito Identity service """ from boto.cognito.identity.layer1 import CognitoIdentityConnection return CognitoIdentityConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs )
[ "def", "connect_cognito_identity", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "cognito", ".", "identity", ".", "layer1", "import", "CognitoIdentityConnection", "return", "CognitoIdentityConnection", "(", "aws_access_key_id", "=", "aws_access_key_id", ",", "aws_secret_access_key", "=", "aws_secret_access_key", ",", "*", "*", "kwargs", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py#L909-L929
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/request_track.py
python
Request.SetHTTPResponseHeader
(self, header, header_value)
Sets the value of a HTTP response header.
Sets the value of a HTTP response header.
[ "Sets", "the", "value", "of", "a", "HTTP", "response", "header", "." ]
def SetHTTPResponseHeader(self, header, header_value): """Sets the value of a HTTP response header.""" assert header.islower() for name in self.response_headers.keys(): if name.lower() == header: del self.response_headers[name] self.response_headers[header] = header_value
[ "def", "SetHTTPResponseHeader", "(", "self", ",", "header", ",", "header_value", ")", ":", "assert", "header", ".", "islower", "(", ")", "for", "name", "in", "self", ".", "response_headers", ".", "keys", "(", ")", ":", "if", "name", ".", "lower", "(", ")", "==", "header", ":", "del", "self", ".", "response_headers", "[", "name", "]", "self", ".", "response_headers", "[", "header", "]", "=", "header_value" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/request_track.py#L286-L292
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/command/easy_install.py
python
easy_install.select_scheme
(self, name)
Sets the install directories by applying the install schemes.
Sets the install directories by applying the install schemes.
[ "Sets", "the", "install", "directories", "by", "applying", "the", "install", "schemes", "." ]
def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key])
[ "def", "select_scheme", "(", "self", ",", "name", ")", ":", "# it's the caller's problem if they supply a bad name!", "scheme", "=", "INSTALL_SCHEMES", "[", "name", "]", "for", "key", "in", "SCHEME_KEYS", ":", "attrname", "=", "'install_'", "+", "key", "if", "getattr", "(", "self", ",", "attrname", ")", "is", "None", ":", "setattr", "(", "self", ",", "attrname", ",", "scheme", "[", "key", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/easy_install.py#L723-L730
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.SetCaretPositionForDefaultStyle
(*args, **kwargs)
return _richtext.RichTextCtrl_SetCaretPositionForDefaultStyle(*args, **kwargs)
SetCaretPositionForDefaultStyle(self, long pos)
SetCaretPositionForDefaultStyle(self, long pos)
[ "SetCaretPositionForDefaultStyle", "(", "self", "long", "pos", ")" ]
def SetCaretPositionForDefaultStyle(*args, **kwargs): """SetCaretPositionForDefaultStyle(self, long pos)""" return _richtext.RichTextCtrl_SetCaretPositionForDefaultStyle(*args, **kwargs)
[ "def", "SetCaretPositionForDefaultStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_SetCaretPositionForDefaultStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4132-L4134
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController.setFrameField
(self, frame)
Set the frame field to the given `frame`. Args: frame (str|int|float): The new frame value.
Set the frame field to the given `frame`.
[ "Set", "the", "frame", "field", "to", "the", "given", "frame", "." ]
def setFrameField(self, frame): """Set the frame field to the given `frame`. Args: frame (str|int|float): The new frame value. """ frame = round(float(frame), ndigits=2) self._ui.frameField.setText(str(frame))
[ "def", "setFrameField", "(", "self", ",", "frame", ")", ":", "frame", "=", "round", "(", "float", "(", "frame", ")", ",", "ndigits", "=", "2", ")", "self", ".", "_ui", ".", "frameField", ".", "setText", "(", "str", "(", "frame", ")", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L2032-L2039
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/Editra.py
python
Editra.DestroySplash
(self)
Destroy the splash screen
Destroy the splash screen
[ "Destroy", "the", "splash", "screen" ]
def DestroySplash(self): """Destroy the splash screen""" # If is created and not dead already if getattr(self, 'splash', None) is not None and \ isinstance(self.splash, wx.SplashScreen): self.splash.Destroy() self.splash = None
[ "def", "DestroySplash", "(", "self", ")", ":", "# If is created and not dead already", "if", "getattr", "(", "self", ",", "'splash'", ",", "None", ")", "is", "not", "None", "and", "isinstance", "(", "self", ".", "splash", ",", "wx", ".", "SplashScreen", ")", ":", "self", ".", "splash", ".", "Destroy", "(", ")", "self", ".", "splash", "=", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/Editra.py#L282-L288
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiToolBar.SetToolPacking
(*args, **kwargs)
return _aui.AuiToolBar_SetToolPacking(*args, **kwargs)
SetToolPacking(self, int packing)
SetToolPacking(self, int packing)
[ "SetToolPacking", "(", "self", "int", "packing", ")" ]
def SetToolPacking(*args, **kwargs): """SetToolPacking(self, int packing)""" return _aui.AuiToolBar_SetToolPacking(*args, **kwargs)
[ "def", "SetToolPacking", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBar_SetToolPacking", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2186-L2188
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py
python
GroupBy.expanding
(self, *args, **kwargs)
return ExpandingGroupby(self, *args, **kwargs)
Return an expanding grouper, providing expanding functionality per group.
Return an expanding grouper, providing expanding functionality per group.
[ "Return", "an", "expanding", "grouper", "providing", "expanding", "functionality", "per", "group", "." ]
def expanding(self, *args, **kwargs): """ Return an expanding grouper, providing expanding functionality per group. """ from pandas.core.window import ExpandingGroupby return ExpandingGroupby(self, *args, **kwargs)
[ "def", "expanding", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "core", ".", "window", "import", "ExpandingGroupby", "return", "ExpandingGroupby", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py#L1572-L1579
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/firefighter/bin/packaging.py
python
TempAppDir
(root_dir, symlinks)
Sets up and tears down a directory for deploying or running an app. Args: root_dir: The root directory of the app. symlinks: If true, use symbolic links instead of copying files. This allows the dev server to detect file changes in the repo, and is faster. Yields: The path to the temporary directory.
Sets up and tears down a directory for deploying or running an app.
[ "Sets", "up", "and", "tears", "down", "a", "directory", "for", "deploying", "or", "running", "an", "app", "." ]
def TempAppDir(root_dir, symlinks): """Sets up and tears down a directory for deploying or running an app. Args: root_dir: The root directory of the app. symlinks: If true, use symbolic links instead of copying files. This allows the dev server to detect file changes in the repo, and is faster. Yields: The path to the temporary directory. """ if symlinks: link = os.symlink else: def Link(src, dest): if os.path.isdir(src): return shutil.copytree(src, dest) else: return shutil.copy2(src, dest) link = Link gcloud_lib_dir = _GcloudLibDir() temp_app_dir = tempfile.mkdtemp(prefix='app-') try: for module in Modules(root_dir): module_source_dir = os.path.join(root_dir, module) module_dest_dir = os.path.join(temp_app_dir, module) os.mkdir(module_dest_dir) # Copy/symlink module into app directory. for node in os.listdir(module_source_dir): link(os.path.join(module_source_dir, node), os.path.join(module_dest_dir, node)) # Copy/symlink base/ into module directory. link(os.path.join(root_dir, 'base'), os.path.join(module_dest_dir, 'base')) # Copy/symlink Gcloud library dependencies into module directory. third_party_dest_dir = os.path.join(module_dest_dir, 'third_party') os.mkdir(third_party_dest_dir) open(os.path.join(third_party_dest_dir, '__init__.py'), 'w').close() for library in constants.GCLOUD_THIRD_PARTY_LIBRARIES: link(os.path.join(gcloud_lib_dir, library), os.path.join(third_party_dest_dir, library)) yield temp_app_dir finally: shutil.rmtree(temp_app_dir)
[ "def", "TempAppDir", "(", "root_dir", ",", "symlinks", ")", ":", "if", "symlinks", ":", "link", "=", "os", ".", "symlink", "else", ":", "def", "Link", "(", "src", ",", "dest", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "return", "shutil", ".", "copytree", "(", "src", ",", "dest", ")", "else", ":", "return", "shutil", ".", "copy2", "(", "src", ",", "dest", ")", "link", "=", "Link", "gcloud_lib_dir", "=", "_GcloudLibDir", "(", ")", "temp_app_dir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'app-'", ")", "try", ":", "for", "module", "in", "Modules", "(", "root_dir", ")", ":", "module_source_dir", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "module", ")", "module_dest_dir", "=", "os", ".", "path", ".", "join", "(", "temp_app_dir", ",", "module", ")", "os", ".", "mkdir", "(", "module_dest_dir", ")", "# Copy/symlink module into app directory.", "for", "node", "in", "os", ".", "listdir", "(", "module_source_dir", ")", ":", "link", "(", "os", ".", "path", ".", "join", "(", "module_source_dir", ",", "node", ")", ",", "os", ".", "path", ".", "join", "(", "module_dest_dir", ",", "node", ")", ")", "# Copy/symlink base/ into module directory.", "link", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'base'", ")", ",", "os", ".", "path", ".", "join", "(", "module_dest_dir", ",", "'base'", ")", ")", "# Copy/symlink Gcloud library dependencies into module directory.", "third_party_dest_dir", "=", "os", ".", "path", ".", "join", "(", "module_dest_dir", ",", "'third_party'", ")", "os", ".", "mkdir", "(", "third_party_dest_dir", ")", "open", "(", "os", ".", "path", ".", "join", "(", "third_party_dest_dir", ",", "'__init__.py'", ")", ",", "'w'", ")", ".", "close", "(", ")", "for", "library", "in", "constants", ".", "GCLOUD_THIRD_PARTY_LIBRARIES", ":", "link", "(", "os", ".", "path", ".", "join", "(", "gcloud_lib_dir", ",", "library", ")", ",", "os", ".", "path", ".", "join", "(", "third_party_dest_dir", ",", "library", ")", ")", "yield", "temp_app_dir", "finally", ":", "shutil", ".", "rmtree", "(", "temp_app_dir", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/firefighter/bin/packaging.py#L38-L86
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/tkSimpleDialog.py
python
Dialog.buttonbox
(self)
add standard button box. override if you do not want the standard buttons
add standard button box.
[ "add", "standard", "button", "box", "." ]
def buttonbox(self): '''add standard button box. override if you do not want the standard buttons ''' box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack()
[ "def", "buttonbox", "(", "self", ")", ":", "box", "=", "Frame", "(", "self", ")", "w", "=", "Button", "(", "box", ",", "text", "=", "\"OK\"", ",", "width", "=", "10", ",", "command", "=", "self", ".", "ok", ",", "default", "=", "ACTIVE", ")", "w", ".", "pack", "(", "side", "=", "LEFT", ",", "padx", "=", "5", ",", "pady", "=", "5", ")", "w", "=", "Button", "(", "box", ",", "text", "=", "\"Cancel\"", ",", "width", "=", "10", ",", "command", "=", "self", ".", "cancel", ")", "w", ".", "pack", "(", "side", "=", "LEFT", ",", "padx", "=", "5", ",", "pady", "=", "5", ")", "self", ".", "bind", "(", "\"<Return>\"", ",", "self", ".", "ok", ")", "self", ".", "bind", "(", "\"<Escape>\"", ",", "self", ".", "cancel", ")", "box", ".", "pack", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/tkSimpleDialog.py#L105-L121
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/ndlstm/python/misc.py
python
pool_as_vector
(images, scope=None)
Reduce images to vectors by averaging all pixels.
Reduce images to vectors by averaging all pixels.
[ "Reduce", "images", "to", "vectors", "by", "averaging", "all", "pixels", "." ]
def pool_as_vector(images, scope=None): """Reduce images to vectors by averaging all pixels.""" with ops.name_scope(scope, "PoolAsVector", [images]): return math_ops.reduce_mean(images, [1, 2])
[ "def", "pool_as_vector", "(", "images", ",", "scope", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "scope", ",", "\"PoolAsVector\"", ",", "[", "images", "]", ")", ":", "return", "math_ops", ".", "reduce_mean", "(", "images", ",", "[", "1", ",", "2", "]", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/ndlstm/python/misc.py#L46-L49
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/windows/windows.py
python
cosine
(M, sym=True)
return _truncate(w, needs_trunc)
Return a window with a simple cosine shape. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- .. versionadded:: 0.13.0 Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.cosine(51) >>> plt.plot(window) >>> plt.title("Cosine window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the cosine window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.show()
Return a window with a simple cosine shape.
[ "Return", "a", "window", "with", "a", "simple", "cosine", "shape", "." ]
def cosine(M, sym=True): """Return a window with a simple cosine shape. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. Returns ------- w : ndarray The window, with the maximum value normalized to 1 (though the value 1 does not appear if `M` is even and `sym` is True). Notes ----- .. versionadded:: 0.13.0 Examples -------- Plot the window and its frequency response: >>> from scipy import signal >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = signal.cosine(51) >>> plt.plot(window) >>> plt.title("Cosine window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 2048) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-0.5, 0.5, -120, 0]) >>> plt.title("Frequency response of the cosine window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.show() """ if _len_guards(M): return np.ones(M) M, needs_trunc = _extend(M, sym) w = np.sin(np.pi / M * (np.arange(0, M) + .5)) return _truncate(w, needs_trunc)
[ "def", "cosine", "(", "M", ",", "sym", "=", "True", ")", ":", "if", "_len_guards", "(", "M", ")", ":", "return", "np", ".", "ones", "(", "M", ")", "M", ",", "needs_trunc", "=", "_extend", "(", "M", ",", "sym", ")", "w", "=", "np", ".", "sin", "(", "np", ".", "pi", "/", "M", "*", "(", "np", ".", "arange", "(", "0", ",", "M", ")", "+", ".5", ")", ")", "return", "_truncate", "(", "w", ",", "needs_trunc", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/windows/windows.py#L1562-L1618
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Layer.DeleteField
(self, *args)
return _ogr.Layer_DeleteField(self, *args)
r""" DeleteField(Layer self, int iField) -> OGRErr OGRErr OGR_L_DeleteField(OGRLayerH hLayer, int iField) Delete an existing field on a layer. You must use this to delete existing fields on a real layer. Internally the OGRFeatureDefn for the layer will be updated to reflect the deleted field. Applications should never modify the OGRFeatureDefn used by a layer directly. This function should not be called while there are feature objects in existence that were obtained or created with the previous layer definition. Not all drivers support this function. You can query a layer to check if it supports it with the OLCDeleteField capability. Some drivers may only support this method while there are still no features in the layer. When it is supported, the existing features of the backing file/database should be updated accordingly. This function is the same as the C++ method OGRLayer::DeleteField(). Parameters: ----------- hLayer: handle to the layer. iField: index of the field to delete. OGRERR_NONE on success. OGR 1.9.0
r""" DeleteField(Layer self, int iField) -> OGRErr OGRErr OGR_L_DeleteField(OGRLayerH hLayer, int iField)
[ "r", "DeleteField", "(", "Layer", "self", "int", "iField", ")", "-", ">", "OGRErr", "OGRErr", "OGR_L_DeleteField", "(", "OGRLayerH", "hLayer", "int", "iField", ")" ]
def DeleteField(self, *args): r""" DeleteField(Layer self, int iField) -> OGRErr OGRErr OGR_L_DeleteField(OGRLayerH hLayer, int iField) Delete an existing field on a layer. You must use this to delete existing fields on a real layer. Internally the OGRFeatureDefn for the layer will be updated to reflect the deleted field. Applications should never modify the OGRFeatureDefn used by a layer directly. This function should not be called while there are feature objects in existence that were obtained or created with the previous layer definition. Not all drivers support this function. You can query a layer to check if it supports it with the OLCDeleteField capability. Some drivers may only support this method while there are still no features in the layer. When it is supported, the existing features of the backing file/database should be updated accordingly. This function is the same as the C++ method OGRLayer::DeleteField(). Parameters: ----------- hLayer: handle to the layer. iField: index of the field to delete. OGRERR_NONE on success. OGR 1.9.0 """ return _ogr.Layer_DeleteField(self, *args)
[ "def", "DeleteField", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "Layer_DeleteField", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L1782-L1818
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/pkt/Packet.py
python
OldLength.fill
(self, d)
oldlength.fill(d) Set the OldLength object's data, filling its attributes. Tag data (d) must be either 1, 2, or 4 octets containing the length (integer count) of the packet body (see rfc2004 4.2.1). :Parameters: - `d`: character (StringType, length == 1) :Returns: Nothing Example: >>> oldlength_octets = [0x88, 0x88] >>> oldlength_data_string = ''.join(map(chr, oldlength_octets)) >>> oldlength = OldLength() >>> oldlength.fill(oldlength_data_string) >>> oldlength.size 34952
oldlength.fill(d)
[ "oldlength", ".", "fill", "(", "d", ")" ]
def fill(self, d): """oldlength.fill(d) Set the OldLength object's data, filling its attributes. Tag data (d) must be either 1, 2, or 4 octets containing the length (integer count) of the packet body (see rfc2004 4.2.1). :Parameters: - `d`: character (StringType, length == 1) :Returns: Nothing Example: >>> oldlength_octets = [0x88, 0x88] >>> oldlength_data_string = ''.join(map(chr, oldlength_octets)) >>> oldlength = OldLength() >>> oldlength.fill(oldlength_data_string) >>> oldlength.size 34952 """ if len(d) in [1, 2, 4]: self._d, self.size = d, STN.str2int(d) elif 0 == len(d): self._d, self.size = '', "UNDEFINED" else: raise PGPFormatError, "Old packet length data must come in 0, 1, 2, or 4 octets. Received->(%s octets)." % (str(len(d)))
[ "def", "fill", "(", "self", ",", "d", ")", ":", "if", "len", "(", "d", ")", "in", "[", "1", ",", "2", ",", "4", "]", ":", "self", ".", "_d", ",", "self", ".", "size", "=", "d", ",", "STN", ".", "str2int", "(", "d", ")", "elif", "0", "==", "len", "(", "d", ")", ":", "self", ".", "_d", ",", "self", ".", "size", "=", "''", ",", "\"UNDEFINED\"", "else", ":", "raise", "PGPFormatError", ",", "\"Old packet length data must come in 0, 1, 2, or 4 octets. Received->(%s octets).\"", "%", "(", "str", "(", "len", "(", "d", ")", ")", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/pkt/Packet.py#L127-L154
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/jax/dqn.py
python
DQN._epsilon_greedy
(self, info_state, legal_actions, epsilon)
return action, probs
Returns a valid epsilon-greedy action and valid action probs. Action probabilities are given by a softmax over legal q-values. Args: info_state: hashable representation of the information state. legal_actions: list of legal actions at `info_state`. epsilon: float, probability of taking an exploratory action. Returns: A valid epsilon-greedy action and valid action probabilities.
Returns a valid epsilon-greedy action and valid action probs.
[ "Returns", "a", "valid", "epsilon", "-", "greedy", "action", "and", "valid", "action", "probs", "." ]
def _epsilon_greedy(self, info_state, legal_actions, epsilon): """Returns a valid epsilon-greedy action and valid action probs. Action probabilities are given by a softmax over legal q-values. Args: info_state: hashable representation of the information state. legal_actions: list of legal actions at `info_state`. epsilon: float, probability of taking an exploratory action. Returns: A valid epsilon-greedy action and valid action probabilities. """ probs = np.zeros(self._num_actions) legal_one_hot = np.zeros(self._num_actions) legal_one_hot[legal_actions] = 1 if np.random.rand() < epsilon: action = np.random.choice(legal_actions) probs[legal_actions] = 1.0 / len(legal_actions) else: info_state = np.reshape(info_state, [1, -1]) q_values = self.hk_network_apply(self.params_q_network, info_state) legal_q_values = q_values[0] + ( 1 - legal_one_hot) * ILLEGAL_ACTION_LOGITS_PENALTY action = int(np.argmax(legal_q_values)) probs[action] = 1.0 return action, probs
[ "def", "_epsilon_greedy", "(", "self", ",", "info_state", ",", "legal_actions", ",", "epsilon", ")", ":", "probs", "=", "np", ".", "zeros", "(", "self", ".", "_num_actions", ")", "legal_one_hot", "=", "np", ".", "zeros", "(", "self", ".", "_num_actions", ")", "legal_one_hot", "[", "legal_actions", "]", "=", "1", "if", "np", ".", "random", ".", "rand", "(", ")", "<", "epsilon", ":", "action", "=", "np", ".", "random", ".", "choice", "(", "legal_actions", ")", "probs", "[", "legal_actions", "]", "=", "1.0", "/", "len", "(", "legal_actions", ")", "else", ":", "info_state", "=", "np", ".", "reshape", "(", "info_state", ",", "[", "1", ",", "-", "1", "]", ")", "q_values", "=", "self", ".", "hk_network_apply", "(", "self", ".", "params_q_network", ",", "info_state", ")", "legal_q_values", "=", "q_values", "[", "0", "]", "+", "(", "1", "-", "legal_one_hot", ")", "*", "ILLEGAL_ACTION_LOGITS_PENALTY", "action", "=", "int", "(", "np", ".", "argmax", "(", "legal_q_values", ")", ")", "probs", "[", "action", "]", "=", "1.0", "return", "action", ",", "probs" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/jax/dqn.py#L221-L247
meritlabs/merit
49dc96043f882b982175fb66934e2bf1e6b1920c
contrib/devtools/github-merge.py
python
retrieve_pr_info
(repo,pull)
Retrieve pull request information from github. Return None if no title can be found, or an error happens.
Retrieve pull request information from github. Return None if no title can be found, or an error happens.
[ "Retrieve", "pull", "request", "information", "from", "github", ".", "Return", "None", "if", "no", "title", "can", "be", "found", "or", "an", "error", "happens", "." ]
def retrieve_pr_info(repo,pull): ''' Retrieve pull request information from github. Return None if no title can be found, or an error happens. ''' try: req = Request("https://api.github.com/repos/"+repo+"/pulls/"+pull) result = urlopen(req) reader = codecs.getreader('utf-8') obj = json.load(reader(result)) return obj except Exception as e: print('Warning: unable to retrieve pull information from github: %s' % e) return None
[ "def", "retrieve_pr_info", "(", "repo", ",", "pull", ")", ":", "try", ":", "req", "=", "Request", "(", "\"https://api.github.com/repos/\"", "+", "repo", "+", "\"/pulls/\"", "+", "pull", ")", "result", "=", "urlopen", "(", "req", ")", "reader", "=", "codecs", ".", "getreader", "(", "'utf-8'", ")", "obj", "=", "json", ".", "load", "(", "reader", "(", "result", ")", ")", "return", "obj", "except", "Exception", "as", "e", ":", "print", "(", "'Warning: unable to retrieve pull information from github: %s'", "%", "e", ")", "return", "None" ]
https://github.com/meritlabs/merit/blob/49dc96043f882b982175fb66934e2bf1e6b1920c/contrib/devtools/github-merge.py#L52-L65
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/plugins/hcprt/hcprt.py
python
PrtPlatoonStops.get_closest_for_trip
(self, coords_from, coords_to, walkspeeds=None, ids_person=None)
return ids_prtstop_closest_from, ids_edge_closest_from, ids_prtstop_closest_to, ids_edge_closest_to
Returns the prt stops and stop edges that minimize door to door trip time. Door from and to positions of each trip are given as coordinates.
Returns the prt stops and stop edges that minimize door to door trip time. Door from and to positions of each trip are given as coordinates.
[ "Returns", "the", "prt", "stops", "and", "stop", "edges", "that", "minimize", "door", "to", "door", "trip", "time", ".", "Door", "from", "and", "to", "positions", "of", "each", "trip", "are", "given", "as", "coordinates", "." ]
def get_closest_for_trip(self, coords_from, coords_to, walkspeeds=None, ids_person=None): """ Returns the prt stops and stop edges that minimize door to door trip time. Door from and to positions of each trip are given as coordinates. """ net = self.get_scenario().net ptstops = net.ptstops lanes = net.lanes n = len(coords_from) print 'get_closest_for_trip', n times_stop_to_stop = self.parent.times_stop_to_stop[1:, 1:] ids_prtstop = self.get_ids() n_stops = len(self) ids_ptstop = self.ids_ptstop[ids_prtstop] coords_stop = ptstops.centroids[ids_ptstop] ids_edge_stop = net.lanes.ids_edge[ptstops.ids_lane[ids_ptstop]] inds_closest_from = np.zeros(n, dtype=np.int32) inds_closest_to = np.zeros(n, dtype=np.int32) if walkspeeds is None: # default walk speed in m/s walkspeeds = 0.8*np.ones(n, dtype=np.float32) i = 0 for coord_from, coord_to, walkspeed in zip(coords_from, coords_to, walkspeeds): walktimes_from = 1.0/walkspeed*np.sqrt(np.sum((coord_from-coords_stop)**2, 1)) walktimes_to = 1.0/walkspeed*np.sqrt(np.sum((coord_to-coords_stop)**2, 1)) times_door_to_door = times_stop_to_stop+np.array([walktimes_from]).transpose() times_door_to_door += walktimes_to ind_from, ind_to = np.divmod(np.argmin(times_door_to_door), n_stops) inds_closest_from[i] = ind_from inds_closest_to[i] = ind_to if 0: # ids_person is not None: id_person = ids_person[i] if id_person == 17214: # print ' walktimes_from',(np.array([walktimes_from]).transpose()).shape # print ' walktimes_to',walktimes_to.shape # print ' times_stop_to_stop',times_stop_to_stop.shape print ' id_person', id_person print ' coord_from, coord_to', coord_from, coord_to print ' times_door_to_door\n', times_door_to_door print ' ind_from, ind_to', ind_from, ind_to print ' id_stop_from, id_stop_to', ids_prtstop[ind_from], ids_prtstop[ind_to] i += 1 ids_prtstop_closest_from = ids_prtstop[inds_closest_from] ids_edge_closest_from = ids_edge_stop[inds_closest_from] ids_prtstop_closest_to = ids_prtstop[inds_closest_to] ids_edge_closest_to = ids_edge_stop[inds_closest_to] return ids_prtstop_closest_from, ids_edge_closest_from, ids_prtstop_closest_to, ids_edge_closest_to
[ "def", "get_closest_for_trip", "(", "self", ",", "coords_from", ",", "coords_to", ",", "walkspeeds", "=", "None", ",", "ids_person", "=", "None", ")", ":", "net", "=", "self", ".", "get_scenario", "(", ")", ".", "net", "ptstops", "=", "net", ".", "ptstops", "lanes", "=", "net", ".", "lanes", "n", "=", "len", "(", "coords_from", ")", "print", "'get_closest_for_trip'", ",", "n", "times_stop_to_stop", "=", "self", ".", "parent", ".", "times_stop_to_stop", "[", "1", ":", ",", "1", ":", "]", "ids_prtstop", "=", "self", ".", "get_ids", "(", ")", "n_stops", "=", "len", "(", "self", ")", "ids_ptstop", "=", "self", ".", "ids_ptstop", "[", "ids_prtstop", "]", "coords_stop", "=", "ptstops", ".", "centroids", "[", "ids_ptstop", "]", "ids_edge_stop", "=", "net", ".", "lanes", ".", "ids_edge", "[", "ptstops", ".", "ids_lane", "[", "ids_ptstop", "]", "]", "inds_closest_from", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "np", ".", "int32", ")", "inds_closest_to", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "np", ".", "int32", ")", "if", "walkspeeds", "is", "None", ":", "# default walk speed in m/s", "walkspeeds", "=", "0.8", "*", "np", ".", "ones", "(", "n", ",", "dtype", "=", "np", ".", "float32", ")", "i", "=", "0", "for", "coord_from", ",", "coord_to", ",", "walkspeed", "in", "zip", "(", "coords_from", ",", "coords_to", ",", "walkspeeds", ")", ":", "walktimes_from", "=", "1.0", "/", "walkspeed", "*", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "coord_from", "-", "coords_stop", ")", "**", "2", ",", "1", ")", ")", "walktimes_to", "=", "1.0", "/", "walkspeed", "*", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "coord_to", "-", "coords_stop", ")", "**", "2", ",", "1", ")", ")", "times_door_to_door", "=", "times_stop_to_stop", "+", "np", ".", "array", "(", "[", "walktimes_from", "]", ")", ".", "transpose", "(", ")", "times_door_to_door", "+=", "walktimes_to", "ind_from", ",", "ind_to", "=", "np", ".", "divmod", "(", "np", ".", "argmin", "(", "times_door_to_door", ")", ",", "n_stops", ")", "inds_closest_from", "[", "i", "]", "=", "ind_from", "inds_closest_to", "[", "i", "]", "=", "ind_to", "if", "0", ":", "# ids_person is not None:", "id_person", "=", "ids_person", "[", "i", "]", "if", "id_person", "==", "17214", ":", "# print ' walktimes_from',(np.array([walktimes_from]).transpose()).shape", "# print ' walktimes_to',walktimes_to.shape", "# print ' times_stop_to_stop',times_stop_to_stop.shape", "print", "' id_person'", ",", "id_person", "print", "' coord_from, coord_to'", ",", "coord_from", ",", "coord_to", "print", "' times_door_to_door\\n'", ",", "times_door_to_door", "print", "' ind_from, ind_to'", ",", "ind_from", ",", "ind_to", "print", "' id_stop_from, id_stop_to'", ",", "ids_prtstop", "[", "ind_from", "]", ",", "ids_prtstop", "[", "ind_to", "]", "i", "+=", "1", "ids_prtstop_closest_from", "=", "ids_prtstop", "[", "inds_closest_from", "]", "ids_edge_closest_from", "=", "ids_edge_stop", "[", "inds_closest_from", "]", "ids_prtstop_closest_to", "=", "ids_prtstop", "[", "inds_closest_to", "]", "ids_edge_closest_to", "=", "ids_edge_stop", "[", "inds_closest_to", "]", "return", "ids_prtstop_closest_from", ",", "ids_edge_closest_from", ",", "ids_prtstop_closest_to", ",", "ids_edge_closest_to" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/hcprt/hcprt.py#L2750-L2807
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/cpplint.py
python
_FunctionState.Check
(self, error, filename, linenum)
Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check.
Report if too many lines in function body.
[ "Report", "if", "too", "many", "lines", "in", "function", "body", "." ]
def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if not self.in_a_function: return if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger))
[ "def", "Check", "(", "self", ",", "error", ",", "filename", ",", "linenum", ")", ":", "if", "not", "self", ".", "in_a_function", ":", "return", "if", "Match", "(", "r'T(EST|est)'", ",", "self", ".", "current_function", ")", ":", "base_trigger", "=", "self", ".", "_TEST_TRIGGER", "else", ":", "base_trigger", "=", "self", ".", "_NORMAL_TRIGGER", "trigger", "=", "base_trigger", "*", "2", "**", "_VerboseLevel", "(", ")", "if", "self", ".", "lines_in_function", ">", "trigger", ":", "error_level", "=", "int", "(", "math", ".", "log", "(", "self", ".", "lines_in_function", "/", "base_trigger", ",", "2", ")", ")", "# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...", "if", "error_level", ">", "5", ":", "error_level", "=", "5", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "error_level", ",", "'Small and focused functions are preferred:'", "' %s has %d non-comment lines'", "' (error triggered by exceeding %d lines).'", "%", "(", "self", ".", "current_function", ",", "self", ".", "lines_in_function", ",", "trigger", ")", ")" ]
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L1212-L1238
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/data_flow_ops.py
python
Barrier.incomplete_size
(self, name=None)
return gen_data_flow_ops.barrier_incomplete_size( self._barrier_ref, name=name)
Compute the number of incomplete elements in the given barrier. Args: name: A name for the operation (optional). Returns: A single-element tensor containing the number of incomplete elements in the given barrier.
Compute the number of incomplete elements in the given barrier.
[ "Compute", "the", "number", "of", "incomplete", "elements", "in", "the", "given", "barrier", "." ]
def incomplete_size(self, name=None): """Compute the number of incomplete elements in the given barrier. Args: name: A name for the operation (optional). Returns: A single-element tensor containing the number of incomplete elements in the given barrier. """ if name is None: name = "%s_BarrierIncompleteSize" % self._name return gen_data_flow_ops.barrier_incomplete_size( self._barrier_ref, name=name)
[ "def", "incomplete_size", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"%s_BarrierIncompleteSize\"", "%", "self", ".", "_name", "return", "gen_data_flow_ops", ".", "barrier_incomplete_size", "(", "self", ".", "_barrier_ref", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/data_flow_ops.py#L1224-L1237
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/GettextCommon.py
python
_init_po_files
(target, source, env)
return 0
Action function for `POInit` builder.
Action function for `POInit` builder.
[ "Action", "function", "for", "POInit", "builder", "." ]
def _init_po_files(target, source, env): """ Action function for `POInit` builder. """ nop = lambda target, source, env: 0 if 'POAUTOINIT' in env: autoinit = env['POAUTOINIT'] else: autoinit = False # Well, if everything outside works well, this loop should do single # iteration. Otherwise we are rebuilding all the targets even, if just # one has changed (but is this our fault?). for tgt in target: if not tgt.exists(): if autoinit: action = SCons.Action.Action('$MSGINITCOM', '$MSGINITCOMSTR') else: msg = 'File ' + repr(str(tgt)) + ' does not exist. ' \ + 'If you are a translator, you can create it through: \n' \ + '$MSGINITCOM' action = SCons.Action.Action(nop, msg) status = action([tgt], source, env) if status: return status return 0
[ "def", "_init_po_files", "(", "target", ",", "source", ",", "env", ")", ":", "nop", "=", "lambda", "target", ",", "source", ",", "env", ":", "0", "if", "'POAUTOINIT'", "in", "env", ":", "autoinit", "=", "env", "[", "'POAUTOINIT'", "]", "else", ":", "autoinit", "=", "False", "# Well, if everything outside works well, this loop should do single", "# iteration. Otherwise we are rebuilding all the targets even, if just", "# one has changed (but is this our fault?).", "for", "tgt", "in", "target", ":", "if", "not", "tgt", ".", "exists", "(", ")", ":", "if", "autoinit", ":", "action", "=", "SCons", ".", "Action", ".", "Action", "(", "'$MSGINITCOM'", ",", "'$MSGINITCOMSTR'", ")", "else", ":", "msg", "=", "'File '", "+", "repr", "(", "str", "(", "tgt", ")", ")", "+", "' does not exist. '", "+", "'If you are a translator, you can create it through: \\n'", "+", "'$MSGINITCOM'", "action", "=", "SCons", ".", "Action", ".", "Action", "(", "nop", ",", "msg", ")", "status", "=", "action", "(", "[", "tgt", "]", ",", "source", ",", "env", ")", "if", "status", ":", "return", "status", "return", "0" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/GettextCommon.py#L362-L383
fdivitto/ESPWebFramework
5c7b644b2d15795d4b2b8d7dda3897222aada7b3
script/esptool.py
python
div_roundup
(a, b)
return (int(a) + int(b) - 1) / int(b)
Return a/b rounded up to nearest integer, equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only without possible floating point accuracy errors.
Return a/b rounded up to nearest integer, equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only without possible floating point accuracy errors.
[ "Return", "a", "/", "b", "rounded", "up", "to", "nearest", "integer", "equivalent", "result", "to", "int", "(", "math", ".", "ceil", "(", "float", "(", "int", "(", "a", "))", "/", "float", "(", "int", "(", "b", ")))", "only", "without", "possible", "floating", "point", "accuracy", "errors", "." ]
def div_roundup(a, b): """ Return a/b rounded up to nearest integer, equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only without possible floating point accuracy errors. """ return (int(a) + int(b) - 1) / int(b)
[ "def", "div_roundup", "(", "a", ",", "b", ")", ":", "return", "(", "int", "(", "a", ")", "+", "int", "(", "b", ")", "-", "1", ")", "/", "int", "(", "b", ")" ]
https://github.com/fdivitto/ESPWebFramework/blob/5c7b644b2d15795d4b2b8d7dda3897222aada7b3/script/esptool.py#L457-L462
psmoveservice/PSMoveService
22bbe20e9de53f3f3581137bce7b88e2587a27e7
misc/python/examples/filter_datafiles.py
python
quat_from_axang
(axang, dt=1)
return result / np.linalg.norm(result)
Convert an axis-angle (3D) representation of orientation into a quaternion (4D) :param axang: :param dt: :return:
Convert an axis-angle (3D) representation of orientation into a quaternion (4D) :param axang: :param dt: :return:
[ "Convert", "an", "axis", "-", "angle", "(", "3D", ")", "representation", "of", "orientation", "into", "a", "quaternion", "(", "4D", ")", ":", "param", "axang", ":", ":", "param", "dt", ":", ":", "return", ":" ]
def quat_from_axang(axang, dt=1): """ Convert an axis-angle (3D) representation of orientation into a quaternion (4D) :param axang: :param dt: :return: """ s = np.linalg.norm(axang) rot_angle = s * dt if rot_angle > 0: rot_axis = axang / s result = np.hstack((np.cos(rot_angle/2), rot_axis*np.sin(rot_angle/2))) else: result = np.asarray([1., 0., 0., 0.]) return result / np.linalg.norm(result)
[ "def", "quat_from_axang", "(", "axang", ",", "dt", "=", "1", ")", ":", "s", "=", "np", ".", "linalg", ".", "norm", "(", "axang", ")", "rot_angle", "=", "s", "*", "dt", "if", "rot_angle", ">", "0", ":", "rot_axis", "=", "axang", "/", "s", "result", "=", "np", ".", "hstack", "(", "(", "np", ".", "cos", "(", "rot_angle", "/", "2", ")", ",", "rot_axis", "*", "np", ".", "sin", "(", "rot_angle", "/", "2", ")", ")", ")", "else", ":", "result", "=", "np", ".", "asarray", "(", "[", "1.", ",", "0.", ",", "0.", ",", "0.", "]", ")", "return", "result", "/", "np", ".", "linalg", ".", "norm", "(", "result", ")" ]
https://github.com/psmoveservice/PSMoveService/blob/22bbe20e9de53f3f3581137bce7b88e2587a27e7/misc/python/examples/filter_datafiles.py#L88-L102
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
TextAttrDimension.SetValue
(*args)
return _richtext.TextAttrDimension_SetValue(*args)
SetValue(self, int value) SetValue(self, int value, TextAttrDimensionFlags flags) SetValue(self, TextAttrDimension dim)
SetValue(self, int value) SetValue(self, int value, TextAttrDimensionFlags flags) SetValue(self, TextAttrDimension dim)
[ "SetValue", "(", "self", "int", "value", ")", "SetValue", "(", "self", "int", "value", "TextAttrDimensionFlags", "flags", ")", "SetValue", "(", "self", "TextAttrDimension", "dim", ")" ]
def SetValue(*args): """ SetValue(self, int value) SetValue(self, int value, TextAttrDimensionFlags flags) SetValue(self, TextAttrDimension dim) """ return _richtext.TextAttrDimension_SetValue(*args)
[ "def", "SetValue", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextAttrDimension_SetValue", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L160-L166
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/macpath.py
python
expandvars
(path)
return path
Dummy to retain interface-compatibility with other operating systems.
Dummy to retain interface-compatibility with other operating systems.
[ "Dummy", "to", "retain", "interface", "-", "compatibility", "with", "other", "operating", "systems", "." ]
def expandvars(path): """Dummy to retain interface-compatibility with other operating systems.""" return path
[ "def", "expandvars", "(", "path", ")", ":", "return", "path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/macpath.py#L145-L147
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpModel.AddBoolOr
(self, literals)
return ct
Adds `Or(literals) == true`.
Adds `Or(literals) == true`.
[ "Adds", "Or", "(", "literals", ")", "==", "true", "." ]
def AddBoolOr(self, literals): """Adds `Or(literals) == true`.""" ct = Constraint(self.__model.constraints) model_ct = self.__model.constraints[ct.Index()] model_ct.bool_or.literals.extend( [self.GetOrMakeBooleanIndex(x) for x in literals]) return ct
[ "def", "AddBoolOr", "(", "self", ",", "literals", ")", ":", "ct", "=", "Constraint", "(", "self", ".", "__model", ".", "constraints", ")", "model_ct", "=", "self", ".", "__model", ".", "constraints", "[", "ct", ".", "Index", "(", ")", "]", "model_ct", ".", "bool_or", ".", "literals", ".", "extend", "(", "[", "self", ".", "GetOrMakeBooleanIndex", "(", "x", ")", "for", "x", "in", "literals", "]", ")", "return", "ct" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1461-L1467
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_subelements.py
python
SubelementHighlight.get_editable_objects_from_selection
(self)
Get editable Draft objects for the selection.
Get editable Draft objects for the selection.
[ "Get", "editable", "Draft", "objects", "for", "the", "selection", "." ]
def get_editable_objects_from_selection(self): """Get editable Draft objects for the selection.""" for obj in Gui.Selection.getSelection(): if obj.isDerivedFrom("Part::Part2DObject"): self.editable_objects.append(obj) elif (hasattr(obj, "Base") and obj.Base.isDerivedFrom("Part::Part2DObject")): self.editable_objects.append(obj.Base)
[ "def", "get_editable_objects_from_selection", "(", "self", ")", ":", "for", "obj", "in", "Gui", ".", "Selection", ".", "getSelection", "(", ")", ":", "if", "obj", ".", "isDerivedFrom", "(", "\"Part::Part2DObject\"", ")", ":", "self", ".", "editable_objects", ".", "append", "(", "obj", ")", "elif", "(", "hasattr", "(", "obj", ",", "\"Base\"", ")", "and", "obj", ".", "Base", ".", "isDerivedFrom", "(", "\"Part::Part2DObject\"", ")", ")", ":", "self", ".", "editable_objects", ".", "append", "(", "obj", ".", "Base", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_subelements.py#L119-L126
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/fallback.py
python
get_func
(obj, doc)
return wrapper
Get new numpy function with object and doc
Get new numpy function with object and doc
[ "Get", "new", "numpy", "function", "with", "object", "and", "doc" ]
def get_func(obj, doc): """Get new numpy function with object and doc""" @wraps(obj) def wrapper(*args, **kwargs): return obj(*args, **kwargs) wrapper.__doc__ = doc return wrapper
[ "def", "get_func", "(", "obj", ",", "doc", ")", ":", "@", "wraps", "(", "obj", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "obj", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapper", ".", "__doc__", "=", "doc", "return", "wrapper" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/fallback.py#L117-L123
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/os_detect.py
python
OsDetect.get_detector
(self, name=None)
Get detector used for specified OS name, or the detector for this OS if name is ``None``. :raises: :exc:`KeyError`
Get detector used for specified OS name, or the detector for this OS if name is ``None``. :raises: :exc:`KeyError`
[ "Get", "detector", "used", "for", "specified", "OS", "name", "or", "the", "detector", "for", "this", "OS", "if", "name", "is", "None", ".", ":", "raises", ":", ":", "exc", ":", "KeyError" ]
def get_detector(self, name=None): """ Get detector used for specified OS name, or the detector for this OS if name is ``None``. :raises: :exc:`KeyError` """ if name is None: if not self._os_detector: self.detect_os() return self._os_detector else: try: return [d for d_name, d in self._os_list if d_name == name][0] except IndexError: raise KeyError(name)
[ "def", "get_detector", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "if", "not", "self", ".", "_os_detector", ":", "self", ".", "detect_os", "(", ")", "return", "self", ".", "_os_detector", "else", ":", "try", ":", "return", "[", "d", "for", "d_name", ",", "d", "in", "self", ".", "_os_list", "if", "d_name", "==", "name", "]", "[", "0", "]", "except", "IndexError", ":", "raise", "KeyError", "(", "name", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/os_detect.py#L559-L573
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/python/google/platform_utils_mac.py
python
PlatformUtility.GetStopHttpdCommand
(self)
return [self._bash, "-c", self._httpd_cmd_string + ' -k stop && sleep 5']
Returns a list of strings that contains the command line+args needed to stop the http server used in the http tests. This tries to fetch the pid of httpd (if available) and returns the command to kill it. If pid is not available, kill all httpd processes
Returns a list of strings that contains the command line+args needed to stop the http server used in the http tests.
[ "Returns", "a", "list", "of", "strings", "that", "contains", "the", "command", "line", "+", "args", "needed", "to", "stop", "the", "http", "server", "used", "in", "the", "http", "tests", "." ]
def GetStopHttpdCommand(self): """Returns a list of strings that contains the command line+args needed to stop the http server used in the http tests. This tries to fetch the pid of httpd (if available) and returns the command to kill it. If pid is not available, kill all httpd processes """ if not self._httpd_cmd_string: return ["true"] # Haven't been asked for the start cmd yet. Just pass. # Add a sleep after the shutdown because sometimes it takes some time for # the port to be available again. return [self._bash, "-c", self._httpd_cmd_string + ' -k stop && sleep 5']
[ "def", "GetStopHttpdCommand", "(", "self", ")", ":", "if", "not", "self", ".", "_httpd_cmd_string", ":", "return", "[", "\"true\"", "]", "# Haven't been asked for the start cmd yet. Just pass.", "# Add a sleep after the shutdown because sometimes it takes some time for", "# the port to be available again.", "return", "[", "self", ".", "_bash", ",", "\"-c\"", ",", "self", ".", "_httpd_cmd_string", "+", "' -k stop && sleep 5'", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/python/google/platform_utils_mac.py#L133-L145
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py
python
spawn.sendeof
(self)
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line.
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line.
[ "This", "sends", "an", "EOF", "to", "the", "child", ".", "This", "sends", "a", "character", "which", "causes", "the", "pending", "parent", "output", "buffer", "to", "be", "sent", "to", "the", "waiting", "child", "program", "without", "waiting", "for", "end", "-", "of", "-", "line", ".", "If", "it", "is", "the", "first", "character", "of", "the", "line", "the", "read", "()", "in", "the", "user", "program", "returns", "0", "which", "signifies", "end", "-", "of", "-", "file", ".", "This", "means", "to", "work", "as", "expected", "a", "sendeof", "()", "has", "to", "be", "called", "at", "the", "beginning", "of", "a", "line", ".", "This", "method", "does", "not", "send", "a", "newline", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "ensure", "the", "eof", "is", "sent", "at", "the", "beginning", "of", "a", "line", "." ]
def sendeof(self): '''This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. ''' n, byte = self.ptyproc.sendeof() self._log_control(byte)
[ "def", "sendeof", "(", "self", ")", ":", "n", ",", "byte", "=", "self", ".", "ptyproc", ".", "sendeof", "(", ")", "self", ".", "_log_control", "(", "byte", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L576-L587
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/DataProbe/DataProbe.py
python
DataProbeTest.runTest
(self)
Run as few or as many tests as needed here.
Run as few or as many tests as needed here.
[ "Run", "as", "few", "or", "as", "many", "tests", "as", "needed", "here", "." ]
def runTest(self): """Run as few or as many tests as needed here. """ self.setUp() self.test_DataProbe1()
[ "def", "runTest", "(", "self", ")", ":", "self", ".", "setUp", "(", ")", "self", ".", "test_DataProbe1", "(", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DataProbe/DataProbe.py#L575-L579
yuxng/PoseCNN
9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04
lib/datasets/rgbd_scene.py
python
rgbd_scene._load_image_set_index
(self)
return image_index
Load the indexes listed in this dataset's image set file.
Load the indexes listed in this dataset's image set file.
[ "Load", "the", "indexes", "listed", "in", "this", "dataset", "s", "image", "set", "file", "." ]
def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ image_set_file = os.path.join(self._rgbd_scene_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.rstrip('\n') for x in f.readlines()] return image_index
[ "def", "_load_image_set_index", "(", "self", ")", ":", "image_set_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_rgbd_scene_path", ",", "self", ".", "_image_set", "+", "'.txt'", ")", "assert", "os", ".", "path", ".", "exists", "(", "image_set_file", ")", ",", "'Path does not exist: {}'", ".", "format", "(", "image_set_file", ")", "with", "open", "(", "image_set_file", ")", "as", "f", ":", "image_index", "=", "[", "x", ".", "rstrip", "(", "'\\n'", ")", "for", "x", "in", "f", ".", "readlines", "(", ")", "]", "return", "image_index" ]
https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/datasets/rgbd_scene.py#L97-L107
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
LimitsProcessor.modifylimits
(self, contents, index)
Modify a limits commands so that the limits appear above and below.
Modify a limits commands so that the limits appear above and below.
[ "Modify", "a", "limits", "commands", "so", "that", "the", "limits", "appear", "above", "and", "below", "." ]
def modifylimits(self, contents, index): "Modify a limits commands so that the limits appear above and below." limited = contents[index] subscript = self.getlimit(contents, index + 1) limited.contents.append(subscript) if self.checkscript(contents, index + 1): superscript = self.getlimit(contents, index + 1) else: superscript = TaggedBit().constant(u' ', 'sup class="limit"') limited.contents.insert(0, superscript)
[ "def", "modifylimits", "(", "self", ",", "contents", ",", "index", ")", ":", "limited", "=", "contents", "[", "index", "]", "subscript", "=", "self", ".", "getlimit", "(", "contents", ",", "index", "+", "1", ")", "limited", ".", "contents", ".", "append", "(", "subscript", ")", "if", "self", ".", "checkscript", "(", "contents", ",", "index", "+", "1", ")", ":", "superscript", "=", "self", ".", "getlimit", "(", "contents", ",", "index", "+", "1", ")", "else", ":", "superscript", "=", "TaggedBit", "(", ")", ".", "constant", "(", "u' ', ", "'", "up class=\"limit\"')", "", "limited", ".", "contents", ".", "insert", "(", "0", ",", "superscript", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4693-L4702
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteDoCmd
(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False)
Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag.
Write a Makefile rule that uses do_cmd.
[ "Write", "a", "Makefile", "rule", "that", "uses", "do_cmd", "." ]
def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = '' if postbuilds: assert ',' not in command suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule(outputs, inputs, actions = ['$(call do_cmd,%s%s)' % (command, suffix)], comment = comment, force = True) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn('all_deps += %s' % ' '.join(outputs))
[ "def", "WriteDoCmd", "(", "self", ",", "outputs", ",", "inputs", ",", "command", ",", "part_of_all", ",", "comment", "=", "None", ",", "postbuilds", "=", "False", ")", ":", "suffix", "=", "''", "if", "postbuilds", ":", "assert", "','", "not", "in", "command", "suffix", "=", "',,1'", "# Tell do_cmd to honor $POSTBUILDS", "self", ".", "WriteMakeRule", "(", "outputs", ",", "inputs", ",", "actions", "=", "[", "'$(call do_cmd,%s%s)'", "%", "(", "command", ",", "suffix", ")", "]", ",", "comment", "=", "comment", ",", "force", "=", "True", ")", "# Add our outputs to the list of targets we read depfiles from.", "# all_deps is only used for deps file reading, and for deps files we replace", "# spaces with ? because escaping doesn't work with make's $(sort) and", "# other functions.", "outputs", "=", "[", "QuoteSpaces", "(", "o", ",", "SPACE_REPLACEMENT", ")", "for", "o", "in", "outputs", "]", "self", ".", "WriteLn", "(", "'all_deps += %s'", "%", "' '", ".", "join", "(", "outputs", ")", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/make.py#L1628-L1648
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/locks.py
python
Semaphore.locked
(self)
return self._value == 0
Returns True if semaphore can not be acquired immediately.
Returns True if semaphore can not be acquired immediately.
[ "Returns", "True", "if", "semaphore", "can", "not", "be", "acquired", "immediately", "." ]
def locked(self): """Returns True if semaphore can not be acquired immediately.""" return self._value == 0
[ "def", "locked", "(", "self", ")", ":", "return", "self", ".", "_value", "==", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/locks.py#L396-L398
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/data_utils.py
python
Data.DATA
(self)
return self.__data
Get the current data.
Get the current data.
[ "Get", "the", "current", "data", "." ]
def DATA(self): """Get the current data.""" return self.__data
[ "def", "DATA", "(", "self", ")", ":", "return", "self", ".", "__data" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/data_utils.py#L92-L94
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Menu.GetEventHandler
(*args, **kwargs)
return _core_.Menu_GetEventHandler(*args, **kwargs)
GetEventHandler(self) -> EvtHandler
GetEventHandler(self) -> EvtHandler
[ "GetEventHandler", "(", "self", ")", "-", ">", "EvtHandler" ]
def GetEventHandler(*args, **kwargs): """GetEventHandler(self) -> EvtHandler""" return _core_.Menu_GetEventHandler(*args, **kwargs)
[ "def", "GetEventHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_GetEventHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12198-L12200
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_AddEqualsMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if not self.ListFields() == other.ListFields(): return False # Sort unknown fields because their order shouldn't affect equality test. unknown_fields = list(self._unknown_fields) unknown_fields.sort() other_unknown_fields = list(other._unknown_fields) other_unknown_fields.sort() return unknown_fields == other_unknown_fields cls.__eq__ = __eq__
[ "def", "_AddEqualsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "(", "not", "isinstance", "(", "other", ",", "message_mod", ".", "Message", ")", "or", "other", ".", "DESCRIPTOR", "!=", "self", ".", "DESCRIPTOR", ")", ":", "return", "False", "if", "self", "is", "other", ":", "return", "True", "if", "not", "self", ".", "ListFields", "(", ")", "==", "other", ".", "ListFields", "(", ")", ":", "return", "False", "# Sort unknown fields because their order shouldn't affect equality test.", "unknown_fields", "=", "list", "(", "self", ".", "_unknown_fields", ")", "unknown_fields", ".", "sort", "(", ")", "other_unknown_fields", "=", "list", "(", "other", ".", "_unknown_fields", ")", "other_unknown_fields", ".", "sort", "(", ")", "return", "unknown_fields", "==", "other_unknown_fields", "cls", ".", "__eq__", "=", "__eq__" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L667-L688
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/common/tokenizer.py
python
Tokenizer.TokenizeFile
(self, file)
return self.__first_token
Tokenizes the given file. Args: file: An iterable that yields one line of the file at a time. Returns: The first token in the file
Tokenizes the given file.
[ "Tokenizes", "the", "given", "file", "." ]
def TokenizeFile(self, file): """Tokenizes the given file. Args: file: An iterable that yields one line of the file at a time. Returns: The first token in the file """ # The current mode. self.mode = self.__starting_mode # The first token in the stream. self.__first_token = None # The last token added to the token stream. self.__last_token = None # The current line number. self.__line_number = 0 for line in file: self.__line_number += 1 self.__TokenizeLine(line) return self.__first_token
[ "def", "TokenizeFile", "(", "self", ",", "file", ")", ":", "# The current mode.", "self", ".", "mode", "=", "self", ".", "__starting_mode", "# The first token in the stream.", "self", ".", "__first_token", "=", "None", "# The last token added to the token stream.", "self", ".", "__last_token", "=", "None", "# The current line number.", "self", ".", "__line_number", "=", "0", "for", "line", "in", "file", ":", "self", ".", "__line_number", "+=", "1", "self", ".", "__TokenizeLine", "(", "line", ")", "return", "self", ".", "__first_token" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/common/tokenizer.py#L54-L76
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/MolStandardize/charge.py
python
Uncharger.__call__
(self, mol)
return self.uncharge(mol)
Calling an Uncharger instance like a function is the same as calling its uncharge(mol) method.
Calling an Uncharger instance like a function is the same as calling its uncharge(mol) method.
[ "Calling", "an", "Uncharger", "instance", "like", "a", "function", "is", "the", "same", "as", "calling", "its", "uncharge", "(", "mol", ")", "method", "." ]
def __call__(self, mol): """Calling an Uncharger instance like a function is the same as calling its uncharge(mol) method.""" return self.uncharge(mol)
[ "def", "__call__", "(", "self", ",", "mol", ")", ":", "return", "self", ".", "uncharge", "(", "mol", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MolStandardize/charge.py#L278-L280