code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def getfield_byname(self, fieldname, defaultval = None): <NEW_LINE> <INDENT> if (hasattr(self, fieldname)): <NEW_LINE> <INDENT> return getattr(self, fieldname) <NEW_LINE> <DEDENT> return defaultval | Accessor. | 625941c56aa9bd52df036da4 |
def scc(self): <NEW_LINE> <INDENT> q = deque() <NEW_LINE> self.dfs(on_finished=lambda x: q.appendleft(x)) <NEW_LINE> return self._transposed_scc_dfs(q) | Find strongly connected components in the graph | 625941c5aad79263cf390a3f |
def featurize(self, audio_clip, overwrite=False): <NEW_LINE> <INDENT> return spectrogram_from_file( audio_clip, step=self.step, window=self.window, max_freq=self.max_freq, overwrite=overwrite) | For a given audio clip, calculate the log of its Fourier Transform
Params:
audio_clip(str): Path to the audio clip | 625941c5cad5886f8bd26fda |
def _GetAggregator(self): <NEW_LINE> <INDENT> return FastBucketAverage(0.1, 0.4, 20) | See signal.py | 625941c5b57a9660fec33883 |
def get_media(item, uri_parser, user): <NEW_LINE> <INDENT> media_url_in_attachment = item.find('wp:attachment_url').string <NEW_LINE> media_url = uri_parser.parse(media_url_in_attachment).file <NEW_LINE> media_url = os.path.join(settings.MEDIA_ROOT, media_url) <NEW_LINE> post_id = item.find('wp:post_parent').string <NE... | Find any URL contained in an "attachment."
If that File has already been created, skip it.
If not, go to the URL, and save the media there as a File.
Loop through Articles and Pages and replace links. | 625941c5a8ecb033257d30ce |
def bundle_logits(self, priors_logits_specs, search_logits_specs): <NEW_LINE> <INDENT> assert search_logits_specs, "Cannot distill with no student model." <NEW_LINE> assert len(search_logits_specs) == 1, "Search has more than one tower." <NEW_LINE> if not priors_logits_specs: <NEW_LINE> <INDENT> return DistillationLogi... | Bundles the priors and the search candidate. | 625941c515baa723493c3f75 |
def __init__(self, val, name, name_utf8) : <NEW_LINE> <INDENT> self.val = val <NEW_LINE> self.name = name <NEW_LINE> self.utf8 = name_utf8 <NEW_LINE> self.trump = False <NEW_LINE> self.dominant = False | val : value based on suit order (P>H>C>T)
name : string representation of the suit
utf8 : utf8 representation of the suit
trump : is it trump suit ?
dominant : is it asked suit ? | 625941c507f4c71912b11482 |
def SetForegroundValue(self, *args): <NEW_LINE> <INDENT> return _itkBinaryShapeOpeningImageFilterPython.itkBinaryShapeOpeningImageFilterIUC3_SetForegroundValue(self, *args) | SetForegroundValue(self, unsigned char _arg) | 625941c5e76e3b2f99f3a80f |
def forwards(self, orm): <NEW_LINE> <INDENT> api = API(orm) <NEW_LINE> moderators = api.get_moderators_and_admins() <NEW_LINE> for flag in orm.FlaggedItem.objects.all(): <NEW_LINE> <INDENT> activity_items = api.get_activity_items_for_object(flag) <NEW_LINE> if len(activity_items) == 0: <NEW_LINE> <INDENT> activity = or... | find all FlaggedItems and the corresponding Activity
transfer content object to Activity
add moderators and admins to the activity recipients
and set the denormalized value of question to the origin post
of the flagged item | 625941c5293b9510aa2c3298 |
def highlightByAlternate(self): <NEW_LINE> <INDENT> palette = QApplication.palette() <NEW_LINE> palette.setColor(palette.HighlightedText, palette.color(palette.Text)) <NEW_LINE> clr = palette.color(palette.AlternateBase) <NEW_LINE> palette.setColor(palette.Highlight, clr.darker(110)) <NEW_LINE> self.setPalette(palette) | Sets the palette highlighting for this tree widget to use a darker
version of the alternate color vs. the standard highlighting. | 625941c5aad79263cf390a40 |
def drawShape(self, painterPath): <NEW_LINE> <INDENT> if self.center and self.vertex: <NEW_LINE> <INDENT> painter.drawPolyline(self.polygonPoint) | overloading of the shape method | 625941c51d351010ab855b1d |
def category(request, category): <NEW_LINE> <INDENT> login_check(request) <NEW_LINE> try: <NEW_LINE> <INDENT> cat = Category.objects.get(category=category) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> redirect_index(request) <NEW_LINE> <DEDENT> groups = Group.objects.filter(categories=cat) <NEW_LINE> affil = {} <NEW... | Displays a list of groups in <category>.
Displays group name with link to the group's profile. | 625941c599fddb7c1c9de392 |
def submit_workflow(self, namespace, body, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.submit_workflow_with_http_info(namespace, body, **kwargs) | submit_workflow # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.submit_workflow(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace... | 625941c5b5575c28eb68e000 |
def load_features_opensmile(file_path: str) -> pd.DataFrame: <NEW_LINE> <INDENT> df = pd.read_csv(open(file_path, encoding='utf-8'), sep=';') <NEW_LINE> df.drop(columns=['name','frameTime'], inplace=True) <NEW_LINE> return df | 读取opensmile特有的CSV格式 | 625941c550485f2cf553cd9a |
def __init__(self, ai_settings, screen, stats): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.stats = stats <NEW_LINE> self.text_color = (30, 30, 30) <NEW_LINE> self.font = pygame.font.SysFont(None, 48) <NEW_LINE> self.... | Inicializa os atributos de pontuação
:param ai_settings:
:param screen:
:param stats: | 625941c55fc7496912cc397f |
@app.route("/") <NEW_LINE> def index(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return render_template( 'template.html', sorted=sorted, stations=fetch_menu()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "<h1>Error</h1>" | The index page with the late night menu items.
:return HTML page with late menu items. | 625941c5a79ad161976cc146 |
def parameters(self): <NEW_LINE> <INDENT> return [] | Return the trainable parameters | 625941c599cbb53fe6792be7 |
def __call__(self, **kwargs): <NEW_LINE> <INDENT> connection = kwargs.pop('connection', self.parent.connect()) <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> self.set_params(**kwargs) <NEW_LINE> <DEDENT> sqllog.debug(self.v7) <NEW_LINE> sql_cp1251 = self.v7.encode('cp1251') <NEW_LINE> return connection.query(sql_cp1251) | выполнение запроса
:param args:
:param kwargs: параметры для запроса
:return: | 625941c531939e2706e4ce6d |
def update_job(current): <NEW_LINE> <INDENT> job = get_job() <NEW_LINE> if 'total' not in job.meta: <NEW_LINE> <INDENT> raise ValueError('Cannot call update_job() because job does not have ' 'a defined total.') <NEW_LINE> <DEDENT> job.meta['current'] = current <NEW_LINE> job.save() <NEW_LINE> notification = json.dumps(... | Update the current job with new progress information. | 625941c5009cb60464c633b4 |
def load_voltages(filename: str) -> list: <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> voltages = f.readlines() <NEW_LINE> <DEDENT> voltages = [int(v) for v in voltages] <NEW_LINE> return voltages | Load the adapter voltages from an input file
:param filename: Location of the voltage file
:return: List of adapter voltages | 625941c521bff66bcd684955 |
def choose_best_alternative( input_word ): <NEW_LINE> <INDENT> alt_d = {} <NEW_LINE> curated_alternatives = {} <NEW_LINE> most_frequent = False <NEW_LINE> sum_occurences = 0 <NEW_LINE> found_record = r.get(input_word.lower()) <NEW_LINE> if not found_record: <NEW_LINE> <INDENT> return most_frequent, curated_alternatives... | return:
- the key with the highest value associated
- a dict with curated spellings as keys and relative freq as values
- sum of all sum_occurences | 625941c591af0d3eaac9ba18 |
def add_group(self, group_id, name, desc): <NEW_LINE> <INDENT> if not is_integer(group_id): <NEW_LINE> <INDENT> raise ValueError('Expected Group numerical key to be integer, was %s.' % type(group_id)) <NEW_LINE> <DEDENT> if not (isinstance(name, str) or name is None): <NEW_LINE> <INDENT> raise ValueError('Expected Grou... | Add a new parameter group.
Parameters
----------
group_id : int
The numeric ID for a group to check or create.
name : str, optional
If a group is created, assign this name to the group.
desc : str, optional
If a group is created, assign this description to the group.
Returns
-------
group : :class:`Group`... | 625941c591f36d47f21ac4f2 |
def get_data_loaders(tokenizer, train_dataset_filename, valid_dataset_filename, train_batch_size = 10, valid_batch_size = 50, max_tokens=24): <NEW_LINE> <INDENT> train_dataset = DimensionDataset(tokenizer, train_dataset_filename, max_tokens=max_tokens) <NEW_LINE> train_dataset_tensor = torch.tensor(train_dataset).type(... | Create instance of dataset and data loader for the given training and validation text files.
:param tokenizer: Bert tokenizer
:param train_dataset_filename: text file with one sample per line
:param valid_dataset_filename: text file with one sample per line
:param max_tokens: Bert maximum token in a sentence
:return: ... | 625941c576d4e153a657eb31 |
def completedefault(self, text, line, begidx, endidx): <NEW_LINE> <INDENT> if not self.useCompletion: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if text.count(".") == 1: <NEW_LINE> <INDENT> prefix, text = text.split(".") <NEW_LINE> prefix += "." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = "" <NEW_LINE> <... | pysql specific completion with self.completeList | 625941c545492302aab5e2c3 |
def wait_for_decorator(*args, **kwargs): <NEW_LINE> <INDENT> if not kwargs and len(args) == 1 and callable(args[0]): <NEW_LINE> <INDENT> return wait_for(args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def g(f): <NEW_LINE> <INDENT> return wait_for(f, *args, **kwargs) <NEW_LINE> <DEDENT> return g | Wrapper for :py:func:`utils.wait.wait_for` that makes it nicer to write testing waits.
It passes the function decorated to to ``wait_for``
Example:
.. code-block:: python
@wait_for_decorator(num_sec=120)
def my_waiting_func():
return do_something()
You can also pass it without parameters, then it uses `... | 625941c5090684286d50ece5 |
def __init__(self, settings=None): <NEW_LINE> <INDENT> Device.__init__(self) <NEW_LINE> self.__settings = settings <NEW_LINE> self.__emitter = EventEmitter() <NEW_LINE> self.__isRunning = False <NEW_LINE> self.__processID = -1 <NEW_LINE> self.__exitCode = -1 <NEW_LINE> self.__captureProc = None <NEW_LINE> self.__syncLo... | Initialize a new instance of PiCameraDevice.
:param StillCaptureSettings settings: The image capture settings. | 625941c5925a0f43d2549e77 |
def __init__(self, fs_type=None, storage_policy_id=None, storage_policy_name=None, volume_path=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration ... | V1VsphereVirtualDiskVolumeSource - a model defined in OpenAPI | 625941c5cc0a2c11143dce91 |
def __init__(self, label, hidden=False): <NEW_LINE> <INDENT> self._label = str(label) <NEW_LINE> self._hidden = hidden | :param label: Name for the ID
:type label: str | 625941c50383005118ecf5e5 |
def update_output_cell(cell): <NEW_LINE> <INDENT> code = cell['source'] <NEW_LINE> m = re.search('<div id=\"(.+)\"></div>\s*<script>(\$\(.+\))\.(\w+)\((.+)\);\<\/script\>', code) <NEW_LINE> groups = m.groups() <NEW_LINE> if m is not None and len(m.groups()) == 4: <NEW_LINE> <INDENT> cell_id = groups[0] <NEW_LINE> cell_... | Updates an output viewer cell to the right new format. | 625941c5796e427e537b05c6 |
def get_msg_search_path(): <NEW_LINE> <INDENT> rospack = rospkg.RosPack() <NEW_LINE> search_path = {} <NEW_LINE> for p in rospack.list(): <NEW_LINE> <INDENT> package_paths = rosmsg._get_package_paths(p, rospack) <NEW_LINE> search_path[p] = [os.path.join(d, 'msg') for d in package_paths] <NEW_LINE> <DEDENT> return searc... | Get ROS search path for messages | 625941c5adb09d7d5db6c791 |
def validate_params(self, user_id, org_id, start_offset, end_offset, tool=None, source_type=None, view=None, date_directory=None, scan_id=None): <NEW_LINE> <INDENT> if source_type is not None: <NEW_LINE> <INDENT> self.view = view <NEW_LINE> self.date_directory = date_directory <NEW_LINE> self.scan_id = scan_id <NEW_LIN... | Validate the parameters.
:param user_id: the user's id
:param org_id: the org's id
:param start_offset: the numeric value for starting record
:param end_offset: the numeric value for ending record
:param tool: the tool to be used for the query
:param source_type: the source type
:param view: a view for the individual ... | 625941c5dc8b845886cb5535 |
def clickOnFood(self): <NEW_LINE> <INDENT> API().clickElementByText(self.testcase, self.driver, self.logger, LSPC.text_food, 10) | usage : 点击美食 | 625941c5d7e4931a7ee9df1e |
def at_start(self): <NEW_LINE> <INDENT> self.obj.cmdset.add(cmdsetexamples.BlindCmdSet) | We want to add the cmdset to the linked object.
Note that the RedButtonBlind cmdset is defined to completly
replace the other cmdsets on the stack while it is active
(this means that while blinded, only operations in this cmdset
will be possible for the account to perform). It is however
not persistent, so should ther... | 625941c50fa83653e4656fbd |
def existing_url(**kwargs): <NEW_LINE> <INDENT> url_base = "/axapi/v3/vcs/reload" <NEW_LINE> f_dict = {} <NEW_LINE> return url_base.format(**f_dict) | Return the URL for an existing resource | 625941c524f1403a92600b69 |
def _compute_fn(self): <NEW_LINE> <INDENT> return self.baseFilename + '.' + time.strftime(self.suffix, time.localtime()) | 返回基本日志文件名+ 后缀格式 | 625941c50c0af96317bb81e9 |
def inelpl(ellipse, plane): <NEW_LINE> <INDENT> return _cspyce0.inelpl(ellipse, plane) | inelpl(ConstSpiceDouble [NELLIPSE] ellipse, ConstSpiceDouble [NPLANE] plane) | 625941c557b8e32f5248349b |
def mixture_from_json(self, mixture, dest=None, *, verify=True): <NEW_LINE> <INDENT> if dest is None: <NEW_LINE> <INDENT> dest = np.empty(self.num_strats, float) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> utils.check(dest.dtype.kind == "f", "dest dtype must be floating") <NEW_LINE> utils.check( dest.shape == (self.n... | Read a json mixture into an array | 625941c597e22403b379cf9b |
def get_dependencies(): <NEW_LINE> <INDENT> deps = {"requests": HAS_REQUESTS, "IPy": HAS_IPY} <NEW_LINE> return config.check_driver_dependencies(__virtualname__, deps) | Warn if dependencies aren't met. | 625941c521a7993f00bc7cee |
def get_release_date(self): <NEW_LINE> <INDENT> return _extract(self._request("album.getInfo", cacheable = True), "releasedate") | Retruns the release date of the album. | 625941c596565a6dacc8f6cd |
def stateless_property(func): <NEW_LINE> <INDENT> return property(func.__name__, setter=property.forbidden, saver=property.DontSave, default=func, doc=func.__doc__) | Decorator similar to :py:class:`builtins.property`, but for properties
exposed through management API (including qvm-prefs etc) | 625941c5a8370b77170528a1 |
def run(self): <NEW_LINE> <INDENT> for file in self.data["keys"]: <NEW_LINE> <INDENT> self.data[file]["header"] = self.list_to_dict(self.data[file]["header"]) <NEW_LINE> Rc, std = self.calculate_resistance(file) <NEW_LINE> self.fill_filename_df(file, Rc, std) <NEW_LINE> <DEDENT> del self.filename_df["_"] <NEW_LINE> '''... | turns all headers into dictionaries and fills file_name_df | 625941c5de87d2750b85fd93 |
def pkcs7(string, blocklen): <NEW_LINE> <INDENT> padlen = blocklen * (divmod(len(string),blocklen)[0]+1) - len(string) <NEW_LINE> string += chr(padlen) * padlen <NEW_LINE> return string | Pad a string according to PKCS#7
Arguments:
string (string): Plaintext to be padded
blocklen (int): Block length
Returns:
String with appropriate padding bytes added. | 625941c53c8af77a43ae37a0 |
def to_uuid(str): <NEW_LINE> <INDENT> return uuid.UUID(str) | 将字符串转换为uuid对象 | 625941c5d18da76e235324d6 |
def initial(self): <NEW_LINE> <INDENT> setglobaloption("unittrue") <NEW_LINE> self.timestepsecs = int(configget(self.config, "run", "timestepsecs", "86400")) <NEW_LINE> sizeinmetres = int(configget(self.config, "layout", "sizeinmetres", "0")) <NEW_LINE> self.basetimestep = 86400 <NEW_LINE> self.wf_updateparameters() <N... | *Required*
Initial part of the model, executed only once. It reads all static model
information (parameters) and sets-up the variables used in modelling.
This function is required. The contents is free. However, in order to
easily connect to other models it is advised to adhere to the directory
structure used in the ... | 625941c594891a1f4081baaa |
def snmp_server_agtconfig_contact(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") <NEW_LINE> if kwargs.pop('delete_snmp_server', False) is True: <NEW_LINE> <INDENT> delete_snmp_server = config.fin... | Auto Generated Code
| 625941c52ae34c7f2600d133 |
def __resolve_local_file_link(tk, attachment_data): <NEW_LINE> <INDENT> log.debug("Attempting to resolve local file link attachment data " "into a local path: %s" % pprint.pformat(attachment_data)) <NEW_LINE> local_path = attachment_data.get("local_path") <NEW_LINE> storage_name = attachment_data["local_storage"]["name... | Resolves the given local path attachment into a local path.
For details, see :meth:`resolve_publish_path`.
:param tk: :class:`~sgtk.Sgtk` instance
:param attachment_data: Shotgun Attachment dictionary.
:returns: A local path to file or file sequence or None if it cannot be resolved. | 625941c55e10d32532c5ef28 |
def retPSA(self): <NEW_LINE> <INDENT> value = {} <NEW_LINE> self.getGranule() <NEW_LINE> psas = self.granule.find('PSAs') <NEW_LINE> for i in psas.findall('PSA'): <NEW_LINE> <INDENT> value[i.find('PSAName').text] = i.find('PSAValue').text <NEW_LINE> <DEDENT> return value | Return the PSA values as dictionary, the PSAName is the key and
and PSAValue is the value | 625941c523e79379d52ee567 |
def testInsertNewStyleAtIndex0(self): <NEW_LINE> <INDENT> l_layer = self.map.getLayerByName('LINE') <NEW_LINE> class0 = l_layer.getClass(0) <NEW_LINE> new_style = mapscript.styleObj() <NEW_LINE> new_style.color.setRGB(255, 255, 0) <NEW_LINE> new_style.symbol = 1 <NEW_LINE> new_style.size = 7 <NEW_LINE> index = class0.i... | NewStylesTestCase.testInsertNewStyleAtIndex0: a new style can be inserted ahead of all others | 625941c5287bf620b61d3a66 |
def WriteSupportPopupKeys( template_file, output_file_basename, output_dir, key_definition_list): <NEW_LINE> <INDENT> for key_definition in key_definition_list: <NEW_LINE> <INDENT> assert len(key_definition['chars']) == len(_REPLACE_CHARS) <NEW_LINE> with open(template_file) as template_f: <NEW_LINE> <INDENT> keytop = ... | Generates and writes keyicons for support popup from template.
Support popup keys may have 5 key characters to be replaced.
Args:
template_file: Path for template file.
output_file_basename: A string indicating the base name of the output.
output_dir: Destination directory path.
key_definition_list: Key defin... | 625941c5167d2b6e31218b97 |
def _dispatch_model_events(pdict, data, key, call_tracker=set()): <NEW_LINE> <INDENT> for cb in pdict.value: <NEW_LINE> <INDENT> if cb not in call_tracker: <NEW_LINE> <INDENT> cb(data) <NEW_LINE> call_tracker.add(cb) <NEW_LINE> <DEDENT> <DEDENT> if len(key) == 0: <NEW_LINE> <INDENT> for k, p in pdict.items(): <NEW_LINE... | Helper function to distribute event throughout the model. | 625941c5e64d504609d74841 |
def parse_config(config: RawConfig, spec: ConfigSpec) -> ConfigNamespace: <NEW_LINE> <INDENT> parser = Parser.from_spec(spec) <NEW_LINE> return parser.parse("", config) | Parse options against a spec and return a structured representation.
:param config: The raw stringy configuration dictionary.
:param spec: A specification of what the configuration should look like.
:raises: :py:exc:`ConfigurationError` The configuration violated the spec.
:return: A structured configuration object. | 625941c560cbc95b062c6544 |
def Rooms_Created_by_Player(self, playerID=1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get(url=Room.__ApiPaths["Rooms_Created_by_Player"]+str(playerID)) <NEW_LINE> r.headers['User-Agent'] = Room.__useragent <NEW_LINE> if r.status_code == 404: <NEW_LINE> <INDENT> return {"error": "Not Found", "code": 4... | ### Rooms created by a player
`playerID` is String | 625941c5cb5e8a47e48b7aae |
def __str__(self): <NEW_LINE> <INDENT> return f'User {self.user} did not found' | Приведение к строке. | 625941c5498bea3a759b9ab1 |
def linewithpeaks(data, peaks): <NEW_LINE> <INDENT> from pylab import plot, show <NEW_LINE> import numpy as np <NEW_LINE> plot(data) <NEW_LINE> for i in peaks: <NEW_LINE> <INDENT> plot([i, i], [np.min(data), np.max(data)]) <NEW_LINE> <DEDENT> show() | plots line with overlaid peaks | 625941c5d10714528d5ffce3 |
def check_name_availability( self, location, parameters, **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', {})) <NEW_LINE> api_version = "2021-1... | Checks that the resource name is valid and is not already in use.
:param location: the region.
:type location: str
:param parameters: Parameters supplied to the operation.
:type parameters: ~azure.mgmt.signalr.models.NameAvailabilityParameters
:keyword callable cls: A custom type or function that will be passed the di... | 625941c5d4950a0f3b08c352 |
def start_router(self): <NEW_LINE> <INDENT> fwglobals.log.info("FWROUTER_API: start_router") <NEW_LINE> if self.router_started == False: <NEW_LINE> <INDENT> self.call('start-router') <NEW_LINE> <DEDENT> fwglobals.log.info("FWROUTER_API: start_router: started") | Execute start router command.
| 625941c526238365f5f0ee6e |
def register(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = RegisterForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> code = request.POST.get('invitecode') <NEW_LINE> code_query = InviteCode.objects.filter(code=code) <NEW_LINE> if len(code_query) == 0: <NEW_LIN... | 用户注册时的函数 | 625941c5a17c0f6771cbe054 |
def goldeneye(data, model, delta=None, classname='Class', goodness_fn=fidelity): <NEW_LINE> <INDENT> if delta is None: <NEW_LINE> <INDENT> delta = 1 / sqrt(data.shape[0]) <NEW_LINE> <DEDENT> if classname not in data.columns: <NEW_LINE> <INDENT> raise ValueError("classname not found in dataset") <NEW_LINE> <DEDENT> X_tr... | Detect optimal groups in a dataset.
:param data: the dataset
:param model: untrained classification model
:param delta: sensitivity parameter
:param classname: name of the column in the dataset with the class labels
:param goodness_fn: function used to investigate the effect of randomising
attributes in the dataset
:r... | 625941c55166f23b2e1a515b |
def test_sample_model(): <NEW_LINE> <INDENT> model = pf.GASLLT(data=data, family=pf.Normal()) <NEW_LINE> x = model.fit('BBVI', iterations=100) <NEW_LINE> sample = model.sample(nsims=100) <NEW_LINE> assert(sample.shape[0]==100) <NEW_LINE> assert(sample.shape[1]==len(data)-1) | Tests sampling function | 625941c507d97122c417888a |
def create_out_string(self, ctx, out_string_encoding='utf8'): <NEW_LINE> <INDENT> ctx.out_string = (yaml.dump(o, **self.out_kwargs) for o in ctx.out_document) <NEW_LINE> if six.PY2 and out_string_encoding is not None: <NEW_LINE> <INDENT> ctx.out_string = ( yaml.dump(o, **self.out_kwargs).encode(out_string_encoding) for... | Sets ``ctx.out_string`` using ``ctx.out_document``. | 625941c576e4537e8c351673 |
def _tokenize(self, text): <NEW_LINE> <INDENT> COMBINING_CHARS = COMBINING_ACCENT_CHAR + COMBINING_BREVE_CHAR + COMBINING_DIURESIS_CHAR <NEW_LINE> pattern = "([0-9]+|[^0-9" + RUS_ALPHABET_STR + COMBINING_CHARS + "]+)" <NEW_LINE> tokens = re.split(pattern, text) <NEW_LINE> tokens = [t for t in tokens if t != ''] <NEW_LI... | Returns a list of tokens (strings) that have been split into groups of russian characters (including accent
marks), and groups of non-russian characters.
Assumptions:
- The input text has been fully decomposed (NFKD form)
- Upper/lower case should be preserved
- Punctuation/whitespace should be preserved
:param str t... | 625941c538b623060ff0adf0 |
def embed_logo_by_name(self, name, width=0, height=0): <NEW_LINE> <INDENT> img, type = self.get_logo_by_name(name) <NEW_LINE> return self.embed_image(type, img, width, height) | Return HTML embedded logo by name | 625941c5fbf16365ca6f61c3 |
def unfold_entities(entity_list, target_level): <NEW_LINE> <INDENT> if target_level not in entity_levels: <NEW_LINE> <INDENT> raise PDBException("%s: Not an entity level." % target_level) <NEW_LINE> <DEDENT> if entity_list == []: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if isinstance(entity_list, Entity) or is... | Unfold entities list to a child level (e.g. residues in chain).
Unfold a list of entities to a list of entities of another
level. E.g.:
list of atoms -> list of residues
list of modules -> list of atoms
list of residues -> list of chains
o entity_list - list of entities or a single entity
o target_level - char (A, ... | 625941c53346ee7daa2b2d6d |
def readAsciiJobfile(self,filename): <NEW_LINE> <INDENT> with open(filename,'r') as f: <NEW_LINE> <INDENT> asciistring = f.read() <NEW_LINE> <DEDENT> self.readAscii(asciistring) | Loads and parses ASCII jobfile | 625941c5baa26c4b54cb1123 |
def open_login_by_email_screen(self): <NEW_LINE> <INDENT> self.ew.wait_and_tap_element(self.LOGIN_WITH_EMAIL_BUTTON, 30) | Opens login screen for login via email and password | 625941c5e64d504609d74842 |
def slotApply(self): <NEW_LINE> <INDENT> pass | void Sonnet.ConfigDialog.slotApply() | 625941c5fff4ab517eb2f43d |
def two_children(self): <NEW_LINE> <INDENT> return self.right is not None and self.left is not None | returns true if node has both children | 625941c5a4f1c619b28b003e |
def createconsole(ifiles, options): <NEW_LINE> <INDENT> console = PNCConsole() <NEW_LINE> exec("from pylab import *", None, console.locals) <NEW_LINE> exec("import pylab as pl", None, console.locals) <NEW_LINE> exec("import matplotlib.pyplot as plt", None, console.locals) <NEW_LINE> exec("import PseudoNetCDF as pnc", N... | Use standard pncparse ifiles and options to create
a working environment.
1) Access files by a short name or indexed name (ifile%d)
2) Access variables by name and file index (var_%d)
3) Has access to pylab and pncview functions | 625941c526068e7796caecde |
def test(nn): <NEW_LINE> <INDENT> maxf, factors = find_max_factor(nn) <NEW_LINE> print(f'{nn} max factor: {maxf}\nfactors: {factors}\n') | test | 625941c59c8ee82313fbb776 |
def set_setting(self, setting, value, area='1', validate_value=True): <NEW_LINE> <INDENT> setting = setting.lower() <NEW_LINE> if setting not in CONST.ALL_SETTINGS: <NEW_LINE> <INDENT> raise AbodeException(ERROR.INVALID_SETTING, CONST.ALL_SETTINGS) <NEW_LINE> <DEDENT> if setting in CONST.PANEL_SETTINGS: <NEW_LINE> <IND... | Set an abode system setting to a given value. | 625941c5eab8aa0e5d26db5a |
def __getitem__(self, key): <NEW_LINE> <INDENT> for h in self.hist_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if h.GetName() == key: <NEW_LINE> <INDENT> return h <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return KeyError(str(key)+' not found') | get Histogram by name | 625941c5be383301e01b548b |
def test_connect_handle(self): <NEW_LINE> <INDENT> app1 = Application() <NEW_LINE> app1.start(_notepad_exe()) <NEW_LINE> handle = app1.UntitledNotepad.handle <NEW_LINE> app_conn = Application() <NEW_LINE> app_conn.connect(handle=handle) <NEW_LINE> self.assertEqual(app1.process, app_conn.process) <NEW_LINE> app_conn.Unt... | Test that connect_() works with a handle | 625941c5a934411ee3751695 |
def remove(self, vswitchname): <NEW_LINE> <INDENT> return execute_soap(self._client, self._host, self.moid, 'vim.EsxCLI.network.vswitch.standard.Remove', vswitchname=vswitchname, ) | Remove a virtual switch from the ESXi networking system.
:param vswitchname: string, The name of the virtual switch to remove.
:returns: boolean | 625941c526068e7796caecdf |
def counter_simple(update, context): <NEW_LINE> <INDENT> message = update.message.reply_text("Pesquisando...") <NEW_LINE> team = [] <NEW_LINE> if len(context.args)<=6: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for arg in context.args: <NEW_LINE> <INDENT> team.append(arg.capitalize()) <NEW_LINE> <DEDENT> result = sim... | Get the best counters against a pokémon ou a team.
:param update: update object that contains all information about the query;
:param context: context object that contains all arguments from the query. | 625941c53c8af77a43ae37a1 |
def test_signed_micalg_cap(self): <NEW_LINE> <INDENT> m = self._make_signed() <NEW_LINE> m.set_param('micalg', 'PGP-SHA1') <NEW_LINE> m = utils.decrypted_message_from_bytes(m.as_bytes()) <NEW_LINE> self.assertIn('expected micalg=pgp-', m[utils.X_SIGNATURE_MESSAGE_HEADER]) | The micalg parameter should be normalized to lower case.
From RFC 3156 § 5
The "micalg" parameter for the "application/pgp-signature" protocol
MUST contain exactly one hash-symbol of the format "pgp-<hash-
identifier>", where <hash-identifier> identifies the Message
Integrity Check (MIC) algorithm use... | 625941c54f88993c3716c06a |
def getRelativeTimeStamps(self): <NEW_LINE> <INDENT> if not hasattr(self, '_relTimeStamps'): <NEW_LINE> <INDENT> self._relTimeStamps = np.asarray([ float(c.getAttribute("Time")) for c in self.root.getElementsByTagName("RelTimeStamp")]) <NEW_LINE> for c in self.root.getElementsByTagName("RelTimeStamp"): <NEW_LINE> <INDE... | Method: Get a numpy array of all image relativetimeStamps in the Serie.
Semi-private attribute `_relTimeStamps`
Return: Numpy array of integers with relativetimeStamps of all successives images in the Serie
warning:: on first call getRelativeTimeStamps() suppresses the data from the XML SerieHeader | 625941c58a43f66fc4b54069 |
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): <NEW_LINE> <INDENT> if strides > 1: <NEW_LINE> <INDENT> inputs = fixed_padding(inputs, kernel_size, data_format) <NEW_LINE> <DEDENT> return tf.compat.v1.layers.conv2d( inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, ... | Strided 2-D convolution with explicit padding. | 625941c5435de62698dfdc4e |
def get_board(self) -> FishBoardModel: <NEW_LINE> <INDENT> return copy.deepcopy(self._game_board) | Purpose: Return a copy of the board for a game state
Signature: Void -> FishBoardModel
:return: A copy of the board for a game state, so that originally state is not modified | 625941c591f36d47f21ac4f3 |
def f_mask_print(self): <NEW_LINE> <INDENT> masks = np.array(self.Masks) <NEW_LINE> masks = masks[np.where(self.Active)] <NEW_LINE> mask_str = str(list(masks)) <NEW_LINE> scannos = np.array(self.scan_nos) <NEW_LINE> scannos = scannos[np.where(self.Active)] <NEW_LINE> scan_str = str(list(scannos)) <NEW_LINE> print('scan... | Print scans and masks | 625941c5851cf427c661a512 |
def project(geom, from_proj=None, to_proj=None): <NEW_LINE> <INDENT> from_proj = wgs84(from_proj) <NEW_LINE> if to_proj is None: <NEW_LINE> <INDENT> to_proj = MOLLWEIDE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_proj = wgs84(to_proj) <NEW_LINE> <DEDENT> to_proj, from_proj = pyproj.Proj(to_proj), pyproj.Proj(from_... | Project a ``shapely`` geometry, and returns a new geometry of the same type from the transformed coordinates.
Default input projection is `WGS84 <https://en.wikipedia.org/wiki/World_Geodetic_System>`_, default output projection is `Mollweide <http://spatialreference.org/ref/esri/54009/>`_.
Inputs:
*geom*: A ``sha... | 625941c5fb3f5b602dac3694 |
def connect(uri): <NEW_LINE> <INDENT> uri = urlparse(uri) <NEW_LINE> assert uri <NEW_LINE> if __debug__: LOGGER.debug("open connection %s:%s", uri.hostname, uri.port) <NEW_LINE> sock = socket.socket() <NEW_LINE> addr = socket.getaddrinfo(uri.hostname, uri.port) <NEW_LINE> sock.connect(addr[0][4]) <NEW_LINE> def send_he... | Connect a websocket. | 625941c510dbd63aa1bd2ba6 |
def train_collate_fn(batch): <NEW_LINE> <INDENT> data = torch.cat([b[0] for b in batch], dim = 0) <NEW_LINE> label = torch.tensor([b[1] for b in batch]) <NEW_LINE> return data,label | batch = [((M,3,H,W), label)]*batch_size | 625941c5cc40096d61595953 |
def parsehtml(self, htmlsource): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tree = fromstring(htmlsource) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.warning("Cannot parse HTML tree", type(doc), len(doc)) <NEW_LINE> return ("", "", "", "") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> title = " ".join(tree.... | Parses the html source to retrieve info that is not in the RSS-keys
Parameters
---- ... | 625941c53cc13d1c6d3c737d |
def writeto(fname, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(fname, "w") as f: <NEW_LINE> <INDENT> f.write(str(data)) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> log.exception("Could not write to %s" % fname) <NEW_LINE> sys.exit(1) | save data into fname | 625941c550485f2cf553cd9b |
def get_applications_installed(self): <NEW_LINE> <INDENT> apps = [] <NEW_LINE> apps.extend(self._operation_handler.get_installed_applications()) <NEW_LINE> apps.extend(self._operation_handler.get_installed_updates()) <NEW_LINE> return apps | Wrapper around the operation handler's call to get installed
applications. | 625941c571ff763f4b54968b |
def occ(sd, i): <NEW_LINE> <INDENT> return sd is not None and gmpy2.bit_test(sd, i) | Check if a given Slater determinant has orbital `i` occupied.
Parameters
----------
sd : {int, gmpy2.mpz}
Integer that describes the occupation of a Slater determinant as a bitstring.
i : int
Index of an orbital.
Returns
-------
is_occ : bool
True if orbital is occupied.
False if orbital is not occupi... | 625941c5379a373c97cfab46 |
@login_required <NEW_LINE> def list_article(request): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> user_article = request.user.article_set.all() <NEW_LINE> return render(request, 'article/list.html', {'all': user_article}) | 文章列表页面
:param request:
:return: | 625941c530dc7b766590196a |
def __init__(self, vertex_coords, cell_vertices): <NEW_LINE> <INDENT> self.dim = vertex_coords.shape[1] <NEW_LINE> if self.dim not in (1, 2): <NEW_LINE> <INDENT> raise ValueError("Only 1D and 2D meshes are supported") <NEW_LINE> <DEDENT> self.vertex_coords = vertex_coords <NEW_LINE> self.cell_vertices = np.sort(cell_ve... | :param vertex_coords: an vertex_count x dim array of the coordinates of
the vertices in the mesh.
:param cell_vertices: an cell_count x (dim+1) array of the
indices of the vertices of which each cell is made up. | 625941c54527f215b584c45b |
def update_score(self, season_id, week, game_id, game): <NEW_LINE> <INDENT> table = boto3.resource(self.db_resource).Table(self.seasons_table) <NEW_LINE> currenttime = str(datetime.datetime.now()) <NEW_LINE> try: <NEW_LINE> <INDENT> game_update = table.update_item( Key={'id':season_id}, UpdateExpression='SET last_updat... | Update season with result | 625941c5ec188e330fd5a7a4 |
def stop(self, mode=None, disarm=False, wait=False): <NEW_LINE> <INDENT> pass | stop detector, optionally setting mode, disarming, and waiting | 625941c5656771135c3eb86f |
def test_issue1061(): <NEW_LINE> <INDENT> text = "I like _MATH_ even _MATH_ when _MATH_, except when _MATH_ is _MATH_! but not _MATH_." <NEW_LINE> tokenizer = English().tokenizer <NEW_LINE> doc = tokenizer(text) <NEW_LINE> assert "MATH" in [w.text for w in doc] <NEW_LINE> assert "_MATH_" not in [w.text for w in doc] <N... | Test special-case works after tokenizing. Was caching problem. | 625941c5442bda511e8be41d |
def __init__(self, address, cache=None, username='anonymous@genialis.com', password='anonymous', connect=True): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.buffer = cache <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self._gen = None <NEW_LINE> if connect: <NEW_LINE> ... | :param str address: The address of the API.
:param str username:
:param str password: Login info; None for public access.
:param CacheSQLite cache: A cache that stores results locally (an
:obj:`CacheSQLite`). | 625941c51b99ca400220aab4 |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 1 <NEW_LINE> (self.success,) = _get_struct_B().unpack(str[start:end]) <NEW_LINE> self.success = bool(self.success) <NEW_LINE> start = end <NEW_LINE> end += 4 <NEW_LINE> (length,) = _str... | 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 | 625941c58e05c05ec3eea376 |
def hashtags(self, quantity=4, category='general'): <NEW_LINE> <INDENT> category = category.lower() <NEW_LINE> supported = ''.join(list(HASHTAGS.keys())) <NEW_LINE> try: <NEW_LINE> <INDENT> hashtags = HASHTAGS[category] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError('Unsupported category. Use: ... | Create a list of hashtags (for Instagram, Twitter etc.)
:param quantity: The quantity of hashtags.
:type quantity: int
:param category: Available categories: general, girls, love,
boys, friends, family, nature, travel, cars, sport, tumblr.
:return: The list of hashtags.
:rtype: list
:Example:
['#love', '#sky', '#... | 625941c563f4b57ef0001120 |
def _to_pickleable_representation(model_name, model_type): <NEW_LINE> <INDENT> return { 'swagger_spec': model_type._swagger_spec, 'model_name': model_name, 'model_spec': model_type._model_spec, 'bases': model_type.__bases__, 'json_reference': model_type._json_reference, } | Extract a pickleable representation of the input Model type.
Model types are runtime created types and so they are not pickleable.
In order to workaround this limitation we extract a representation,
which is pickleable such that we can re-create the input Model type
(via ``_from_pickleable_representation``).
NOTE: ... | 625941c53346ee7daa2b2d6e |
def get_boundary_elements(self): <NEW_LINE> <INDENT> top_boundary_elements = [] <NEW_LINE> bottom_boundary_elements = [] <NEW_LINE> front_boundary_elements = [] <NEW_LINE> back_boundary_elements = [] <NEW_LINE> left_boundary_elements = [] <NEW_LINE> right_boundary_elements = [] <NEW_LINE> for i in range(self.number_of_... | Метод для нахождения индексов граничных элементов
:return: | 625941c52ae34c7f2600d134 |
def test_disable_snmp_v2_will_raise_exception_in_case_of_empty_snmp_community_string(self): <NEW_LINE> <INDENT> snmp_parameters = SNMPV2ReadParameters(ip="10.10.10.10", snmp_read_community="") <NEW_LINE> cli_service = mock.MagicMock() <NEW_LINE> with self.assertRaisesRegexp(Exception, "SNMP community can not be empty")... | Check that method will raise an Exception if snmp_parameters is an empty string | 625941c5460517430c39418b |
def test_invalid_apikey(self): <NEW_LINE> <INDENT> response = self.post(url_for('api.fake'), headers={'X-API-KEY': 'fake'}) <NEW_LINE> self.assert401(response) <NEW_LINE> self.assertEqual(response.content_type, 'application/json') <NEW_LINE> self.assertEqual(response.json, {'status': 401, 'message': 'Invalid API Key'}) | Should raise a HTTP 401 if an invalid API Key is provided | 625941c529b78933be1e56b1 |
def plotBET( P, T, slope, y_intercept, max ): <NEW_LINE> <INDENT> pl.figure() <NEW_LINE> pl.plot( P, T, 'ro' ) <NEW_LINE> pl.title('BET Surface Area Plot') <NEW_LINE> pl.ylabel('$1/[Q(p^\circ/p-1)]$') <NEW_LINE> pl.xlabel('Relative Pressure($p/p^\circ$)') <NEW_LINE> X = np.array([0.0, max]) <NEW_LINE> Y = slope*X + y_i... | Show a BET transform plot with the line of best fit overlaid. | 625941c532920d7e50b281d2 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ODMcomplexTypeDefinitionSubjectData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941c5d10714528d5ffce4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.