code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_user_agent(): <NEW_LINE> <INDENT> global user_agent_string <NEW_LINE> if user_agent_string is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sysinfo = subprocess.check_output('lsb_release -i -r -s'.split(' ')) <NEW_LINE> dockerinfo = subprocess.check_output('docker --version'.split(' ')) <NEW_LINE> user_age... | Construct and informative user-agent string.
Includes OS version and docker version info
Not thread-safe
:return: | 625941eccb5e8a47e48b7fbf |
def update_target(self): <NEW_LINE> <INDENT> self.old_model.load_state_dict(self.model.state_dict()) | Updates the old network with the weights of the actor network | 625941eccad5886f8bd274f6 |
def vehicle(vehicleObject): <NEW_LINE> <INDENT> def whichAccessible(state): <NEW_LINE> <INDENT> if len(state) == 1: <NEW_LINE> <INDENT> if state[0]: <NEW_LINE> <INDENT> return "any" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "none" <NEW_LINE> <DEDENT> <DEDENT> elif len(state) == 2: <NEW_LINE> <INDENT> back, f... | Takes vehicle object and processes. | 625941ec099cdd3c635f1176 |
def delete_tabs(self, account_id, recipient_id, template_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.delete_tabs_with_http_info(account_id, recipient_id, template_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE... | Deletes the tabs associated with a recipient in a template.
Deletes one or more tabs associated with a recipient in a template.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_f... | 625941ec97e22403b379d4b9 |
def simple_cleanup(data): <NEW_LINE> <INDENT> max_condition=0.55 <NEW_LINE> min_condition=0.0 <NEW_LINE> i=0 <NEW_LINE> data[where(data > max_condition)] = -9999 <NEW_LINE> data[where(data < min_condition)] = -9999 <NEW_LINE> return data | Simply removes all values above or below two thresholds | 625941ec8c3a8732951588de |
def traverse_add(self, q, lower, upper, l, u): <NEW_LINE> <INDENT> lower[q.idx] = l <NEW_LINE> upper[q.idx] = u <NEW_LINE> return lower, upper | :param q: one node query in the query data tree
:param lower: maintain lower contribution of each point in the query data tree.
:param upper: maintain upper contribution of each point in the query data tree.
:param l: min value of density contribution
:param u: max value of density contribution
:return: two array.
Thi... | 625941ec96565a6dacc8fbe7 |
def modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(self, base_space_id, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.modify_response_descriptor_subscriptions_subscription_subscription... | Modify a SubscriptionResource by ID # noqa: E501
Updates an existing subscription # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.modify_response_descriptor_subscriptions_subscription_subscription_resource_spaces(... | 625941ecd268445f265b538d |
def minimize_base_ring(self): <NEW_LINE> <INDENT> R = self.base_ring() <NEW_LINE> if R.is_prime_field(): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> p = R.characteristic() <NEW_LINE> if p: <NEW_LINE> <INDENT> K = rings.IntegerModRing(p) <NEW_LINE> <DEDENT> elif self.order() <= 2: <NEW_LINE> <INDENT> K = rings.Q... | Return a Dirichlet character that equals this one, but over as
small a subfield (or subring) of the base ring as possible.
.. note::
This function is currently only implemented when the base
ring is a number field. It's the identity function in
characteristic p.
EXAMPLES::
sage: G = DirichletGroup(13)
... | 625941ec55399d3f05588bd5 |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApiPipelineVersion): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941ec50485f2cf553d2b9 |
def __die(self, synchronous=False): <NEW_LINE> <INDENT> already_killed = self.__killed <NEW_LINE> self.__killed = True <NEW_LINE> if self.__id and not already_killed: <NEW_LINE> <INDENT> if self.__exhaust and self.__exhaust_mgr: <NEW_LINE> <INDENT> self.__exhaust_mgr.sock.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Closes this cursor.
| 625941ecbf627c535bc136ed |
def sum_fusion_method_test(self): <NEW_LINE> <INDENT> data = [1,2,3,4,5,6,0,7] <NEW_LINE> data2 = [1,3,5,65,3,2,1,34,0.5] <NEW_LINE> assert FusionMethods["sum"](data) == 28 <NEW_LINE> assert FusionMethods["sum"](data2) == 114.5 | Testing the sum fusion method. | 625941ecbe383301e01b5999 |
def spawn_editor(self, help_text=None): <NEW_LINE> <INDENT> text = '' if help_text is None else help_text <NEW_LINE> tmp_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.markdown', delete=False) <NEW_LINE> tmp_file.write(text) <NEW_LINE> tmp_file.close() <NEW_LINE> fname = tmp_file.name <NEW_LINE> self.loop.scree... | Open a editor with a temporary file containing ``help_text``.
If the exit code is 0 the text from the file will be returned.
Otherwise, ``None`` is returned. | 625941ec66673b3332b925af |
def update_aliens(ai_settings, screen,stats, sb,ship, aliens, bullets): <NEW_LINE> <INDENT> check_fleet_edges(ai_settings, aliens) <NEW_LINE> aliens.update() <NEW_LINE> '''check collissions between aliens and ship''' <NEW_LINE> if pygame.sprite.spritecollideany(ship,aliens): <NEW_LINE> <INDENT> ship_hit(ai_settings, sc... | check alien appears at the screen edge or not, and update aliens location | 625941ecb5575c28eb68e523 |
def highlight(self) -> None: <NEW_LINE> <INDENT> system = platform.system() <NEW_LINE> if system == 'Darwin': <NEW_LINE> <INDENT> value = Keys.COMMAND + 'a' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = Keys.CONTROL + 'a' <NEW_LINE> <DEDENT> self.type(value) | Highlight the text content in an input element. | 625941ecbe7bc26dc91cdb14 |
def knot_averages(t, p): <NEW_LINE> <INDENT> n = len(t) - p - 1 <NEW_LINE> k = np.zeros(n) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> k[i] = sum(t[i + 1: i + p + 1]) / float(p) <NEW_LINE> <DEDENT> return k | Given a knot vector of length p + n + 1,
returns the knot averages. Main use case is
the plotting of control polygons, and the
variation diminishing spline approximation.
:param t: knot vector
:param p: spline degree
:return: array of knot averages | 625941ec4c3428357757c842 |
def height(self, certificate=False): <NEW_LINE> <INDENT> if not certificate: <NEW_LINE> <INDENT> return self.rank() + 1 <NEW_LINE> <DEDENT> levels = self.level_sets() <NEW_LINE> height = len(levels) <NEW_LINE> if height == 0: <NEW_LINE> <INDENT> return (0, []) <NEW_LINE> <DEDENT> n = height - 2 <NEW_LINE> previous = le... | Return the height (number of elements in a longest chain) of the poset.
INPUT:
- ``certificate`` -- (default: ``False``) whether to return
a certificate
OUTPUT:
- If ``certificate=True`` return ``(h, c)``, where ``h`` is the
height and ``c`` is a chain of maximum cardinality.
If ``certificate=False`` return o... | 625941ec3617ad0b5ed68414 |
def SearchL(self, target, blocking=True): <NEW_LINE> <INDENT> self.link._moveX(target, self, MOVE_TYPE_LINEARSEARCH, blocking) <NEW_LINE> return self.SimulatorJoints() | Moves a robot to a specific target and stops when a specific input switch is detected ("Search Linear" mode). This function waits (blocks) until the robot finishes its movements.
:param target: Target to move to. It can be the robot joints (Nx1 or 1xN), the pose (4x4) or a target (item pointer)
:type target: :class:`r... | 625941ec4e696a04525c996b |
def degree_calculator(graph): <NEW_LINE> <INDENT> node_degree={} <NEW_LINE> for key,value in graph.items(): <NEW_LINE> <INDENT> node_degree[key]=(-1)*len(value) <NEW_LINE> <DEDENT> for value in graph.values(): <NEW_LINE> <INDENT> for i in value: <NEW_LINE> <INDENT> if i in node_degree.keys(): <NEW_LINE> <INDENT> node_d... | for a given graph which is a dictionary represent the edges in graph,
calculate each node's degree,indgree puls 1,outdgree minus 1
return the node with the min degrees which less than 0 | 625941ec57b8e32f524839bc |
def get_options(): <NEW_LINE> <INDENT> parser = OptionParser() <NEW_LINE> parser.add_option("-w","--winter", help="Winter Classes") <NEW_LINE> parser.add_option("-g","--spring", help="Spring Classes") <NEW_LINE> parser.add_option("-f","--fall", help="Fall Classes") <NEW_LINE> parser.add_option("-p","--prereqs", help="C... | Uses an OptionParser to parse command line options
Returns a python dict of str -> file if successful. Prints an error and returns 1
otherwise | 625941ec82261d6c526ab9c5 |
def _initialize_plugin_configuration(self): <NEW_LINE> <INDENT> plugin_config_qs = PluginConfiguration.objects.filter(name=self.PLUGIN_NAME) <NEW_LINE> plugin_config = self._cached_config or plugin_config_qs.first() <NEW_LINE> if plugin_config: <NEW_LINE> <INDENT> self._cached_config = plugin_config <NEW_LINE> self.act... | Initialize plugin by fetching configuration from internal cache or DB. | 625941ec656771135c3ebd93 |
def count(self) -> int: <NEW_LINE> <INDENT> return self._component_count | :return: the number of connected components in the graph. | 625941ec0fa83653e46574d6 |
def __init__( self, *, value: List["OutboundEnvironmentEndpoint"], **kwargs ): <NEW_LINE> <INDENT> super(OutboundEnvironmentEndpointCollection, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | :keyword value: Required. Collection of resources.
:paramtype value: list[~azure.mgmt.web.v2019_08_01.models.OutboundEnvironmentEndpoint] | 625941ec2c8b7c6e89b35cda |
def increment(self, template, shapes, group=None, shape_forgetting_factor=1.0, verbose=False, batch_size=None): <NEW_LINE> <INDENT> return self._train(template, shapes, group=group, verbose=verbose, shape_forgetting_factor=shape_forgetting_factor, increment=True, batch_size=batch_size) | Method to increment the trained ATM with a new set of training shapes
and a new template.
Parameters
----------
template : `menpo.image.Image`
The template image.
shapes : `list` of `menpo.shape.PointCloud`
The `list` of training shapes.
group : `str` or ``None``, optional
The landmark group of the `templa... | 625941ec23849d37ff7b35a9 |
def remove_candidate_from_user_database(self, keycode): <NEW_LINE> <INDENT> if keycode not in self._select_keys: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> index = self._select_keys.index(keycode) <NEW_LINE> cursor_pos = self._lookup_table.get_cursor_pos() <NEW_LINE> cursor_in_page = self._lookup_table.get_cu... | Remove a candidate displayed in the lookup table from the user database.
The candidate indicated by the selection key with the key code
“keycode” is removed, if possible. If it is not in the user
database at all, nothing happens.
If this is a candidate which is also in the system database,
removing it from the user ... | 625941ecb545ff76a8914333 |
def conv3x3(self, in_planes, out_planes, stride=1): <NEW_LINE> <INDENT> return self.conv_fn(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | 3x3 convolution with padding | 625941ec67a9b606de4a83d5 |
@decorators.aws_resource(IAMInstanceProfile, RESOURCE_TYPE) <NEW_LINE> def create(ctx, iface, resource_config, **_): <NEW_LINE> <INDENT> params = dict() if not resource_config else resource_config.copy() <NEW_LINE> resource_id = utils.get_resource_id( ctx.node, ctx.instance, params.get(RESOURCE_NAME), use... | Creates an AWS IAM Profile | 625941ec67a9b606de4a83d4 |
def _get_where_list(key): <NEW_LINE> <INDENT> from .operator import BooleanExpression <NEW_LINE> from .merge import BooleanMergeExpression <NEW_LINE> if key is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif isinstance(key, BooleanExpression): <NEW_LINE> <INDENT> return key._to_where_list() <NEW_LINE> <D... | Generate a WHERE clause list to be used in the SQL query.
Parameters
----------
key : BooleanExpression or tuple
An abstrct expression of WHERE condition.
Returns
-------
list[str]
The deduced WHERE-list starting with WHERE keyword.
Raises
------
TypeError
If the key is neither a BooleanExpression nor a ... | 625941ec32920d7e50b286f3 |
def terminate(self): <NEW_LINE> <INDENT> if not self.pipe or not self.stream(): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> debug('tcpdump_helper terminate fd %s' % self.stream().fileno()) <NEW_LINE> self.pipe.terminate() <NEW_LINE> result = self.pipe.wait() <NEW_LINE> if result == 124: <... | Terminate the helper. | 625941ecb57a9660fec33da9 |
@permission_required('siteman.add_haus') <NEW_LINE> def haus(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> form = forms.AddHausForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> projekt_id = request.session['current_projekt_id'] <NEW_LINE> haus_nr = form.cleaned_data... | display list of haus associated with selected project
add haus to a project with defalult settings | 625941ec5fc7496912cc3e9b |
def get(self, key): <NEW_LINE> <INDENT> if key not in self.dict: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> v = self.dict.pop(key) <NEW_LINE> self.dict[key] = v <NEW_LINE> return v | :rtype: int | 625941ecfff4ab517eb2f95d |
def relative_enthalpy(myp,feos0,peos0,feos1,peos1): <NEW_LINE> <INDENT> h0 = reference_enthalpy(myp, feos0, peos0) <NEW_LINE> v1 = volpp_at_pressures(myp,peos1) <NEW_LINE> e1 = feos1(v1) <NEW_LINE> p1 = peos1(v1) <NEW_LINE> h1 = e1+p1*v1 <NEW_LINE> dh = h1-h0 <NEW_LINE> return dh | evaluate the relative enthalpy between two eos at selected myp
Args:
myp (np.array): a list of pressures in Hartree atomic units
feos0 (function): reference eos
peos0 (function): reference pressure eos
feos1 (function): target eos
peos1 (function): target pressure eos
Returns:
np.array: dh, the enthalpy dif... | 625941ecd10714528d600207 |
def set_freq(self, channel=1, frequency=1): <NEW_LINE> <INDENT> self.check_ch(channel) <NEW_LINE> if frequency <= 0: <NEW_LINE> <INDENT> raise ValueError('The selected frequency must be greater than zero. Or maybe you are just dumb!') <NEW_LINE> <DEDENT> if frequency > 200e6: <NEW_LINE> <INDENT> raise ValueError('The s... | set desired frequency value [Hz] | 625941ec24f1403a92601080 |
@app.route('/users') <NEW_LINE> def get_users(): <NEW_LINE> <INDENT> user_input = session["users"] <NEW_LINE> user_info = {key: value for key, value in user_input.items() if value} <NEW_LINE> if len(list(user_info.keys())) <= 1: <NEW_LINE> <INDENT> session["error"] = "Search Result is too large, be more specific!" <NEW... | Render search result template with Github API data
:return: Rendered Template | 625941eccc40096d61595e6c |
def get_activation_url(self, user): <NEW_LINE> <INDENT> uid = urlsafe_base64_encode(force_bytes(user.pk)) <NEW_LINE> uid = uid.decode('utf-8') <NEW_LINE> token = default_token_generator.make_token(user) <NEW_LINE> url = settings.ADMIN_DASHBOARD_URL['reset_password'].format(uid, token) <NEW_LINE> print(url) <NEW_LINE> r... | get the activation url | 625941ec55399d3f05588bd6 |
@requester('script', root=True, infomodel=ScriptDataModel) <NEW_LINE> def fake_script( request_items: List[Requester], rule: str or int, **options ): <NEW_LINE> <INDENT> from app.script.manager import ScriptTask <NEW_LINE> from app.script import ScriptBaseClass <NEW_LINE> url = 'http://fake.script' <NEW_LINE> script = ... | (调试模式) 调试模式下的虚假脚本请求Root。 | 625941ecad47b63b2c50a49d |
def test_1_new_feature_community(self): <NEW_LINE> <INDENT> fc = FeaturedCommunity.query.filter_by( id_community=self.test_name).first() <NEW_LINE> self.assertEqual(fc.id_community, self.test_name) | communities - creates new featured community. | 625941ec283ffb24f3c55e1a |
def next(self, done): <NEW_LINE> <INDENT> self.execution.returncode = self.tasks[done].execution.returncode <NEW_LINE> if self.complete() and done == len(self.tasks)-1: <NEW_LINE> <INDENT> return Run.State.TERMINATED <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.execution.returncode != 0: <NEW_LINE> <INDENT> re... | Return collection state after step number `done` is terminated.
Note that the task collection state should be set to
``TERMINATED`` after the last task has been executed,
regardless of whether it failed or not. Now, there are two
distinct contexts where `next` could be applied in a
`SequentialTaskCollection` instance... | 625941ecd4950a0f3b08c866 |
def load_ontology_graph(self, uri): <NEW_LINE> <INDENT> with URLZSource(uri).open() as source: <NEW_LINE> <INDENT> self.rdf_graph.parse(file = source, format='xml') | Loads the ontology from a URI in a RDFLib graph.
Given a uri pointing to a OWL file, load the ontology representation in a graph.
Args:
uri (str): the URI for the ontology representation in OWL.
Returns:
None
Raises:
None | 625941ecab23a570cc2506a5 |
def __go_login_page(self): <NEW_LINE> <INDENT> if self.s is not None: <NEW_LINE> <INDENT> self.s.get(self.config['logout_api']) <NEW_LINE> <DEDENT> self.s = requests.session() <NEW_LINE> self.s.get(self.config['login_page']) | 访问登录页面获取 cookie | 625941ecf8510a7c17cf9c1e |
def get_id(self): <NEW_LINE> <INDENT> return self.id | To retrieve the DocEntry's id value
DocEntry's id attribute getter method.
To get the id associated to the DocEntry's document
:return: The DocEntry's id value | 625941ecb545ff76a8914334 |
def answer_inline_query(inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None, **kwargs): <NEW_LINE> <INDENT> if next_offset is None: <NEW_LINE> <INDENT> next_offset = "" <NEW_LINE> <DEDENT> json_results = [] <NEW_LINE> for result in results: <NEW_L... | Use this method to send answers to an inline query. On success, True is returned.
:param inline_query_id: Unique identifier for the message recipient — String
:param results: An array of results for the inline query — Array of InlineQueryResult
:param cache_time: The maximum amount of time the result of the inline que... | 625941ece8904600ed9f2454 |
def get_dependency_dict (self): <NEW_LINE> <INDENT> return {'': [], 'devel': [], 'doc': [], 'runtime': [], 'x11': []} | subpackage -> list of dependency dict. | 625941eccc0a2c11143dd3b0 |
def setROI(self, bounds): <NEW_LINE> <INDENT> logger.debug("Set ROI for the wavelength to {}".format(bounds)) <NEW_LINE> self.wavRegionWidget.setValue(bounds) | Set the region of interest for the wavelength in the widget.
Parameters
----------
bounds : list, tuple
The absolute lower and upper bounds for the wavelength. | 625941ec4e696a04525c996c |
def _parseUserInput(self, raw): <NEW_LINE> <INDENT> if raw is None: <NEW_LINE> <INDENT> return NoInput() <NEW_LINE> <DEDENT> raw = str(raw) <NEW_LINE> raw = raw.strip() <NEW_LINE> raw = raw.lower() <NEW_LINE> if raw == '': <NEW_LINE> <INDENT> return NoInput() <NEW_LINE> <DEDENT> if raw in ['yes', 'y', '1', 'true']: <NE... | Translate string to desired output. Pass None and '' (as no input), as
NoInput objects, and pass all other outputs as IncompleteInput objects.
>>> d = configure.YesOrNo()
>>> d._parseUserInput('y')
True
>>> d._parseUserInput('')
<music21.configure.NoInput: None>
>>> d._parseUserInput('asdf')
<music21.configure.Incompl... | 625941ecbde94217f368330a |
def leaky_relu(x, alpha=0.01): <NEW_LINE> <INDENT> return tf.maximum(x,alpha*x) | Compute the leaky ReLU activation function.
Inputs:
- x: TensorFlow Tensor with arbitrary shape
- alpha: leak parameter for leaky ReLU
Returns:
TensorFlow Tensor with the same shape as x | 625941ec97e22403b379d4ba |
def randomwalk(periods, start=pd.datetime.today().date(), index=None, name=None, tick=1, freq='B'): <NEW_LINE> <INDENT> if not index: <NEW_LINE> <INDENT> index = pd.date_range(start=start, periods=periods, freq=freq) <NEW_LINE> <DEDENT> bullbear = pd.Series(tick * np.random.randint(-1, 2, periods), index=index, name=na... | periods日分だけランダムウォークを返す | 625941ec44b2445a339325b0 |
def get_filters(self,request): <NEW_LINE> <INDENT> filter_specs = [] <NEW_LINE> filter_fields = [self.lookup_opts.get_field(field_name) for field_name in self.field_names] <NEW_LINE> for f in filter_fields: <NEW_LINE> <INDENT> spec = FilterSpec.create(f, self.request, self.params, self.model) <N... | Retrieves a list of FilterSpec objects based on the fields we may
filter on. | 625941ecd164cc617578326d |
def test_staff_list_with_cursor(self): <NEW_LINE> <INDENT> bob = self.new_user(name="Bob Smith", is_admin=True) <NEW_LINE> headers = self.login(user=bob) <NEW_LINE> response = self.app.get( '%s/dashboard/staff' % api.path, headers=headers ).json <NEW_LINE> self.assertTrue(response.get('cursor')) <NEW_LINE> response = s... | Should list staff using the cursor for a previous request
| 625941ec26238365f5f0f394 |
def test_add_network_multiple_events( currency_network_registry_contract, currency_network_contract, accounts ): <NEW_LINE> <INDENT> currency_added_event_filter = ( currency_network_registry_contract.events.CurrencyNetworkAdded.createFilter( fromBlock=0 ) ) <NEW_LINE> currency_network_registry_contract.functions.addCur... | Adding the same network with multiple accounts.
Each call emits a new event with the corresponding account as
registrar. | 625941ec3346ee7daa2b328f |
def set_num_neighbors(self, num_neighbors: int = 1, analyze: bool = True) -> None: <NEW_LINE> <INDENT> warnings.warn( "Configuring neighbors with `set_num_neighbors` is deprecated " "and will be removed in a future version. Use the " "`add_connections` instead.", DeprecationWarning, ) <NEW_LINE> self.add_connections(nu... | Sets the maximal neighbor distance of the lattice.
Parameters
----------
num_neighbors: int, optional
The number of neighbor-distance levels,
e.g. setting to ``1`` means only nearest neighbors.
analyze: bool
Flag if lattice base is analyzed. If ``False`` the ``analyze``-method
needs to be called manual... | 625941ecd8ef3951e3243a5c |
def move_left(self, duration=None): <NEW_LINE> <INDENT> if duration is None: <NEW_LINE> <INDENT> self._send_cmd(self._LEFT) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._send_cmd_with_timer(self._LEFT, duration) | Moves the turret left.
Args:
duration (optional), mumber of milliseconds to keep moving | 625941ec627d3e7fe0d69370 |
def test_delimitString_string(): <NEW_LINE> <INDENT> delim = " | " <NEW_LINE> xadd = "A String Added" <NEW_LINE> zstr = UT.delimitString(xadd, delim) <NEW_LINE> assert zstr == "A | String | Added" | It splits the input string and concatenates each string with the delimeter. | 625941eca4f1c619b28b054b |
def to_parallel(args, module="bcbio.distributed"): <NEW_LINE> <INDENT> ptype, cores = _get_cores_and_type(args.numcores, getattr(args, "paralleltype", None), args.scheduler) <NEW_LINE> parallel = {"type": ptype, "cores": cores, "scheduler": args.scheduler, "queue": args.queue, "tag": args.tag, "module": module, "resour... | Convert input arguments into a parallel dictionary for passing to processing.
| 625941ec44b2445a339325b1 |
def start_suite(self, suite): <NEW_LINE> <INDENT> pass | Called when suite starts. Default implementation does nothing.
Can return explicit ``False`` to stop visiting. | 625941ec73bcbd0ca4b2c594 |
def execute_command(self, *args, **options): <NEW_LINE> <INDENT> pool = self.connection_pool <NEW_LINE> command_name = args[0] <NEW_LINE> connection = pool.get_connection(command_name, **options) <NEW_LINE> try: <NEW_LINE> <INDENT> connection.send_command(*args) <NEW_LINE> return self.parse_response(connection, command... | Execute a command and return a parsed response | 625941ec76e4537e8c351b95 |
def __init__(self, name="Data Experiment", *args, **kwargs): <NEW_LINE> <INDENT> def_opts = { 'data_bounds': [tuple, (0, 1E21), None, None, '-', 'The bounds for the spline to represent the ' 'data'], 'n_knots': [int, 200, 5, None, '-', 'The number of knots to represent the data'], 'n_smooth': [int, 0, 0, None, '-', 'Th... | Loads the data and performs pre-processing activities
| 625941ec21a7993f00bc8218 |
def _looks_like_url(txt): <NEW_LINE> <INDENT> if " " in txt or "\n" in txt: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if "/" in txt: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if re.search(r'\?\w+=.+', txt): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if re.match(r"\w+\.html", txt): <NEW_LIN... | Return True if text looks like an URL (probably relative).
>>> _looks_like_url("foo.bar")
False
>>> _looks_like_url("http://example.com")
True
>>> _looks_like_url("/page2")
True
>>> _looks_like_url("index.html")
True
>>> _looks_like_url("foo?page=1")
True
>>> _looks_like_url("x='what?'")
False
>>> _looks_like_url("visi... | 625941ec8c0ade5d55d3eede |
def payload(self): <NEW_LINE> <INDENT> payload = {'type': self.resource_type(), 'attributes': self.attributes} <NEW_LINE> if self.id: <NEW_LINE> <INDENT> payload['id'] = self.id <NEW_LINE> <DEDENT> return payload | Renders the resource payload.
:returns: a dict representing the object to be used as payload for a request | 625941eca219f33f34628e80 |
def find_bad_building1099(X, y): <NEW_LINE> <INDENT> return X[(X.building_id == 1099) & (X.meter == 2) & (y > 3e4)].index | Returns indices of bad rows (with absurdly high readings) from building 1099. | 625941eca79ad161976cc664 |
def init_ui(self): <NEW_LINE> <INDENT> super().init_ui() <NEW_LINE> self.setAttribute(Qt.WA_DeleteOnClose) <NEW_LINE> db_def = Path(settings.get('DATABASES.SERVER.NAME')) <NEW_LINE> def open_file_dialog(): <NEW_LINE> <INDENT> global dialog <NEW_LINE> dialog = QFileDialog(config_window, 'Путь до папки с БД', str(db_def.... | Инициализация интерфейса. | 625941ec596a897236089fd8 |
def train_data(self, alpha, errors, punish=0.0001): <NEW_LINE> <INDENT> self.punish = punish <NEW_LINE> dimension = self.x.shape[1] <NEW_LINE> self.theta = np.random.random(dimension) <NEW_LINE> compute_error = 100000000 <NEW_LINE> times = 0 <NEW_LINE> while compute_error > errors: <NEW_LINE> <INDENT> res = np.dot(self... | :param alpha: alpha为学习速率
:param errors: 误差小于多少时停止迭代的阈值
:param punish: 惩罚系数
:param times: 最大迭代次数
:return: | 625941ed0c0af96317bb8706 |
def calculateFeasibleRegion(points, inecuations, resources, sign): <NEW_LINE> <INDENT> if type(points) != list or type(inecuations) != np.ndarray or type(resources) != np.ndarray or not isStringList(sign) or len(inecuations) != len(resources) or len(inecuations) != len(sign) or len(sign) != len(resources): <NEW_LINE> <... | This method receives a list of points, the restrictions of the problem without sign and resource in a numpy array, the resources of the restrictions in a numpy array,a list of
strings with the signs of the restrictions. The method calculates which points belong to feasible region
and returns these points in a list.If t... | 625941ed10dbd63aa1bd30c1 |
def preemphasis(signal, coeff=0.95): <NEW_LINE> <INDENT> return signal | perform preemphasis on the input signal.
:param signal: The signal to filter.
:param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95.
:returns: the filtered signal. | 625941ed377c676e912726c5 |
def isValidLogin(username, password): <NEW_LINE> <INDENT> check = getUserFromDatabase(username) <NEW_LINE> print(check.getPassword()) <NEW_LINE> passwordAttempt = hash224(password) <NEW_LINE> print(passwordAttempt) <NEW_LINE> return check.getPassword() == passwordAttempt | Function that checks whether login info is valid. Takes username and pass
as parameters
Additional notes: | 625941ed293b9510aa2c37af |
def is_red(self): <NEW_LINE> <INDENT> state = self.get_state() <NEW_LINE> if state is None: <NEW_LINE> <INDENT> LOGGER.error("Bulb state check failed in is_red()") <NEW_LINE> return False <NEW_LINE> <DEDENT> if (state['c_mode'] == 'COLOUR' and state['hue'] == 0 and state['state'] == 1): <NEW_LINE> <INDENT> return True ... | Check if the bulb is red and on
| 625941ed45492302aab5e7e8 |
def update(self, x, y, alpha): <NEW_LINE> <INDENT> losses = self.predict(x) <NEW_LINE> for (i,(p,k)) in enumerate(itertools.izip(losses,self.labels)): <NEW_LINE> <INDENT> self._update_one(alpha, self.W[i], self.N[i], x, p, y[k]) <NEW_LINE> p = max(min(p, 1.-1e-15), 1e-15) <NEW_LINE> losses[i] = -log(p if y[k]==1. else... | Update the model.
@param x: features, in sparse format [(idx,value)*]
@param y: truth labels
@param alpha: learning rate | 625941eda8ecb033257d35ea |
def is_pythagorean(a: int, b: int, c: int) -> bool: <NEW_LINE> <INDENT> return ( a > 0 and b > 0 and c > 0 and a ** 2 + b ** 2 == c ** 2 ) | Returns True if a, b, and c form a Pythagorean triple. | 625941edd6c5a1020814456e |
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, downsample=0, padding_type='reflect', aef='relu'): <NEW_LINE> <INDENT> assert(n_blocks >= 0) <NEW_LINE> super(EncoderRes, self).__init__() <NEW_LINE> if type(norm_layer) == functools.partial: <NEW_LINE> <INDENT> us... | Construct a Resnet-based Encoder | 625941eda05bb46b383ecd3c |
def __init__(self, src, sport): <NEW_LINE> <INDENT> self.src = src <NEW_LINE> self.sport = sport <NEW_LINE> self.verbose = False <NEW_LINE> self.tcp_flags = { 'TCP_FIN': 0x01, 'TCP_SYN': 0x02, 'TCP_RST': 0x04, 'TCP_PSH': 0x08, 'TCP_ACK': 0x10, 'TCP_URG': 0x20, 'TCP_ECE': 0x40, 'TCP_CWR': 0x80 } | Initializes server parameters. | 625941ed7b180e01f3dc4d11 |
def MurmurHash2(input, seed=0): <NEW_LINE> <INDENT> l = len(input) <NEW_LINE> m = 0x5bd1e995 <NEW_LINE> h = seed ^ l <NEW_LINE> x = l % 4 <NEW_LINE> o = l - x <NEW_LINE> for k in array.array(uint32_t, input[:o]): <NEW_LINE> <INDENT> k = (k * m) & 0xFFFFFFFF <NEW_LINE> h = (((k ^ (k >> 24)) * m) ^ (h * m)) & 0xFFFFFFFF ... | Generate a 32-bit hash from a string using the MurmurHash2 algorithm
takes a bytestring!
Pure-python implementation. | 625941ed26068e7796caf206 |
def _tls12_sign_dsa_SKE(self, serverKeyExchange, sigHash=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> serverKeyExchange.hashAlg, serverKeyExchange.signAlg = getattr(SignatureScheme, sigHash) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> serverKeyExchange.signAlg = SignatureAlgorit... | Sign a TLSv1.2 SKE message. | 625941ed15baa723493c4499 |
def meta_load_from_dir(meta_dir_path): <NEW_LINE> <INDENT> files = [f for f in os.listdir(meta_dir_path) if os.path.isfile(os.path.join(meta_dir_path, f))] <NEW_LINE> meta = BaserockMeta() <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if f.endswith('.meta'): <NEW_LINE> <INDENT> meta.import_meta( open(os.path.join(meta... | Read Baserock metadata from a directory | 625941ed15fb5d323cde1036 |
def get_AWAP(filename = ["/home/563/gt3409/Documents/AWAP_PRCP_2010-2011_0.5deg_land.nc", "/home/563/gt3409/Documents/AWAP_PRCP_2012-2013_0.5deg_land.nc"]): <NEW_LINE> <INDENT> AWAP_start_date = date(2010,1,1) <NEW_LINE> AWAP_end_date = date(2013,12,31) <NEW_LINE> AWAP = {} <NEW_LINE> times = {} <NEW_LINE> for i in ran... | THis function loads the AWAP data from the netCDF file, and changes the AWAP times to datetime.dates | 625941ed6aa9bd52df0372c6 |
def cppRepr(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.DataArray_cppRepr(self, *args) | cppRepr(self, char varName) -> string
1 | 625941edb5575c28eb68e524 |
def get_middle_position(self): <NEW_LINE> <INDENT> a=self.adjustment <NEW_LINE> return self.pixel2unit( a.get_value() + a.get_page_size() / 2, absolute=True ) | Return the current middle position, in ms.
| 625941edcad5886f8bd274f7 |
def get_user_date(self, user_day=1): <NEW_LINE> <INDENT> now = self.now() <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_month_int = int(input("Ведите месяц: ")) <NEW_LINE> if user_month_int in range(1, now.month + 1): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except ValueError as... | Return user act date | 625941ed0c0af96317bb8707 |
def use_order(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> code = request.POST.get('code') <NEW_LINE> order_id = request.POST.get('id') <NEW_LINE> order = Order.objects.get(id=order_id, code=code) <NEW_LINE> order.completed_time = now() <NEW_LINE> order.status = OrderStatus.USED <NEW_L... | 用户就餐时,餐厅管理员标记订单为已使用 | 625941edadb09d7d5db6ccab |
def add(self, key, value): <NEW_LINE> <INDENT> self._buffer[key] = value <NEW_LINE> self._total_size += self._get_nbytes(value) <NEW_LINE> while self._total_size > self._max_size_in_bytes: <NEW_LINE> <INDENT> _, v = self._buffer.popitem(last=False) <NEW_LINE> self._total_size -= self._get_nbytes(v) | Add an item to the buffer and make sure that the buffer does not exceed
the maximum size in memory. | 625941edac7a0e7691ed45e1 |
def setUp(self): <NEW_LINE> <INDENT> self.new_user = User(password = 'mypassword') | method that creates an instance of User class. we pass in the password property | 625941edd8ef3951e3243a5d |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkAddConstantToImageFilterPython.itkAddConstantToImageFilterIUC2DIUC2_Superclass_GetPointer(self) | GetPointer(self) -> itkAddConstantToImageFilterIUC2DIUC2_Superclass | 625941edbaa26c4b54cb1639 |
def genNameStemDict(fastaPathDict): <NEW_LINE> <INDENT> nameStemsDict = {} <NEW_LINE> for nflPath, flncPathList in fastaPathDict.iteritems(): <NEW_LINE> <INDENT> flncNameStems = [] <NEW_LINE> for flncPath in flncPathList: <NEW_LINE> <INDENT> flncBaseName = os.path.basename(flncPath) <NEW_LINE> reResults = re.search(FAS... | The FLNC fasta file names will be the basis for the cluster output folder
names because it has the size, group, tissue/pooled, and number of cells in
the group. Will use for making output directories and file output names.
Note: Although a bit long and unwieldly the NFL fasta full path will remain
the key, which will... | 625941ed16aa5153ce362998 |
def minDiffInBST(self, root): <NEW_LINE> <INDENT> def _helper(root, min_val, prev): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> arr[0] = min(arr[0], abs(root.val - prev)) <NEW_LINE> if root.left: <NEW_LINE> <INDENT> _helper(root.left, min_val, root.val) <NEW_LINE> <DEDENT> if root.ri... | :type root: TreeNode
:rtype: int | 625941ed283ffb24f3c55e1b |
def get_avg_word_length_in_characters(num_words, num_characters): <NEW_LINE> <INDENT> return 0 if num_words == 0 else num_characters / num_words | Returns the average word length in characters
:param num_words: number of words
:param num_characters: number of characters
:return: average word length in characters | 625941ed8a349b6b435e8692 |
def Queue(queue_config): <NEW_LINE> <INDENT> name = '{0}_{1}'.format(queue_config['ENV_MODE'], queue_config['BASENAME']) <NEW_LINE> t = 'TYPE' <NEW_LINE> if t not in queue_config.keys(): <NEW_LINE> <INDENT> raise Exception('Could not find {0} in configuration'.format(t)) <NEW_LINE> <DEDENT> if queue_config[t] == 'ironi... | Abstract queue object
Arguments:
- queue_config (dict): contains configuration for queue
Example queue configuration:
{
'BASENAME': 'my_queue',
'ENV_MODE': 'dev',
'TYPE': 'ironio',
'ironio': {
'TOKEN': 'xxxxxxxxx',
'PROJECT_ID': yyyy... | 625941ed004d5f362079a84f |
def __init__(self, iterator, source_names, **kwargs): <NEW_LINE> <INDENT> super(DataIterator, self).__init__(source_names=source_names, **kwargs) <NEW_LINE> self.iterator = iterator | Wraps the python iterator and names the values it yields.
Arguments:
----------
iterator: python iterator to wrap. It must return tuples of nympy arrays
source_names: names of elements returned by the iterator | 625941ed7b25080760e39975 |
def get_account_name(identifier): <NEW_LINE> <INDENT> log.debug(f"Fetching account information. Name: {identifier}") <NEW_LINE> account_data = swag.get(f"[?id=='{identifier}']") <NEW_LINE> if not account_data: <NEW_LINE> <INDENT> raise ResolveException( f"Unable to find any account information. Identifier: {identifier}... | Fetches account name from SWAG.
:param identifier: identifier to fetch | 625941edaad79263cf390f68 |
def testProjectCreationExceptions(self): <NEW_LINE> <INDENT> project = Project() <NEW_LINE> self.assertRaises(Exception, project.save) <NEW_LINE> project.name = 'Foo project' <NEW_LINE> self.assertRaises(Exception, project.save) <NEW_LINE> project.shortname = 'What' <NEW_LINE> self.assertRaises(Exception, project.save)... | Sanity tests. Check that required fields, are in fact required. | 625941ed4f6381625f114f5b |
def _periodicFrequentOneItem(self): <NEW_LINE> <INDENT> global _last <NEW_LINE> tidLast = {} <NEW_LINE> la = {} <NEW_LINE> for transaction in self._Database: <NEW_LINE> <INDENT> ts = int(transaction[0]) <NEW_LINE> for item in transaction[1:]: <NEW_LINE> <INDENT> if item not in self.SPPList: <NEW_LINE> <INDENT> la[item]... | Calculates the support of each item in the database and assign ranks to the items
by decreasing support and returns the frequent items list
:returns: return the one-length periodic frequent patterns | 625941edd268445f265b538e |
def p_extr_lic_name_value_1(self, p): <NEW_LINE> <INDENT> p[0] = p[1].decode(encoding='utf-8') | extr_lic_name_value : LINE | 625941ed6fb2d068a760f5c5 |
def __init__(self): <NEW_LINE> <INDENT> self.Name = None <NEW_LINE> self.Type = None <NEW_LINE> self.NumberValue = None <NEW_LINE> self.StringValue = None <NEW_LINE> self.ListValue = None <NEW_LINE> self.MapValue = None | :param Name: 属性名 长度 128 [a-zA-Z0-9-\.]*
:type Name: str
:param Type: 属性类型: 0 数值; 1 string; 默认 0
:type Type: int
:param NumberValue: 数字属性值 默认 0.0
:type NumberValue: float
:param StringValue: 字符串属性值 长度 128 默认 ""
:type StringValue: str
:param ListValue: list 属性值
:type ListValue: list of str
:param MapValue: 字典属性值
:type Ma... | 625941ed099cdd3c635f1178 |
def get_system_group(name, org): <NEW_LINE> <INDENT> if name is None or org is None: <NEW_LINE> <INDENT> raise InvalidInputError('name and org should be provided to ' 'execute this task') <NEW_LINE> <DEDENT> cmd = 'system_group info --name {0} --org {1}'.format(name, org) <NEW_LINE> run_command(cmd) | Gets a system group | 625941edfbf16365ca6f66ee |
def dfs_testing_recursive(self, v): <NEW_LINE> <INDENT> e = self.parent_edge[v] <NEW_LINE> for w in self.ordered_adjs[v]: <NEW_LINE> <INDENT> ei = (v, w) <NEW_LINE> self.stack_bottom[ei] = top_of_stack(self.S) <NEW_LINE> if ei == self.parent_edge[w]: <NEW_LINE> <INDENT> if not self.dfs_testing_recursive(w): <NEW_LINE> ... | Recursive version of :meth:`dfs_testing`. | 625941ed0a366e3fb873ed3f |
def get_instance_profile_role(): <NEW_LINE> <INDENT> info = get_instance_metadata('iam/info') <NEW_LINE> if info: <NEW_LINE> <INDENT> profile_id = info.get('InstanceProfileId') <NEW_LINE> if profile_id: <NEW_LINE> <INDENT> iam = Iam() <NEW_LINE> iprofile = iam.get_instance_profile_by_id(profile_id) <NEW_LINE> roles = i... | Gets the role name for the current instance, if any | 625941ed07f4c71912b119a4 |
def testEmpty(self): <NEW_LINE> <INDENT> self.assertEqual(pyfribidi.log2vis(''), '') | utf8: empty string | 625941ed1d351010ab85603a |
@xfail <NEW_LINE> def test_user_name(): <NEW_LINE> <INDENT> assert False | Expect to search users by name. | 625941ed596a897236089fd9 |
def encode(question): <NEW_LINE> <INDENT> return sha_constructor(djsettings.SECRET_KEY + question).hexdigest() + hexlify(question) | Given a mathematical question, eg '1 - 2 + 3', the question is hashed
with the ``SECRET_KEY`` and the hex version of the question is appended.
To the end user it looks like an extra long hex string, but it cryptographically ensures
against any tampering. | 625941edf7d966606f6aa52a |
def get_currency_name(self, currency_id): <NEW_LINE> <INDENT> etree = et.parse(self.data) <NEW_LINE> xpath = "currencies/currency[@id='{}']".format(currency_id) <NEW_LINE> currency_el = etree.find(xpath) <NEW_LINE> return currency_el.text | Повертає ім'я валюти згідно її id | 625941ed956e5f7376d7138b |
def RecalculateCentroid(self): <NEW_LINE> <INDENT> if not self.GetSize(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.centroid = np.average(self.points, axis=0) <NEW_LINE> return True | Recalculate the cluster centroid by calculating the average point over all cluster points.
Returns:
bool -- Returns False if there are not any points within the cluster. | 625941edb545ff76a8914335 |
def select_action(self, state): <NEW_LINE> <INDENT> if self.exploring: <NEW_LINE> <INDENT> action = self.exp_strategy(state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.policy_check(state) <NEW_LINE> <DEDENT> return action | When this method is called, the agent executes an action based on its Q-table | 625941edd18da76e235329fd |
def colors_to_mask_void(self, colors): <NEW_LINE> <INDENT> points = [] <NEW_LINE> if len(colors) < 3: <NEW_LINE> <INDENT> return points <NEW_LINE> <DEDENT> for col in colors: <NEW_LINE> <INDENT> points.append(self.get_pos_for_color(col)) <NEW_LINE> <DEDENT> return geom.convex_hull(points) | Converts a set of colors to a mask void (convex hull).
Mask voids are the convex hulls of the (x, y) positions for the
colors making up the mask, so mask shapes with fewer than 3 colors
are returned as the empty list. | 625941ed3d592f4c4ed1d57f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.