code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self): <NEW_LINE> <INDENT> pass | Initialize the base wire format instance. | 625941f64f88993c3716c6ad |
def for_class(self, klass, date): <NEW_LINE> <INDENT> schoolyear = self.pupils.schoolyear <NEW_LINE> pdlist = self.pupils.class_pupils(klass) <NEW_LINE> template = Template(cover_template(klass)) <NEW_LINE> gmap0 = self.base_data(klass, date) <NEW_LINE> gmaplist = [] <NEW_LINE> for pdata in pdlist: <NEW_LINE> <INDENT> ... | <data>: date of issue ('YYYY-MM-DD')
<klass>: a <Klass> instance for the school-class
Return the path to the resulting pdf-file. | 625941f68c3a873295158a10 |
def spawn_process(self, msg): <NEW_LINE> <INDENT> self.processes[msg.uuid] = Process(self, self.parent().connection, msg) | Spawn a process in the container | 625941f64428ac0f6e5bae45 |
def get_icrs_coordinates(name): <NEW_LINE> <INDENT> from .. import conf <NEW_LINE> database = sesame_database.get() <NEW_LINE> db = database.upper()[0] <NEW_LINE> urls = [] <NEW_LINE> domains = [] <NEW_LINE> for url in sesame_url.get(): <NEW_LINE> <INDENT> domain = urllib.parse.urlparse(url).netloc <NEW_LINE> if domain... | Retrieve an ICRS object by using an online name resolving service to
retrieve coordinates for the specified name. By default, this will
search all available databases until a match is found. If you would like
to specify the database, use the science state
``astropy.coordinates.name_resolve.sesame_database``. You can al... | 625941f666673b3332b926de |
def getpol(self, palavra): <NEW_LINE> <INDENT> node = self <NEW_LINE> for char in palavra: <NEW_LINE> <INDENT> node = node.child[char] <NEW_LINE> <DEDENT> return node.pol | Entrada: palavra de arquivo em que queremos saber a polaridade das frases
Saída: polaridade da palavra | 625941f691af0d3eaac9c06b |
def test_return_with_state(self): <NEW_LINE> <INDENT> q = Query('Host') <NEW_LINE> expected = 'RETURN environment, host, host_state' <NEW_LINE> self.assertTrue(expected in str(q)) | Test return clause that should include state. | 625941f69b70327d1c4e1425 |
def _check_shapeit_align_file(fn, task=None): <NEW_LINE> <INDENT> log_fn = fn.replace(".snp.strand", "") + ".log" <NEW_LINE> if not os.path.isfile(log_fn): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> log = None <NEW_LINE> with open(log_fn, "r") as i_file: <NEW_LINE> <INDENT> log = i_file.read() <NEW_LINE> <DED... | Checks the log to explain the absence of an .snp.strand file.
Args:
fn (str): the name of the file to check
task (str): the name of the task
Returns:
bool: ``True`` if everything is normal, ``False`` otherwise.
This function looks for known message in the log file. If the SNPs were
read from the legend f... | 625941f6ad47b63b2c50a5cd |
def write_result_file(simulated: pd.DataFrame, test_id: str, result_path: str): <NEW_LINE> <INDENT> filename = os.path.join(result_path, f'{test_id}.csv') <NEW_LINE> simulated.to_csv(filename, index=False) | Create test result file for upload to
http://sbml.org/Facilities/Database/Submission/Create
Requires csv file with test ID in name and content of [time, Species, ...] | 625941f6d58c6744b42582aa |
def pick_follower(self): <NEW_LINE> <INDENT> elements = list(self.followers.elements()) <NEW_LINE> if not elements: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return choice(elements) | Pick and return a random follower node. More frequent followers
are more likely to be picked. If this node has no followers, this
method returns None. | 625941f6a934411ee3751ce2 |
def maximum(num_list): <NEW_LINE> <INDENT> list_len = len(num_list) <NEW_LINE> if list_len == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> max_val = 0 <NEW_LINE> for i in range(0, list_len): <NEW_LINE> <INDENT> if num_list[i] > max_val: <NEW_LINE> <INDENT> max_val = num_list[i] <NEW_LINE> <DEDENT> <DEDENT> re... | This function returns the maximum
number from num_list
:param num_list: list of numbers
:return: the maximum number | 625941f624f1403a926011ae |
def _selectDbidGeoloc(self,distance=0): <NEW_LINE> <INDENT> return sql_select('adresses_tb', ['dbid','terre_dist_plus(latitude, longitude,%s,%s)AS distance'], 'terre_dist_plus(latitude, longitude,%s,%s)<%s ORDER BY distance', [self.latitude,self.longitude,self.latitude,self.longitude,distance], self._verbose) | Select les adresses qui sont a une distance d et rend liste des dbid adresses | 625941f656b00c62f0f14cab |
def print_split_information(self, output_file): <NEW_LINE> <INDENT> print("features used to split") <NEW_LINE> for i in range(self.ls_split_features): <NEW_LINE> <INDENT> print("layer {}:".format(i)) <NEW_LINE> print(self.ls_split_features[i]) <NEW_LINE> <DEDENT> print("leafs logistic features") <NEW_LINE> for i in ran... | print split information and output it to a file
:return: | 625941f6adb09d7d5db6cdd9 |
def quaternion_to_str(q): <NEW_LINE> <INDENT> return "{:.3f} {:+.3f}i {:+.3f}j {:+.3f}k".format(*q) | An informal, nicely printable string representation of the Quaternion object.
| 625941f6046cf37aa974d38e |
@main <NEW_LINE> def print_sentiment(text='Are you virtuous or verminous?'): <NEW_LINE> <INDENT> words = extract_words(text.lower()) <NEW_LINE> assert words, 'No words extracted from "' + text + '"' <NEW_LINE> layout = '{0:>' + str(len(max(words, key=len))) + '}: {1}' <NEW_LINE> for word in extract_words(text.lower()):... | Print the words in text, annotated by their sentiment scores.
For example, to print each word of a sentence with its sentiment:
# python3 trends.py "computer science is my favorite!" | 625941f64527f215b584ca9e |
def transform(self): <NEW_LINE> <INDENT> if self.is_legacy_event: <NEW_LINE> <INDENT> self._set_legacy_event_type() <NEW_LINE> self.process_legacy_fields() <NEW_LINE> <DEDENT> self.process_event() <NEW_LINE> self.dump_payload() | Transform the event with legacy fields and other necessary
modifications. | 625941f6be383301e01b5ac6 |
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self._conn.close() | Context manager exit. | 625941f6de87d2750b8603e7 |
def _sign(self, data: bytes) -> bytes: <NEW_LINE> <INDENT> salt = self._get_salt() <NEW_LINE> signature = self._signify(data=data, salt=salt, key=self._hasher.signing_key) <NEW_LINE> return salt + signature | Sign given data and produce a signature stream composed of salt and signature.
The signature stream (salt and signature) is encoded using the chosen encoder.
Args:
data: data to sign.
Returns:
A signature stream containing salt and signature. | 625941f671ff763f4b549ce5 |
def median(list_in): <NEW_LINE> <INDENT> list_in.sort() <NEW_LINE> half = int(len(list_in) / 2) <NEW_LINE> if len(list_in) % 2 != 0: <NEW_LINE> <INDENT> return float(list_in[half]) <NEW_LINE> <DEDENT> elif len(list_in) % 2 ==0: <NEW_LINE> <INDENT> value = (list_in[half - 1] + list_in[half]) / 2 <NEW_LINE> return float(... | Calculates the median of the data
:param list_in: A list
:return: float | 625941f6627d3e7fe0d6949f |
def initialize(self, inputs, initial_state=None, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError | Called before any decoding iterations.
This methods must compute initial input values and initial state.
Args:
inputs: (structure of) tensors that contains the input for the
decoder. In the normal case, its a tensor with shape
[batch, timestep, embedding].
initial_state: (structure of) tensors that contai... | 625941f632920d7e50b28823 |
def flush_db(db_name, db_user, db_port, db_host, db_passwd): <NEW_LINE> <INDENT> db_host = db_host if db_host is not None else 'localhost' <NEW_LINE> db_port = db_port if db_port is not None else 5432 <NEW_LINE> conn = get_db_conn(db_name, db_user, db_port, db_host, db_passwd) <NEW_LINE> curs = conn.cursor() <NEW_LINE>... | HARD Truncate all DB Tables | 625941f660cbc95b062c6b91 |
def test_mixed_set_core_size(self, backend, mset): <NEW_LINE> <INDENT> assert mset.core_size == sum(s.core_size for s in mset) | MixedSet core_size should return the sum of the Set core_sizes. | 625941f6bde94217f3683438 |
def date_time_exit(): <NEW_LINE> <INDENT> date_time() <NEW_LINE> sys.exit() | Function to exit the program after displaying the current date and time | 625941f6d53ae8145f87a8b0 |
def register(self, hyperp_name, hyperp_fn): <NEW_LINE> <INDENT> assert hyperp_name not in self.name_to_h_fn <NEW_LINE> self.name_to_h_fn[hyperp_name] = hyperp_fn | Registers a function that can be called to create an hyperparameter
with a given name.
Delayed creation of the hyperparameter is implemented through a thunk.
Args:
hyperp_name (str): Hyperparameter name to associate with the function.
The hyperparameter name must be unique.
hyperp_fn (() -> (deep_arch... | 625941f645492302aab5e918 |
def run(self): <NEW_LINE> <INDENT> for i in range(2): <NEW_LINE> <INDENT> self.register() <NEW_LINE> <DEDENT> for i in range(3): <NEW_LINE> <INDENT> if self.login(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('登录失败') | 主程序,先进行2次用户注册,在进行用户登录(3次尝试机会)
:return: | 625941f6a05bb46b383ece68 |
def compile_scripts(command, target): <NEW_LINE> <INDENT> installer_src = path.dirname(path.abspath(__file__)) <NEW_LINE> mod_path = path.join(path.dirname(installer_src), "MAGSBS") <NEW_LINE> import gleetex <NEW_LINE> for script in ["matuc.py", "matuc_js.py"]: <NEW_LINE> <INDENT> subprocess_call( f"pyinstaller --clean... | Compile matuc using py2exe. Cross-compilation is determined by
`python_command` (either 'python' or 'wine python'). | 625941f697e22403b379d5e9 |
def cast(*args): <NEW_LINE> <INDENT> return _itkMorphologicalWatershedImageFilterPython.itkMorphologicalWatershedImageFilterIUS3IUL3_cast(*args) | cast(itkLightObject obj) -> itkMorphologicalWatershedImageFilterIUS3IUL3 | 625941f699fddb7c1c9de9db |
def calc_longwave_irradiance(ea, t_a_k, p=1013.25, z_T=2.0, h_C=2.0): <NEW_LINE> <INDENT> lapse_rate = met.calc_lapse_rate_moist(t_a_k, ea, p) <NEW_LINE> t_a_surface = t_a_k - lapse_rate * (h_C - z_T) <NEW_LINE> emisAtm = calc_emiss_atm(ea, t_a_surface) <NEW_LINE> L_dn = emisAtm * met.calc_stephan_boltzmann(t_a_surface... | Longwave irradiance
Estimates longwave atmospheric irradiance from clear sky.
By default there is no lapse rate correction unless air temperature
measurement height is considerably different than canopy height, (e.g. when
using NWP gridded meteo data at blending height)
Parameters
----------
ea : float
atmospheri... | 625941f650812a4eaa59c968 |
def interpolate(kvs, f, geo=None, nodes=None): <NEW_LINE> <INDENT> if isinstance(kvs, bspline.KnotVector): <NEW_LINE> <INDENT> kvs = (kvs,) <NEW_LINE> <DEDENT> if nodes is None: <NEW_LINE> <INDENT> nodes = [kv.greville() for kv in kvs] <NEW_LINE> <DEDENT> if geo is not None: <NEW_LINE> <INDENT> rhs = utils.grid_eval_tr... | Perform interpolation in a spline space.
Returns the coefficients for the interpolant of the function `f` in the
tensor product B-spline basis `kvs`.
By default, `f` is assumed to be defined in the parameter domain. If a
geometry is passed in `geo`, interpolation is instead done in physical
coordinates.
`nodes` shou... | 625941f6f548e778e58cdbce |
def node_all_children(self, node_id=None): <NEW_LINE> <INDENT> if self.static: <NEW_LINE> <INDENT> if not node_id or self.__maintree.has_node(node_id): <NEW_LINE> <INDENT> return self.__maintree.get_node(node_id).get_children() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> else: <... | Return children of a node | 625941f6bf627c535bc1381d |
def test_get_participants_unauthorized(client, add_participants): <NEW_LINE> <INDENT> rv = client.get("/api/participants/") <NEW_LINE> response = rv.get_json() <NEW_LINE> assert rv.status_code == HTTPStatus.UNAUTHORIZED <NEW_LINE> assert response["msg"] == "Missing Authorization Header" | Test get participants list when user is not logged in. | 625941f6435de62698dfe29b |
def draw_events(self, ctx, events, x, y, width, height): <NEW_LINE> <INDENT> if (self.grey_background % 2) == 0: <NEW_LINE> <INDENT> ctx.rectangle(x, y - self.padding / 2, width, height + self.padding) <NEW_LINE> ctx.set_source_rgb(0.9, 0.9, 0.9) <NEW_LINE> ctx.fill() <NEW_LINE> <DEDENT> last_x_drawn = int(x) <NEW_LINE... | ! Draw Event
@param self this object
@param ctx ctx
@param events events
@param x x
@param y y
@param width width
@param height height
@return none | 625941f65166f23b2e1a57a7 |
def test_columns_alignment(self): <NEW_LINE> <INDENT> self.check_columns_alignment(self.csv_file) | Have the header, second and last records the same number of columns?
| 625941f64a966d76dd551664 |
def AddIndexer(self, element_type): <NEW_LINE> <INDENT> ext_attrs = self._interface.ext_attrs <NEW_LINE> has_indexed_getter = ('IndexedGetter' in ext_attrs or 'CustomIndexedSetter' in ext_attrs) <NEW_LINE> if has_indexed_getter: <NEW_LINE> <INDENT> indexed_getter = ('JS("%s", "#[#]", this, index)' % self.SecureOutputTy... | Adds all the methods required to complete implementation of List. | 625941f6f9cc0f698b140c43 |
def run(self): <NEW_LINE> <INDENT> limits = self._limits <NEW_LINE> column = self._column <NEW_LINE> values_within_range = list(set((self._df .rdd.map(lambda x: x[column]) .filter(lambda x: x >= limits[0] and x <= limits[1]) .collect()))) <NEW_LINE> return values_within_range | Get list of values within accepted range, without duplicates | 625941f64e696a04525c9a9c |
def save(self, key: str, value: str) -> None: <NEW_LINE> <INDENT> self.redis.set(key, value) | Add/update db record for given (key, value) pair
:param key: the key in the db
:param value: the value to be stored under the given key in db | 625941f6b5575c28eb68e654 |
def ghostnet(**kwargs): <NEW_LINE> <INDENT> return get_ghostnet(model_name="ghostnet", **kwargs) | GhostNet model from 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters. | 625941f6711fe17d825429aa |
def for_participants(self, participants): <NEW_LINE> <INDENT> user_ids = sorted(user.pk for user in participants) <NEW_LINE> str_ids = '_'.join(str(uid) for uid in user_ids) <NEW_LINE> key = PARTICIPANTS_CACHE_KEY_PATTERN.format(str_ids) <NEW_LINE> conversations = cache.get(key) <NEW_LINE> if conversations: <NEW_LINE> ... | Query a specific conversation for a specified list of participants.
If possible, retrieve it from cache (no invalidation required) as a
unique set of participants can have only one conversation. | 625941f6e8904600ed9f2586 |
def ffmpeg_convert(ogg_audio): <NEW_LINE> <INDENT> wav = ogg_audio.replace(".oga", ".wav") <NEW_LINE> try: <NEW_LINE> <INDENT> process = subprocess.Popen(['ffmpeg', '-i', ogg_audio, wav], shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) <NEW_LINE> <DEDENT> except subprocess.SubprocessError as e: <NEW_L... | converts the .ogg audios into .wav using ffmpeg from shell
:return str | 625941f68a43f66fc4b546ab |
def __init__(self, value, indices): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.indices = indices | Arguments:
value: the value to compare against
indices: the indices to compare, if None then compare all indices | 625941f66fece00bbac2dd94 |
def rename_snapshot_set(self, ss_set_name, new_ss_set_name, cluster_name): <NEW_LINE> <INDENT> object_type = SNAPSHOT_SETS <NEW_LINE> payload = {'new-name': new_ss_set_name, 'cluster-id': cluster_name} <NEW_LINE> return self.modify_resource(object_type, payload, object_name=ss_set_name) | Get resource details from xtremio cluster.
:param cluster_name: the xtremio cluster name
:param ss_set_name: the name of a snapshot set
:param new_ss_set_name: new snapshot set name
:returns: resource object -- dict or None | 625941f65fdd1c0f98dc0884 |
def execute_google_api_request(request): <NEW_LINE> <INDENT> maximum_request_attempts = 3 <NEW_LINE> request_attempt_count = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> request_attempt_count += 1 <NEW_LINE> try: <NEW_LINE> <INDENT> return request.execute() <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> ... | Execute a Google API request and return the response.
Keyword arguments:
request -- request object | 625941f631939e2706e4d4ae |
def generate_test_customers(): <NEW_LINE> <INDENT> all_customers = [] <NEW_LINE> genders = (Customers.MALE, Customers.FEMALE) <NEW_LINE> for name in range(10): <NEW_LINE> <INDENT> customer = Customers.objects.create( name='test_{}'.format(name), phone='342324{}'.format(name), email='test_{}@mail.com'.format(name), age=... | Generates test customers
:return: list of generated customer objects
:rtype: list | 625941f650485f2cf553d3ea |
def get_legislation_reported_out_of_committee( committee_name: str, agency: str, begin_date: datetime, end_date: datetime ) -> Dict[str, Any]: <NEW_LINE> <INDENT> argdict: Dict[str, Any] = dict( committeeName=committee_name, agency=agency, beginDate=begin_date, endDate=end_date ) <NEW_LINE> keydict: Dict[str, Any] = { ... | See: http://wslwebservices.leg.wa.gov/committeeactionservice.asmx?op=GetLegislationReportedOutOfCommittee | 625941f6236d856c2ad44e32 |
def __init__(self): <NEW_LINE> <INDENT> self.z_26 = list(range(0,26)) <NEW_LINE> self.letters = ['A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] <NEW_LINE> self.choice = 1 <NEW_LINE> self.plain_text = '' <NEW_LINE> self.cipher_text = '' <NEW_LINE> self.b = -1 <N... | Intialize data needed to do Affine encryption | 625941f63c8af77a43ae3df6 |
def should_not_be_items_in_basket(self): <NEW_LINE> <INDENT> items_list = self.is_not_element_present(*BasketPageLocators.BASKET_ITEMS) <NEW_LINE> assert items_list, "List items is presented." | Ожидаем, что в корзине нет товаров | 625941f6956e5f7376d714b9 |
def neatenDisplay(self): <NEW_LINE> <INDENT> currVal = self.var.get() <NEW_LINE> neatValue = RO.StringUtil.neatenDMSStr(currVal) <NEW_LINE> if currVal != neatValue: <NEW_LINE> <INDENT> self.var.set(neatValue) | Neaten up the display -- preserve the final field as is
(rather than trying to guess the # of digits to display),
but format the others. | 625941f69c8ee82313fbbdc6 |
def _make_geoserver_context(): <NEW_LINE> <INDENT> return { 'url': config['ckanext.publicamundi.vectorstorer.geoserver.url'].rstrip('/'), 'api_url': config['ckanext.publicamundi.vectorstorer.geoserver.api_url'].rstrip('/'), 'reload_url': config.get('ckanext.publicamundi.vectorstorer.geoserver.reload_url'), 'workspace':... | Returns a dictionary containg the geoserver configuration | 625941f663f4b57ef0001754 |
def mixed_net34(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = MixedNet_V10(BasicBlock3D, [3, 4, 6, 3], **kwargs) <NEW_LINE> return model | Constructs a ResNet-34 model.
| 625941f676d4e153a657f180 |
def print_omim(out_dir, api_key): <NEW_LINE> <INDENT> mim_files = fetch_mim_files(api_key, mim2genes=True, genemap2=True) <NEW_LINE> file_name = "genemap2.txt" <NEW_LINE> file_path = out_dir / file_name <NEW_LINE> LOG.info("Print genemap genes to %s", file_path) <NEW_LINE> with file_path.open("w", encoding="utf-8") as ... | Print HPO files to a directory
Args:
out_dir(Path) | 625941f6283ffb24f3c55f48 |
def draw(self, update=True, text_color=(0, 0, 0), bkp_pos=None, fancy_format=True) -> str: <NEW_LINE> <INDENT> self.was_clicked = pygame.mouse.get_pressed()[0] <NEW_LINE> if self.active and update: <NEW_LINE> <INDENT> outline_color = self.outline_color_active <NEW_LINE> outline_width = 4 <NEW_LINE> self.update() <NEW_L... | Usage: 'temp = field_name.draw(...); if temp is not False: target = temp' where target is the string you want to get as user input | 625941f68a349b6b435e87c0 |
def disallowed_table(*tables): <NEW_LINE> <INDENT> return not bool(settings.WHITELIST.issuperset(tables)) if settings.WHITELIST else bool(settings.BLACKLIST.intersection(tables)) | Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise. | 625941f6fff4ab517eb2fa8f |
def c2py(plural): <NEW_LINE> <INDENT> import token, tokenize <NEW_LINE> tokens = tokenize.generate_tokens(io.StringIO(plural).readline) <NEW_LINE> try: <NEW_LINE> <INDENT> danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n'] <NEW_LINE> <DEDENT> except tokenize.TokenError: <NEW_LINE> <INDENT> raise ValueEr... | Gets a C expression as used in PO files for plural forms and returns a
Python lambda function that implements an equivalent expression. | 625941f6460517430c3947c1 |
def getValue(self): <NEW_LINE> <INDENT> data = self.getData() <NEW_LINE> return data.getValue() | Значение ячейки. | 625941f6004d5f362079a97c |
def goodNodes(self, root: TreeNode) -> int: <NEW_LINE> <INDENT> pass | put solution here | 625941f6711fe17d825429ab |
def phot_dens_black_body(eps, T = 2.726): <NEW_LINE> <INDENT> result = (eps * u.eV) ** 2. / (c.hbar * c.c).to('eV cm')**3. / np.pi**2. <NEW_LINE> result /= (np.exp(eps * u.eV / (c.k_B * T * u.K).to('eV')) - 1.) <NEW_LINE> return result | Calculate photon density of black body spectrum
in units of 1 / eV / cm^3
Parameters
----------
eps: `~numpy.ndarray`
Photon energy in eV
T: float
Temperature of black body spectrum in K, optional
Returns
-------
`~astropy.Quantity` with photon densities
See e.g. Blumenthal & Gould 1970 Eq. 2.58 | 625941f6187af65679ca576f |
def selectBaseSequence(cards, sequence_table, scope): <NEW_LINE> <INDENT> one_seq_table = np.zeros_like(cards, dtype=int) <NEW_LINE> for rank in scope: <NEW_LINE> <INDENT> for suit in range(4): <NEW_LINE> <INDENT> if sequence_table[suit, rank] > 0: <NEW_LINE> <INDENT> for con_num in range(sequence_table[suit, rank]): <... | 階段を一つ選択する
Parameters
----------
cards: np.array((5,15))
持っているカードを示す配列
sequence_table: np.array((5,15))
持っているカードで構成出来る階段の情報を示す配列 ref: tableMaker
scope: list(int)
構成する組を置くための探索順序を示すリスト
昇順なら弱いカード, 降順なら強いカードを選択する
Return
------
one_seq_table: np.array((5,15))
選んだ一つの階段を示す配列 | 625941f67b25080760e39aa3 |
def parseLog(log_path): <NEW_LINE> <INDENT> ip_list = set() <NEW_LINE> with open(log_path) as fd: <NEW_LINE> <INDENT> for line in fd: <NEW_LINE> <INDENT> ip = line.strip().split()[0] <NEW_LINE> ip_list.add(ip) <NEW_LINE> <DEDENT> <DEDENT> return ip_list | 解析日志提取IP
:param log_path:
:return: set{'192.168.1.15','45.44.84.64',} | 625941f6baa26c4b54cb1766 |
def process_item(self,item,spider): <NEW_LINE> <INDENT> cols = item.keys() <NEW_LINE> values = [item[col] for col in cols] <NEW_LINE> sql = "INSERT INTO `yiyao` ("+','.join(cols)+") VALUES ("+','.join(['%s']*13)+");" <NEW_LINE> self.cur.execute(sql,values) <NEW_LINE> self.conn.commit() <NEW_LINE> logger.info('mysql: ad... | 在MySQL中插入数据。 | 625941f62eb69b55b151cf07 |
def RegisterUser( self, request: chupacabra_pb2.UserRequest, context: Any ) -> chupacabra_pb2.UserResponse: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> auth_handler = get_user_authentication_handler() <NEW_LINE> return chupacabra_implementation.register_user( request, auth_handler) <NEW_LINE> <DEDENT> except Exception... | Try to register a new user. | 625941f632920d7e50b28824 |
def get_data(self, table, columns): <NEW_LINE> <INDENT> if len(columns) < 1: <NEW_LINE> <INDENT> return [[]] <NEW_LINE> <DEDENT> sqlselect = ','.join(columns) <NEW_LINE> con = open_db_con(self.db_con_str) <NEW_LINE> cur = con.cursor() <NEW_LINE> cur.execute('SELECT %s from %s'%(sqlselect, table)) <NEW_LINE> rows = [r f... | basically does "select" ','.join(columns) "from table"
columns is a list of strings | 625941f6796e427e537b0c1a |
def logMe(logItem): <NEW_LINE> <INDENT> print(logItem) | This function prints out logging when the program is called form the command line. | 625941f6a79ad161976cc794 |
def create_graph(A=None): <NEW_LINE> <INDENT> N = A.shape[0] <NEW_LINE> G=nx.Graph() <NEW_LINE> G.add_nodes_from(range(N)) <NEW_LINE> list_edges = [] <NEW_LINE> for u in range(N-1): <NEW_LINE> <INDENT> for v in range(u+1,N): <NEW_LINE> <INDENT> w = A[u,v] <NEW_LINE> if w != 0.0: <NEW_LINE> <INDENT> list_edges.append((u... | Create a undirected, unweighted graph given adjacency matrix
Parameters:
- A: adjacency matrix
Return: a graph | 625941f6d10714528d60033a |
def __check_if_username_used__(self, user_name: str, resp): <NEW_LINE> <INDENT> user = self.model.select().where(self.model.email == user_name) <NEW_LINE> if user.exists(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks if the username already exists
:param user_name: str
:param resp: object
:return: boolean | 625941f626068e7796caf338 |
def test_all_4(self): <NEW_LINE> <INDENT> t = True <NEW_LINE> p = self.d4.all() <NEW_LINE> msg = printfail(t, p, 'Truth') <NEW_LINE> self.assertTrue(t == p, msg) | larry.all_4 | 625941f6009cb60464c639fb |
def writeIndex(self): <NEW_LINE> <INDENT> with open('index.txt','a') as index: <NEW_LINE> <INDENT> index.write(json.dumps(sorted([(k,v) for k,v in self.index.items()],key = lambda x: x[0]))) <NEW_LINE> <DEDENT> with open('termID_mapping.txt','a') as index: <NEW_LINE> <INDENT> for term, termID in sorted([(k,v) for k,v i... | write index, and ID mappings to disk | 625941f644b2445a339326e0 |
def plot_shape(self, shape): <NEW_LINE> <INDENT> shape.make_papath() <NEW_LINE> shape.starrow = self.createstarrow(shape) <NEW_LINE> shape.enarrow = self.createenarrow(shape) <NEW_LINE> shape.stmove = self.createstmove(shape) <NEW_LINE> shape.starrow.setParentItem(shape) <NEW_LINE> shape.enarrow.setParentItem(shape) <N... | Create all plotting related parts of one shape.
@param shape: The shape to be plotted. | 625941f6ab23a570cc2507d7 |
def maxProfit(self, prices): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> for i in range(len(prices)-1): <NEW_LINE> <INDENT> if prices[i] < prices[i+1]: <NEW_LINE> <INDENT> result += prices[i+1] - prices[i] <NEW_LINE> <DEDENT> <DEDENT> return result | :type prices: List[int]
:rtype: int | 625941f6cdde0d52a9e53688 |
def create_placeholders(nx, classes): <NEW_LINE> <INDENT> x = tf.placeholder(tf.float32, shape=(None, nx), name='x') <NEW_LINE> y = tf.placeholder(tf.float32, shape=(None, classes), name='y') <NEW_LINE> return x, y | Returns two placeholders, x and y, for the neural network
nx: the number of feature columns in our data
classes: the number of classes in our classifier
x is the placeholder for the input data to the neural network
y is the placeholder for the one-hot labels for the input data | 625941f638b623060ff0b43b |
def load_any_files_wildcard(path: str, cur_filepath: str = None): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for filepath in expand_wildcard_path(path, cur_filepath): <NEW_LINE> <INDENT> out.append(load_any_file(filepath, cur_filepath)) <NEW_LINE> <DEDENT> return out | Load any supported file format, supporting wildcard matches as well.
Args:
path (str): Path to files (including any wildcards)
cur_filepath (str): The path to the current file from which we
are loading the new file
(important for relative paths) | 625941f676d4e153a657f181 |
def setParams(self, **kwargs): <NEW_LINE> <INDENT> if kwargs.has_key('weight'): <NEW_LINE> <INDENT> self.params['nr_weight'] = len(kwargs['weight']) <NEW_LINE> <DEDENT> if kwargs.has_key('log2C'): <NEW_LINE> <INDENT> self.params['C'] = 2 ** kwargs['log2C'] <NEW_LINE> kwargs.pop('log2C') <NEW_LINE> <DEDENT> if kwargs.ha... | Set parameters for SVM training. Apart from the ones below, you can use all parameters
defined for the LIBSVM svm_model class, see their documentation.
:key searchlog: Save a list of coordinates and the achieved CV accuracy to this file. | 625941f66fb2d068a760f6f6 |
def sum(x): <NEW_LINE> <INDENT> if not isinstance(x.tensor, tf.Tensor): <NEW_LINE> <INDENT> raise TypeError('Expected a Tensor, but got %r' % x.tensor) <NEW_LINE> <DEDENT> return api._AnalyzerOutput(tf.placeholder(x.tensor.dtype, ()), api.CanonicalAnalyzers.SUM, [x], {}) | Computes the sum of a `Column`.
Args:
x: An input `Column' wrapping a `Tensor`.
Returns:
A `Statistic`. | 625941f666656f66f7cbc7fc |
def createFile(self, subtitle): <NEW_LINE> <INDENT> suburl = subtitle["link"] <NEW_LINE> videofilename = subtitle["filename"] <NEW_LINE> srtbasefilename = videofilename.rsplit(".", 1)[0] <NEW_LINE> zipfilename = srtbasefilename + ".zip" <NEW_LINE> self.downloadFile(suburl, zipfilename) <NEW_LINE> if zipfile.is_zipfile(... | pass the URL of the sub and the file it matches, will unzip it
and return the path to the created file | 625941f60c0af96317bb8835 |
def set_trusted_cert_file_path(self, trusted_cert_file_path): <NEW_LINE> <INDENT> if trusted_cert_file_path.strip() != "": <NEW_LINE> <INDENT> self.trusted_cert_file_path = trusted_cert_file_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.trusted_cert_file_path = "" | Sets the path to the CA file for SSL peer/chain verification | 625941f65fcc89381b1e1d13 |
def update_base(self): <NEW_LINE> <INDENT> result = self.status_base.update_base() <NEW_LINE> if result: <NEW_LINE> <INDENT> log.info("Status base updated") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StandardError <NEW_LINE> <DEDENT> return | Create the base for twitter status | 625941f6dd821e528d63b7f2 |
def main(): <NEW_LINE> <INDENT> opts = parse_arguments() <NEW_LINE> if opts.debug: <NEW_LINE> <INDENT> logging.basicConfig(level=logging.DEBUG) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.basicConfig(level=logging.WARNING) <NEW_LINE> <DEDENT> repo = git.Repo(os.getcwd()) <NEW_LINE> with repo.git.custom_enviro... | Generate widget report and commit changes | 625941f68e7ae83300e4b61e |
def sizeof_int(self): <NEW_LINE> <INDENT> raise NotImplementedError("Abstract method") | Return the size of an int in bits | 625941f61f5feb6acb0c5198 |
def getBDBEntryHTML( self, key ): <NEW_LINE> <INDENT> if BibleOrgSysGlobals.debugFlag and debuggingThisModule: <NEW_LINE> <INDENT> print( t("HebrewLexicon.getBDBEntryHTML( {} )").format( repr(key) ) ) <NEW_LINE> <DEDENT> if '.' not in key: <NEW_LINE> <INDENT> if self.hix is None: self.load() <NEW_LINE> key = self.hix.g... | The key is a BDB number (string) like 'ah.ba.aa'.
but can also be a Strong's number (with or without the leading H)
Returns an HTML entry for the given key.
Returns None if the key is not found. | 625941f6dc8b845886cb5b86 |
def related_filenames(full_filename, num=2): <NEW_LINE> <INDENT> basename, extension = path.splitext(full_filename) <NEW_LINE> return ["{}_{}{}".format(basename, i, extension) for i in range(num)] | returns num filenames similar to the input
| 625941f65f7d997b871750ed |
def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> super(GetSnapshotInputSet, self)._set_input('ResponseFormat', value) | Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.) | 625941f6adb09d7d5db6cdda |
def write_from_image(image, file_name, compression=True): <NEW_LINE> <INDENT> tiff_image = TiffImage(file_name, mode='w') <NEW_LINE> tiff_image.write(image, compression) | Write a Tiff file from an *image* instance. | 625941f6fbf16365ca6f6821 |
def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(owner=self.request.user) | Set owner to the user creating the project and create entry. | 625941f6507cdc57c630733a |
def tile_subwindows(mdi: QtWidgets.QMdiArea, except_type: Type = type(None)): <NEW_LINE> <INDENT> windows_hidden = list() <NEW_LINE> for window in mdi.subWindowList(): <NEW_LINE> <INDENT> if type(window) == except_type: <NEW_LINE> <INDENT> windows_hidden.append(window) <NEW_LINE> window.hide() <NEW_LINE> <DEDENT> <DEDE... | Tile all subwindows of an MDI area, except for objects of 'except_type'. | 625941f6a17c0f6771cbe69d |
def FlaskKv(app, kv_store, url_prefix =''): <NEW_LINE> <INDENT> from . import server <NEW_LINE> blueprint = server.construct_kv_blueprint(kv_store, url_prefix) <NEW_LINE> app.register_blueprint(blueprint) <NEW_LINE> return blueprint | :param app: Your flask application
:param kv_store: Something that presents a dictionary interface
:param url_prefix: The sub-path to use for the key value store. Default is /.
:return: the generated blueprint for the kv store | 625941f6293b9510aa2c38de |
def getPrintOutput(event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return EventReferences[event].printoutput <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return "Err getting output:"+str(e) | Given a tuple of (module, resource), return
the doc string of an event if it exists, else return '' | 625941f6851cf427c661ab58 |
def reset(self): <NEW_LINE> <INDENT> self.image = self.__static <NEW_LINE> self.__right = False <NEW_LINE> self.__left = False <NEW_LINE> self.__rightImage = 0 <NEW_LINE> self.__leftImage = 0 <NEW_LINE> self.rect.center = (320, -50) <NEW_LINE> self.__dy = 6 <NEW_LINE> if self.rect.centery < 440: <NEW_LINE> <INDENT> sel... | This method resets the player's position when they lose a life. | 625941f673bcbd0ca4b2c6c4 |
def test_additional_vars(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse('main')) <NEW_LINE> self.assertEqual(resp.context['user'].username, 'regular') <NEW_LINE> self.assertEqual(resp.context['version'], settings.VERSION) <NEW_LINE> self.assertEqual(resp.context['search_on'], 'orders') <NEW_LINE> self.assert... | Test the remaining vars. | 625941f6b545ff76a8914464 |
def test_output_messages_51_start_25(url, user_1, public_channel_1): <NEW_LINE> <INDENT> message_list = create_messages(url, user_1, public_channel_1['channel_id'], 0, 51) <NEW_LINE> assert len(message_list) == 51 <NEW_LINE> resp = requests.get(url + '/channel/messages', params={ 'token': user_1['token'], 'channel_id':... | Testing when a channel has 51 total messages at start 25.
| 625941f673bcbd0ca4b2c6c5 |
def _node_to_csv(self, node, sep=','): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if node.type == self.TYPE_TOP: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> out = [] <NEW_LINE> if node.type == self.TYPE_STORAGE: <NEW_LINE> <INDENT> out.append(node.name) <NEW_LINE> out.appen... | print a node to csv
@node: the node to consider | 625941f6498bea3a759ba0fc |
def _update_access_obj(access, res_access, resource_list): <NEW_LINE> <INDENT> for res in resource_list: <NEW_LINE> <INDENT> access_items = access.get(res, []) <NEW_LINE> for access_item in access_items: <NEW_LINE> <INDENT> operation = _get_operation(access_item, res) <NEW_LINE> res_list = access_item.get('resources', ... | Update access object with access data. | 625941f601c39578d7e7548a |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._include_dirs = kwargs.pop('include_dirs', []) <NEW_LINE> self._library_dirs = kwargs.pop('library_dirs', []) <NEW_LINE> self._libraries = kwargs.pop('libraries', []) <NEW_LINE> self._extra_compile_args = kwargs.pop('extra_compile_args', []) <NEW_LINE> self.... | Instantiates a Cython code wrapper.
The following optional parameters get passed to ``distutils.Extension``
for building the Python extension module. Read its documentation to
learn more.
Parameters
==========
include_dirs : [list of strings]
A list of directories to search for C/C++ header files (in Unix
for... | 625941f6b7558d58953c5555 |
def extract_subthreshold(x, tt, dt=0.02, thresh_v=-50, thresh_dv=0, min_size=10, **kwargs): <NEW_LINE> <INDENT> from quickspikes._spikes import extract_subthreshold as es <NEW_LINE> return es(x, tt, thresh_v, thresh_dv * dt, min_size) | Extract subthreshold activity
Spikes are removed from the voltage trace by beginning at each peak and
moving in either direction until V drops below thresh_v OR dv drops below
thresh_dv.
- x : signal to analyze
- tt : times of the peaks (in samples)
- dt : time step of signal
- thresh_v : do not include points contig... | 625941f6cc40096d61595f9d |
def remove_from_cache(self, query): <NEW_LINE> <INDENT> return | Delete query from cache | 625941f655399d3f05588d08 |
def test_ode_solutions(self): <NEW_LINE> <INDENT> timepoints = np.linspace(0,10,100) <NEW_LINE> params_values = [2, 4, 6] <NEW_LINE> ode_object = ODE(self.x, self.f, self.params, self.C, self.g, self.h, self.u, params_values = params_values , x_init = np.ones(4), input_values = self.input_values, timepoints = timepoint... | Solve the ODE manually and solve using
ODE class to compare the two solutions | 625941f671ff763f4b549ce7 |
def open(self, _fname, mode): <NEW_LINE> <INDENT> modes = { 'wb': QIODevice.WriteOnly | QIODevice.Truncate, 'w': QIODevice.WriteOnly | QIODevice.Text | QIODevice.Truncate, 'rb': QIODevice.ReadOnly, 'r': QIODevice.ReadOnly | QIODevice.Text, } <NEW_LINE> try: <NEW_LINE> <INDENT> qt_mode = modes[mode] <NEW_LINE> <DEDENT> ... | Open an in-memory PyQIODevice instead of a real file. | 625941f6e5267d203edce2e4 |
def create_database(): <NEW_LINE> <INDENT> conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=student") <NEW_LINE> conn.set_session(autocommit=True) <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute("DROP DATABASE IF EXISTS sparkifydb") <NEW_LINE> cur.execute("CREATE DATABASE sparkifydb ... | Connects to PostgreSQL server and creates sparkifydb database | 625941f63d592f4c4ed1d6ab |
def test_default_initial_amount(): <NEW_LINE> <INDENT> a = 5 <NEW_LINE> assert(a == 5) | A | 625941f6187af65679ca5770 |
def __init__(self, pedido): <NEW_LINE> <INDENT> self.__pedido = pedido | Cria o comando pagar e insere o pedido na qual o comando irá agir. | 625941f6a934411ee3751ce5 |
def __init__( self, *, service_specification: Optional["ServiceSpecification"] = None, **kwargs ): <NEW_LINE> <INDENT> super(OperationProperties, self).__init__(**kwargs) <NEW_LINE> self.service_specification = service_specification | :keyword service_specification: Service specifications of the operation.
:paramtype service_specification:
~azure.mgmt.appplatform.v2021_06_01_preview.models.ServiceSpecification | 625941f6d18da76e23532b2e |
def ClearApplicationState(self, package): <NEW_LINE> <INDENT> self.CloseApplication(package) <NEW_LINE> self.RunShellCommand('rm -r /data/data/%s/cache/*' % package) <NEW_LINE> self.RunShellCommand('rm -r /data/data/%s/files/*' % package) <NEW_LINE> self.RunShellCommand('rm -r /data/data/%s/shared_prefs/*' % package) | Closes and clears all state for the given |package|. | 625941f6fb3f5b602dac3cea |
def process_date_created(self, text): <NEW_LINE> <INDENT> date = parse(text) <NEW_LINE> if self.date_created == 'N/A': <NEW_LINE> <INDENT> self.date_created = date <NEW_LINE> <DEDENT> if date < self.date_created: <NEW_LINE> <INDENT> self.date_created = date | Set date_created to the oldest date (date created). | 625941f650812a4eaa59c96a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.