code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def scaledb(c_1,c_2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = c_1.data.max()-c_2.data.max() <NEW_LINE> a = Series(data=c_2.data.values+d,index=c_2.data.index) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> d = c_1.max()-c_2.max() <NEW_LINE> a = Series(data=c_2.values+d,index=c_2.index) <NEW_LIN...
scale c_2 on c_1, max are then the same
625941c20c0af96317bb8184
def mask(array, mask): <NEW_LINE> <INDENT> masked = np.copy(array) <NEW_LINE> masked[mask == 0] = np.nan <NEW_LINE> return masked
utility function for masking an array :param array: 2d numpy array :param mask: 2d numpy pseudo-boolean array (1 and 0) :return: masked 2d numpy array (nan assigned to 0 values on mask)
625941c2cc0a2c11143dce2c
def __init__(self, k): <NEW_LINE> <INDENT> self.k = k
Initializes the KNN classifier with the k.
625941c2d164cc6175782ce9
def __init__(self, padding_x=0, padding_y=0, mask_bound_height=24, ): <NEW_LINE> <INDENT> gtk.DrawingArea.__init__(self) <NEW_LINE> self.padding_x = padding_x <NEW_LINE> self.padding_y = padding_y <NEW_LINE> self.mask_bound_height = mask_bound_height <NEW_LINE> self.add_events(gtk.gdk.ALL_EVENTS_MASK) <NEW_LINE> self.s...
Initialize IconView class. @param padding_x: Horizontal padding value. @param padding_y: Vertical padding value.
625941c24d74a7450ccd415f
def _post(self, endpoint, params, custompostfix=False, dwollaparse='dwolla'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = requests.post((c.sandbox_host if c.sandbox else c.production_host) + (custompostfix if custompostfix else c.default_postfix) + endpoint, json.dumps(params, default=self._decimal_default), pr...
Wrapper for requests' POST functionality. :param endpoint: String containing endpoint desire :param params: Dictionary containing parameters for request. :param custompostfix: String containing custom OAuth postfix (for special endpoints). :param dwollaparse: Boolean deciding whether or not to call self._parse(). :ret...
625941c2167d2b6e31218b32
def to_url(self, value): <NEW_LINE> <INDENT> print("to_url方法被调用") <NEW_LINE> return value
使用url_for的方法的时候被调用
625941c25fc7496912cc391a
@bootstrap_setup('macbook') <NEW_LINE> def bootstrap_macbook(): <NEW_LINE> <INDENT> bin_path = (pathlib.Path.home() / 'bin') <NEW_LINE> if not bin_path.exists(): <NEW_LINE> <INDENT> bin_path.mkdir() <NEW_LINE> <DEDENT> batcharge = bin_path / 'batcharge' <NEW_LINE> batcharge.symlink_to(git_dir() / 'fenhl.net' / 'syncbin...
Installs `batcharge` for MacBooks.
625941c2b7558d58953c4eb4
def create(self): <NEW_LINE> <INDENT> self.sysadmin = factories.Sysadmin() <NEW_LINE> self.org = factories.Organization() <NEW_LINE> self.public_records = factories.Dataset(**self._package_data()) <NEW_LINE> self._make_resource(self.public_records['id'], self._records) <NEW_LINE> self.public_no_records = factories.Data...
Runs all the creation functions in the class, e.g. creating a test org and test datasets.
625941c2adb09d7d5db6c72c
def package_name_not_changed(key, data, errors, context): <NEW_LINE> <INDENT> package = context.get('package') <NEW_LINE> if data[key] == u'': <NEW_LINE> <INDENT> data[key] = package.name <NEW_LINE> <DEDENT> value = data[key] <NEW_LINE> if package and value != package.name: <NEW_LINE> <INDENT> raise Invalid('Cannot cha...
Checks that package name doesn't change
625941c292d797404e304125
@marc21_holdings.over('date_and_time_of_latest_transaction', '^005') <NEW_LINE> def date_and_time_of_latest_transaction(self, key, value): <NEW_LINE> <INDENT> return value
Date and Time of Latest Transaction.
625941c24f6381625f1149d8
def id_or_maxval(self): <NEW_LINE> <INDENT> if self.id: <NEW_LINE> <INDENT> return int(self.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return maxsize
Method used to compare 2 instances by 'id'-parameter. In case when some instance have empty 'id', method returns 'maxsize' const.
625941c22c8b7c6e89b3575e
def save_img(figure, country): <NEW_LINE> <INDENT> figure.savefig("Trend in number of confirmed cases for {}.png".format(country)) <NEW_LINE> tk.messagebox.showinfo(title="Alert", message='Saved as: "Trend in number of confirmed cases for {}.png"'.format(country))
Saves graph as image
625941c230c21e258bdfa438
def getsize(self,kk): <NEW_LINE> <INDENT> return str(self._ifgs[kk].width), str(self._ifgs[kk].length)
Return width and length IFG
625941c2460517430c394126
def begin_environment(χ=1): <NEW_LINE> <INDENT> return np.eye(χ, dtype=np.float64)
Initiate the computation of a left environment from two MPS. The bond dimension χ defaults to 1. Other values are used for states in canonical form that we know how to open and close.
625941c2e76e3b2f99f3a7ab
def sanitize_generated_module(generated_module_filepath: str): <NEW_LINE> <INDENT> with open(generated_module_filepath, 'r') as sip_module_orig: <NEW_LINE> <INDENT> module_code_orig = sip_module_orig.readlines() <NEW_LINE> <DEDENT> sanitized_code = [] <NEW_LINE> for line_orig in module_code_orig: <NEW_LINE> <INDENT> sa...
Takes the module code as generated by sip and sanitizes it to be compatible with the current standard. It replaces the original file. Currently: - removes all throw() specifications as they are not supported in C++ 17 :param generated_module_filepath:
625941c263b5f9789fde7081
def register(self, module): <NEW_LINE> <INDENT> assert not module.get_module_id() in self.modules <NEW_LINE> self.modules[module.get_module_id()] = module
Register a new module The only restriction is that the given class has to implement the static method get_module_id Args: module (Class): the module class to register
625941c2377c676e91272145
def main(args): <NEW_LINE> <INDENT> tab_printer(args) <NEW_LINE> model = Role2Vec(args) <NEW_LINE> model.do_walks() <NEW_LINE> model.create_structural_features() <NEW_LINE> model.learn_embedding() <NEW_LINE> model.save_embedding()
Role2Vec model fitting. :param args: Arguments object.
625941c2baa26c4b54cb10bd
@marc21.over('copy_and_version_identification_note', '^562..') <NEW_LINE> @utils.for_each_value <NEW_LINE> @utils.filter_values <NEW_LINE> def copy_and_version_identification_note(self, key, value): <NEW_LINE> <INDENT> return { 'identifying_markings': utils.force_list( value.get('a') ), 'version_identification': utils....
Copy and Version Identification Note.
625941c221bff66bcd6848f0
def read_person(): <NEW_LINE> <INDENT> with open(filedialog.askopenfilename(defaultextension='.csv' , filetypes=[('CSV', '*.csv')] , title=PICK_FILE_TEXT), 'r', newline='') as base_file: <NEW_LINE> <INDENT> reader = csv.DictReader(base_file) <NEW_LINE> person = [] <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> if p...
Reads in person and their activities from the external file
625941c27d43ff24873a2c3b
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PlaybackNearlyFinishedRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c2a219f33f34628908
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your application logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message':'Hello!','an...
Returns a list of APIView features.
625941c267a9b606de4a7e57
def WriteOutput( output, options ): <NEW_LINE> <INDENT> if options.global_sort: <NEW_LINE> <INDENT> output.sort() <NEW_LINE> <DEDENT> for o in output: <NEW_LINE> <INDENT> options.stdout.write( "%s\t%s\t%s\t%s\t%f\t%s\t%f\t%5.2f\t%s\n" % o[1])
sort output.
625941c223e79379d52ee502
def _full_from_frags(self, frags): <NEW_LINE> <INDENT> full_line = '\n'.join([l for l, _ in frags]) <NEW_LINE> line_info = frags[-1][-1] <NEW_LINE> return full_line, line_info
Join partial lines to full lines
625941c2004d5f362079a2d1
def test_first_line(self): <NEW_LINE> <INDENT> content = "ho-hum 567\n" + get_directory_authority(content = True) <NEW_LINE> self.assertRaises(ValueError, DirectoryAuthority, content) <NEW_LINE> authority = DirectoryAuthority(content, False) <NEW_LINE> self.assertEqual("turtles", authority.nickname) <NEW_LINE> self.ass...
Includes a non-mandatory field before the 'dir-source' line.
625941c296565a6dacc8f668
def __init__(self, x, y, w, h, colors, title=None, border=True, shadow=True): <NEW_LINE> <INDENT> self.frame = Rect(x, y, w, h) <NEW_LINE> self.colors = colors <NEW_LINE> self.title = title <NEW_LINE> self.has_border = border <NEW_LINE> self.has_shadow = shadow <NEW_LINE> if border: <NEW_LINE> <INDENT> self.bounds = Re...
initialize
625941c2462c4b4f79d1d66c
def regression_signature_fn(examples, unused_features, predictions): <NEW_LINE> <INDENT> if examples is None: <NEW_LINE> <INDENT> raise ValueError('examples cannot be None when using this signature fn.') <NEW_LINE> <DEDENT> default_signature = exporter.regression_signature( input_tensor=examples, output_tensor=predicti...
Creates regression signature from given examples and predictions. Args: examples: `Tensor`. unused_features: `dict` of `Tensor`s. predictions: `Tensor`. Returns: Tuple of default regression signature and empty named signatures. Raises: ValueError: If examples is `None`.
625941c20383005118ecf580
def _grow_bin(self, bin_id, trajs, target_pop): <NEW_LINE> <INDENT> while len(trajs) < target_pop: <NEW_LINE> <INDENT> traj_split = max(trajs) <NEW_LINE> clones = traj_split.clone(self.clone_num) <NEW_LINE> for clone in clones: <NEW_LINE> <INDENT> heappush(trajs, clone)
Split trajectories to increase the population of a bin.
625941c207d97122c4178824
def export_ca_certs_file(self, cafile, ca_is_configured, conn=None): <NEW_LINE> <INDENT> if conn is None: <NEW_LINE> <INDENT> conn = api.Backend.ldap2 <NEW_LINE> <DEDENT> ca_certs = None <NEW_LINE> try: <NEW_LINE> <INDENT> ca_certs = certstore.get_ca_certs( conn, self.suffix, self.realm, ca_is_configured) <NEW_LINE> <D...
Export the CA certificates stored in LDAP into a file :param cafile: the file to write the CA certificates to :param ca_is_configured: whether IPA is CA-less or not :param conn: an optional LDAP connection to use
625941c2be383301e01b5426
def get_cluster_info_by_id(self, region, id): <NEW_LINE> <INDENT> raise Exception("Unimplemented")
Given a region and cluster id, return more information about that cluster. :param region: Region name (str) :param id: Cluster ID (str) :return: Return a Cluster instance
625941c28c0ade5d55d3e955
def config_to_templates(project: Config) -> ProjectTemplates: <NEW_LINE> <INDENT> iam_template = iam.build(project) <NEW_LINE> inputs_template = inputs.build(project) <NEW_LINE> pipeline_templates = codepipeline.build(project) <NEW_LINE> core_template = core.build( project=project, inputs_template=inputs_template, iam_...
Construct all standalone templates from project. :param project: Source project :return: Constructed templates
625941c2187af65679ca50ba
def test_serialize(self): <NEW_LINE> <INDENT> attr_spec_dict = PRES_PREVIEW.attributes[0].serialize() <NEW_LINE> assert attr_spec_dict == { "name": "player", "cred_def_id": CD_ID, "value": "Richie Knucklez" }
Test serialization.
625941c2a8ecb033257d306a
def global_subscribe(bot, event, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> raise commands.Help('Missing keyword and/or conversation!') <NEW_LINE> <DEDENT> if len(args) == 2 and (bot.call_shared('alias2convid', args[0]) or args[0] in bot.conversations): <NEW_LINE> <INDENT> conv_id = bot.call_shared('a...
subscribe keywords globally with a custom conversation as target Args: bot (hangupsbot.core.HangupsBot): the running instance event (hangupsbot.event.ConversationEvent): a message container args (str): the query for the command Returns: str: a status message Raises: commands.Help: the keyword to ...
625941c23539df3088e2e2e8
def has_dwarf_info(self): <NEW_LINE> <INDENT> return bool(self.get_section_by_name('.debug_info'))
Check whether this file appears to have debugging information. We assume that if it has the debug_info section, it has all theother required sections as well.
625941c2956e5f7376d70e0b
def tearDown(self): <NEW_LINE> <INDENT> for image_creator in self.image_creators: <NEW_LINE> <INDENT> image_creator.clean() <NEW_LINE> <DEDENT> if os.path.exists(self.tmp_dir) and os.path.isdir(self.tmp_dir): <NEW_LINE> <INDENT> shutil.rmtree(self.tmp_dir) <NEW_LINE> <DEDENT> super(self.__class__, self).__clean__()
Cleans the images and downloaded image file
625941c29f2886367277a82b
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 12 <NEW_LINE> (_x.y, _x.x, _x.z,) = _struct_3i.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <INDENT> raise...
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941c2090684286d50ec80
def _is_raising(body: List) -> bool: <NEW_LINE> <INDENT> return any(isinstance(node, nodes.Raise) for node in body)
Return whether the given statement node raises an exception.
625941c24a966d76dd550faa
def test_write_int(self): <NEW_LINE> <INDENT> self.assertEqual(_write_int(0x00), b'\x00') <NEW_LINE> self.assertEqual(_write_int(-0x01), b'\xff') <NEW_LINE> self.assertEqual(_write_int(0x80), b'\x80') <NEW_LINE> self.assertEqual(_write_int(0xffff), b'\xff\xff') <NEW_LINE> self.assertEqual(_write_int(0xffffffff), b'\xff...
Test _write_int
625941c215baa723493c3f10
def ContextSetupDisplay( self, node): <NEW_LINE> <INDENT> super( SelectRenderPass, self).ContextSetupDisplay( node ) <NEW_LINE> self.PickProjection()
Customization point calls PickProjection after standard setup
625941c20fa83653e4656f59
def input_boss_name(self, boss_name): <NEW_LINE> <INDENT> self.driver.find_element(*createcustomer.SHOP_BOSS).send_keys(boss_name) <NEW_LINE> handler.logger.info('输入老板名称') <NEW_LINE> return self
输入老板名称
625941c26fb2d068a760f038
def test__build_keys_weekly_week_starts_monday(self): <NEW_LINE> <INDENT> test_settings = TEST_SETTINGS.copy() <NEW_LINE> test_settings['MONDAY_FIRST_DAY_OF_WEEK'] = True <NEW_LINE> with override_settings(REDIS_METRICS=test_settings): <NEW_LINE> <INDENT> d = datetime(2012, 4, 1) <NEW_LINE> keys = self.r._build_keys('te...
Tests ``R._build_keys``. with a *weekly* granularity.
625941c2cad5886f8bd26f76
def __init__(self, generator, **kwargs): <NEW_LINE> <INDENT> self.availableOptions.update({ 'replace': False, 'summary': None, 'text': 'Test', 'top': False, 'outpage': u'User:mastiBot/test', 'maxlines': 1000, 'testprint': False, 'negative': False, 'test': False, }) <NEW_LINE> super(BasicBot, self).__init__(site=True, *...
Constructor. @param generator: the page generator that determines on which pages to work @type generator: generator
625941c2a8370b771705283d
def inv_line_characteristic_hashcode(self, invoice_line): <NEW_LINE> <INDENT> code = super().inv_line_characteristic_hashcode( invoice_line ) <NEW_LINE> hashcode = '%s-%s-%s' % ( code, invoice_line.get('start_date', 'False'), invoice_line.get('end_date', 'False'), ) <NEW_LINE> return hashcode
Add start and end dates to hashcode used when the option "Group Invoice Lines" is active on the Account Journal
625941c2a17c0f6771cbdfef
def test_make_procurement_order(self): <NEW_LINE> <INDENT> vals = { 'picking_type_id': self.env.ref('stock.picking_type_in').id, 'requested_by': SUPERUSER_ID, 'location_id': self.env['stock.location'].search([], limit=1).id, 'warehouse_id': self.env['stock.warehouse'].search([], limit=1).id, 'state': 'approved', } <NEW...
test generation of procurement order
625941c2379a373c97cfaae1
def __init__(self, dustmap, mapname, inmaps, scale=1., errorname='None',hpx=True): <NEW_LINE> <INDENT> self.dustmap = fits.open(dustmap) <NEW_LINE> self.mapname = mapname <NEW_LINE> self.scale = scale <NEW_LINE> self.errorname = errorname <NEW_LINE> self.hpx = hpx <NEW_LINE> self.gasmaps = [] <NEW_LINE> self.nreg = len...
Constructor for class to create extinction residuals from dust map and set of gas maps for given distance range. :param dustmap: `string` FITS file with dust map :param mapname: `string` name of column (HPX) or HDU (WCS) containing dust map :param inmaps: `list` FITS file with WCS map in first HDU (gas maps) :param sca...
625941c24428ac0f6e5ba78e
def welcome_messages_rules_new(): <NEW_LINE> <INDENT> binding = {} <NEW_LINE> url = 'https://api.twitter.com/1.1/direct_messages/welcome_messages/rules/new.json' <NEW_LINE> return _TwitterRequest('POST', url, 'rest:direct_messages', 'post-direct-messages-welcome-messages-rules-new', binding)
Creates a new Welcome Message Rule that determines which Welcome Message will be shown in a given conversation. Returns the created rule if successful.
625941c224f1403a92600b05
def _get_closest_ontology_node(self, name): <NEW_LINE> <INDENT> if not self._ontology_regex: <NEW_LINE> <INDENT> nodes = self._session.query(OntologyNode).all() <NEW_LINE> def sort_function(x, y): <NEW_LINE> <INDENT> return cmp(len(y.name), len(x.name)) or cmp(y.depth, x.depth) <NEW_LINE> <DEDENT> nodes.sort(sort_funct...
Find the ontlogy node that is the best match against the input string, or None if no node matches.
625941c28a349b6b435e8110
def numAtoms(self, flag=None): <NEW_LINE> <INDENT> return len(self._getSubset(flag)) if flag else len(self._indices)
Return number of atoms, or number of atoms with given *flag*.
625941c2fb3f5b602dac362e
def t_LBRACE(t): <NEW_LINE> <INDENT> t.lexer.paren_stack.append("}") <NEW_LINE> return OP(t, "{")
BUCKET\b
625941c2f7d966606f6a9f9f
def _main(args): <NEW_LINE> <INDENT> main_path = pathlib.Path(args.output_dir).resolve() <NEW_LINE> main_path.mkdir(exist_ok=True) <NEW_LINE> template_definition = args.template_definition <NEW_LINE> template_location = template_utilities.get_template_directory() <NEW_LINE> templates_path = template_utilities.install_t...
Generate the content for storage.
625941c2187af65679ca50bb
@main.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> entertainment_news = get_news('entertain') <NEW_LINE> title = 'Home - Welcome to The best news Review Website Online' <NEW_LINE> return render_template('index.html', title = title,entertain = entertainment_news)
View root page function that returns the index page and its data
625941c2b830903b967e98aa
def DA(self, n): <NEW_LINE> <INDENT> pass
R/W Modo de adquisicion de datos: si 'n' es omitido este comano devolvera el modo de adquisicion de datos que se esta utilizando. Si si el valor de 'n' es definido se ajustara el modo de adquisicion de datos a ese valor. (Ver Data Adquisitions Mode Section XVIII 1461's manual)
625941c255399d3f05588650
def get_node_type(order, csv_line_dict): <NEW_LINE> <INDENT> if order == str(0): <NEW_LINE> <INDENT> return consts.Consts.start_event <NEW_LINE> <DEDENT> if csv_line_dict[consts.Consts.csv_terminated] == 'yes': <NEW_LINE> <INDENT> return consts.Consts.end_event <NEW_LINE> <DEDENT> if csv_line_dict[consts.Consts.csv_sub...
:param order: :param csv_line_dict: :return:
625941c276e4537e8c35160d
@api.cache.memoize() <NEW_LINE> def get_solved_problems(tid=None, uid=None, category=None, show_disabled=False): <NEW_LINE> <INDENT> if uid is not None and tid is None: <NEW_LINE> <INDENT> team = api.user.get_team(uid=uid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> team = api.team.get_team(tid=tid) <NEW_LINE> <DEDEN...
Gets the solved problems for a given team or user. Args: tid: The team id category: Optional parameter to restrict which problems are returned Returns: List of solved problem dictionaries
625941c2ad47b63b2c509f1c
def is_unused(name: str) -> bool: <NEW_LINE> <INDENT> return UNUSED_VARIABLE_REGEX.match(name) is not None
Checks whether the given ``name`` is unused. >>> is_unused('_') True >>> is_unused('___') True >>> is_unused('_protected') False >>> is_unused('__private') False
625941c2a219f33f34628909
def generate_random_name(): <NEW_LINE> <INDENT> return '{} {}'.format(random.choice(CSS_COLOR_NAMES), random.choice(ANIMAL_NAMES))
Return a random name generated from a list of colors and animals :return:
625941c263d6d428bbe4448c
def e_monossilabo(arg): <NEW_LINE> <INDENT> check_str(arg, 'e_monossilabo:argumento invalido') <NEW_LINE> return arg in monossilabo
Verifica se um objeto e um monossilabo Args: arg (object) Levanta: ValueError: Caso `arg` nao for uma string. Retorna: bool: True se `arg` for considerado um monossilabo. False caso o contrario.
625941c26fece00bbac2d6da
def hook_point(hooks): <NEW_LINE> <INDENT> def hook_point_dec(func): <NEW_LINE> <INDENT> hook_name = func.__name__ <NEW_LINE> if asyncio.iscoroutinefunction(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> async def async_wrapped(*args, **kwargs): <NEW_LINE> <INDENT> return await run_async_hooks(hooks, hook...
Define a function with pre and post hooks given a hooks dictionary.
625941c27d43ff24873a2c3c
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 19998 if testnet else 9998 <NEW_LINE> <DEDENT> connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpa...
Connect to a CryptoPlay Core JSON-RPC server
625941c215fb5d323cde0aaa
def test_post_apps_empty_body(self): <NEW_LINE> <INDENT> user = User.objects.create(username='ivan') <NEW_LINE> self.client.force_authenticate(user=user) <NEW_LINE> url = reverse('apps') <NEW_LINE> response = self.client.post(url, {}, format='json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_...
Ensure posting to apps when body is empty returns 400
625941c23c8af77a43ae373b
def getFileHandle(self, filePath): <NEW_LINE> <INDENT> import zipfile <NEW_LINE> import tarfile <NEW_LINE> if self.fileType == '.zip' or not self.fileType and zipfile.is_zipfile(filePath): <NEW_LINE> <INDENT> z = zipfile.ZipFile(filePath, 'r') <NEW_LINE> archiveContent = self.getArchiveContentName(z.namelist...
Returns a handle to the give file. The file can be either normal content, zip, tar, .tar.gz, tar.bz2 or gz. :type filePath: str :param filePath: path of file :rtype: file :return: handle to file's content
625941c2925a0f43d2549e12
def manifest_upload(org): <NEW_LINE> <INDENT> manifest_name = settings.fake_manifest.url.default.split('/')[-1] <NEW_LINE> try: <NEW_LINE> <INDENT> with open(f'{manifest_name}', 'rb') as manifest: <NEW_LINE> <INDENT> entities.Subscription(nailgun_conf, organization=org).upload( data={'organization_id': org.id}, files={...
Use to download and upload the manifest file.
625941c207f4c71912b1141e
def exitonclick(self): <NEW_LINE> <INDENT> def exitGracefully(x, y): <NEW_LINE> <INDENT> self.bye() <NEW_LINE> <DEDENT> self.onclick(exitGracefully) <NEW_LINE> if _CFG["using_IDLE"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> mainloop() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> ...
『0027 中文說明』 在點擊時離開,進入主​​迴圈,直到鼠標點擊關閉視窗。 沒有參數。 在龜幕類點擊鼠標時綁定 再見() 函數。 如果"using_IDLE" - 在配置詞典值為 假(默認值), 並進入主循環。 如果在-n模式下的IDLE(無子程式)時 - 在 turtle.cfg 值設置為 真。 在這種情況下,客戶端腳本的IDLE進行主循環。 這是Screen-class的函數,在 龜幕類 沒有可用的實例。 範例: >>> 在點擊時離開() Go into mainloop until the mouse is clicked. No arguments. Bind bye() method to mou...
625941c28c3a873295158355
def remove(self, rule): <NEW_LINE> <INDENT> del self._rules[rule.condition]
Remove this classifier rule from the action set. (Does not affect numerosity.) A KeyError is raised if the rule is not present in the action set when this method is called. Usage: if rule in action_set: action_set.remove(rule) Arguments: rule: The ClassifierRule instance to be removed. Return: None
625941c25fcc89381b1e165a
def create_model_trainable(self): <NEW_LINE> <INDENT> outputs, reg = self.nn(self.input_placeholder) <NEW_LINE> self.predictions = outputs <NEW_LINE> self.q_vals = tf.reduce_sum(tf.mul(self.predictions, self.actions_placeholder), 1) <NEW_LINE> self.loss = tf.reduce_sum(tf.square(self.labels_placeholder - self.q_vals)) ...
The model definition.
625941c2377c676e91272146
def randstring(l): <NEW_LINE> <INDENT> tmp = [struct.pack("B", random.randrange(0, 256, 1)) for x in [""]*l] <NEW_LINE> return "".join(tmp)
Returns a random string of length l (l >= 0)
625941c2dd821e528d63b148
def auto_eat(self): <NEW_LINE> <INDENT> cur_player_species = self.player_state(self.current_player_index).species <NEW_LINE> hungry_herbivores = [species for species in cur_player_species if "carnivore" not in species.trait_names() and species.can_eat()] <NEW_LINE> hungry_carnivores = [species for species in cur_player...
feeds a species when there is only one herbivore or one carnivore with one defender :param list_of_species: the current players species :return: A Feeding, or None if a feeding choice cannot be automatic.
625941c2d268445f265b4e0c
def HWIndex(session_id, top_N_size, refined_positive, refined_negative): <NEW_LINE> <INDENT> ret_pool_size = top_N_size * 5 <NEW_LINE> ordered_id_list = __hw_clip_ids[session_id].intersection(refined_positive).union( __hw_clip_ids[session_id].difference(refined_positive, refined_negative).union( __hw_clip_ids[se...
:param session_id: The UUID of an initialized session. :type session_id: uuid.UUID :param top_N_size: The number of clips that are to have a high probability of being in the list of clip IDs that this function returns. :type top_N_size: int :param refined_negative: Iterable of clip IDs that are known to be positive...
625941c210dbd63aa1bd2b42
def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'Patch'})
patch request where pk is id with which only we are gonna update only the field that is given as input
625941c2b545ff76a8913db4
def chunks(lst, num): <NEW_LINE> <INDENT> for i in range(0, len(lst), num): <NEW_LINE> <INDENT> yield lst[i:i + num]
Yield successive n-sized chunks from l.
625941c2a05bb46b383ec7c1
def set_can_edit_billing_address(self, can_edit_billing_address): <NEW_LINE> <INDENT> self.can_edit_billing_address = can_edit_billing_address
Turns edit-ability of the billing address on/off.
625941c2090684286d50ec81
def on_click(self, int): <NEW_LINE> <INDENT> config.config.set('window.quitPrompt', self.checkbox.isChecked()) <NEW_LINE> config.config.save()
save checkbox state to config
625941c27cff6e4e81117923
def test_warp_reproject_bounds_crossup_fail(runner, tmpdir): <NEW_LINE> <INDENT> srcname = 'tests/data/shade.tif' <NEW_LINE> outputname = str(tmpdir.join('test.tif')) <NEW_LINE> out_bounds = [-11850000, 4810000, -11849000, 4812000] <NEW_LINE> result = runner.invoke(main_group, [ 'warp', srcname, outputname, '--dst-crs'...
Crossed-up bounds raises click.BadParameter.
625941c2ac7a0e7691ed406d
def unescape_html(text): <NEW_LINE> <INDENT> def fixup(m): <NEW_LINE> <INDENT> text = m.group(0) <NEW_LINE> if text[:2] == "&#": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if text[:3] == "&#x": <NEW_LINE> <INDENT> return unichr(int(text[3:-1], 16)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return unichr(int(text[...
Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)
625941c2d53ae8145f87a210
def read_running_games(session): <NEW_LINE> <INDENT> rgs = session.query(RunningGame).all() <NEW_LINE> return [(rg.gameid, rg.situationid, rg.public_ranges, rg.current_userid, rg.next_hh, rg.board_raw, rg.total_board_raw, rg.current_round, rg.pot_pre, rg.increment, rg.bet_count, rg.current_factor, rg.last_action_time, ...
Read RunningGame table from DB into memory
625941c26aa9bd52df036d40
def forward(self, x): <NEW_LINE> <INDENT> h_0 = Variable(torch.zeros( self.n_layers, x.size(0), self.hidden_size)) <NEW_LINE> c_0 = Variable(torch.zeros( self.n_layers, x.size(0), self.hidden_size)) <NEW_LINE> output, (hn, cn) = self.lstm(x, (h_0, c_0)) <NEW_LINE> return output
Train the model to fit the data
625941c263f4b57ef00010bc
def locateMark( mark, payload ): <NEW_LINE> <INDENT> index = payload.find(mark) <NEW_LINE> if index < 0: <NEW_LINE> <INDENT> log.debug("Could not find the mark just yet.") <NEW_LINE> return None <NEW_LINE> <DEDENT> if (len(payload) - index - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH: <NEW_LINE> <INDENT> l...
Locate the given `mark' in `payload' and return its index. The `mark' is placed before the HMAC of a ScrambleSuit authentication mechanism and makes it possible to efficiently locate the HMAC. If the `mark' could not be found, `None' is returned.
625941c2cc40096d615958ee
def convert_params_dict_to_list(model_params_dict): <NEW_LINE> <INDENT> configs = list() <NEW_LINE> for encoding_dimension in model_params_dict["encoding_dimension"]: <NEW_LINE> <INDENT> for activation in model_params_dict["activation"]: <NEW_LINE> <INDENT> for loss in model_params_dict["loss"]: <NEW_LINE> <INDENT> for...
convert params dict to list :param model_params_dict: model params dict :return: model params dict to list
625941c285dfad0860c3adf7
def delete_lungroup_mapping_view(self, view_id, lungroup_id): <NEW_LINE> <INDENT> url = "/mappingview/REMOVE_ASSOCIATE" <NEW_LINE> data = json.dumps({"ASSOCIATEOBJTYPE": "256", "ASSOCIATEOBJID": lungroup_id, "TYPE": "245", "ID": view_id}) <NEW_LINE> result = self.call(url, data, "PUT") <NEW_LINE> self._assert_rest_resu...
Remove lungroup associate from the mapping view.
625941c2be8e80087fb20be3
def test_cmd_write_piezo() -> None: <NEW_LINE> <INDENT> assert type(CMD_WRITE_PIEZO) is WriteCommand <NEW_LINE> assert CMD_WRITE_PIEZO.code == 8
Test that the CMD_WRITE_PIEZO.
625941c20a50d4780f666e2e
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date', value_col: str = 'profit_percent' ) -> Tuple[float, pd.Timestamp, pd.Timestamp]: <NEW_LINE> <INDENT> if len(trades) == 0: <NEW_LINE> <INDENT> raise ValueError("Trade dataframe empty.") <NEW_LINE> <DEDENT> profit_results = trades.sort_valu...
Calculate max drawdown and the corresponding close dates :param trades: DataFrame containing trades (requires columns close_date and profit_percent) :param date_col: Column in DataFrame to use for dates (defaults to 'close_date') :param value_col: Column in DataFrame to use for values (defaults to 'profit_percent') :re...
625941c2009cb60464c63351
def contribute_to_class(self, cls, name): <NEW_LINE> <INDENT> models.signals.pre_save.connect(self._pre_save, sender=cls) <NEW_LINE> models.signals.post_save.connect(self._post_save, sender=cls) <NEW_LINE> super(ObfuscatedIdField, self).contribute_to_class(cls, name)
We register against save signals, so that when this class tries to save, we can update its oid fields.
625941c297e22403b379cf37
def draw_schacht(name): <NEW_LINE> <INDENT> wasserstand = self.__simulation.get("schaechte").get(name) <NEW_LINE> self.__x += [self.__x_pointer, self.__x_pointer + self.__schacht_breite] <NEW_LINE> self.__y += [wasserstand, wasserstand] <NEW_LINE> self.__x_pointer += self.__schacht_breite
Zeichnet den maximalen Wasserstand des Schachts ein und geht dabei von einer festen Schachtbreite aus. :param name: Entspricht dem Namen des Schachts. :type name: str
625941c23c8af77a43ae373c
def test_intercompany_read(self): <NEW_LINE> <INDENT> self.env["res.partner"].with_user(self.user_x).browse(self.partner_y.id).name <NEW_LINE> self.env["res.partner"].with_user(self.user_y).browse(self.partner_x.id).name
Company contacts are readable by other companies
625941c2656771135c3eb80a
def __read_str(self, numchars=1, utf=None): <NEW_LINE> <INDENT> rawstr = np.asscalar(np.fromfile(self._fsrc, dtype='S%s' % numchars, count=1)) <NEW_LINE> if utf or (utf is None and PY_VER == 3): <NEW_LINE> <INDENT> return rawstr.decode('utf-8') <NEW_LINE> <DEDENT> return rawstr
Read a string of a specific length. This is compatible with python 2 and python 3.
625941c2cc0a2c11143dce2e
def delete(self, key): <NEW_LINE> <INDENT> if self.size > 1: <NEW_LINE> <INDENT> nodeToRemove = self._get(key, self.root) <NEW_LINE> if nodeToRemove: <NEW_LINE> <INDENT> self.remove(nodeToRemove) <NEW_LINE> self.size = self.size - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('Error, key not in tree') ...
删除某个节点
625941c2d486a94d0b98e0e3
def decode_body(self): <NEW_LINE> <INDENT> self.body = self.body.decode(self.encoding)
Decode (and replace) self.body via the charset encoding specified in the content-type header
625941c23cc13d1c6d3c7319
def update_profile_network(uci, network_id, current_profile, new_profile): <NEW_LINE> <INDENT> reload_dropbear, reload_firewall = (False, False) <NEW_LINE> if new_profile["ssh"] != current_profile["ssh"]: <NEW_LINE> <INDENT> uci.set_option(SSH_PKG, network_id, "enable", "1" if new_profile["ssh"]["enabled"] else "0") <N...
helper function which will change from the current profile to the new profile for a specific network
625941c2925a0f43d2549e13
def _create_overlay(server_id, backing, bitmap): <NEW_LINE> <INDENT> filenames = _find_bitmap(backing, bitmap) <NEW_LINE> if not filenames: <NEW_LINE> <INDENT> raise se.BitmapDoesNotExist(bitmap=bitmap) <NEW_LINE> <DEDENT> overlay = transientdisk.create_disk( server_id, OVERLAY, backing=backing, backing_format="qcow2")...
To export bitmaps from entire chain, we need to create an overlay, and merge all bitmaps from the chain into the overlay.
625941c2d58c6744b4257bfe
def test_is_suppressed(self): <NEW_LINE> <INDENT> self.assertFalse(SuppressorPipeLine().is_suppressed(incident=self.incident))
Expect false if incident is not suppressed :return:
625941c2c432627299f04be2
def parse_column(line): <NEW_LINE> <INDENT> line = line.rstrip(',') <NEW_LINE> words = line.split() <NEW_LINE> if len(words) < 2: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> column = words[0] <NEW_LINE> col_type = words[1] <NEW_LINE> nullable = "NOT NULL" not in line <NEW_LINE> column = dict(name=column, type=c...
Try to parse column definition. Parameters ---------- line : str Line with column definition. Returns ------- None if line is not a column definition, otherwise returns a dict with column description.
625941c2e5267d203edcdc3d
def distance_matrix(sample_list: List[np.ndarray]) -> np.ndarray: <NEW_LINE> <INDENT> distance_matrix = np.nan * np.ones(shape=(len(sample_list), len(sample_list))) <NEW_LINE> for i in range(0, len(sample_list)): <NEW_LINE> <INDENT> for j in range(0, len(sample_list)): <NEW_LINE> <INDENT> distance_matrix[i, j] = comput...
Compute symmetric matrix of pair distances for a list of samples. Parameters ---------- sample_list Set of samples. Returns ------- distance_matrix Symmatric matrix of pair distances.
625941c2097d151d1a222df9
def WriteRSAPrivateKey(filepath, key): <NEW_LINE> <INDENT> with open(filepath, "wb") as key_file: <NEW_LINE> <INDENT> key_file.write(key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ))
Writes a given private RSA key to a PEM file :param filepath: :param key:
625941c230c21e258bdfa43a
def numSubarrayProductLessThanK(self, nums, k): <NEW_LINE> <INDENT> length = len(nums) <NEW_LINE> res = [] <NEW_LINE> for i in range(length): <NEW_LINE> <INDENT> self.search(i, length, res, nums, k) <NEW_LINE> <DEDENT> return len(res)
:type nums: List[int] :type k: int :rtype: int
625941c28e05c05ec3eea311
@pytest.mark.slowtest <NEW_LINE> @testing.requires_testing_data <NEW_LINE> @requires_version('scipy', '0.11') <NEW_LINE> def test_add_source_space_distances(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> src = read_source_spaces(fname) <NEW_LINE> src_new = read_source_spaces(fname) <NEW_LINE> del src_new[0]['di...
Test adding distances to source space.
625941c244b2445a33932035
def GetClickForce(devicename): <NEW_LINE> <INDENT> return xswGet(devicename, "ClickForce")
Get the ClickForce of a device using xsetwacom. Values are in the range 1 - 21.
625941c28e7ae83300e4af6a
def numDistinct(self, S, T): <NEW_LINE> <INDENT> len_s = len(S) <NEW_LINE> len_t = len(T) <NEW_LINE> dp = [[-1 for _ in xrange(len_s+1)] for _ in xrange(len_t+1)] <NEW_LINE> for col in xrange(len_s+1): <NEW_LINE> <INDENT> dp[0][col] = 1 <NEW_LINE> <DEDENT> for row in xrange(1, len_t+1): <NEW_LINE> <INDENT> dp[row][0] =...
Algorithm: dp, sub-sequence and matching Let W(i, j) stand for the number of subsequences of S(0, i) in T(0, j). If S.charAt(i) == T.charAt(j), W(i, j) = W(i-1, j-1) + W(i-1,j); Otherwise, W(i, j) = W(i-1,j). reference: http://www.programcreek.com/2013/01/leetcode-distinct-subsequences-total-java/ - r a b b b i t -...
625941c263b5f9789fde7083
def affine_forward(x, w, b): <NEW_LINE> <INDENT> out = None <NEW_LINE> number_of_images = x.shape[0] <NEW_LINE> reshaped_vector = x.reshape(number_of_images, -1) <NEW_LINE> out = reshaped_vector.dot(w) + b <NEW_LINE> cache = (x, w, b) <NEW_LINE> return out, cache
Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). For example, batch of 500 RGB CIFAR-10 images would have shape (500, 32, 32, 3). We will reshape each input into a vector...
625941c24f6381625f1149d9
def system_individual_writer(appname, appurl, target, fsize): <NEW_LINE> <INDENT> fnone = get_fnone(fsize) <NEW_LINE> if fnone: <NEW_LINE> <INDENT> target.write("{0} [{1}] {2}\n".format(appname, fsizer(0), appurl)) <NEW_LINE> <DEDENT> elif fsize > 0: <NEW_LINE> <INDENT> target.write("{0} [{1}] {2}\n".format(appname, fs...
Write individual OS/radio link to file. :param appname: App name. :type appname: str :param appurl: App URL. :type appurl: str :param target: File to write to. :type target: file :param fsize: Filesize. :type fsize: int
625941c2460517430c394128
def new_tag(): <NEW_LINE> <INDENT> if line[4] == '+': <NEW_LINE> <INDENT> strand= 'F' <NEW_LINE> <DEDENT> elif line[4] == '-': <NEW_LINE> <INDENT> strand= 'R' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit('Unrecognized character for strand: ' + strand) <NEW_LINE> <DEDENT> tss_tag= 'SSTSC_' + line[0] + '_' + st...
Generate a new TSS tag like this: SSTSC_1_F_000000123
625941c2283ffb24f3c558a1
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument("-d", "--device_os", type=str, default="cisco_ios", help='Device OS default=Cisco IOS', metavar="") <NEW_LINE> parser.add_argument("-D", "--domain", type=str, default="ne.pvhmc.org", help='Domain, default is=ne.pvhmc.org',...
Run if as run as a program. Parsing
625941c2507cdc57c6306c74