code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def update(self): <NEW_LINE> <INDENT> if self.derived: <NEW_LINE> <INDENT> for par in self.derived._PARCLASSES: <NEW_LINE> <INDENT> name = objecttools.instancename(par) <NEW_LINE> try: <NEW_LINE> <INDENT> self.derived.__dict__[name].update() <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> objecttools.augm...
Calls the update methods of all derived parameters.
625941eadc8b845886cb5a0d
def createOneRow( n ): <NEW_LINE> <INDENT> row = [] <NEW_LINE> for col in range(n): <NEW_LINE> <INDENT> row.append(0) <NEW_LINE> <DEDENT> return row
returns a row of n zeros... You might use this as the INNER loop in createBoard
625941eaadb09d7d5db6cc63
def list_by_vpn_connection( self, resource_group_name, gateway_name, connection_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NE...
Retrieves all vpn site link connections for a particular virtual wan vpn gateway vpn connection. :param resource_group_name: The resource group name of the vpn gateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the vpn conne...
625941ead99f1b3c44c67a5c
def update_status(self, provisioning=False, rebooting=False, failed=None): <NEW_LINE> <INDENT> raise NotImplementedError
Check the current status and update it if it has changed
625941ea627d3e7fe0d69327
def fit(self, x, y): <NEW_LINE> <INDENT> x_values = x.values if isinstance(x, pd.DataFrame) else x <NEW_LINE> y_values = y.values if isinstance(y, pd.DataFrame) else y <NEW_LINE> self.weights = np.zeros(x.shape[1], dtype='float') <NEW_LINE> for index_x, target in zip(x_values, y_values): <NEW_LINE> <INDENT> update = se...
Fit perceptron
625941ea460517430c39464e
def coefficient(activity): <NEW_LINE> <INDENT> if activity == 'минимальный': <NEW_LINE> <INDENT> AMR = 1.2 <NEW_LINE> return AMR <NEW_LINE> <DEDENT> if activity == 'низкий': <NEW_LINE> <INDENT> AMR = 1.375 <NEW_LINE> return AMR <NEW_LINE> <DEDENT> if activity == 'средний': <NEW_LINE> <INDENT> AMR = 1.55 <NEW_LINE> retu...
Сalculation of basal metabolism
625941ea5f7d997b87174f73
def ask_for_asn(question): <NEW_LINE> <INDENT> while(True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = input(question) <NEW_LINE> check_asn_range(int(result)) <NEW_LINE> return result <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('Must be an integer.')
Ask for the required ASN and return the result.
625941eae5267d203edce16d
def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> searched_appkey = resource_auth(self.request.headers.get(TAG_APPKEY, default=''), RESOURCE_POS, None, self.get_argument(TAG_APPID, default='')) <NEW_LINE> if searched_appkey is None: <NEW_LINE> <INDENT> self.set_status(401) <NEW_LINE> self.write({"status": 100...
查询符合条件的pos列表
625941ea293b9510aa2c3767
def gene_distance_score(X, collection, metric='euclidean'): <NEW_LINE> <INDENT> gene_dict = mongo_group_by(collection, 'gene_name') <NEW_LINE> nsamples = X.shape[0] <NEW_LINE> npairs = int(nsamples * (nsamples - 1) / 2) <NEW_LINE> all_intragene_index = [] <NEW_LINE> for key in gene_dict: <NEW_LINE> <INDENT> if len(gene...
Find intra/inter gene distance scores between samples. Parameters ---------- X : Data frame, shape (n_samples, n_features) Feature data frame. metric : string, optional Which distance measure to use when calculating distances. Must be one of the options allowable in scipy.spatial.distance.pdist. Defau...
625941ea8da39b475bd65450
def test_raise_error(self): <NEW_LINE> <INDENT> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> mgmpe = NRCan15SiteTerm(gmpe_name='FukushimaTanaka1990')
Tests that exception is raised
625941ea32920d7e50b286ab
def getAction(self, gameState): <NEW_LINE> <INDENT> return self._getAction(gameState, self._minimax)
Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Terminal states can be found by one of the following: pacman won, pacman lost or there are no legal moves. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex...
625941ea55399d3f05588b8e
def maybe_xrange_iter(lst, coerce = True): <NEW_LINE> <INDENT> if isinstance(lst, PiecewiseXrange): <NEW_LINE> <INDENT> return lst.my_iter() <NEW_LINE> <DEDENT> elif coerce: <NEW_LINE> <INDENT> return xrange_iter(lst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return lst.__iter__()
if lst is a PiecewiseXrange or coerce, iterate as though lst is a piecewise xrange otherwise, normal lst iteration
625941ea01c39578d7e75312
def ensure_at_least_n_paths(self, n, retries=20): <NEW_LINE> <INDENT> for trial in range(retries): <NEW_LINE> <INDENT> self.construct_connected_graph() <NEW_LINE> if len(self.reduced_paths) >= n: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> """ If failed to construct graph with n paths after retrying ""...
Construct a connected graph with at-least n reduced paths
625941ea627d3e7fe0d69328
@before(LockingWith(actor, X, Y) <= PNot(Lockable(X))) <NEW_LINE> def before_locking_lockable(actor, x, y, ctxt) : <NEW_LINE> <INDENT> raise AbortAction(ctxt.world[NoLockMessages(x, "no_lock")], actor=actor)
One can't lock that which has no lock.
625941ea283ffb24f3c55dd3
def log_likelihood(self): <NEW_LINE> <INDENT> N = float(self.N) <NEW_LINE> return sum( count*math.log(count/N) for inst,count in self )
log likelihood of a dataset, given the data distribution
625941ead7e4931a7ee9e3f6
def fetch_debate_list(): <NEW_LINE> <INDENT> parser = scrape(INDEX_URL) <NEW_LINE> rows = parser.find_all('tr') <NEW_LINE> rows_with_debates = [ row for row in rows if [ klass for child in row.find_all('td') for klass in child.get('class', []) ] == DEBATE_CLASSES ] <NEW_LINE> debates = [_row_to_debate(row) for row in r...
Get a list of debates to download.
625941ea925a0f43d254a352
def reproject(input_data, output_projection, shape_out=None, projection_type='bilinear'): <NEW_LINE> <INDENT> if isinstance(input_data, (PrimaryHDU, ImageHDU)): <NEW_LINE> <INDENT> array_in = input_data.data <NEW_LINE> wcs_in = WCS(input_data.header) <NEW_LINE> <DEDENT> elif isinstance(input_data, tuple) and isinstance...
Reproject data to a new projection. Parameters ---------- input_data : `~astropy.io.fits.PrimaryHDU` or `~astropy.io.fits.ImageHDU` or tuple The input data to reproject. This can be an image HDU object from :mod:`astropy.io.fits`, such as a `~astropy.io.fits.PrimaryHDU` or `~astropy.io.fits.ImageHDU`, or i...
625941eacdde0d52a9e5350d
def config_syslog(syslog): <NEW_LINE> <INDENT> syslog.ipv4.tos.type = xr_infra_syslog_cfg.LoggingTos.dscp <NEW_LINE> syslog.ipv4.tos.dscp = xr_infra_syslog_cfg.LoggingDscpValue.cs2 <NEW_LINE> syslog.logging_facilities.facility_level = xr_infra_syslog_cfg.Facility.local0 <NEW_LINE> vrf = syslog.host_server.vrfs.Vrf() <N...
Add config data to syslog_service object.
625941ea56ac1b37e626469c
def __init__(self, coordinator, blind, device_class, config_entry, motor): <NEW_LINE> <INDENT> super().__init__(coordinator, blind, device_class, config_entry) <NEW_LINE> self._motor = motor <NEW_LINE> self._motor_key = motor[0] <NEW_LINE> if self._motor not in ["Bottom", "Top"]: <NEW_LINE> <INDENT> _LOGGER.error("Unkn...
Initialize the blind.
625941ea30dc7b7665901e37
def _guardar_tag(self, tag, categoria=None): <NEW_LINE> <INDENT> guardado_ok = False <NEW_LINE> datos = self.sesion.recuento.a_tag(categoria) <NEW_LINE> tipo_tag = self.sesion.recuento.tipo_tag <NEW_LINE> def _intento(datos): <NEW_LINE> <INDENT> return self.rampa.guardar_tag(tipo_tag, datos, QUEMA) <NEW_LINE> <DEDENT> ...
Guarda los datos en el tag, lo vuelve a leer y compara los dos strings para verificar la correcta escritura. Devuelve True si el guardado y la comprobación están correctos, False en caso contrario.
625941ead164cc6175783225
def init_vars(self): <NEW_LINE> <INDENT> GLib.timeout_add(self.SPEED, self.on_timer)
Tell Glib some stuff
625941ea71ff763f4b549b6b
def run(self,func,args): <NEW_LINE> <INDENT> if len(self.free_list) == 0 and len(self.thread_list) < self.max_num: <NEW_LINE> <INDENT> self.generate_thread() <NEW_LINE> <DEDENT> w = (func, args,) <NEW_LINE> self.q.put(w)
线程池执行一个任务 :param func: 任务函数 :param args: 任务函数所需参数 :return: 如果线程池已经终止,则返回True否则None
625941ea1f037a2d8b9466d3
def main(): <NEW_LINE> <INDENT> response = get_open_weather() <NEW_LINE> data = decode_json(response) <NEW_LINE> iterate_data(data)
Run all functions
625941ea4527f215b584c929
def import_file(package: str, fname: str) -> ModuleType: <NEW_LINE> <INDENT> mod_name = fname.rstrip('.py') <NEW_LINE> spec = spec_from_file_location(mod_name, '{}/{}'.format(package, fname)) <NEW_LINE> module = module_from_spec(spec) <NEW_LINE> spec.loader.exec_module(module) <NEW_LINE> return module
Import file directly. This is a hack to import files from packages without importing <package>/__init__.py, its purpose is to allow import without requiring all the dependencies at this point. Args: package: Package to import from fname: File to import Returns: Imported module
625941eae1aae11d1e74a193
def adjust_learning_rate(opt, optimizer, epoch): <NEW_LINE> <INDENT> lr = opt.learning_rate * (0.1 ** (epoch // opt.lr_update)) <NEW_LINE> for param_group in optimizer.param_groups: <NEW_LINE> <INDENT> param_group['lr'] = lr <NEW_LINE> <DEDENT> return lr
Sets the learning rate to the initial LR decayed by 10 every [lr_update] epochs
625941ea76e4537e8c351b4d
def additional_function_domain(self, arg): <NEW_LINE> <INDENT> arg0, arg1, arg_1 = super(product_product, self).additional_function_domain(arg) <NEW_LINE> if arg[0] == 'domain_maintenance_contract': <NEW_LINE> <INDENT> arg0 = 'id' <NEW_LINE> arg1 = 'in' <NEW_LINE> product_ids = [] <NEW_LINE> if arg[-1] and arg[-1][-1] ...
Fonction qui permet de faire un point d'entrée pour modifier le domain du search dans un module qui hérite de product_product
625941ead10714528d6001bf
def pausar(self): <NEW_LINE> <INDENT> self._pausado = not self._pausado <NEW_LINE> if self._pausado: <NEW_LINE> <INDENT> self._dt = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._dt = DT
Pausa o continúa la ejecución de la aplicación :return:
625941ea21a7993f00bc81cf
def go_to(self, location): <NEW_LINE> <INDENT> destination_place = self.place.get_neighbor(location) <NEW_LINE> if destination_place.locked: <NEW_LINE> <INDENT> print(destination_place.name, 'is locked! Go look for a key to unlock it') <NEW_LINE> print("You are at", self.place.name) <NEW_LINE> <DEDENT> else: <NEW_LINE>...
Go to a location if it's among the exits of player's current place. >>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [], []) >>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], []) >>> sather_gate.add_exits([gbc]) >>> sather_gate.locked = True >>> gbc.add_exits([sather_gate]) >>> me = Player('pla...
625941eac4546d3d9de72f0f
def testUserSearchFn(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> c.login(username=self.admin.username, password=self.password) <NEW_LINE> response = c.get("/manage/usersearch", { "userstr": str(self.fake_admin.username) }) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertStringContain...
Tests whether the user-search page works properly. Note that this doubles as a test of the find_user function, because this page is a very lightweight wrapper around that function.
625941ea5510c4643540f8ae
def stop_commands(self, cohs=[]): <NEW_LINE> <INDENT> cmd_ids = get_commands(cohs) <NEW_LINE> active_circuits = [c for c in self._circuits if c.id in cohs] <NEW_LINE> active_cohs = [c.id for c in active_circuits] <NEW_LINE> self.logger.info("Prepare %d circuits to STOP ..." % len(active_cohs)) <NEW_LINE> for cmd_id in ...
Stops all or selected circuits. @param cohs: list of commands_on_host @type cohs: list
625941eab545ff76a89142ec
def boosted_trees_center_bias_eager_fallback(tree_ensemble_handle, mean_gradients, mean_hessians, l1, l2, name=None, ctx=None): <NEW_LINE> <INDENT> _ctx = ctx if ctx else _context.context() <NEW_LINE> tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) <NEW_LINE> mean_gradients = _ops....
This is the slowpath function for Eager mode. This is for function boosted_trees_center_bias
625941ea956e5f7376d71342
def signal_handler(signal, frame): <NEW_LINE> <INDENT> print('Interruption signal received!') <NEW_LINE> if ('instances_df' in globals()) and (len(instances_df) > 0): <NEW_LINE> <INDENT> print('Saving current status in {}'.format(instances_df_filename)) <NEW_LINE> done_df = pd.DataFrame([{'instance_id': instance_id_fro...
Callback function called on interruption.
625941eab57a9660fec33d62
def __repr__(self): <NEW_LINE> <INDENT> return u' '.join([u'%02x' % ord(b) for b in self.encode()])
Returns a human readable string of hex digits corresponding to the encoded full packet content.
625941ea66656f66f7cbc684
def usage(): <NEW_LINE> <INDENT> print("Usage: %s --file=[filename]" % sys.argv[0]) <NEW_LINE> sys.exit()
HW PRE DIFINED FUNCTION FOR HOME GROWN ARGPARSE
625941eaf548e778e58cda57
def Datetimegen(t): <NEW_LINE> <INDENT> gpst = round(t, 2) <NEW_LINE> gpst = from_gps(gpst) <NEW_LINE> gpst = str(gpst)[0:22] <NEW_LINE> date = gpst[8:10]+gpst[5:7]+gpst[2:4] <NEW_LINE> time = gpst[11:] <NEW_LINE> return date, time
Generate a date and a time in my own format. Arguments: t -- A GPS time (unit removed). Returns: A date of form DDMMYYYY and a time of form HH:MM:SS.
625941ea16aa5153ce36294f
def sample(h, seed_ix, n): <NEW_LINE> <INDENT> x = np.zeros((vocab_size, 1)) <NEW_LINE> x[seed_ix] = 1 <NEW_LINE> ixes = [] <NEW_LINE> for t in range(n): <NEW_LINE> <INDENT> h = np.tanh(np.dot(Weights_input_hidden, x) + np.dot(Weights_hidden_hidden, h) + bias_hidden) <NEW_LINE> y = np.dot(Weights_hidden_output, h) + bi...
sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step n is how many characters to predict
625941eaa219f33f34628e39
def get(self, media_id): <NEW_LINE> <INDENT> return jsonify({})
Get a list of users who have liked this media. --- parameters: - name: media_id in: path description: Media ID type: integer required: true tags: - Likes - Media responses: 200: description: OK schema: properties: meta: properties: code: ...
625941ea097d151d1a22332e
def get_paper_fos_count(self): <NEW_LINE> <INDENT> self.logger.info('Counting number of fields of study per paper') <NEW_LINE> num_fos = self.fos_m.sum(axis=1).ravel().tolist()[0] <NEW_LINE> self.logger.info('Least and most fields of study per paper: %s, %s', min(num_fos), max(num_fos)) <NEW_LINE> return np.array(num_f...
:return: numpy.array with number of publications per field of study
625941ea956e5f7376d71343
def sample_freqs(freqs_path, sample_size): <NEW_LINE> <INDENT> df = normalize_two_alleles(freqs_path) <NEW_LINE> major_allele = df[df.Rank == 0].copy() <NEW_LINE> major_allele['Sampled_freq'] = major_allele['Freq'].apply(lambda x: np.random.binomial(sample_size, x) / sample_size) <NEW_LINE> minor_allele = df[df.Rank ==...
Gets a path to a freqs file, and return a df after sampling n allelles for each position, where n equals sample size.
625941eaa17c0f6771cbe526
def getConnectionInfo( self, userService: typing.Union['models.UserService', 'models.ServicePool'], user: 'models.User', password: str, ) -> typing.Mapping[str, str]: <NEW_LINE> <INDENT> return {'protocol': self.protocol, 'username': '', 'password': '', 'domain': ''}
This method must provide information about connection. We don't have to implement it, but if we wont to allow some types of connections (such as Client applications, some kinds of TC, etc... we must provide it or those kind of terminals/application will not work Args: userService: UserService for witch we are rend...
625941ea009cb60464c63884
def remove(self, *args): <NEW_LINE> <INDENT> return _gnsdk.GnMusicIdFileInfoManager_remove(self, *args)
remove(GnMusicIdFileInfoManager self, GnMusicIdFileInfo fileInfo)
625941ea4f6381625f114f13
def checkfib(n): <NEW_LINE> <INDENT> if n < 2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif n > 2: <NEW_LINE> <INDENT> if fib(n-1) + fib(n-2) == n: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Please enter something valid.") <NEW_LINE>...
Checks if n is a fibonacci number.
625941ea2c8b7c6e89b35c94
@login_required <NEW_LINE> def claim_delete(request): <NEW_LINE> <INDENT> if request.is_ajax() and request.method == 'POST': <NEW_LINE> <INDENT> claim_id = request.POST.get('pk') <NEW_LINE> if claim_id is not None: <NEW_LINE> <INDENT> claim = get_object_or_404(Claim, pk=claim_id) <NEW_LINE> claim.delete() <NEW_LINE> re...
Удаление претензии (AJAX).
625941ea99cbb53fe67930bc
def GetReservedConcurrencyConfig(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("GetReservedConcurrencyConfig", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.Get...
获取函数的保留并发详情。 :param request: Request instance for GetReservedConcurrencyConfig. :type request: :class:`tencentcloud.scf.v20180416.models.GetReservedConcurrencyConfigRequest` :rtype: :class:`tencentcloud.scf.v20180416.models.GetReservedConcurrencyConfigResponse`
625941ea63f4b57ef00015e2
@bind_add_query( '--maintainer', action='append', help='comma-separated list of regexes to search for maintainers') <NEW_LINE> def parse_maintainer(value): <NEW_LINE> <INDENT> return packages.PackageRestriction( 'maintainers', values.AnyMatch(values.UnicodeConversion( mk_strregex(value.lower(), case_sensitive=False))))
Case insensitive Regex match on the combined 'name <email>' bit of metadata.xml's maintainer data.
625941ead268445f265b5346
def parse_args(self): <NEW_LINE> <INDENT> args = super(NeonArgparser, self).parse_args() <NEW_LINE> try: <NEW_LINE> <INDENT> log_thresh = max(10, 40 - args.verbose*10) <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> log_thresh = 40 <NEW_LINE> <DEDENT> fmtr = logging.Formatter('%(asctime)s - ...
Parse the command line arguments and setup neon runtime environment accordingly Returns: namespace: contains the parsed arguments as attributes
625941ea0a366e3fb873ecf6
def postponed(self, task): <NEW_LINE> <INDENT> postponed = task.is_postponed() <NEW_LINE> if postponed: <NEW_LINE> <INDENT> msg = _('The request was accepted but postponed due to one or more previous requests against the resource.\n' 'This request will proceed at the earliest possible time.') <NEW_LINE> self.context.p...
Test for postponed tasks. If postponed, an appropriate message is displayed for the user and and the test result flag is returned. :param task: A queued task. :type task: Task :return: Whether the task was postponed. :rtype: bool
625941eae64d504609d74d17
def collect_incoming_data(self, data): <NEW_LINE> <INDENT> self.buffer.append(data)
docstring placeholder
625941ea3d592f4c4ed1d537
def test_complete_Cart_fail(self): <NEW_LINE> <INDENT> url = reverse('commerce:itemlist', kwargs={'version':'v2'}) <NEW_LINE> cart_id = Cart.objects.all()[0].cart_id <NEW_LINE> data = {'command':'complete', 'cart_id':cart_id } <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> response = self.client.p...
Ensure that cart fails when already completed and if cart doesnt exist.
625941eacb5e8a47e48b7f7a
def surname_match(self,name): <NEW_LINE> <INDENT> for (first,last) in self.names(): <NEW_LINE> <INDENT> if string.lower(last).find(string.lower(name)) >= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Match a string with the surname of an individual
625941ea4428ac0f6e5bacce
def pairBincount(x, y, weights=None): <NEW_LINE> <INDENT> xuniq = np.sort(np.unique(x)) <NEW_LINE> yuniq = np.sort(np.unique(y)) <NEW_LINE> ind1 = np.searchsorted(xuniq, x) <NEW_LINE> ind2 = np.searchsorted(yuniq, y) <NEW_LINE> indMult = np.max(ind2) + 1 <NEW_LINE> ind = ind1 * indMult + ind2 <NEW_LINE> count = np.binc...
counts number of unique pairs of (fragid1, fragid2) with weights
625941ead6c5a10208144526
def compare(self, adverse): <NEW_LINE> <INDENT> selfScore = self.computeValue() <NEW_LINE> adverseScore = adverse.computeValue() <NEW_LINE> for i in range(0, len(selfScore)): <NEW_LINE> <INDENT> if selfScore[i] > adverseScore[i]: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif selfScore[i] < adverseScore[i]: <NEW...
Compares the hand with an adverse hand returns: -1 if the adverse hand wins, 1 if this hand wins, 0 if tie
625941eaa219f33f34628e3a
def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.autofilter('A1:D51') <NEW_LINE> worksheet.filter_column(0, 'x == East or x = South') <NEW_LINE> textfile = open(self.txt_filename) <NEW_LINE> headers = textfile.rea...
Test the creation of a simple XlsxWriter file with an autofilter. This test corresponds to the following examples/autofilter.py example: Example 3. Autofilter with a dual filter condition in one of the columns.
625941ea5510c4643540f8af
def check_role_exists(self, role): <NEW_LINE> <INDENT> role_path = os.path.join(self.roles_dir, role) <NEW_LINE> if not os.path.isdir(role_path): <NEW_LINE> <INDENT> raise TestException( "Could not find ansible role directory at %r" % role_path )
Ensure that a role exists.
625941ea3eb6a72ae02ec9c2
def queue_research(self, branch): <NEW_LINE> <INDENT> assert type(branch) is UnitType, "incorrect type of arg branch: should be UnitType, is {}".format(type(branch)) <NEW_LINE> result = _lib.bc_GameController_queue_research(self._ptr, branch) <NEW_LINE> _check_errors() <NEW_LINE> result = bool(result) <NEW_LINE> return...
Adds a branch to the back of the queue, if it is a valid upgrade, and starts research if it is the first in the queue. Returns whether the branch was successfully added. :type self: GameController :type branch: UnitType :rtype: bool
625941ea090684286d50f1c5
def orderAndTrade(self, future): <NEW_LINE> <INDENT> pass
查询下单下单及成交 :return:
625941ea8c0ade5d55d3ee97
def escape_bytes(self, b, delim_char, multidelim=False, inline=False): <NEW_LINE> <INDENT> if delim_char != "'" and delim_char != '"': <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> d = self._escape_bytes_dict <NEW_LINE> if inline: <NEW_LINE> <INDENT> if delim_char == "'": <NEW_LINE> <INDENT> if multidelim: <N...
Within a binary string, replace all bytes whose corresponding Latin-1 code points are not allowed to appear literally with their escaped counterparts.
625941eaa934411ee3751b6c
def poolRunner(target, queue, coverage_number=None, omit_patterns=[]): <NEW_LINE> <INDENT> saved_tempdir = tempfile.tempdir <NEW_LINE> tempfile.tempdir = tempfile.mkdtemp() <NEW_LINE> def cleanup(): <NEW_LINE> <INDENT> if sys.platform != 'darwin' or sys.version_info[0] == 2: <NEW_LINE> <INDENT> shutil.rmtree(tempfile.t...
I am the function that pool worker processes run. I run one unit test.
625941eade87d2750b86026f
@array_function_dispatch(_count_dispatcher) <NEW_LINE> def find(a, sub, start=0, end=None): <NEW_LINE> <INDENT> return _vec_string( a, int_, 'find', [sub, start] + _clean_args(end))
For each element, return the lowest index in the string where substring `sub` is found. Calls `str.find` element-wise. For each element, return the lowest index in the string where substring `sub` is found, such that `sub` is contained in the range [`start`, `end`]. Parameters ---------- a : array_like of str or uni...
625941ea5e10d32532c5f3fc
def generate_listings_delete_holiday_inline_active(oauth_session): <NEW_LINE> <INDENT> data = get_multiple_listings_responses(oauth_session, ONE_TO_FOUR) <NEW_LINE> change_all_listings_responses(data, 100001, state='active', last_modified_tsz=LAST_MODIFIED_TSZ, creation_tsz=CREATION_TSZ, original_creation_tsz=CREATION_...
Generate listings_delete_holiday_inline_active.json file Data of listings are downloaded from Etsy, modified as needed for the test data and saved to a file. :param oauth_session: OAuth session object
625941eaa8370b7717052d75
def whack(self, n=1): <NEW_LINE> <INDENT> return ' '.join('whack!' for _ in range(n))
Prints "whack!" n times.
625941ea7b25080760e3992e
def format_response(self, output): <NEW_LINE> <INDENT> if self.response_type == 'json': <NEW_LINE> <INDENT> json_output = json.dumps(output) <NEW_LINE> response = HttpResponse(json_output) <NEW_LINE> response['Content-Type'] = 'application/json' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if output != None: <NEW_LINE...
Formats the response type based on ``response_type`` attribute.
625941eabf627c535bc136a7
def rna_to_dna(RNA): <NEW_LINE> <INDENT> return "".join([nuc if nuc != 'U' else 'T' for nuc in RNA])
Reverse-transcribes a String of RNA back into DNA
625941ea7d43ff24873a317c
def capacity(self): <NEW_LINE> <INDENT> return _almathswig.vectorPosition6D_capacity(self)
capacity(self) -> size_type
625941ea379a373c97cfb01f
def parse_response(self, selector, response): <NEW_LINE> <INDENT> loader = NewsLoader(NewsItem(), selector) <NEW_LINE> loader.add_value('domain', self.get_base_domain(response.url)) <NEW_LINE> loader.add_value('link', response.url) <NEW_LINE> loader.add_xpath('headline', settings['FIELD_HEADLINE_NODE']) <NEW_LINE> load...
Parse response and load item retrieving from response :param selector: Selector used to extract data from response :param response: Response from scrapping :return: News Item
625941ea16aa5153ce362950
def recommend(frame, userID, p, q, TopN=10): <NEW_LINE> <INDENT> userItemlist = list(set(frame[frame['UserID'] == userID]['MovieID'])) <NEW_LINE> otherItemList = [item for item in set(frame['MovieID'].values) if item not in userItemlist] <NEW_LINE> predictList = [lfmPredict(p, q, userID, itemID) for itemID in otherItem...
推荐TopN个物品给目标用户 :param frame: 源数据 :param userID: 目标用户 :param p: 用户兴趣和隐类的关系 :param q: 隐类和物品的关系 :param TopN: 推荐数量 :return: 推荐物品
625941ea9c8ee82313fbbc4f
def test_intent_load(self): <NEW_LINE> <INDENT> intent = Intent.load(('1', '2', '3')) <NEW_LINE> self.assertEqual(intent.qid, '1') <NEW_LINE> self.assertRaises(Exception, Intent.load, ('1', '2', '3', '4'))
Intent.load
625941ead53ae8145f87a73e
def get_nodes_count(self): <NEW_LINE> <INDENT> return len(self.__nodes)
Return the count of nodes in the node tree.
625941eafff4ab517eb2f917
def updateList(self, computes): <NEW_LINE> <INDENT> for compute_id in copy.copy(self._computes): <NEW_LINE> <INDENT> if compute_id in ["local", "vm"]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if compute_id not in [c.id() for c in computes]: <NEW_LINE> <INDENT> log.debug("Delete compute %s", compute_id) <NEW_LIN...
Sync an array of compute with remote
625941ea66673b3332b92569
def __init__(self, wtype: WidgetType, name: str): <NEW_LINE> <INDENT> self._wtype = wtype <NEW_LINE> self._name = name
Initialize the widget base class :param wtype: type of widget :param name: name of widget, must be unique across all widgets
625941eaadb09d7d5db6cc64
def __init__(self): <NEW_LINE> <INDENT> self.x=0 <NEW_LINE> self.y=0 <NEW_LINE> self.id=0 <NEW_LINE> self.links=[] <NEW_LINE> self.toIds=[] <NEW_LINE> self.shape = "" <NEW_LINE> self.status=0 <NEW_LINE> self.role = "" <NEW_LINE> self.probability = "" <NEW_LINE> self.color = "" <NEW_LINE> self.follower=[] <NEW_LINE> sel...
Constructor
625941ea1b99ca400220af8b
def get_medial_twill_twists(bm, orig_face_len): <NEW_LINE> <INDENT> twists = [TWIST_CW] * len(bm.edges) <NEW_LINE> for face in bm.faces[0:orig_face_len]: <NEW_LINE> <INDENT> for edge in face.edges: <NEW_LINE> <INDENT> twists[edge.index] = TWIST_CCW <NEW_LINE> <DEDENT> <DEDENT> return twists
Gets twists per edge assuming bm has been transformed by remesh_medial.
625941ea21bff66bcd684e26
def create(self, model, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start = datetime.now() <NEW_LINE> try: <NEW_LINE> <INDENT> result = self.server.create(self.uid, self.password, model, data) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> _logger.error("create(%s, %s) failed", model, data) <N...
Create a record on the external system
625941ea5fcc89381b1e1b9b
def require_float(self, key): <NEW_LINE> <INDENT> v = self.get_float(key) <NEW_LINE> if v is None: <NEW_LINE> <INDENT> raise ConfigMissingError(self.full_key(key)) <NEW_LINE> <DEDENT> return v
Returns a configuration value, as a float, by its given key. If it doesn't exist, or the configuration value is not a legal number, an error is thrown.
625941ea6fece00bbac2dc1d
def covar_samp(column1, column2): <NEW_LINE> <INDENT> return col(CovarSamp( column1=parse(column1), column2=parse(column2) ))
:rtype: Column
625941ea236d856c2ad44cb9
def __add_edge(self, from_verb, to_verb, weight): <NEW_LINE> <INDENT> if from_verb not in self.graph: <NEW_LINE> <INDENT> self.graph[from_verb] = {} <NEW_LINE> <DEDENT> self.graph[from_verb][to_verb] = weight
Добавление ребра в граф. Аргументы: from_verb -- начало узла to_verb -- конец узла weight -- длина ребра
625941ea097d151d1a22332f
def run_markov_chain(transition_matrix, initial_state_prob, time_steps): <NEW_LINE> <INDENT> transition_matrix = np.array(transition_matrix) <NEW_LINE> num_states = transition_matrix.shape[0] <NEW_LINE> if not np.allclose(np.sum(transition_matrix, axis=1), np.ones(num_states,)): <NEW_LINE> <INDENT> raise ValueError('In...
Runs the markov chain for a given transition matrix. Args: transition_matrix: a 2d matrix specifying the probability of transition across states. initial_state_prob: A probability vector specifying the probability of state at t=0. time_steps: Number of steps for which the markov chain will run. Returns:...
625941ea4e696a04525c9926
def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.children = []
initializes a node with given data Args: data(object): data, that will be stored in the node
625941ea67a9b606de4a838f
def read_input(): <NEW_LINE> <INDENT> _clear_last_frame() <NEW_LINE> pygame.event.pump() <NEW_LINE> keys = pygame.key.get_pressed() <NEW_LINE> if keys[pygame.K_LEFT]: last_frame[X_AXIS] = -0.01 <NEW_LINE> if keys[pygame.K_RIGHT]: last_frame[X_AXIS] = 0.01 <NEW_LINE> if keys[pygame.K_UP]: last_frame[Y_AXIS] = -0.01 ...
Reads input from the configured input sources, translating keypresses/analog input into game input, and then places that translated input into a global structure so that the game logic can read it.
625941ea2c8b7c6e89b35c95
def update_bill( self, data=None, bill_id=None, auth_needed=True): <NEW_LINE> <INDENT> import json <NEW_LINE> data = data or { 'categories': [] } <NEW_LINE> bill_id = bill_id or self.bill.id <NEW_LINE> if auth_needed: <NEW_LINE> <INDENT> self.client.force_login(self.user) <NEW_LINE> <DEDENT> return self.client.patch( r...
Helper to retrieve bill via api
625941ea167d2b6e3121906d
def __expected_entropy(self, attr_dict): <NEW_LINE> <INDENT> total = len(self.train_set) <NEW_LINE> expected_value = 0 <NEW_LINE> for attr_value in attr_dict: <NEW_LINE> <INDENT> attr_class_dict = attr_dict[attr_value] <NEW_LINE> occurence = sum(attr_class_dict.values()) <NEW_LINE> entropy = self.__entropy(attr_class_d...
Calculate the expected entropy with the given attribute dictionary
625941ea498bea3a759b9f86
def de_casteljau(p0, p1, p2, p3, t): <NEW_LINE> <INDENT> if not 0 <= t <= 1: <NEW_LINE> <INDENT> raise BezierError('t should be in the interval [0, 1]') <NEW_LINE> <DEDENT> q01 = (1-t)*p0 + t*p1 <NEW_LINE> q12 = (1-t)*p1 + t*p2 <NEW_LINE> q23 = (1-t)*p2 + t*p3 <NEW_LINE> r012 = (1-t)*q01 + t*q12 <NEW_LINE> r123 = (1-t)...
This is a helper function for Bezier evaluation and splitting. It is explictly unrolled instead of recursive.
625941ead6c5a10208144527
def authenticated(): <NEW_LINE> <INDENT> return hasattr(flask.g, 'fas_user') and flask.g.fas_user
Simple utility method returning whether the user in the current requests has authenticated or not.
625941ea0c0af96317bb86c0
def task(): <NEW_LINE> <INDENT> node = REDIS_CONN.spop('reachable') <NEW_LINE> (address, port, start_height) = eval(node) <NEW_LINE> handshake_msgs = [] <NEW_LINE> connection = Connection((address, port), socket_timeout=SETTINGS['socket_timeout'], user_agent=SETTINGS['user_agent'], start_height=start_height) <NEW_LINE>...
Assigned to a worker to retrieve (pop) a node from the reachable set and attempt to establish and maintain connection with the node.
625941ea627d3e7fe0d69329
def rearrangeNodesVertical(self): <NEW_LINE> <INDENT> nodesort = NodeSort(self.getNodes(), self.__view, True) <NEW_LINE> self.__networkManager.checkLayersForMovement(self.getNodeIds())
Automatically sorts the node items Vertical
625941eaec188e330fd5ac6d
def concept_uri(self): <NEW_LINE> <INDENT> entity_id = self.getID() <NEW_LINE> if entity_id == '-1': <NEW_LINE> <INDENT> raise NoWikibaseEntityError(self) <NEW_LINE> <DEDENT> return '{}{}'.format(self.repo.concept_base_uri, entity_id)
Return the full concept URI. :raise NoWikibaseEntityError: if this entity doesn't exist
625941eacb5e8a47e48b7f7b
def filename_path(self, name, lang): <NEW_LINE> <INDENT> results = [p for p in self.timeline if p.source_path == name] <NEW_LINE> if not results: <NEW_LINE> <INDENT> utils.LOGGER.warning("Can't resolve path request for filename: {0}".format(name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(results) > 1: <NEW_...
filename path handler
625941ea32920d7e50b286ad
def run_algo(python_call, module_name, num_pts=3, num_iter=3): <NEW_LINE> <INDENT> this_dir = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> if not os.path.exists(this_dir + '/data'): <NEW_LINE> <INDENT> os.mkdir(this_dir + '/data') <NEW_LINE> <DEDENT> data_call, target_call = find_data_target(python_call) <NEW_...
Calls an arbitrary module and runs the module with three different amounts of data for the purpose of timing the module and predicting how long the module will take to run with entire data set. :param python_call: str python string calling the algorithm to be timed :param module_name: str name of module from which fun...
625941ead8ef3951e3243a16
def get_circular_primes_under(maximum): <NEW_LINE> <INDENT> if type(maximum) != int: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> sieve = {d:0 for d in range(1,maximum+1)} <NEW_LINE> for (i,v) in sieve.items(): <NEW_LINE> <INDENT> if v != 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> strung = str(i) <N...
find all circular primes under a given maximum problem 35
625941ea55399d3f05588b90
def get_dataset_edges(root, desired_dataset): <NEW_LINE> <INDENT> for rel, left, right, dataset, _ in read_edges(root): <NEW_LINE> <INDENT> if dataset == desired_dataset: <NEW_LINE> <INDENT> yield (rel, left, right)
Read all csv files (assumed to be ConceptNet edge files) under the given root (typically $CONCEPTNET_DATA/edges or a single edge csv file) and generate one three-tuple for every edge they contain from the given dataset, consisting of the relation, and the (uri-prefixes of the) left and right endpoints.
625941ead7e4931a7ee9e3f7
def handle(self, **options): <NEW_LINE> <INDENT> if int(options['verbosity']) > 0: <NEW_LINE> <INDENT> self.stdout.write_maybe = self.stdout.write <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write_maybe = lambda *args: None <NEW_LINE> <DEDENT> self.strict_empty_text_nodes = options['strict'] <NEW_LINE> se...
Handle command
625941ea30c21e258bdfa97b
def edge (self, index, source, target, type_name=None): <NEW_LINE> <INDENT> e = { "id" : f"e{index}", "source_id": source, "target_id": target } <NEW_LINE> if type_name is not None: <NEW_LINE> <INDENT> e["type"] = type_name <NEW_LINE> <DEDENT> return e
Generate a question edge.
625941ea8a43f66fc4b54538
def move_up(self): <NEW_LINE> <INDENT> if self.rect.top > 0: <NEW_LINE> <INDENT> self.rect.top -= self.speed
Makes player move up
625941ea3539df3088e2e824
def test_contains_seperate_words(e_trie): <NEW_LINE> <INDENT> e_trie.insert('word') <NEW_LINE> e_trie.insert('struggle') <NEW_LINE> assert e_trie.contains('word') <NEW_LINE> assert e_trie.contains('struggle')
Test contains sees two seperate words.
625941ea3346ee7daa2b3248
def provision_node(conference, message, node, user): <NEW_LINE> <INDENT> auth = Auth(user=user) <NEW_LINE> try: <NEW_LINE> <INDENT> wiki = WikiPage.objects.create_for_node(node, 'home', message.text, auth) <NEW_LINE> <DEDENT> except NodeStateError: <NEW_LINE> <INDENT> wiki = WikiPage.objects.get_for_node(node, 'home') ...
:param Conference conference: :param ConferenceMessage message: :param Node node: :param User user:
625941ea004d5f362079a808
def find_roots(a, b, c): <NEW_LINE> <INDENT> x = (-b + sqrt(b*b - 4*a*c))/(2*a) <NEW_LINE> y = (-b - sqrt(b*b - 4*a*c))/(2*a) <NEW_LINE> return x, y
Function that takes a, b, c and returns the roots of a the polynomial ax^2 + bx + c
625941ea627d3e7fe0d6932a
def maxArea(self, height: List[int]) -> int: <NEW_LINE> <INDENT> area = 0 <NEW_LINE> i, j = 0, len(height) - 1 <NEW_LINE> while i < j: <NEW_LINE> <INDENT> if height[i] > height[j]: <NEW_LINE> <INDENT> area = max(height[j] * (j - i), area) <NEW_LINE> j -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> area = max(height...
Honing in on target again to solve in O(n) Come towards each other from the smaller height Compute the area before in/de-creasing x-axis to keep track of max area
625941ea8a349b6b435e864b
@runs_once <NEW_LINE> def pre_deploy(branch=None): <NEW_LINE> <INDENT> execute('local.deploy.prep', branch=branch)
Make sure that local.deploy.prep is only run once when the deploy command is run on multiple hosts.
625941ea4c3428357757c7fd
@parse_method <NEW_LINE> def parse_config(config): <NEW_LINE> <INDENT> if not isinstance(config, list): <NEW_LINE> <INDENT> raise ConfigParseError('Config must be a list') <NEW_LINE> <DEDENT> buckets = [] <NEW_LINE> for bucket_config in config: <NEW_LINE> <INDENT> buckets.append(parse_bucket(bucket_config)) <NEW_LINE> ...
Return a list of fully configured Buckets from 'config'.
625941ea5fdd1c0f98dc070e
def set_callback(self): <NEW_LINE> <INDENT> self.bricklet.set_temperature_callback_configuration(self.callback_period, value_has_to_change=True, option='x', min=0, max=0) <NEW_LINE> self.bricklet.register_callback(self.bricklet.CALLBACK_TEMPERATURE, self.callback)
Sets the callback period and registers the method callback() with the Tinkerforge API.
625941ea57b8e32f52483977