code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_strategies(self): <NEW_LINE> <INDENT> return
获取系统的所有策略。
625941c86e29344779a62676
def cap_test(text): <NEW_LINE> <INDENT> return text.capitalize()
Input text
625941c8de87d2750b85fdf6
def terminal_test(self, game): <NEW_LINE> <INDENT> if not game.get_legal_moves(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Return True if the game is over for the active player and False otherwise.
625941c85f7d997b87174afb
@shared_task <NEW_LINE> def create_sip_for_record(recid, agent=None, user_id=432): <NEW_LINE> <INDENT> pid = PersistentIdentifier.get('recid', recid) <NEW_LINE> rec = ZenodoRecord.get_record(pid.object_uuid) <NEW_LINE> recsip = RecordSIP.query.filter_by( pid_id=pid.id).order_by(RecordSIP.created.desc()).first() <NEW_LI...
Create a new SIP if the record's files diverged from last SIPFiles. :param agent: Agent JSON passed to the SIP. :param user_id: ID of the user resposible for the SIP (by default, user ID of info@zenodo.org)
625941c838b623060ff0ae52
def getMethods(jclass): <NEW_LINE> <INDENT> return jclass.class_.getMethods()[:]
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
625941c83d592f4c4ed1d0d4
def print_error(msg: str, loc: Optional[str] = None) -> None: <NEW_LINE> <INDENT> if loc is None: <NEW_LINE> <INDENT> print(f"{col('')}error:{col('')} {msg}", file=sys.stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"{col('')}{loc}: {col('')}error:{col('')} {msg}", file=sys.stderr)
Prints a message with a (possibly colored) 'error: ' prefix.
625941c85fcc89381b1e1722
def _setup_head_shape(fname, use_hpi=True): <NEW_LINE> <INDENT> idx_points, dig_points = _read_head_shape(fname) <NEW_LINE> idx_points, dig_points, t = _convert_head_shape(idx_points, dig_points) <NEW_LINE> all_points = np.r_[idx_points, dig_points].astype('>f4') <NEW_LINE> idx_idents = list(range(1, 4)) + list(range(1...
Read index points and dig points from BTi head shape file Parameters ---------- fname : str The absolute path to the head shape file Returns ------- dig : list of dicts The list of dig point info structures needed for the fiff info structure. use_hpi : bool Whether to treat additional hpi coils as dig...
625941c829b78933be1e5711
def test_is_milestone_argument_is_skipped(self): <NEW_LINE> <INDENT> kwargs = copy.copy(self.kwargs) <NEW_LINE> kwargs.pop("is_milestone") <NEW_LINE> new_task = Task(**kwargs) <NEW_LINE> assert new_task.is_milestone is False
testing if the default value of the is_milestone attribute is going to be False when the is_milestone argument is skipped
625941c8f548e778e58cd5e1
def create_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=__doc__) <NEW_LINE> parser.add_argument('-d', '--dictionary', nargs='?', default='dictionaries/all_en_US.dict', help='Specify a non-default word dictionary to use.') <NEW_LINE> parser.add_argument('-c', '--count', help='Specify the nu...
Creates the Namespace object to be used by the rest of the tool
625941c83346ee7daa2b2dcf
def logp_xnext(self, particles, next_part, u, t): <NEW_LINE> <INDENT> N = len(particles) <NEW_LINE> return numpy.zeros((N,))
Return the log-pdf value for the possible future state 'next' given input u. Always returns zeros since all particles are always equivalent for this type of model Args: - particles (array-like): Model specific representation of all particles, with first dimension = N (number of particles) - next_part: Unused ...
625941c8dd821e528d63b20e
def get_message(url, initial_price, current_price, delta): <NEW_LINE> <INDENT> config = Configuration() <NEW_LINE> message = MESSAGE_TEMPLATE.format( url=url, initial_price=initial_price, current_price=current_price, delta=delta) <NEW_LINE> msg = MIMEText(message) <NEW_LINE> msg['To'] = ", ".join(formataddr(('Recipient...
Return the email message (body + headers).
625941c8f7d966606f6aa067
def __init__(self, executable, args=None, cwd=None, env=None, stdout_handler=None, stderr_handler=None, output_encoding=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.executable = executable <NEW_LINE> self.args = args <NEW_LINE> self.cwd = cwd <NEW_LINE> self.envmerge = True <NEW_LINE> self._env = env <...
:param executable: full path of the tool executable or just the tool program name if it is in the system search path :param args: default args for command (list of strings) :type args: list :param cwd: program working directory :param env: environment dictionary :param envmerge: if set to Tr...
625941c89b70327d1c4e0e39
def test_append_line_with_tab_data(self): <NEW_LINE> <INDENT> data = 'chr1\t10000\t20000\t+' <NEW_LINE> tabfile = TabFile('test',self.fp) <NEW_LINE> self.assertEqual(len(tabfile),3) <NEW_LINE> line = tabfile.append(tabdata=data) <NEW_LINE> self.assertEqual(len(tabfile),4) <NEW_LINE> self.assertTrue(str(line) == data)
Append line to a TabFile populated from tabbed data
625941c8566aa707497f45cf
def preview_fees_public_api_using_post(self, wrapper_type_for_preview_conditions, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.preview_fees_public_api_using_post_with_http_info(wrapper_type_for_preview_conditions, **kwargs)
Preview offer fees # noqa: E501 This endpoint calculates fees for a provided offer conditions. The quotation is estimated and based on the current configuration of the Allegro price list and the data entered in this API. The stated price does not include package discounts. The rules of charging and amount of charges ...
625941c86aa9bd52df036e08
def get_behaviour_data(self, behaviour_name): <NEW_LINE> <INDENT> behaviour_path = self._behaviours[behaviour_name] <NEW_LINE> module = __import__(behaviour_path, fromlist=[behaviour_path]) <NEW_LINE> behaviour = getattr(module, behaviour_name) <NEW_LINE> return behaviour, module
Returns the class and module of the given behaviour Args: behaviour_name: The name of the behaviour
625941c8009cb60464c63416
def overload(func: Callable) -> Callable: <NEW_LINE> <INDENT> if not hasattr(func, '__annotations__'): <NEW_LINE> <INDENT> raise TypeError("Not type annotations found {}".format(func)) <NEW_LINE> <DEDENT> param_types: Dict[str, type] = {k: v for k, v in func.__annotations__.items() if k != 'return'} <NEW_LINE> args = _...
Decorator to allow overloading parameters of different types in python. Be careful with this as python duck typing us awkward and this may not account for everything. Useful for the visitor pattern. Motivations: Take this inheritance hierarchy as an example: class A(): ... class B(...
625941c88e7ae83300e4b030
def crop_cmap(cmapin, vmin, vmax, pivot=0): <NEW_LINE> <INDENT> cmapin = plt.get_cmap(cmapin) <NEW_LINE> return cmocean.tools.crop(cmapin, vmin, vmax, pivot)
Crop a colormap so that it is centered around pivot This is a wrapper for :func:`cmocean.tools.crop`. Parameters ---------- cmap: colormap Compatible with :func:`matplotlib.pyplot.get_cmap`. vmin: float Min data value vmax: float Max data value pivot: float The colormap will be centered on this value....
625941c899fddb7c1c9de3f5
def check_config_values(keys, config): <NEW_LINE> <INDENT> missing = list() <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> config[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> missing.append(key) <NEW_LINE> logger.critical("'{:s}' missing from configuration".format(key)) <NEW_L...
Raise an exception if all keys in `keys` are not represented in `config`. >>> check_config_values(['foo', 'bar'], {'foo': 'value'}) Traceback (most recent call last): ... KeyError: "Missing configuration value(s): ['bar']" >>> check_config_values(['foo'], {'foo': 'value'})
625941c8d268445f265b4ed2
def svn_delta_noop_window_handler(*args): <NEW_LINE> <INDENT> return _delta.svn_delta_noop_window_handler(*args)
svn_delta_noop_window_handler(svn_txdelta_window_t window, void * baton) -> svn_error_t
625941c8236d856c2ad4483d
def init_two_layer_convnet(weight_scale=1e-7, bias_scale=0, input_shape=(6, 8, 8), num_classes=64, num_filters=64, filter_size=3): <NEW_LINE> <INDENT> C, H, W = input_shape <NEW_LINE> assert filter_size % 2 == 1, 'Filter size must be odd; got %d' % filter_size <NEW_LINE> model = {} <NEW_LINE> model['W1'] = weight_scale...
Initialize the weights for a two-layer ConvNet. Inputs: - weight_scale: Scale at which weights are initialized. Default 1e-3. - bias_scale: Scale at which biases are initialized. Default is 0. - input_shape: Tuple giving the input shape to the network; default is (3, 32, 32) for CIFAR-10. - num_classes: The number o...
625941c8a17c0f6771cbe0b6
def get_tensors(self, node_name, output_slot, debug_op, device_name=None): <NEW_LINE> <INDENT> watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) <NEW_LINE> try: <NEW_LINE> <INDENT> device_name = self._infer_device_name(device_name, node_name) <NEW_LINE> return [datum.get_tensor() for datum in self._wa...
Get the tensor value from for a debug-dumped tensor. The tensor may be dumped multiple times in the dump root directory, so a list of tensors (`numpy.ndarray`) is returned. Parameters ---------- node_name: (`str`) name of the node that the tensor is produced by. output_slot: (`int`) output slot index of tensor. ...
625941c8be7bc26dc91cd666
def register_custom_filters(jinjaenv): <NEW_LINE> <INDENT> jinjaenv.filters['authorize'] = authorize <NEW_LINE> jinjaenv.filters['onlystaff'] = onlystaff <NEW_LINE> jinjaenv.filters['attrencode'] = _attrencode <NEW_LINE> jinjaenv.filters['cssencode'] = cssencode <NEW_LINE> jinjaenv.filters['to_json'] = _to_json <NEW_LI...
Register the filters to the given Jinja environment.
625941c8a05bb46b383ec886
def is_state_equivalent(self, state1, state2): <NEW_LINE> <INDENT> return IAMRole.equivalent_states.get(state1) == IAMRole.equivalent_states.get(state2)
Determines if states are equivalent. Uses equivalent_states defined in the IAMRole class. Args: state1 (State): state1 (State): Returns: bool
625941c88e71fb1e9831d80e
def remove_num_threads_option(args: List[str]) -> None: <NEW_LINE> <INDENT> for i in range(0, len(args)): <NEW_LINE> <INDENT> if args[i] == "-n": <NEW_LINE> <INDENT> del args[i : i + 2] <NEW_LINE> break
Remove -n <n> from argument list
625941c863d6d428bbe44554
def decode(self, serialized_example, items=None): <NEW_LINE> <INDENT> context, sequence = tf.parse_single_sequence_example( serialized_example, self._context_keys_to_features, self._sequence_keys_to_features) <NEW_LINE> example = {} <NEW_LINE> example.update(context) <NEW_LINE> example.update(sequence) <NEW_LINE> all_f...
Decodes the given serialized TF-example.
625941c84e4d5625662d443d
def word_bank (word): <NEW_LINE> <INDENT> return r
randomly selects a string from a word bank
625941c8d53ae8145f87a2d6
def add_isl_child(name, isl_device=ROOT_ISL_DEVICE): <NEW_LINE> <INDENT> if isl_device: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not isl_device.started: <NEW_LINE> <INDENT> log = isl_device.start() <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise InvalidLogDeviceError() <NEW_LINE> <D...
Manage using an InspyLogger device with Inspyre Toolbox. Args: name: The name you'd like for your log-device. isl_device (inspy_logger.InspyLogger.device | None): An instantiated inspy-logger device. Returns: The log device.
625941c8fff4ab517eb2f4a0
def Insert(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Insert') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Creates a new table. Args: request: (Table) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Table) The response message.
625941c8442bda511e8be47e
def setTPX(self,temperature:float=-1,pressure:float=-1,conditions_perturb:dict={}): <NEW_LINE> <INDENT> if temperature== -1: <NEW_LINE> <INDENT> temperature = self.temperature <NEW_LINE> <DEDENT> if pressure == -1: <NEW_LINE> <INDENT> pressure = self.pressure <NEW_LINE> <DEDENT> if conditions_perturb == {}: <NEW_LINE> ...
Set solution object for a simulation Parameters ---------- temperature : float, optional Temperature for simulation [K]. The default is -1. pressure : float, optional Pressure for simulation [P]. The default is -1. conditions_perturb : dict, optional Initial mole fractions for species in simulation. The de...
625941c88c3a87329515841e
def finalize(self): <NEW_LINE> <INDENT> self._close_output() <NEW_LINE> return
Finalize the simulation.
625941c85510c4643540f44b
def primal_lifting_cdf2x(decomp_src, decomp_wav): <NEW_LINE> <INDENT> decomp_wav -= div_ceil((decomp_src + numpy.append(decomp_src[1:], decomp_src[-1])), 2) <NEW_LINE> decomp_src += div_ceil((numpy.append(decomp_src[0], decomp_src[:-1]) + decomp_wav), 4) <NEW_LINE> return [decomp_src, decomp_wav]
CDF2/X基底によるPrimal Lifting
625941c8d4950a0f3b08c3b4
def bitter_rivals(voting_dict): <NEW_LINE> <INDENT> ln = [ (policy_compare(name,least_similar(name,voting_dict),voting_dict),least_similar(name,voting_dict),name) for name in voting_dict ] <NEW_LINE> return (min(ln)[1],min(ln)[2])
Input: a dictionary mapping senator names to lists representing their voting records Output: a tuple containing the two senators who most strongly disagree with one another. Example: >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]} >>> bitter_rivals(voting_dic...
625941c8cc40096d615959b5
def test_was_published_recently_with_old_question(self): <NEW_LINE> <INDENT> time = timezone.now() + datetime.timedelta(days=30) <NEW_LINE> old_question = Question(pub_date=time) <NEW_LINE> self.assertIs(old_question.was_published_recently(), False)
was_published_recently() should return False for questions whose pub_date is older than 1 days
625941c83c8af77a43ae3804
def format_single(self, element): <NEW_LINE> <INDENT> status = element[0:3] <NEW_LINE> channel = element[3] <NEW_LINE> data_name = element[4] <NEW_LINE> data_name = self.data_names[data_name] <NEW_LINE> if data_name in self.data_names_int: <NEW_LINE> <INDENT> value = int(float(element[5:])) <NEW_LINE> <DEDENT> else: <N...
Format single measurement value :param element: Single measurement value read from the instrument :type element: str :return: Status (three digits), channel, data name, value :rtype: (str, str, str, float)
625941c8d10714528d5ffd47
def __init__(self): <NEW_LINE> <INDENT> self.ts = 0 <NEW_LINE> self.users = {}
Initialize your data structure here.
625941c8e5267d203edcdd03
def is_in_cone(idx_a, idx_b, vllist): <NEW_LINE> <INDENT> n = len(vllist) <NEW_LINE> idx_a0 = idx_a - 1 <NEW_LINE> idx_a1 = (idx_a + 1) % n <NEW_LINE> a = vllist[idx_a] <NEW_LINE> b = vllist[idx_b] <NEW_LINE> a0 = vllist[idx_a0] <NEW_LINE> a1 = vllist[idx_a1] <NEW_LINE> if is_left_on(a, a1, a0): <NEW_LINE> <INDENT> ret...
returns true iff diagonal (idx_a, idx_b) is strictly internal to the polygon in sht neighborhood of the endpoint
625941c84e696a04525c94b0
def getRandom(self) -> int: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> ch = random.choice(self.nums) <NEW_LINE> if ch is not None: <NEW_LINE> <INDENT> return ch
Get a random element from the set.
625941c8e64d504609d748a4
def random_eye_type(): <NEW_LINE> <INDENT> mods = ["evil", "gay", "snek", "high", "ogre", "emoji", "small"] <NEW_LINE> eye_type = "" <NEW_LINE> for number_of_mods in range(0, random.randrange(0, len(mods))): <NEW_LINE> <INDENT> mod = random.choice(mods) <NEW_LINE> eye_type += mod <NEW_LINE> mods.remove(mod) <NEW_LINE> ...
A random eye type pos + mods
625941c815baa723493c3fda
def _get_conn2(service='cloudformation'): <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> print('[debug] Created conn2:resource:client.') <NEW_LINE> <DEDENT> return boto3.resource( service, aws_access_key_id=AWS_KEYID, aws_secret_access_key=AWS_KEY, region_name=AWS_REGION, )
Generates a boto3 resource for the given service. :param str service: The service to generate resource for. Defaults to AWS CloudFormation. Inherits Gitlab CI/CD environment variables: - `AWS_KEYID` - `AWS_KEY` - `AWS_REGION`
625941c82eb69b55b151c913
def isPalindrome(self, x): <NEW_LINE> <INDENT> if x < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if x < 10: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> length = int(math.log(x, 10) + 1) <NEW_LINE> while (length > 0): <NEW_LINE> <INDENT> first = x / 10 ** (length - 1) <NEW_LINE> last = x % 10 <NEW_L...
:type x: int :rtype: bool
625941c8097d151d1a222ebf
def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> tgtScore, tgtModel = float("inf"), None <NEW_LINE> for components in range(self.min_n_components, self.max_n_components + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chModel = self.base_model(components)...
select the best model for self.this_word based on BIC score for n between self.min_n_components and self.max_n_components :return: GaussianHMM object
625941c85e10d32532c5ef8c
def getSourceSetAccessors(): <NEW_LINE> <INDENT> return zip(*getSourceSetNameList())[0]
Get a list of all accessor names for Source objects.
625941c87cff6e4e811179eb
def process_response(self, request, response): <NEW_LINE> <INDENT> s_id = request.session.get("YH_SID", None) <NEW_LINE> if s_id is None: <NEW_LINE> <INDENT> s_id = request.session["YH_SID"] = uuid.uuid4().hex <NEW_LINE> response.set_cookie( key="YH_SID", value=s_id, expires=datetime.now() + timedelta(days=common_const...
用作用户统计 :param request: :param response: :return:
625941c8656771135c3eb8d3
def char_map_eta_s_deriv(self, increment_filter, k): <NEW_LINE> <INDENT> f = self.char_map_eta_s_func <NEW_LINE> if not increment_filter[0, 0]: <NEW_LINE> <INDENT> self.jacobian[k, 0, 0] = self.numeric_deriv(f, 'm', 0) <NEW_LINE> <DEDENT> if not increment_filter[0, 1]: <NEW_LINE> <INDENT> self.jacobian[k, 0, 1] = self....
Partial derivatives for compressor map characteristic. Parameters ---------- increment_filter : ndarray Matrix for filtering non-changing variables. k : int Position of derivatives in Jacobian matrix (k-th equation).
625941c84527f215b584c4bd
def _mouse_scroll_h(self, event): <NEW_LINE> <INDENT> args = (int(-1 * (event.delta / 120)), "units") <NEW_LINE> self._canvas_scroll.xview_scroll(*args) <NEW_LINE> self._canvas_ticks.xview_scroll(*args)
Callback for <Shift-MouseWheel> event for horizontal scrolling
625941c8435de62698dfdcb1
def getPositionPdf(i): <NEW_LINE> <INDENT> return [int(i/5), i%5]
Return the position of the square on the pdf page
625941c8b7558d58953c4f7b
@testing.requires_testing_data <NEW_LINE> def test_source_psd_epochs(): <NEW_LINE> <INDENT> raw = read_raw_fif(fname_data) <NEW_LINE> inverse_operator = read_inverse_operator(fname_inv) <NEW_LINE> label = read_label(fname_label) <NEW_LINE> event_id, tmin, tmax = 1, -0.2, 0.5 <NEW_LINE> lambda2, method = 1. / 9., 'dSPM'...
Test multi-taper source PSD computation in label from epochs.
625941c8091ae35668666fc5
def impulse(self, key): <NEW_LINE> <INDENT> self.key_impulses.add(key)
Ask for impulses to be emitted for a specific key.
625941c826068e7796caed42
def get_wikipathways_reactome_df() -> pd.DataFrame: <NEW_LINE> <INDENT> return pd.read_csv(WIKIPATHWAYS_REACTOME_PATH, sep='\t')
Get WikiPathways-Reactome data.
625941c83617ad0b5ed67f5d
def ghash(self, nouce): <NEW_LINE> <INDENT> header_hash = self.header_hash() <NEW_LINE> token = ''.join((header_hash, str(nouce))).encode('utf-8') <NEW_LINE> return hashlib.sha256(token).hexdigest()
Block hash generate.
625941c86fb2d068a760f101
def _generate_all_variables(self): <NEW_LINE> <INDENT> columns_larger_zero = get_columns_larger_zero(self.X) <NEW_LINE> columns_boolean = get_boolean_columns(self.X) <NEW_LINE> all_variables = [] <NEW_LINE> for exponent in range(2, self.max_exponent + 1): <NEW_LINE> <INDENT> for variable in self.variables: <NEW_LINE> <...
Generates all additional variables (exponents, roots, logs, interactions). Exponents are only generated for non-boolean columns. Roots and logs are only generated for columns with every value larger than zero. Overwrites self.variables with the new variables.
625941c891af0d3eaac9ba7d
def OnHelpButtonClicked(self,*args): <NEW_LINE> <INDENT> pass
OnHelpButtonClicked(self: Form,e: CancelEventArgs) Raises the System.Windows.Forms.Form.HelpButtonClicked event. e: A System.ComponentModel.CancelEventArgs that contains the event data.
625941c810dbd63aa1bd2c09
def add_image(name,img_array): <NEW_LINE> <INDENT> detections, shapes, descriptors = detect_faces(person_database,img_array) <NEW_LINE> if len(descriptors)==0: <NEW_LINE> <INDENT> print("No people found.") <NEW_LINE> <DEDENT> elif len(descriptors)>1: <NEW_LINE> <INDENT> print("Multiple people detected. Picture can only...
Given a name and image of one person, logs person in database. If person already exists, it updates, taking the average of the current and given descriptor vectors. :param: name:str name of person in image file_path:str path to file of image of person
625941c86fece00bbac2d7a3
def _email_entry_changed(self, x, y): <NEW_LINE> <INDENT> ok_button = self.get_widget_for_response(gtk.RESPONSE_OK) <NEW_LINE> if self.email_entry.is_valid(): <NEW_LINE> <INDENT> ok_button.set_sensitive(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ok_button.set_sensitive(False)
Disable the OK button if the email is invalid
625941c885dfad0860c3aec0
def write_issues(r, csvout, repo): <NEW_LINE> <INDENT> if not r.status_code == 200: <NEW_LINE> <INDENT> raise Exception(r.status_code) <NEW_LINE> <DEDENT> for issue in r.json(): <NEW_LINE> <INDENT> labels = [] <NEW_LINE> for label in issue['labels']: <NEW_LINE> <INDENT> labels.append(label.get(u'name')) <NEW_LINE> <DED...
output a list of issues to csv
625941c826068e7796caed43
def _trans_subdomain(data): <NEW_LINE> <INDENT> dname, sname = parse_name(data['DOMAIN'][0]) <NEW_LINE> subdomains.append({'name': sname, 'domain__name': dname}) <NEW_LINE> for role in ROLES & set(data.keys()): <NEW_LINE> <INDENT> sr = {'role': role, 'subdomain__name': sname, 'subdomain__domain__name': dname} <NEW_LINE...
transform subdomain item
625941c81d351010ab855b81
@restricted <NEW_LINE> def check_result(bot, update): <NEW_LINE> <INDENT> user = update.message.from_user <NEW_LINE> area = [] <NEW_LINE> row = list(set(update.message.text.replace(' ', '').split(',')))[:10] <NEW_LINE> for i in row: <NEW_LINE> <INDENT> area_tmp = re.search(r'^[a-zA-Z]$', i) <NEW_LINE> if area_tmp is no...
Get the check results
625941c8eab8aa0e5d26dbbd
def variance(marks): <NEW_LINE> <INDENT> mean_mark = mean(marks) <NEW_LINE> num_total = 0 <NEW_LINE> for m in marks: <NEW_LINE> <INDENT> num_total += (m - mean_mark) ** 2 <NEW_LINE> <DEDENT> return num_total/len(marks)
Calculate the variance of the marks.
625941c8cc0a2c11143dcef6
def gsw(self, X, Y, theta=None, p=1, L=1000): <NEW_LINE> <INDENT> N, dn = X.shape <NEW_LINE> M, dm = Y.shape <NEW_LINE> assert dn == dm and M == N <NEW_LINE> if theta is None: <NEW_LINE> <INDENT> theta = self.random_slice(dn, L) <NEW_LINE> <DEDENT> Xslices = self.get_slice(X, theta) <NEW_LINE> Yslices = self.get_slice(...
Calculates GSW between two empirical distributions. Note that the number of samples is assumed to be equal (This is however not necessary and could be easily extended for empirical distributions with different number of samples)
625941c8377c676e9127220e
def safe_lower(p_str): <NEW_LINE> <INDENT> new_str = None <NEW_LINE> if p_str is not None: <NEW_LINE> <INDENT> if isinstance(p_str, str): <NEW_LINE> <INDENT> new_str = p_str.lower() <NEW_LINE> <DEDENT> <DEDENT> return new_str
Convert str to lower case
625941c8046cf37aa974cdae
def add(self, price): <NEW_LINE> <INDENT> self.__price[self.__count] = price <NEW_LINE> self.__count += 1 <NEW_LINE> if self.__count < self.__period: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__count = 0 <NEW_LINE> cs_open = self.__price[0] <NEW_LINE> cs_high = max(self.__price...
仮想通貨のカレントプライスを追加し、ローソク足情報ができたらTrueを戻す :param price: カレントプライス :return: 1ローソク足が作れたらTrue
625941c88a43f66fc4b540cb
def get_fieldnames(host, index): <NEW_LINE> <INDENT> mappings = elsec.actions.get_mappings(host, index) <NEW_LINE> _temp = dict() <NEW_LINE> for m in mappings.values(): <NEW_LINE> <INDENT> _temp.update(m) <NEW_LINE> <DEDENT> return _collapse_mapping(_temp)
Return a list of names of all fields in mappings for the index. Calls elsec.actions.get_mappings(), and then dot-collapses the field names into mapping.object.fieldname format, returning a list of all the fields. (This is later used for tab completions) Input: - host, index: str Returns: List of str, each element a...
625941c8ff9c53063f47c259
def retract_bindings(self, bindings): <NEW_LINE> <INDENT> return retract_bindings(self, bindings)
:see: ``nltk.featstruct.retract_bindings()``
625941c8be383301e01b54ed
def get_environment(self, environment_id, **kwargs): <NEW_LINE> <INDENT> if environment_id is None: <NEW_LINE> <INDENT> raise ValueError('environment_id must be provided') <NEW_LINE> <DEDENT> headers = {} <NEW_LINE> if 'headers' in kwargs: <NEW_LINE> <INDENT> headers.update(kwargs.get('headers')) <NEW_LINE> <DEDENT> pa...
Get environment info. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse
625941c83cc13d1c6d3c73e0
def __init__(__self__, *, backup_vault_arn: Optional[pulumi.Input[str]] = None, backup_vault_events: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, backup_vault_name: Optional[pulumi.Input[str]] = None, sns_topic_arn: Optional[pulumi.Input[str]] = None): <NEW_LINE> <INDENT> if backup_vault_arn is not None:...
Input properties used for looking up and filtering VaultNotifications resources. :param pulumi.Input[str] backup_vault_arn: The ARN of the vault. :param pulumi.Input[Sequence[pulumi.Input[str]]] backup_vault_events: An array of events that indicate the status of jobs to back up resources to the backup vault. :param pul...
625941c8004d5f362079a399
def dropout_forward(x, dropout_param): <NEW_LINE> <INDENT> p, mode = dropout_param['p'], dropout_param['mode'] <NEW_LINE> if 'seed' in dropout_param: <NEW_LINE> <INDENT> np.random.seed(dropout_param['seed']) <NEW_LINE> <DEDENT> mask = None <NEW_LINE> out = None <NEW_LINE> if mode == 'train': <NEW_LINE> <INDENT> pass <N...
Performs the forward pass for (inverted) dropout. Inputs: - x: Input data, of any shape - dropout_param: A dictionary with the following keys: - p: Dropout parameter. We keep each neuron output with probability p. - mode: 'test' or 'train'. If the mode is train, then perform dropout; if the mode is test, then ...
625941c86aa9bd52df036e09
def get_gosubdagplot(self, godag, kws_plt): <NEW_LINE> <INDENT> goids, go2color = CliGetGOs(godag).get_go_color(**kws_plt) <NEW_LINE> assert goids, "GO IDs NEEDED" <NEW_LINE> kws_dag = self._get_kwsdag(goids, godag, **kws_plt) <NEW_LINE> relationships = self._get_relationships(kws_plt, hasattr(next(iter(godag.values())...
Get GoSubDagPlot
625941c8b545ff76a8913e7c
def get_synset(line): <NEW_LINE> <INDENT> original = line.strip() <NEW_LINE> pos = original[0] <NEW_LINE> offset = int(original[1:]) <NEW_LINE> synset = wn.synset_from_pos_and_offset(pos, offset) <NEW_LINE> return original, pos, offset, synset
Produce synset from a line containing offset ID.
625941c801c39578d7e74ea1
def changeColor(id, newColor): <NEW_LINE> <INDENT> _canvas.itemconfigure(id, fill=newColor)
Change the color of an item.
625941c894891a1f4081bb0e
def remove_item(self, kernel_name: str) -> Optional[CacheItemType]: <NEW_LINE> <INDENT> cache_item = None <NEW_LINE> if self.cache_enabled: <NEW_LINE> <INDENT> if kernel_name.lower() in self.cache_items: <NEW_LINE> <INDENT> cache_item = self.cache_items.pop(kernel_name.lower()) <NEW_LINE> self.log.info("KernelSpecCache...
Removes the cache item corresponding to kernel_name from the cache.
625941c855399d3f05588719
def srwl_uti_write_data_cols(_file_path, _cols, _str_sep, _str_head=None, _i_col_start=0, _i_col_end=-1): <NEW_LINE> <INDENT> f = open(_file_path, 'w') <NEW_LINE> if(_str_head != None): <NEW_LINE> <INDENT> lenStrHead = len(_str_head) <NEW_LINE> if(lenStrHead > 0): <NEW_LINE> <INDENT> strHead = _str_head <NEW_LINE> if(_...
Auxiliary function to write tabulated data (columns, i.e 2D table) to ASCII file :param _file_path: full path (including file name) to the file to be (over-)written :param _cols: array of data columns to be saves to file :param _str_sep: column separation symbol(s) (string) :param _str_head: header (string) to write be...
625941c86fb2d068a760f102
def compare_sessions_to_text(pathserv, pathserv_other): <NEW_LINE> <INDENT> count_bads = ins.CountBads() <NEW_LINE> comparison = extractors.CollectSessionComparisonData(pathserv, pathserv_other, count_bads.count_bads) <NEW_LINE> text = reports.report_session_comparison(comparison) <NEW_LINE> return text
compares two sessions, returns text
625941c8d53ae8145f87a2d7
def isInBoundsHalf(self, x, y, Color): <NEW_LINE> <INDENT> if Color == WHITE: <NEW_LINE> <INDENT> if y >= 0 and y <= 4 and x >= 0 and x < 9: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> elif Color == BLACK: <NEW_LINE> <INDENT> if y >= 5 and y <= 9 and x >= 0 and x < 9: <NEW_LINE>...
checks if a position is on the half board
625941c8a4f1c619b28b00a1
def Digitization(sTree, SmearedHits): <NEW_LINE> <INDENT> Hits = [] <NEW_LINE> for i in range(len(SmearedHits)): <NEW_LINE> <INDENT> xtop=SmearedHits[i]['xtop'] <NEW_LINE> xbot=SmearedHits[i]['xbot'] <NEW_LINE> ytop=SmearedHits[i]['ytop'] <NEW_LINE> ybot=SmearedHits[i]['ybot'] <NEW_LINE> ztop=SmearedHits[i]['z'] <NEW_L...
Digitizes hit for the track pattern recognition. Parameters ---------- sTree : root file Events in raw format. SmearedHits : list of dicts List of smeared hits. A smeared hit is a dictionary: {'digiHit':key,'xtop':top x,'ytop':top y,'z':top z,'xbot':bot x,'ybot':bot y,'dist':smeared dist2wire} Retruns ---...
625941c830dc7b76659019cd
def updateStatusBar(self): <NEW_LINE> <INDENT> if not hasattr(self, 'size_label'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> df = self.table.model.df <NEW_LINE> meminfo = self.table.getMemory() <NEW_LINE> s = '{r} rows x {c} columns | {m}'.format(r=len(df), c=len(df.columns),m=meminfo) <NEW_LINE> self.size_label.s...
Update the table details in the status bar
625941c8167d2b6e31218bfc
def _run_container(self, docker_client) -> docker.models.containers.Container: <NEW_LINE> <INDENT> base_image = self._get_base_image() <NEW_LINE> try: <NEW_LINE> <INDENT> container = docker_client.containers.run( base_image, command="sleep {}".format(TIME_OUT), auto_remove=True, remove=True, detach=True) <NEW_LINE> <DE...
Build the container which contains a Python interpreter.
625941c8956e5f7376d70ed4
def toString( obj ): <NEW_LINE> <INDENT> return obj.toString() if hasattr( obj, 'toString' ) else obj
Use this on QString objects if you can't force PyQt4 into APIv2 mode.
625941c892d797404e3041ef
def fully_connected(inputs, num_outputs, scope, use_xavier=True, stddev=1e-3, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): <NEW_LINE> <INDENT> with tf2.variable_scope(scope) as sc: <NEW_LINE> <INDENT> num_input_units = inputs.get_shape()[-1].value <NEW_LINE> weights = _variabl...
Fully connected layer with non-linear operation. Args: inputs: 2-D tensor BxN num_outputs: int Returns: Variable tensor of size B x num_outputs.
625941c8187af65679ca5184
def totalFruit(self, tree): <NEW_LINE> <INDENT> dic = collections.Counter() <NEW_LINE> start, res =0,0 <NEW_LINE> for i in range(len(tree)): <NEW_LINE> <INDENT> dic[tree[i]] += 1 <NEW_LINE> while len(dic) > 2: <NEW_LINE> <INDENT> dic[tree[start]] -= 1 <NEW_LINE> if dic[tree[start]] == 0: <NEW_LINE> <INDENT> del dic[tre...
:type tree: List[int] :rtype: int
625941c82c8b7c6e89b35827
def all_results(self): <NEW_LINE> <INDENT> if self.test_session_setup: <NEW_LINE> <INDENT> yield self.test_session_setup <NEW_LINE> <DEDENT> for result in flatten_results(self.get_suites()): <NEW_LINE> <INDENT> yield result <NEW_LINE> <DEDENT> if self.test_session_teardown: <NEW_LINE> <INDENT> yield self.test_session_t...
An iterator over all results (tests, setups, teardowns) contained in the report.
625941c8ad47b63b2c509fe5
def run(): <NEW_LINE> <INDENT> if FLAGS.enable_mlir_bridge: <NEW_LINE> <INDENT> tf.config.experimental.enable_mlir_bridge() <NEW_LINE> <DEDENT> strategy = distribute_utils.get_distribution_strategy( distribution_strategy=FLAGS.distribution_strategy, tpu_address=FLAGS.tpu) <NEW_LINE> if strategy: <NEW_LINE> <INDENT> log...
Runs NHNet using Keras APIs.
625941c8e5267d203edcdd04
def test_update_counter(self): <NEW_LINE> <INDENT> hostname = '10.72.168.3' <NEW_LINE> nmap_xml = NmapXML(self.printer_file) <NEW_LINE> host = nmap_xml.parse_xml() <NEW_LINE> assert host <NEW_LINE> printer = nmap_xml.identify_host(hostname) <NEW_LINE> self.assertIsInstance(printer, Printer) <NEW_LINE> printer_counter =...
Testa inserção dos parâmetros do contador em impressora existente
625941c84a966d76dd551074
def checkBlacklist(client, message): <NEW_LINE> <INDENT> rowCount, retval, exists = lib.db.queryDatabase( "SELECT is_blacklisted FROM chronicles_info WHERE channel_id={id}". format(id=str(message.channel.id)), client, message.channel, tablename="chronicles_info", getResult=True, closeConn=True) <NEW_LINE> if exists == ...
Functions That Checks the Database to See if the Channel is Blacklisted Parameters: ----------- client (discord.Client) The Chronicler Client message (discord.Message) The Message of the Channel to Check
625941c84e696a04525c94b1
def VVI(image): <NEW_LINE> <INDENT> return (1 - abs((image[:,:,R] - 30) / (image[:,:,R] + 30))) * (1 - abs((image[:,:,G] - 50) / (image[:,:,G] + 50))) * (1 - abs((image[:,:,B] - 1) / (image[:,:,B] + 1)))
Returns Visible Vegetation Index http://phl.upr.edu/projects/visible-vegetation-index-vvi
625941c832920d7e50b28235
def build_centre(gene, condi): <NEW_LINE> <INDENT> center_list = [] <NEW_LINE> for i in range(len(gene.junctionL)): <NEW_LINE> <INDENT> column_values = [] <NEW_LINE> for sample in gene.conditions[condi]: <NEW_LINE> <INDENT> column_values.append(gene.conditions[condi][sample][i]) <NEW_LINE> <DEDENT> if len(column_values...
build centre :type gene: Gene :type condi: str :rtype : list
625941c8925a0f43d2549edc
def getAttrs(self): <NEW_LINE> <INDENT> return self.attrs
Returns attr
625941c816aa5153ce3624de
def __init__(self, bucket=None): <NEW_LINE> <INDENT> self.s3_conn = boto.connect_s3() <NEW_LINE> if bucket is not None: <NEW_LINE> <INDENT> self.bucket = bucket <NEW_LINE> <DEDENT> get_required_env_variable('AWS_ACCESS_KEY_ID') <NEW_LINE> get_required_env_variable('AWS_SECRET_ACCESS_KEY')
Establish connections. Assume credentials are in environment or in a config file.
625941c86e29344779a62678
def isUnique(attr, value): <NEW_LINE> <INDENT> pass
Determine whether a given LDAP attribute (attr) and its value (value) are unique in the LDAP tree branch set as the user record base in the LDAPUserFolder. This method should be called before inserting a new user record with attr being the attribute chosen as the login name in your LDAPUserFolder because that attribu...
625941c8ff9c53063f47c25a
def lists(): <NEW_LINE> <INDENT> n = "Stevens is awesome" <NEW_LINE> p = n.split(' ') <NEW_LINE> r = p[2][1:] <NEW_LINE> import numpy as np <NEW_LINE> c = np.array([[1,4,5], [6,10,11], [12,17,38]]) <NEW_LINE> print(c[:,2]) <NEW_LINE> d = [x for x in c.diagonal() if x % 2 == 0] <NEW_LINE> o = [ord(x) for x in (p[0])] <N...
This is to review basic operations with lists.
625941c8baa26c4b54cb1186
def to_dict(self, convert=True): <NEW_LINE> <INDENT> attrlist = [a for a in list(self.__dict__.keys()) if not a.startswith('_')] <NEW_LINE> data = {} <NEW_LINE> for name in attrlist: <NEW_LINE> <INDENT> attr_data = getattr(self, name, None) <NEW_LINE> if not convert: <NEW_LINE> <INDENT> data[name] = attr_data <NEW_LINE...
Extend Ablity To Dict Orm Object Data
625941c838b623060ff0ae54
def munge_source(v): <NEW_LINE> <INDENT> lines = v.split('\n') <NEW_LINE> if not lines: <NEW_LINE> <INDENT> return tuple(), '' <NEW_LINE> <DEDENT> firstline = lines[0].lstrip() <NEW_LINE> while firstline == '' or firstline[0] == '@': <NEW_LINE> <INDENT> del lines[0] <NEW_LINE> firstline = lines[0].lstrip() <NEW_LINE> <...
Take Python source code, return a pair of its parameters and the rest of it dedented
625941c891f36d47f21ac558
def set_value(slack_username, channel, charval): <NEW_LINE> <INDENT> character, key, value = charval[0], charval[1], charval[2] <NEW_LINE> character_channel = character.lower() + channel.lower() <NEW_LINE> try: <NEW_LINE> <INDENT> response = dbot.update_item( Key={ 'character_channel': character_channel }, UpdateExpres...
Sets a stat of the character record passed
625941c8460517430c3941ed
def parse_time(self, time_string): <NEW_LINE> <INDENT> parssed_time = re.findall(r'(\d+)(\s?)(\D+)', time_string) <NEW_LINE> if len(parssed_time) > 0: <NEW_LINE> <INDENT> inTime = int(parssed_time[0][0]) <NEW_LINE> inUnit = parssed_time[0][2] <NEW_LINE> if 's' in inUnit[0] or 'S' in inUnit[0]: <NEW_LINE> <INDENT> timeM...
Parses a <number><unit> i.e. 60s to a fncs timestep number. :param time_string: :return:
625941c83eb6a72ae02ec541
def _metadata_db_name(self): <NEW_LINE> <INDENT> my_metadata_dir = os.path.join( self.global_conf['metadata']['metadata_path'], self.METADATA_SUBDIR ) <NEW_LINE> if not os.path.isdir(my_metadata_dir): <NEW_LINE> <INDENT> os.makedirs(my_metadata_dir) <NEW_LINE> <DEDENT> return os.path.join(my_metadata_dir, self.source_n...
Figure out where to keep this source's Metadata
625941c8f9cc0f698b140662
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument( "--file", type=str, default="train.jsonl", ) <NEW_LINE> args = parser.parse_args() <NEW_LINE> return args
Parse args.
625941c87c178a314d6ef4c4
def __init__(self, model_file=None, do_lower_case=True, normalize_text=True, never_split=None): <NEW_LINE> <INDENT> self.tokenizer = sp.SentencePieceProcessor() <NEW_LINE> if self.tokenizer.Load(model_file): <NEW_LINE> <INDENT> print("Loaded a trained SentencePiece model.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
Constructs a SentencePieceTokenizer.
625941c8283ffb24f3c55968
def __init__(self): <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> self.min_stack = [] <NEW_LINE> self.min_value = 0
initialize your data structure here.
625941c896565a6dacc8f732
def findKthLargest(self, nums, k): <NEW_LINE> <INDENT> nums.sort() <NEW_LINE> print(nums) <NEW_LINE> print(nums[len(nums)-k]) <NEW_LINE> return (nums[len(nums)-k])
:type nums: List[int] :type k: int :rtype: int
625941c8be383301e01b54ee
def change_baudrate(self, baudrate_for_ids): <NEW_LINE> <INDENT> self._change_baudrate(baudrate_for_ids) <NEW_LINE> for motor_id in baudrate_for_ids.iterkeys(): <NEW_LINE> <INDENT> if motor_id in self._known_models: <NEW_LINE> <INDENT> del self._known_models[motor_id] <NEW_LINE> <DEDENT> if motor_id in self._known_mode...
Changes the baudrate of the specified motors.
625941c85e10d32532c5ef8d
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = len(self.costs) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> pattern = '<%sd'%length <NEW_LINE> buff.write(self.costs.tostring()) <NEW_LINE> length = len(self.gradient) <NEW_LINE> buff.write(_struct_I.pack(length))...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941c88e7ae83300e4b033