code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def datalen(self): <NEW_LINE> <INDENT> return unpack('<H', self.__header[2])[0] | Returns the length in bytes of the currently encapsulated data. | 625941db6fb2d068a760f379 |
def waste_water(osm_path): <NEW_LINE> <INDENT> return (retrieve(osm_path,'multipolygons',['man_made'],**{'man_made':["='wastewater_plant'"]})).rename(columns={'man_made': 'asset'}) | Function to extract water waste polygons from OpenStreetMap
Arguments:
*osm_path* : file path to the .osm.pbf file of the region
for which we want to do the analysis.
Returns:
*GeoDataFrame* : a geopandas GeoDataFrame with specified unique water waste multipolygons. | 625941dbb830903b967e9be1 |
def _sameFrag(f, g): <NEW_LINE> <INDENT> if (hasattr(f, 'cbDefn') or hasattr(g, 'cbDefn') or hasattr(f, 'lineBreak') or hasattr(g, 'lineBreak')): return 0 <NEW_LINE> for a in ('fontName', 'fontSize', 'textColor', 'backColor', 'rise', 'underline', 'strike', 'link'): <NEW_LINE> <INDENT> if getattr(f, a, None) != getattr(... | returns 1 if two ParaFrags map out the same | 625941dbdd821e528d63b47f |
def loop_day(rowid_start, day, events_annual, events_daily): <NEW_LINE> <INDENT> tbl_chance = [] <NEW_LINE> rowid = rowid_start <NEW_LINE> for hh in hours: <NEW_LINE> <INDENT> for ev in events_daily: <NEW_LINE> <INDENT> if hh == ev[0]: <NEW_LINE> <INDENT> chance = int(ev[2]) <NEW_LINE> rowid += 1 <NEW_LINE> tbl_chance.... | loops through a day, checking daily events and running randomly | 625941dbcdde0d52a9e5330d |
def test_00_mrp_maintenance(self): <NEW_LINE> <INDENT> equipment_form = Form(self.equipment) <NEW_LINE> equipment_form.name = 'Acer Laptop' <NEW_LINE> equipment_form.maintenance_team_id = self.maintenance_team_id <NEW_LINE> equipment_form.category_id = self.category_id <NEW_LINE> equipment_form.technician_user_id = sel... | In order to check Next preventive maintenance date | 625941db91f36d47f21ac7cd |
def __update(self, key1, key2, action, value=None, upvalue=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if action == 'incr': <NEW_LINE> <INDENT> upaction = 'inc__' + key2 <NEW_LINE> self.Object(__raw__={key1: value}).update(**{upaction: upvalue}) <NEW_LINE> <DEDENT> elif action == 'decr': <NEW_LINE> <INDENT> up... | 说明:调用接口为UPDATE,UPDATE函数内部调用__update
eg:对匹配article_title的文档的article_views_count数值增加5
MGeng(Article).UPDATE('article_title', 'article_views_count',
# 'incr', kvalue=artilcTitle, upvalue=5)
:param key1: 用于查询文档的key
注意:若key1是id,则必须用 _id 形式,因数据库存储形式为 ... | 625941db7cff6e4e81117c5d |
def _record(self): <NEW_LINE> <INDENT> return struct.pack(self.FMT, 1, self.platform_id, 0, self.id_string, self.checksum, 0x55, 0xaa) | An internal method to generate a string representing this El Torito
Validation Entry.
Parameters:
None.
Returns:
String representing this El Torito Validation Entry. | 625941db8e05c05ec3eea64f |
def getPageNumber(link, index): <NEW_LINE> <INDENT> temp = 0 <NEW_LINE> while link != '\n' and link[int(index) + int(temp)] != '&': <NEW_LINE> <INDENT> temp += 1 <NEW_LINE> <DEDENT> page = link[index:index + temp] <NEW_LINE> return page | **Function to search and parse for page numbers in the link header | 625941db15baa723493c424f |
def render_choice_component(self, component, dialog): <NEW_LINE> <INDENT> if not component.choices: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> indices = '0123456789abcdefghijklmnopqrstuvwxyz' <NEW_LINE> selected = set() <NEW_LINE> if component.multi and component.default: <NEW_LINE> <INDENT> selected = {component.c... | Renders the choices component
:param component: The choices component to render
:type component: leapp.dialogs.components.ChoicesComponent
:param dialog: The dialog to render
:type dialog: leapp.dialogs.dialog.Dialog
:return: None | 625941dba8ecb033257d33a4 |
def route(self, method='GET', path='/'): <NEW_LINE> <INDENT> def register(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def wrapper(*args, **kwds): <NEW_LINE> <INDENT> return fn(*args, **kwds) <NEW_LINE> <DEDENT> if isinstance(method, str): <NEW_LINE> <INDENT> self.__setitem__(path, (wrapper, [method])) <NEW_LINE> <DE... | Register a function in the routing table of this server. | 625941db5f7d997b87174d72 |
def connect_enode(node0, node1) -> bool: <NEW_LINE> <INDENT> url = "http://{}:8545".format(node0[0]) <NEW_LINE> data = { "jsonrpc": "2.0", "method": "parity_addReservedPeer", "params": [node1[1]], "id": 0 } <NEW_LINE> r = post(url, json=data) <NEW_LINE> return r.json()["result"] | Connect node1 to node0. | 625941db507cdc57c6306fb9 |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return StoryCluster( id = 56, phrases = [ '0' ], score = 1.337, size = 56, stories = [ 56 ] ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return StoryCluster( ) | Test StoryCluster
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941dbf9cc0f698b1408d1 |
def __get_user(update): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> userid = update.effective_user.username <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> userid = str(update['from']['id']) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(userid=userid) <NEW_LINE> <DEDENT> except DoesNotExist as e... | Returns Telegram username if exists, overwise user id | 625941db4e696a04525c9724 |
def tally(self, df, remove_exclusions=True): <NEW_LINE> <INDENT> unit_record = df[self.variable] <NEW_LINE> freqs = dict(unit_record.value_counts()) <NEW_LINE> cts = [] <NEW_LINE> values = self.scale.get_values(remove_exclusions) <NEW_LINE> for k in values: <NEW_LINE> <INDENT> if k in freqs: <NEW_LINE> <INDENT> cts.app... | Returns ([response frequencies], respondents, nonrespondents)
tuple where response frequencies is a count of responses for
each answer choice in order. | 625941db63f4b57ef00013ea |
def reset(self): <NEW_LINE> <INDENT> self.links = {} | remove all hyperlinks | 625941db01c39578d7e75114 |
def setup_defaults(self): <NEW_LINE> <INDENT> usd, = self.currency_obj.create([{ 'name': 'US Dollar', 'code': 'USD', 'symbol': '$', 'rates': [('create', [{'rate': Decimal('1')}])], }]) <NEW_LINE> self.party, = self.party_obj.create([{ 'name': 'Openlabs', }]) <NEW_LINE> self.company, = self.company_obj.create([{ 'curren... | Setup the defaults | 625941db796e427e537b08a0 |
def setLabels(self, labels): <NEW_LINE> <INDENT> self.labels = labels | setLabels() sets captions for each column
@param labels should be an array of captions of each column.
@example setLabels(['col 1', 'col 2', 'col 3']) | 625941dbdc8b845886cb580e |
def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age | initialization method | 625941db7d43ff24873a2f7a |
def can_view(self, user, task): <NEW_LINE> <INDENT> return user.has_perm(self.flow_class._meta.view_permission_name) | Check if user has a view task detail permission. | 625941dbbde94217f36830c6 |
def username_to_uuid(username): <NEW_LINE> <INDENT> if not username.startswith('u-') or len(username) != 28: <NEW_LINE> <INDENT> raise ValueError('Not an UUID based username: %r' % (username,)) <NEW_LINE> <DEDENT> decoded = base64.b32decode(username[2:].upper() + '======') <NEW_LINE> return UUID(bytes=decoded) | Convert username to UUID.
>>> username_to_uuid('u-ad52zgilvnpgnduefzlh5jgr6y')
UUID('00fbac99-0bab-5e66-8e84-2e567ea4d1f6') | 625941db460517430c394457 |
def get_vlan_ports(self, vlan_name): <NEW_LINE> <INDENT> output = CommandTemplateExecutor(self._cli_service, command_template.SHOW_VLAN_INTERFACES).execute_command( vlan_name=vlan_name) <NEW_LINE> ports = re.findall(r'[a-zA-Z]+-(?:\d+/)+\d+|ae\d+', re.sub(r'\n|\r', '', output)) <NEW_LINE> return [port.strip() for port ... | Return list of interfaces assigned on vlan
:param vlan_name:
:return: List of interfaces
:rtype: list | 625941dbd10714528d5fffbe |
def members(self): <NEW_LINE> <INDENT> elements = self.connect_to_slave().smembers(self.key) <NEW_LINE> if not elements: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return [self.decode(e) for e in elements] | List all pool items.
:rtype: list | 625941dbc432627299f04f20 |
def save(self): <NEW_LINE> <INDENT> xml_file = open(self.__file, "w") <NEW_LINE> xml_file.write('<?xml version="1.0" encoding="utf-8"?>\n') <NEW_LINE> xml_file.write('<stylelist>\n') <NEW_LINE> for name, sheet in self.map.iteritems(): <NEW_LINE> <INDENT> if name == "default": <NEW_LINE> <INDENT> continue <NEW_LINE> <DE... | Saves the current StyleSheet definitions to the associated file. | 625941db5510c4643540f6b6 |
def _calc_vacancy_number(self, partitions, a, i, **options): <NEW_LINE> <INDENT> if a != len(self._rc_index) - 1: <NEW_LINE> <INDENT> return RCTypeA2Even._calc_vacancy_number(self, partitions, a, i, **options) <NEW_LINE> <DEDENT> vac_num = 0 <NEW_LINE> if "B" in options: <NEW_LINE> <INDENT> for tab in options["B"]: <NE... | Calculate the vacancy number `p_i^{(a)}` in ``self``. A special case
is needed for the `n`-th partition for type `A_{2n}^{(2)\dagger}`.
INPUT:
- ``partitions`` -- the list of rigged partitions we are using
- ``a`` -- the rigged partition index
- ``i`` -- the row lenth
TESTS::
sage: RC = RiggedConfigurations(C... | 625941dbcc40096d61595c28 |
def intersection(geom_1, geom_2, intersection_type): <NEW_LINE> <INDENT> if intersection_type[:-2] == "segment": <NEW_LINE> <INDENT> if intersection_type == "segment2D": <NEW_LINE> <INDENT> x1, y1 = geom_1.points[0] <NEW_LINE> x2, y2 = geom_1.points[1] <NEW_LINE> x3, y3 = geom_2.points[0] <NEW_LINE> x4, y4 = geom_2.poi... | Returns intersection between geometric objects.
Explanation
===========
Note that this function is meant for use in integration_reduction and
at that point in the calling function the lines denoted by the segments
surely intersect within segment boundaries. Coincident lines are taken
to be non-intersecting. Also, the... | 625941db7047854f462a16df |
def _is_field_a_date(self, item: str) -> bool: <NEW_LINE> <INDENT> return bool(self._date_fields and item in self._date_fields and self.json[item]) | Determine if given field is a date.
:param item: field to check.
:return: True if field is a date. | 625941dbde87d2750b86006d |
def updateTimes(self): <NEW_LINE> <INDENT> if self.readTime(): <NEW_LINE> <INDENT> self.times[int(self.lane) - 1] = self.finalTime <NEW_LINE> self.ledits[int(self.lane) - 1].setText(self.finalTime) <NEW_LINE> self.laneFinish[int(self.lane) - 1] = True <NEW_LINE> <DEDENT> t = time.perf_counter() - self.t1 <NEW_LINE> for... | Records any received times from 'readTime()' and continues GUI clock | 625941dbd164cc6175783027 |
def train(train_data,model_save_path=None, verbose=False, loss="modified_huber"): <NEW_LINE> <INDENT> ln_clf = linear_model.SGDClassifier(loss=loss) <NEW_LINE> ln_clf.fit(train_data[0], train_data[1]) <NEW_LINE> if model_save_path is not None: <NEW_LINE> <INDENT> with open(model_save_path, 'wb') as f: <NEW_LINE> <INDEN... | Trains a k-nearest neighbors classifier for face recognition.
:param model_save_path: (optional) path to save model on disk
:param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified
:param knn_algo: (optional) underlying data structure to support knn.default i... | 625941db4527f215b584c72d |
def lengthOfLongestSubstring(self, s): <NEW_LINE> <INDENT> if(len(s) == 1): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> last_seen_position = dict() <NEW_LINE> long_sub = "" <NEW_LINE> current_sub = "" <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> while j < len(s): <NEW_LINE> <INDENT> current_alphabet = s[j] <NEW_LI... | :type s: str
:rtype: int | 625941db45492302aab5e59f |
def climate_records(data, dates=None, mask=nomask, ensoindicator=None, refperiod=None, freq=None, start_date=None, length=None, dtype=None, copy=False, **options): <NEW_LINE> <INDENT> series = climate_series(data, dates=dates, mask=mask, ensoindicator=ensoindicator, refperiod=refperiod, freq=freq, start_date=start_date... | Creates a :class:`~scikits.hydroclimpy.enso.ClimateSeriesRecords` object.
Parameters
----------
data : array_like
Data portion of the array. Any data that is valid for constructing a
MaskedArray can be used here. May also be a TimeSeries object.
dates : {None, DateArray}, optional
A sequence of dates corre... | 625941db32920d7e50b284ab |
def set_light_intensity(self, intensity): <NEW_LINE> <INDENT> ... | Set illumination for LEDs. | 625941dbe1aae11d1e749f92 |
def test_ascent_stages_free(self): <NEW_LINE> <INDENT> self.engine.add_gas(0, 21) <NEW_LINE> self.engine.add_gas(22, 50) <NEW_LINE> self.engine.add_gas(11, 80) <NEW_LINE> self.engine.add_gas(6, 100) <NEW_LINE> gas_list = self.engine._gas_list <NEW_LINE> stages = list(self.engine._free_ascent_stages(gas_list)) <NEW_LINE... | Test dive ascent stages calculation (no deco) | 625941db3d592f4c4ed1d340 |
def get_default_parameters(self): <NEW_LINE> <INDENT> return self.params | :return: | 625941dbcad5886f8bd272b1 |
def search_view(request): <NEW_LINE> <INDENT> search_context_obj = SearchContext() <NEW_LINE> json_ld = LastUpdatedOrderedDict() <NEW_LINE> json_ld['@context'] = search_context_obj.context <NEW_LINE> req_neg = RequestNegotiation('application/json') <NEW_LINE> req_neg.supported_types = ['application/ld+json'] <NEW_LINE>... | Get the search context JSON-LD | 625941db3eb6a72ae02ec7bc |
def initSpecialIvars(self): <NEW_LINE> <INDENT> k = self; c = k.c <NEW_LINE> trace = False or c.config.getBool('trace_bindings_verbose') <NEW_LINE> warn = c.config.getBool('warn_about_missing_settings') <NEW_LINE> for ivar, commandName in ( ('fullCommandKey', 'full-command'), ('abortAllModesKey', 'keyboard-quit'), ('un... | Set ivars for special keystrokes from previously-existing bindings. | 625941dbaad79263cf390d1e |
def timeboard_send_step_skipped(self, step_indexes, timeout): <NEW_LINE> <INDENT> payload = json.dumps({ 'id': str(uuid.uuid4()), 'timestamp': time.time(), 'args': { 'indexes': step_indexes } }) <NEW_LINE> status, result = self._execute_request("stepSkipped", payload, timeout) <NEW_LINE> return status | Set skipped a list of steps
:param step_indexes: A list of indexes of the steps
:type step_indexes: list
:param timeout: maximum time to wait for a reaction from the local manager
:type timeout: float | 625941db30bbd722463cc0a1 |
def do_machine(self, s): <NEW_LINE> <INDENT> m = Machine() <NEW_LINE> m.prompt = 'paul:machine > ' <NEW_LINE> m.cmdloop() | Load machine module to manage lucy machines | 625941db99cbb53fe6792ebf |
def prepare_data(self): <NEW_LINE> <INDENT> if not ("cos" in self.function or "cosine" in self.function): <NEW_LINE> <INDENT> self.data = self.generateSynthData(self.num_tasks, self.ptsPerTask, self.noise, self.graph) <NEW_LINE> self.trainRatings = {} <NEW_LINE> self.testRatings = {} <NEW_LINE> train_split = 1 - self.t... | Run this public method to prepare data | 625941db21a7993f00bc7fcd |
def ioctl(function, devicetype = FILE_DEVICE_UNKNOWN, access = FILE_ANY_ACCESS, method = METHOD_NEITHER): <NEW_LINE> <INDENT> return ((devicetype << 16) | (access << 14) | (function << 2) | method) | Calculate the IOCTL | 625941db07f4c71912b1175d |
def normalize_strings(table_path, values): <NEW_LINE> <INDENT> A = pd.read_csv(table_path) <NEW_LINE> values_list = values.split("|") <NEW_LINE> for value in values_list: <NEW_LINE> <INDENT> current_values = value.split(",") <NEW_LINE> retain_value = current_values[0].strip() <NEW_LINE> for i in range(1, len(current_va... | Normalize the strings to be merged.
Arguments:
table_path: The absolute path of list of strings.
values: The string of values to be normalized in the format
"GROUP1|GROUP2|...."
where
GROUPi = RETAIN_VALUE,VALUE1,VALUE2...
VALUE1,VALUE2 etc will get replac... | 625941db67a9b606de4a8190 |
def __init__( self, hass: HomeAssistantType, username: str, password: str, icloud_dir: Store, max_interval: int, gps_accuracy_threshold: int, ): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self._username = username <NEW_LINE> self._password = password <NEW_LINE> self._fetch_interval = max_interval <NEW_LINE> self._... | Initialize an iCloud account. | 625941dbf9cc0f698b1408d2 |
def check_valid_json(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json.loads(self.settings) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.raise_user_error('invalid_json') | Check if it is possible to at least load the JSON
as a check for its validity | 625941dbe8904600ed9f2209 |
def testSymmetryAddedByGetThermoData(self): <NEW_LINE> <INDENT> spc = Species(molecule=[Molecule().fromSMILES('C[CH]C=CC')]) <NEW_LINE> thermoWithSym = self.databaseWithoutLibraries.getThermoData(spc) <NEW_LINE> thermoWithoutSym = self.databaseWithoutLibraries.estimateThermoViaGroupAdditivity(spc.molecule[0]) <NEW_LINE... | Test that `getThermoData` properly accounts for symmetry in thermo
by comping with the method `estimateThermoViaGroupAdditivity` | 625941db8a43f66fc4b5433b |
def govuk_link_callback(self, response): <NEW_LINE> <INDENT> html = HtmlXPathSelector(response) <NEW_LINE> related_links = html.select("//div[@class='related']/*/nav[@role='navigation']/ul/li").extract() <NEW_LINE> if len(related_links) > 0: <NEW_LINE> <INDENT> return GovUKItem(url=response.url, status=response.status,... | If the given page on www.gov.uk has a related links box, keep track
of the count so that we know which pages have missing related links. | 625941db8c0ade5d55d3ec96 |
def __init__(self, term=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._term = None <NEW_LINE> self.discriminator = ... | TopicTermChangeSet - a model defined in OpenAPI | 625941db57b8e32f52483775 |
def getNeighbors(self, office): <NEW_LINE> <INDENT> return self.paths[str(office.getNumber())] | returns a list of neighbors that the given office has | 625941dba8ecb033257d33a5 |
def notice(self, text, dest): <NEW_LINE> <INDENT> self.write(('NOTICE', dest), text) | Send an IRC NOTICE to a user or a channel.
See IRC protocol documentation for more information. | 625941dbec188e330fd5aa73 |
def releaseLink( self, event ): <NEW_LINE> <INDENT> if self.link is not None: <NEW_LINE> <INDENT> self.canvas.delete( self.link ) <NEW_LINE> <DEDENT> self.linkWidget = self.linkItem = self.link = None | Give up on the current link. | 625941db3c8af77a43ae3a7b |
def ReadFasta(filename): <NEW_LINE> <INDENT> fasta_dict={} <NEW_LINE> content_list=[] <NEW_LINE> header_list=[] <NEW_LINE> header_index_list=[] <NEW_LINE> sequence_list=[] <NEW_LINE> with open(filename, 'r') as infile: <NEW_LINE> <INDENT> for line in infile: <NEW_LINE> <INDENT> line = line.rstrip() <NEW_LINE> if line: ... | 1.Read the contents from the fasta file
2.Count the number of headers
3.logging.info the number of sequences
4.Store the header and sequence in a dictionary as key value pairs
5.Return the dictionary | 625941db92d797404e304464 |
def change_txt_to_excel(input_file, output_file, gap='\t'): <NEW_LINE> <INDENT> workbook = xlwt.Workbook(encoding = 'utf-8') <NEW_LINE> worksheet = workbook.add_sheet('My Worksheet') <NEW_LINE> line_count = 0 <NEW_LINE> with open(input_file, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <IN... | 将一个txt文档转为excel表格 | 625941db26068e7796caefbb |
def __init__(self, date, seq): <NEW_LINE> <INDENT> self.date = date <NEW_LINE> self.seq = seq | :param Optional[datetime] date:
:param int seq:
Constructor for updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong. | 625941db3d592f4c4ed1d341 |
def format_changelog_entry(commit_info, options, last_commit=False): <NEW_LINE> <INDENT> entry = [commit_info['subject']] <NEW_LINE> body = commit_info['body'].splitlines() <NEW_LINE> commitid = commit_info['id'] <NEW_LINE> (git_dch_cmds, body) = extract_git_dch_cmds(body, options) <NEW_LINE> if 'ignore' in git_dch_cmd... | Return a list of lines (without newlines) as the changelog
entry for commit_info (generated by
GitRepository.get_commit_info()). If last_commit is not False,
then this entry is the last one in the series. | 625941db4428ac0f6e5baacd |
def selection_sort(L: list) -> None: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i != len(L): <NEW_LINE> <INDENT> L[i], L[smallest] = L[smallest], L[i] <NEW_LINE> i = i + 1 | L 내 항목을 가장 작은 값부터 큰 값 순으로 다시 정렬한다.
>>> L = [3, 4, 7, -1, 2, 5]
>>> selection_sort(L)
>>> L
[-1, 2, 3, 4, 5, 7] | 625941dbcb5e8a47e48b7d80 |
def get_scores(link_matrix): <NEW_LINE> <INDENT> epsilon = 1E-5 <NEW_LINE> m = 15E-2 <NEW_LINE> num_pages = len(link_matrix) <NEW_LINE> initial_scores = [1./num_pages]*num_pages <NEW_LINE> old_scores = initial_scores <NEW_LINE> new_scores = dot_product(link_matrix, old_scores) <NEW_LINE> norm_initial_scores = multiply_... | Calculate the vector of scores of a network.
Args:
link_matrix (list): the list (of lists) which represents the link
matrix.
Returns:
list: the (final) importance scores of the pages. | 625941db0a366e3fb873eaf5 |
def show_library(self): <NEW_LINE> <INDENT> self.set_page('library') | Show library page. | 625941db4c3428357757c600 |
def get_key(self): <NEW_LINE> <INDENT> return self.key | Subclasses to return the fully qualified key, e.g. a FilesystemConfParam
prepends the filesystem name to self.key | 625941db8e71fb1e9831da82 |
def __init__(self, numTicks=5, tz=None): <NEW_LINE> <INDENT> super(NiceDateLocator, self).__init__() <NEW_LINE> self.numTicks = numTicks <NEW_LINE> self._spacing = None <NEW_LINE> self._unit = None <NEW_LINE> self.tz = tz | :param numTicks: target number of ticks
:param datetime.tzinfo tz: optional time zone. None is local time. | 625941db1d351010ab855df5 |
def handleParameterUpdate(self, event): <NEW_LINE> <INDENT> self.traceids = event.traceids | Update trace IDs | 625941db1f5feb6acb0c4e25 |
def test_template(self): <NEW_LINE> <INDENT> self.assertTemplateUsed(self.response, 'core/index.html') | GET / must use index.html | 625941dbfff4ab517eb2f717 |
def nextYear(date): <NEW_LINE> <INDENT> if hyphenated(date): <NEW_LINE> <INDENT> return str(int(date[:4])+1) + '-01-01' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(int(date[:4])+1) + '0101' | Returns the date string of january 1st of the next year.
date - YYYY-MM-DD or YYYYMMDD. | 625941dbac7a0e7691ed43a1 |
def set_block_alias(self, name): <NEW_LINE> <INDENT> return _hydra_swig.hydra_async_sink_sptr_set_block_alias(self, name) | set_block_alias(hydra_async_sink_sptr self, std::string name) | 625941db851cf427c661a7e6 |
def __init__(self, providing_args=None): <NEW_LINE> <INDENT> self.__signal_results = {'before': None, 'after': None} <NEW_LINE> self.__connection_queue = {type_: queue.Queue() for type_ in ServiceSignalBindType} <NEW_LINE> self.__signals_before = [] <NEW_LINE> self.__signals_after = [] <NEW_LINE> if not providing_args:... | Due to how python manage class prototypes, there's a chance that class definition using register_service_signal
will not be loaded until first import of given class. Therefore it's likely that binding function responsible
for loading functions called before/after signal will be invoked before signal register. In this c... | 625941db30dc7b7665901c3d |
def ols(trendline_options, x_raw, x, y, x_label, y_label, non_missing): <NEW_LINE> <INDENT> valid_options = ["add_constant", "log_x", "log_y"] <NEW_LINE> for k in trendline_options.keys(): <NEW_LINE> <INDENT> if k not in valid_options: <NEW_LINE> <INDENT> raise ValueError( "OLS trendline_options keys must be one of [%s... | Ordinary Least Squares (OLS) trendline function
Requires `statsmodels` to be installed.
This trendline function causes fit results to be stored within the figure,
accessible via the `plotly.express.get_trendline_results` function. The fit results
are the output of the `statsmodels.api.OLS` function.
Valid keys for t... | 625941db3617ad0b5ed681d0 |
def set_instance_attr(instance, value_fields=[], bool_fields=[], datetime_fields=[], image_fields=[], data_list=[]): <NEW_LINE> <INDENT> __field_list = [] <NEW_LINE> def __add_field(field, data): <NEW_LINE> <INDENT> if data.has_key(field): <NEW_LINE> <INDENT> if field in __field_list: <NEW_LINE> <INDENT> return False <... | 为对象的属性设置属性值,
value_fields 普通值
bool_fields 布尔值,有值时为True
data_list 为数据的数组 例:[request.POST, request.FILES]
datetime_fields 时间字段,格式是%Y-%m-%dT%H:%M,
image_fields 图片字段 | 625941db56ac1b37e62644a5 |
def DeleteSnapshotByTimeOffsetTemplate(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DeleteSnapshotByTimeOffsetTemplate", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model ... | This API is used to delete a custom time point screencapturing template.
:param request: Request instance for DeleteSnapshotByTimeOffsetTemplate.
:type request: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOffsetTemplateRequest`
:rtype: :class:`tencentcloud.mps.v20190612.models.DeleteSnapshotByTimeOff... | 625941db4e4d5625662d46ae |
def rotate(self, matrix): <NEW_LINE> <INDENT> temp = 0 <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> for j in range(i, len(matrix)): <NEW_LINE> <INDENT> temp = matrix[i][j] <NEW_LINE> matrix[i][j] = matrix[j][i] <NEW_LINE> matrix[j][i] = temp <NEW_LINE> <DEDENT> <DEDENT> for i in range(len(matrix)): <NEW_... | first transpose
than flip
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead. | 625941dbf7d966606f6aa2e1 |
def __return_repository_format(self): <NEW_LINE> <INDENT> from .repository import RepositoryFormat5 <NEW_LINE> return RepositoryFormat5() | Circular import protection. | 625941db26068e7796caefbc |
def zoom(self): <NEW_LINE> <INDENT> return [self.zoomx(), self.zoomy()] | calculate zoom factors from relation between given size and
width and height of rect in all channels | 625941dbec188e330fd5aa74 |
def updateEnables(self): <NEW_LINE> <INDENT> player = self.mapW.game.player <NEW_LINE> ter = self.square.ter <NEW_LINE> sieged = ter.is_sieged() <NEW_LINE> self.hireCavB.setEnabled(player.can_hire_cav() and not sieged) <NEW_LINE> self.hireInfB.setEnabled(player.can_hire_inf() and not sieged) <NEW_LINE> self.marketUpgrB... | Updates the enables of the buttons in the territory dialog. | 625941db0c0af96317bb84c2 |
def task_release(): <NEW_LINE> <INDENT> return { 'actions': [ validate_in_git_master_branch, remove_dist_files, 'poetry build', 'poetry publish', (webbrowser.open, [f'https://pypi.org/project/{PROJECT}']), ], 'verbosity': 2, } | Upload to pypi.org.
This step must *always* be taken while in the git master branch.
This is an enforced requirement. | 625941dbbf627c535bc134a9 |
def frange(min_val, max_val, step): <NEW_LINE> <INDENT> val = min_val <NEW_LINE> while val < max_val: <NEW_LINE> <INDENT> yield val <NEW_LINE> val += step | Returns an iterator of floats
in the range [<min_val>,<max_val>] including
<min_val> but excluding <max_val> with
an interval of <step>.
>>> from pisotope import iso_gen
>>> lst = list(iso_gen.frange(10,20,1))
>>> min(lst)
10
>>> max(lst)
19
>>> len(lst)
10 | 625941db23849d37ff7b3367 |
def recipe_to_dicts(recipe, fname, recipe_id, origin): <NEW_LINE> <INDENT> core_vals = {} <NEW_LINE> ingredients = [] <NEW_LINE> core_vals["id"] = recipe_id <NEW_LINE> core_vals["recipe_file"] = fname <NEW_LINE> core_vals["origin"] = origin <NEW_LINE> fill_core(core_vals, recipe) <NEW_LINE> for ferm, hop, yeast, misc i... | Given a pybeerxml.recipe.Recipe, convert to a dataframe and write in a
more efficient format.
recipe: pybeerxml Recipe object
fname: file name that beer xml object came from (for recording)
recipe_id: unique id to assign to recipe
origin: source where recipe came from (e.g. brewtoad.com) | 625941db5fdd1c0f98dc050e |
def monkey_patch(): <NEW_LINE> <INDENT> if not CONF.monkey_patch: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if six.PY3: <NEW_LINE> <INDENT> def is_method(obj): <NEW_LINE> <INDENT> return inspect.ismethod(obj) or inspect.isfunction(obj) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> is_method = inspect.isme... | If the CONF.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module path:Decorator function".
Example:
'nova.api.ec2.cloud:nova.notifications.notify_decorator'
Parameters of the de... | 625941db3317a56b86939f2c |
def get_devices(self, device_type): <NEW_LINE> <INDENT> return_type = {} <NEW_LINE> if device_type == 'light': <NEW_LINE> <INDENT> return self.filter_devices(FahLight) <NEW_LINE> <DEDENT> if device_type == 'scene': <NEW_LINE> <INDENT> return self.filter_devices(FahLightScene) <NEW_LINE> <DEDENT> if device_type == 'cove... | After all the devices have been extracted from the xml file,
the lists with device objects are returned to HA | 625941db009cb60464c6368a |
def state_navigate_wp(self, **kwargs): <NEW_LINE> <INDENT> if self.next_wp is not None: <NEW_LINE> <INDENT> self.update_position(self.world_time) <NEW_LINE> if self.world_time >= self.expected_timeout: <NEW_LINE> <INDENT> self.next_wp = None <NEW_LINE> self.waypoints.pop(0) <NEW_LINE> self.state = 'wait' <NEW_LINE> <DE... | If you have reached your goal go to wait state.
Else just update your position. | 625941db4d74a7450ccd449e |
def feed_data(batch_ids, batch_mask, batch_segment, batch_label, keep_prob): <NEW_LINE> <INDENT> feed_dict = { model.input_ids: np.array(batch_ids), model.input_mask: np.array(batch_mask), model.segment_ids: np.array(batch_segment), model.labels: np.array(batch_label), model.keep_prob: keep_prob } <NEW_LINE> return fee... | Data for text_model construction. | 625941db63d6d428bbe447ca |
def getRelativeDirection(myX,myY,nextX,nextY,stat): <NEW_LINE> <INDENT> mydirection=stat['now']['me']['direction'] <NEW_LINE> moveX=nextX-myX <NEW_LINE> moveY=nextY-myY <NEW_LINE> if moveX==0: <NEW_LINE> <INDENT> if moveY==1: <NEW_LINE> <INDENT> newdirection=0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newdirection=... | 辅助函数:纸卷和相邻点的坐标传入,可以返回相对方向
传入参数:
myX: int 当前的横坐标
myY: int 当前的纵坐标
nextX: int 下一步的横坐标
nextY: int 下一步的纵坐标
stat
传出参数:
'left'
'right'
'straight'
version:
1.0: date:2018/6/7 sid 完成函数 | 625941db1f037a2d8b9464d7 |
def isSpecConnected(self): <NEW_LINE> <INDENT> return self.connection is not None and self.connection.isSpecConnected() | Return whether the remote Spec version is connected or not. | 625941db55399d3f0558898f |
def update_db_record(self): <NEW_LINE> <INDENT> self._current.te.test_results_db.db_action( 'update_test_set_record', { 'id': self._id, 'tset_id': self._current_test_set_file, 'test_run_id': self._current.te.test_run.id, 'start_time': self._start_time, 'end_time': self._end_time, 'total_tests': self._total_tests, 'fail... | Method updates record in results database
Args:
none
Returns:
void | 625941db45492302aab5e5a0 |
def test_read_stock_market_data__ignore_missing_file(self): <NEW_LINE> <INDENT> stock_market_data = read_stock_market_data([CompanyEnum.COMPANY_A, CompanyEnum.COMPANY_B], [PERIOD_1, "this-file-does-not-exist"]) <NEW_LINE> assert stock_market_data.get_number_of_companies() > 0 <NEW_LINE> assert CompanyEnum.COMPANY_A in ... | Tests: evaluator_utils.py/read_stock_market_data
Read "../datasets/stock_[a|b]_[1962-2011|this-file-does-not-exist].csv" and check if that happens correctly,
e.g. ignore that one file does not exist | 625941dbdd821e528d63b481 |
def names(import_expr): <NEW_LINE> <INDENT> if isinstance(import_expr, ast.Import): <NEW_LINE> <INDENT> return [alias.name for alias in import_expr.names] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [f'{import_expr.module}.{alias.name}' for alias in import_expr.names] | Get referenced names from an import expression.
| 625941db507cdc57c6306fbb |
def test_jlink_set_reset_pin(self): <NEW_LINE> <INDENT> self.jlink.set_reset_pin_high() <NEW_LINE> self.dll.JLINKARM_SetRESET.assert_called_once() <NEW_LINE> self.jlink.set_reset_pin_low() <NEW_LINE> self.dll.JLINKARM_ClrRESET.assert_called_once() | Tests the J-Link ``set_reset_pin_*`` methods.
Args:
self (TestJLink): the ``TestJLink`` instance
Returns:
``None`` | 625941dbbe383301e01b575b |
def get_id(self): <NEW_LINE> <INDENT> return self.id | Get the numerical identifier of a category. | 625941dbd268445f265b5149 |
@click.command() <NEW_LINE> @environment.pass_env <NEW_LINE> def cli(env): <NEW_LINE> <INDENT> manager = AccountManager(env.client) <NEW_LINE> summary = manager.get_summary() <NEW_LINE> env.fout(get_snapshot_table(summary)) | Prints some various bits of information about an account | 625941db94891a1f4081bd85 |
def put_image(self, img_name, img_tensor): <NEW_LINE> <INDENT> self._vis_data.append((img_name, img_tensor, self._iter)) | Add an `img_tensor` associated with `img_name`, to be shown on
tensorboard.
Args:
img_name (str): The name of the image to put into tensorboard.
img_tensor (torch.Tensor or numpy.array): An `uint8` or `float`
Tensor of shape `[channel, height, width]` where `channel` is
3. The image format shoul... | 625941db7d43ff24873a2f7c |
def centerOnScreen(self): <NEW_LINE> <INDENT> resolution = QtWidgets.QDesktopWidget().screenGeometry() <NEW_LINE> self.move((resolution.width() / 2) - (self.frameSize().width() / 2), (resolution.height() / 2) - (self.frameSize().height() / 2)) | Centers the window on the screen. | 625941db6e29344779a628ea |
def get_html_pages(self, lst_of_questions_id, result_directory): <NEW_LINE> <INDENT> HtmlGenerator.questions_to_html(lst_of_questions_id, self, result_directory) | :param lst_of_questions_id:
:param result_directory:
:return: | 625941db60cbc95b062c681e |
def sum_series(n, x=0, y=1): <NEW_LINE> <INDENT> if n > 0: <NEW_LINE> <INDENT> sumser = [0] * n <NEW_LINE> sumser[0] = x <NEW_LINE> if n > 1: <NEW_LINE> <INDENT> sumser[1] = y <NEW_LINE> <DEDENT> for i in range(2, n): <NEW_LINE> <INDENT> sumser[i] = sumser[i-2] + sumser[i-1] <NEW_LINE> <DEDENT> return(sumser[n-1]) <NEW... | Create a sum series with initial values x and y to create a
series where each value is the sum of the prior two values | 625941dbdd821e528d63b482 |
def write_dual_data(Z, t, series): <NEW_LINE> <INDENT> series.store(Z.vector(), t) | Write dual solution at given time | 625941db099cdd3c635f0f34 |
def add(self, row_dict): <NEW_LINE> <INDENT> self.df = self.df.append(row_dict, ignore_index=True) | Add an other dataframe to the existing one
Keyword Arguments:
other -- [pd.DataFrame] the df to add | 625941dbbde94217f36830c9 |
def triples(self, node=None): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> node = self.root <NEW_LINE> <DEDENT> head = (node["word"], node["ctag"]) <NEW_LINE> for i in sorted(chain.from_iterable(node["deps"].values())): <NEW_LINE> <INDENT> dep = self.get_by_address(i) <NEW_LINE> yield (head, dep["rel"], (dep["w... | Extract dependency triples of the form:
((head word, head tag), rel, (dep word, dep tag)) | 625941db4f6381625f114d16 |
def print_trainable_params(scope=None): <NEW_LINE> <INDENT> n_params = 0 <NEW_LINE> print('name \t| shape \t| num parameters') <NEW_LINE> for var in tf.trainable_variables(scope): <NEW_LINE> <INDENT> shape = var.get_shape() <NEW_LINE> n_elems = shape.num_elements() <NEW_LINE> print(var.name, shape, n_elems) <NEW_LINE> ... | Print to stdout a summary of the number of trainable parameters for the
given scope of the default graph. If scope=None, then all the graph
trainable parameters are consider. | 625941db851cf427c661a7e7 |
@time_pass <NEW_LINE> def handle_dat_edge(data_all): <NEW_LINE> <INDENT> def cal_multi_3(string): <NEW_LINE> <INDENT> s = string.split(',') <NEW_LINE> month_times = len(s) <NEW_LINE> df = list(map(lambda x: list(map(eval, x.split(':')[1].split('_'))), s)) <NEW_LINE> times_sum, weight_sum = pd.DataFrame(df).sum().values... | 把dat_edge个每一条记录的info拆开,然后输出,方便后续的计算
为了简化计算,忽略时间信息,把所有的月份的联系记录汇总起来 | 625941db5f7d997b87174d75 |
def _choose_worst_status(self, status1: str, status2: str) -> str: <NEW_LINE> <INDENT> statuses = [status[0] for status in Data.STATUS_CHOICES] <NEW_LINE> assert status1 in statuses <NEW_LINE> assert status2 in statuses <NEW_LINE> return max([status1, status2], key=lambda status: statuses.index(status)) | Get more problematic status of the two.
Assumption: statuses in Data.STATUS_CHOICES are ordered from least
to most problematic.
:raises AssertionError: when status1 or status2 do not represent
possible status of Data object. | 625941db004d5f362079a60c |
def update(self, sess, states, actions, targets): <NEW_LINE> <INDENT> feed_dict = { self.states_pl: states, self.targets_pl: targets, self.actions_pl: actions} <NEW_LINE> loss = sess.run([self.train_op, self.loss], feed_dict) <NEW_LINE> return loss | Updates the weights of the neural network, based on its targets, its
predictions, its loss and its optimizer.
Args:
sess: TensorFlow session.
states: [current_state] or states of batch
actions: [current_action] or actions of batch
targets: [current_target] or targets of batch | 625941dbcc40096d61595c2a |
def clean_scope(self): <NEW_LINE> <INDENT> flags = self.cleaned_data.get('scope', []) <NEW_LINE> return flags | The scope is assembled by combining all the set flags into a single
integer value which we can later check again for set bits.
If *no* scope is set, we return the default scope which is the first
defined scope in :attr:`provider.constants.SCOPES`. | 625941dbf7d966606f6aa2e2 |
def delete( self, group_id, cache_control="no-cache", custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/providers/Microsoft.Management/managementGroups/{groupId}' <NEW_LINE> path_format_arguments = { 'groupId': self._serialize.url("group_id", group_id, 'str') } <NEW_LINE> url = self._clie... | Delete management group.
If a management group contains child resources, the request will fail.
.
:param group_id: Management Group ID.
:type group_id: str
:param cache_control: Indicates that the request shouldn't utilize any
caches.
:type cache_control: str
:param dict custom_headers: headers that will be added to ... | 625941db9f2886367277ab66 |
def process_job_queue(): <NEW_LINE> <INDENT> jobs = Job.objects.prefetch_related('job_inputs'). prefetch_related('outputs').filter(_status__lt=JobStatus.JOB_TERMINATED) <NEW_LINE> if jobs.count() > 0: <NEW_LINE> <INDENT> logger.info("Starting queue process with %i(s) unfinished jobs", jobs.count()) <NEW_LINE> <D... | Very very simple daemon to monitor jobs queue.
- Retrieve all current non terminated job, and process according to current status.
- Jobs are run on a stateless process
:return: None | 625941dbd58c6744b4257f39 |
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'It is similar to a triditional Django view', 'Gives you the most control over your logic', 'Is mapped manually to URLS' ] <NEW_LINE> return Response({'message': 'Hello!', 'an_apiview... | Returns a list of APIView features | 625941dbd7e4931a7ee9e1f9 |
def query_last_call(self): <NEW_LINE> <INDENT> _resp = requests.get('{}{}'.format(self.test_app_url, 'last_call'), timeout=1) <NEW_LINE> assert _resp.status_code == 200, 'Response headers: {}, response body: {}'.format(_resp.headers, _resp.content) <NEW_LINE> return json.loads(_resp.content.decode("utf-8")) | Queries the test application and gets the details of the last call which sent by the fuzzer
:return: dict | 625941db21a7993f00bc7fcf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.