code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def main(): <NEW_LINE> <INDENT> from optparse import OptionParser <NEW_LINE> config = json.load(open('/Users/sgarrett/github/w3c_testmirror/config.json')) <NEW_LINE> parser = OptionParser() <NEW_LINE> parser.add_option('--w3cdir', action='store', type="string", dest='localW3CDir', default=config["default_w3cdir"], help... | This main function gets executed daily
so that we can be updated when a new
test is submitted/approved by W3C. | 625941ea1b99ca400220af77 |
def dofit(ref,mob,xyz) : <NEW_LINE> <INDENT> ref_com = np.average(ref,axis=0) <NEW_LINE> mob_com = np.average(mob,axis=0) <NEW_LINE> ref = ref - ref_com <NEW_LINE> mob = mob - mob_com <NEW_LINE> xyz = xyz - mob_com <NEW_LINE> rotmat = kabschFit(ref,mob) <NEW_LINE> xyz = rotate(xyz,rotmat) <NEW_LINE> xyz = xyz + ref_com... | Performing fitting of mobile coordinates on top of references
coordinates and then move a full set of coordinates
Parameters
----------
ref : numpy.ndarray
the reference coordinates
mob : numpy.ndarray
the mobile coordinates
xyz : numpy.ndarray
the full set of coordinates to move
Returns
-------
numpy.ndarray
... | 625941eaadb09d7d5db6cc50 |
def quitConfirmed(self): <NEW_LINE> <INDENT> reply = QtGui.QMessageBox.question(self, 'Message', "Quit without saving?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) <NEW_LINE> if reply == QtGui.QMessageBox.Yes: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ... | Make sure an accidental quit doesn't ruin the user's day.
| 625941ea01c39578d7e752ff |
def set_user_sensor_callback(self, function, args): <NEW_LINE> <INDENT> self.sensors.set_user_callback_function(function, args) | Set the (optional) user callback function for sensors. Every time a sensor
is updated, it calls this function.
:param function: name of the function
:param args: tuple of arguments to the function
:return: nothing | 625941eafb3f5b602dac3b5c |
def popular_month(city_data, year): <NEW_LINE> <INDENT> months_popularity_counter = {} <NEW_LINE> for data in city_data: <NEW_LINE> <INDENT> if not check_valid_start_date(data["start_time"],year,None,None): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if data["start_time"].month in months_popularity_counter: <NEW_L... | Process the city_data list for calculating the most popular
month for start time in a specific time period
Args:
(list): list with the city_data dictionary.
(int): year for filtering data - Optional, pass None if no filtering by year is required
(dictionary): month for filtering data - Dictionary in the f... | 625941eae1aae11d1e74a180 |
def handle_received_text(self, event): <NEW_LINE> <INDENT> pass | handle_received_text
Handles a message that contains text. This can contain text, quick replies, etc. | 625941ea5fdd1c0f98dc06f9 |
def __asr_resume(self): <NEW_LINE> <INDENT> self.__pipeline.set_state(gst.STATE_PLAYING) | Resume the ASR daemon. | 625941ea236d856c2ad44ca5 |
def test01_emplist(self): <NEW_LINE> <INDENT> doc = "custom/emplist/105710052/" <NEW_LINE> url = ''.join([self.host,doc]) <NEW_LINE> print(url) <NEW_LINE> resp = requests.get(url, headers=self.header) <NEW_LINE> json_str = resp.json() <NEW_LINE> print(resp) <NEW_LINE> print(json_str) <NEW_LINE> code = resp.status_code ... | 员工列表 | 625941ea32920d7e50b28698 |
def set_ThreadLink(self, value): <NEW_LINE> <INDENT> super(ListThreadsInputSet, self)._set_input('ThreadLink', value) | Set the value of the ThreadLink input for this Choreo. ((optional, string) A link pointing to the thread that is to be retrieved. Note that a Forum must also be provided when using this parameter. If set, ThreadID and ThreadIdentifier cannot be set.) | 625941ea0fa83653e465747c |
def is_root(self): <NEW_LINE> <INDENT> return not self.parent | Check if node is root node of tree.
Returns:
(bool): if node is root node of tree. | 625941ea4e696a04525c9912 |
def test_conentfilter_remove_images_from_toc(self): <NEW_LINE> <INDENT> ast = { "blocks": [ { "t": "Header", "c": [1, ["header_id1", [], []], [{"t": "Str", "c": "Text"}],], }, { "t": "Header", "c": [2, ["header_id2", [], []], [{"t": "Str", "c": "Text"}],], }, ] } <NEW_LINE> ast = pandocfilters.walk( ast, pandoc.content... | ast contains a header with the id: 'header_id1', Level 1 and text 'Text'.
It should get converted to
'<p id=\"header_id1\" class=\"header pagebreak\" data-level=\"1\">Text</p>'.
ast contains a header with the id: 'header_id2', Level 2 and text 'Text'.
It should get converted to
'<p id=\"header_id2\" class=\"header\" da... | 625941ea99cbb53fe67930a9 |
def test_proxy_config_save_config(self): <NEW_LINE> <INDENT> commands = ["feature bgp", "router bgp 65535"] <NEW_LINE> with patch("salt.proxy.nxos.DEVICE_DETAILS", {"save_config": None}): <NEW_LINE> <INDENT> with patch( "salt.proxy.nxos._nxapi_request", autospec=True ) as nxapi_request: <NEW_LINE> <INDENT> result = nxo... | UT: nxos module:proxy_config method - nxapi success path | 625941ea3617ad0b5ed683bb |
def longestIncreasingPath(self, matrix): <NEW_LINE> <INDENT> def dfs(i,j): <NEW_LINE> <INDENT> if not dp[i][j]: <NEW_LINE> <INDENT> val=matrix[i][j] <NEW_LINE> left=dfs(i-1,j) if i-1>=0 and val>matrix[i-1][j] else 0 <NEW_LINE> right=dfs(i+1,j) if i+1<row and val>matrix[i+1][j] else 0 <NEW_LINE> down=dfs(i,j-1) if j-1>=... | :type matrix: List[List[int]]
:rtype: int | 625941ea85dfad0860c3b320 |
def preorder_print(self, start, traversal): <NEW_LINE> <INDENT> if start: <NEW_LINE> <INDENT> traversal += (str(start.value) + "-") <NEW_LINE> traversal = self.preorder_print(start.left, traversal) <NEW_LINE> traversal = self.preorder_print(start.right, traversal) <NEW_LINE> <DEDENT> return traversal | Root -> Left -> Right | 625941ea3317a56b8693a111 |
def test_returns_word_lengths(self): <NEW_LINE> <INDENT> result = word_processor.words_lengths_map("once a lifetime twice a day") <NEW_LINE> expect = {1: 2, 3: 1, 4: 1, 5: 1, 8: 1} <NEW_LINE> self.assertEqual(expect, result) | tests that the words_length_map function returns a dictionary with the lengths of every word and how many times that given length occurs | 625941ea3539df3088e2e810 |
def set_image_at(self, imageIndex, frame): <NEW_LINE> <INDENT> if self.images is None: <NEW_LINE> <INDENT> self.images = [None] * self.number_of_tiles <NEW_LINE> for i in range(self.number_of_tiles): <NEW_LINE> <INDENT> self.images[i] = np.zeros((frame.shape), np.uint8) <NEW_LINE> <DEDENT> <DEDENT> if (imageIndex < sel... | Sets the image at the specified index. Once all images have been set, the tiled image result can be retrieved with `compose`. | 625941ea30dc7b7665901e25 |
def sample(self, signum, frame): <NEW_LINE> <INDENT> if not self.profiling: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> timestamp = time.time() <NEW_LINE> sample_stack(self.stack_count, frame) <NEW_LINE> sample_memory(timestamp, os.getpid(), self.memory_stream) <NEW_LINE> if timestamp - self.last_sample > 1 * SECOND... | Signal handler used to sample the running process. | 625941ea5510c4643540f89c |
def definitions(self): <NEW_LINE> <INDENT> it = apr_hash_iterator(self._defs) <NEW_LINE> while it: <NEW_LINE> <INDENT> k, v = apr_hash_get_kv(it, 0) <NEW_LINE> if k is not None: <NEW_LINE> <INDENT> yield k, v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break | Returns an iterator that looks at every definition this parser has
parsed so far.
Example:
.. code-block:: python
for k, v in parser.definitions():
if k == b'foo.bar.Baz':
print('Baz found!') | 625941ead486a94d0b98e60b |
@route_broadcast(channel='{function}',message='context') <NEW_LINE> def img_show(context,*args): <NEW_LINE> <INDENT> with open_image(context['uuid'],context['key']) as img: <NEW_LINE> <INDENT> img.show() <NEW_LINE> <DEDENT> return context | Display image
Args:
context(dict): dictionary of context info
*args:
Returns:
dict | 625941ea50485f2cf553d260 |
def trace_names(self): <NEW_LINE> <INDENT> with h5py.File(self.h5_path, 'r') as h5_file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return list(h5_file['data']['traces'].keys()) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return [] | Return a list of all saved data traces in Run.
Raises:
KeyError: If the group `'/data/traces/'` does not yet exist.
Returns:
list: List of keys in the h5 file's `'/data/traces/'` group. | 625941ead7e4931a7ee9e3e4 |
def available_translations(self, transcripts, verify_assets=True): <NEW_LINE> <INDENT> translations = [] <NEW_LINE> sub, other_langs = transcripts["sub"], transcripts["transcripts"] <NEW_LINE> if not verify_assets: <NEW_LINE> <INDENT> if other_langs: <NEW_LINE> <INDENT> translations = list(other_langs) <NEW_LINE> <DEDE... | Return a list of language codes for which we have transcripts.
Args:
verify_assets (boolean): If True, checks to ensure that the transcripts
really exist in the contentstore. If False, we just look at the
VideoDescriptor fields and do not query the contentstore. One reason
we might do this ... | 625941ea1f037a2d8b9466c1 |
def test_scene(self): <NEW_LINE> <INDENT> scene = { "type": "Scene", "id": 5, "code": "scenename", "project": self.project } <NEW_LINE> extra_step = { "type": "Step", "id": 6, "code": "step_code", "short_name": "extra_short_name" } <NEW_LINE> self.add_to_sg_mock_db([scene, extra_step]) <NEW_LINE> expected_paths = [self... | Tests folder creation works with Step higher up the hierarchy than normal | 625941ea15fb5d323cde0fdb |
def get_minimal_nfa(dfa): <NEW_LINE> <INDENT> for i in range(2, len(dfa.states) + 1): <NEW_LINE> <INDENT> for nfa in automatons_of_size(dfa.input_symbols, i): <NEW_LINE> <INDENT> test_dfa = convert_to_dfa(nfa) <NEW_LINE> min_dfa = test_dfa.minify() <NEW_LINE> if (dfa == test_dfa): <NEW_LINE> <INDENT> return nfa <NEW_LI... | This is the core function of the project. Returns a NFA with
the minimal number of states, that corresponds to this DFA. | 625941ea66656f66f7cbc671 |
def create_response(prox_resp): <NEW_LINE> <INDENT> return make_response((prox_resp.text, prox_resp.status_code, dict(prox_resp.headers))) | wrapper method for requests.response to flask.response | 625941eaad47b63b2c50a443 |
def setVolume(self,volume): <NEW_LINE> <INDENT> self.volume = volume | Define your active detector volume in cubic meters | 625941ea96565a6dacc8fb8e |
def move(self, new_location): <NEW_LINE> <INDENT> pass | :param new_location: | 625941ead164cc6175783214 |
def parse(self, response): <NEW_LINE> <INDENT> schools_profiles_urls_xpath1 = '//*[@id="FindSchoolContainer"]/div[5]/div[3]/div[2]/div/div/a/@href' <NEW_LINE> schools_profiles_urls_xpath2 = '//*[@id="FindSchoolContainer"]/div[5]/div[6]/div[2]/div/div/a/@href' <NEW_LINE> driver = webdriver.Chrome() <NEW_LINE> driver.get... | extract schools_profiles_urls from the two sections Elementary Schools and Secondary Schools | 625941eaf548e778e58cda44 |
def distribution_uniform(self, x0, sigma_x, num_points=100, positive=True): <NEW_LINE> <INDENT> if positive: <NEW_LINE> <INDENT> Xs = np.linspace(np.maximum(0,x0-sigma_x), x0 + sigma_x, num_points) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Xs = np.linspace(x0-sigma_x, x0+sigma_x, num_points) <NEW_LINE> <DEDENT> wts... | Gaussian distribution. Here, assumes that x can only be positive.
Chooses a range of X and provides its weights. Normalizes by
the total sum rather than the probability distribution.
This is really a Gaussian prob dist with cutoff.
sigma_x : percentage standard deviation | 625941ea30bbd722463cc28d |
def encode(self, value): <NEW_LINE> <INDENT> if not (self.min <= value <= self.max): <NEW_LINE> <INDENT> raise ValueError('Value outside of the range of the encoder.') <NEW_LINE> <DEDENT> signal_length = math.ceil(self.sparsity * self.length) <NEW_LINE> signal_range = self.length - signal_length <NEW_LINE> signal_start... | Encode a value.
The signal length is determined by the output length and the sparsity.
The encoded value contains a band of activations of said length that
slide across the representation.
Args:
value: The value to encode
Returns:
The encoded representation of the value | 625941ea596a897236089f7f |
def compute_all(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, force_excluded=False, fiscal_position=False, insurance_value=0.0, freight_value=0.0, other_costs_value=0.0): <NEW_LINE> <INDENT> obj_precision = self.pool.get('decimal.precision') <NEW_LINE> precision = obj_precision.precision_get(c... | Compute taxes
Returns a dict of the form::
{
'total': Total without taxes,
'total_included': Total with taxes,
'total_tax_discount': Total Tax Discounts,
'taxes': <list of taxes, objects>,
'total_base': Total Base by tax,
}
:Parameters:
- 'cr': Database cursor.
- 'uid': Current user.
... | 625941ea3c8af77a43ae3c6b |
def test_endpoints(self): <NEW_LINE> <INDENT> self.assertEqual(self.client.get(reverse('rest_framework:login')).status_code, 200) <NEW_LINE> self.assertEqual(self.client.get(reverse('rest_framework:logout')).status_code, 200) <NEW_LINE> self.assertEqual(self.client.get(reverse('approved_list')).status_code, 200) | test for endpoints | 625941ead53ae8145f87a72b |
def ApplyConnectivityChanges(self, context, request): <NEW_LINE> <INDENT> with LoggingSessionContext(context) as logger, ErrorHandlingContext(logger): <NEW_LINE> <INDENT> self._log(logger, 'ApplyConnectivityChanges_request', request) <NEW_LINE> self._log(logger, 'ApplyConnectivityChanges_context', context) <NEW_LINE> c... | Configures VLANs on multiple ports or port-channels
:param ResourceCommandContext context: The context object for the command with resource and reservation info
:param str request: A JSON string with the list of requested connectivity changes
:return: a json object with the list of connectivity changes which were carri... | 625941ea1f037a2d8b9466c2 |
def test_cleanUpLinks_pipes(self): <NEW_LINE> <INDENT> self.assertEqual('[[title]]', self.cct.cleanUpLinks('[[title|title]]')) <NEW_LINE> self.assertEqual('[[title]]', self.cct.cleanUpLinks('[[Title|title]]')) <NEW_LINE> self.assertEqual('[[sand]]box', self.cct.cleanUpLinks('[[sand|sandbox]]')) <NEW_LINE> self.assertEq... | Test cleanUpLinks method. | 625941eaad47b63b2c50a444 |
def formatList(self, result): <NEW_LINE> <INDENT> listOut = [] <NEW_LINE> for r in result: <NEW_LINE> <INDENT> descriptions = r.keys <NEW_LINE> for i in r.fetchall(): <NEW_LINE> <INDENT> for index in range(0, len(descriptions)): <NEW_LINE> <INDENT> if isinstance(i[index], (str, bytes)): <NEW_LINE> <INDENT> listOut.appe... | Returns a flat array with the results.
Ideally used for single column queries | 625941eaaad79263cf390f0d |
def _eval_subs(self, old, new): <NEW_LINE> <INDENT> args = list(self.args) <NEW_LINE> for i, (e, c) in enumerate(args): <NEW_LINE> <INDENT> if isinstance(c, bool): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(c, Basic): <NEW_LINE> <INDENT> c = c._subs(old, new) <NEW_LINE> <DEDENT> if c != False: <NEW_LI... | Piecewise conditions may contain bool which are not of Basic type. | 625941ea0fa83653e465747d |
def configure_commands(self): <NEW_LINE> <INDENT> for (path, a, files) in os.walk(System.dir('pagrant/command')): <NEW_LINE> <INDENT> for f in files: <NEW_LINE> <INDENT> filename = os.path.join(path, f) <NEW_LINE> match = re.search('^.+/([a-zA-Z0-9_]+).py$', filename) <NEW_LINE> try: <NEW_LINE> <INDENT> command_name = ... | Loop through 'command' folder and let all the sub processes to configure.
:return: | 625941ea5510c4643540f89d |
def test_update_all_cluster_resources(self): <NEW_LINE> <INDENT> offer_1 = ResourceOffer('offer_1', self.agent_1.agent_id, self.framework_id, NodeResources([Cpus(2.0), Mem(22048.0), Disk(1024.0)]), now(), None) <NEW_LINE> offer_2 = ResourceOffer('offer_2', self.agent_2.agent_id, self.framework_id, NodeResources([Cpus(2... | Tests successfully updating the all cluster resources database in a cluster | 625941ea7d847024c06be785 |
def __init__(self): <NEW_LINE> <INDENT> self._transcript_container = {} | Constructor | 625941eacad5886f8bd2749e |
def __init__(self, addr, R2min=1E-4, R2max=1.0, N=400, report=None, debug=0): <NEW_LINE> <INDENT> self.data = DATA_ILT(addr, R2min=R2min, R2max=R2max, N=N, report=report) <NEW_LINE> self.meth = METHODS_ILT(self.data, report=report) <NEW_LINE> self.view = VIEW_ILT(self.data, self.meth, report=report) <NEW_LINE> if debug... | Read the data then instantiate self.meth and self.view | 625941eaa17c0f6771cbe514 |
def show_favorites_docu_menu(self): <NEW_LINE> <INDENT> self._favorites.refresh(ttl=ttl('indirect')) <NEW_LINE> self._resumepoints.refresh(ttl=ttl('indirect')) <NEW_LINE> episode_items, sort, ascending, content = self._apihelper.list_episodes(category='docu', season='allseasons', programtype='oneoff') <NEW_LINE> show_l... | The VRT NU add-on 'My documentaries' listing menu | 625941ea99cbb53fe67930aa |
def generate_expr_convert_param_type_to_storage_type(self, var_name): <NEW_LINE> <INDENT> if self.syntax_kind == 'Token': <NEW_LINE> <INDENT> return var_name <NEW_LINE> <DEDENT> expr = var_name <NEW_LINE> if self.is_optional: <NEW_LINE> <INDENT> expr += '?' <NEW_LINE> <DEDENT> expr += '.' <NEW_LINE> expr += 'create%s()... | Generate an expression that converts a variable named `var_name` which is of `expressible_as()` type to an object of type `buildable()`. | 625941ea851cf427c661a9d0 |
def uses_keras_history(tensors): <NEW_LINE> <INDENT> checked_tensors = set() <NEW_LINE> tensors_to_check = nest.flatten(tensors) <NEW_LINE> while tensors_to_check: <NEW_LINE> <INDENT> new_tensors_to_check = set() <NEW_LINE> for tensor in tensors_to_check: <NEW_LINE> <INDENT> if getattr(tensor, '_keras_history_checked',... | Check if at least one Tensor originates from a `keras.Input`.
This is `True` if at least one Tensor has its origin in a `keras.Input`.
Any Tensor that originates from a `keras.Input` will have a dependency
Tensor with a `_keras_history` attribute attached. Tensors that have
already been checked to not originate from a... | 625941ea956e5f7376d71331 |
def drivers(self): <NEW_LINE> <INDENT> return self._list(_driver.Driver, paginated=False) | Retrieve a generator of drivers.
:returns: A generator of driver instances. | 625941eae8904600ed9f23fa |
def _update_subnet_postcommit(self, context, orig, result): <NEW_LINE> <INDENT> update_ports_needed = (result['cidr'] != orig['cidr'] and ipv6_utils.is_ipv6_pd_enabled(result)) <NEW_LINE> if update_ports_needed: <NEW_LINE> <INDENT> filters = {'fixed_ips': {'subnet_id': [result['id']]}} <NEW_LINE> ports = self.get_ports... | Subnet update operations that happen after transaction completes.
:param context: neutron api request context
:param orig: subnet dictionary representing state before update
:param result: subnet dictionary representing state after update | 625941eaf7d966606f6aa4cf |
def test_set_aux_heat_bad_attr(self): <NEW_LINE> <INDENT> state = self.hass.states.get(ENTITY_CLIMATE) <NEW_LINE> assert 'off' == state.attributes.get('aux_heat') <NEW_LINE> with pytest.raises(vol.Invalid): <NEW_LINE> <INDENT> common.set_aux_heat(self.hass, None, ENTITY_CLIMATE) <NEW_LINE> <DEDENT> self.hass.block_till... | Test setting the auxiliary heater without required attribute. | 625941ea009cb60464c63873 |
def __init__(self, ledger=None, sub_ledgers=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._ledger = None <NEW_LINE>... | LoyaltyLedger - a model defined in OpenAPI | 625941eacb5e8a47e48b7f68 |
def load(self): <NEW_LINE> <INDENT> logging.info("Loading postproc queue") <NEW_LINE> data = sabnzbd.filesystem.load_admin(POSTPROC_QUEUE_FILE_NAME) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> version, history_queue = data <NEW_LINE> if POSTPROC_QUEUE_VERSION != v... | Save postproc queue | 625941eaf9cc0f698b140abc |
def findRowWords(): <NEW_LINE> <INDENT> row_words = [] <NEW_LINE> for i in range(15): <NEW_LINE> <INDENT> row_words.append([]) <NEW_LINE> <DEDENT> for row_idx in range(15): <NEW_LINE> <INDENT> word = "" <NEW_LINE> for col_idx in range(15): <NEW_LINE> <INDENT> letter = lookAtBoard(row_idx, col_idx) <NEW_LINE> if letter ... | Get a list of the words in each row (and the column number at which each word starts) | 625941ea7b25080760e3991b |
def add_to_cart(self, product_id=None, quantity=1): <NEW_LINE> <INDENT> product = DBSession.query(BackendProduct).get(product_id) <NEW_LINE> content_record = self.get_content_record(product_id=product_id) <NEW_LINE> if content_record: <NEW_LINE> <INDENT> self.change_product_quantity(product_id=product_id, delta=quantit... | Add product to cart
| 625941ea50485f2cf553d261 |
def recursive_getattr(obj, path, *default): <NEW_LINE> <INDENT> attrs = path.split('.') <NEW_LINE> try: <NEW_LINE> <INDENT> return functools.reduce(getattr, attrs, obj) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> if default: <NEW_LINE> <INDENT> return default[0] <NEW_LINE> <DEDENT> raise | Recursive getattr. | 625941ea3d592f4c4ed1d526 |
def _get_calculated_conditions(self): <NEW_LINE> <INDENT> return ', '.join(['{}={}'.format(*call) for call in self._calls]) | Get all calculated conditions (names and results).
Returns:
str: string with all calculated conditions | 625941ea15fb5d323cde0fdc |
def centered_moment(moments, order): <NEW_LINE> <INDENT> moment_c = 0 <NEW_LINE> for j in range(order + 1): <NEW_LINE> <INDENT> combin = int(comb(order, j)) <NEW_LINE> if j == order: <NEW_LINE> <INDENT> a_1 = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a_1 = moments[order - j - 1] <NEW_LINE> <DEDENT> moment_c += (-... | Compute a single moment of a specific order about the mean (centered) given moments about the origin (raw).
:param moments: (list) First 'order' raw moments
:param order: (int) The order of the moment to calculate
:return: (float) The central moment of specified order. | 625941eae5267d203edce15c |
def merge_regions(regions, cooler): <NEW_LINE> <INDENT> if not regions: <NEW_LINE> <INDENT> return regions <NEW_LINE> <DEDENT> regions = sort_regions(regions, cooler) <NEW_LINE> merged = [] <NEW_LINE> for higher in regions: <NEW_LINE> <INDENT> if not merged: <NEW_LINE> <INDENT> merged.append(higher) <NEW_LINE> <DEDENT>... | merge overlaped regions. | 625941ea8c0ade5d55d3ee84 |
def init_NN(target, weight, ctx): <NEW_LINE> <INDENT> print(global_variable.magenta) <NEW_LINE> print('use pretrain weight: %s' % weight) <NEW_LINE> try: <NEW_LINE> <INDENT> target.collect_params().load(weight, ctx=ctx) <NEW_LINE> print('Load Pretrain Successfully') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE>... | load NN weight, if load fail, use Xavier_init
Parameter:
----------
target: gluon.HybridBlock
weight: string
NN weight path
ctx: mxnet.gpu/cpu or list of mxnet.gpu/cpu
Returns
----------
target.hybridize(): gluon.HybridBlock | 625941ea507cdc57c63071ac |
def Raw_get_estimator(price_data, window=30, trading_periods=252, clean=True): <NEW_LINE> <INDENT> log_return = (price_data['close'] / price_data['close'].shift(1)).apply(np.log) <NEW_LINE> result = log_return.rolling(window=window, center=False).std() * math.sqrt(trading_periods) <NEW_LINE> if clean: <NEW_LINE> <INDEN... | 最经常用的收盘价方差计算的波动率 | 625941ea67a9b606de4a837c |
def creerDamesParCouleur(self, positionsNoires, positionsBlanches): <NEW_LINE> <INDENT> self.creerDamesParPositionEtCouleur(positionsNoires, Couleur.NOIR) <NEW_LINE> self.creerDamesParPositionEtCouleur(positionsBlanches, Couleur.BLANC) | Crée des dames noires et blanches
@param positionsNoires
liste des positions des dames noires
@param positionsBlanches
liste des positions des dames blanches
@return "null" ou le message d'erreur | 625941ea9c8ee82313fbbc3c |
def preprocess_text(text): <NEW_LINE> <INDENT> text = preprocess_text1(text) <NEW_LINE> text = remove_stopwords(text) <NEW_LINE> text = lemmatize_text(text) <NEW_LINE> text = stemming_text(text) <NEW_LINE> return text | Function to preprocess the data.
1. Tokenize the text
2. Remove punctuations
3. Change to lower case
4. Remove stop words
5. Lemmatization
6. Stemming
Input - raw text
Output - Preprocessed text | 625941ea8a349b6b435e8638 |
def get_cert_subject_subfield(self, subfield_name: int) -> Optional[str]: <NEW_LINE> <INDENT> subfield_value = pn_ssl_get_remote_subject_subfield(self._ssl, subfield_name) <NEW_LINE> return subfield_value | Returns a string that contains the value of the sub field of
the subject field in the ssl certificate. The subject field
usually contains the following values:
* :const:`CERT_COUNTRY_NAME`
* :const:`CERT_STATE_OR_PROVINCE`
* :const:`CERT_CITY_OR_LOCALITY`
* :const:`CERT_ORGANIZATION_NAME`
* :const:... | 625941ea5e10d32532c5f3ea |
def shuffle_discard_cards(self) -> NoReturn: <NEW_LINE> <INDENT> shuffle(self._discard_pile) | Shuffles the discard pile | 625941eabaa26c4b54cb15e0 |
def __orderLoaders(self): <NEW_LINE> <INDENT> ordered_loaders = OrderedDict() <NEW_LINE> self.all_loaders.sort(key=lambda x: x[1]) <NEW_LINE> for loader, version in self.all_loaders: <NEW_LINE> <INDENT> ordered_loaders[version] = loader <NEW_LINE> <DEDENT> return ordered_loaders | Create an OrderedDict of loaders, ordered by version strings. | 625941ea5fcc89381b1e1b88 |
def prims(n, adj, must = None): <NEW_LINE> <INDENT> frontier = [] <NEW_LINE> vs = set() <NEW_LINE> ans = 0 <NEW_LINE> def process_vertex(ve): <NEW_LINE> <INDENT> for edge in adj[ve]: <NEW_LINE> <INDENT> if edge[0] in vs: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> heappush(frontier, (edge[1], edge[0])) <NEW_LINE> ... | takes n, adjacency list `adj`, and optionally a (u,v,weight) edge `must`.
If `must` is given, start prim's with that edge and those two vertices already present.
Returns the size of the MST (or a really really big number if impossible i.e. graph is disconnected). | 625941ea60cbc95b062c6a09 |
def put(self, key, value): <NEW_LINE> <INDENT> if key in self.array: <NEW_LINE> <INDENT> del self.array[key] <NEW_LINE> <DEDENT> elif len(self.array) >= self.capacity: <NEW_LINE> <INDENT> del self.array[next(iter(self.array))] <NEW_LINE> <DEDENT> self.array[key] = value | :type key: int
:type value: int
:rtype: void | 625941ea090684286d50f1b3 |
def test_reset_password_get_method(self): <NEW_LINE> <INDENT> user, token = self.create_user_and_make_token() <NEW_LINE> reset_password_url = reverse("account.views.reset_password", args=(user.id, token)) <NEW_LINE> response = self.client.get(reset_password_url) <NEW_LINE> self.assertTrue(response.status_code == 200) <... | want return a new blank ResetPasswordForm, no error msg | 625941ea7c178a314d6ef92d |
def return_job(self, job): <NEW_LINE> <INDENT> if self._active_jobs == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._return_queue.append(job) | Requeues an incomplete job to be run again later. If the job set is
already complete, the job is simply discarded instead. | 625941ea44b2445a33932558 |
def __signal_decision_report( self, signal_decision_report_request, **kwargs ): <NEW_LINE> <INDENT> kwargs['async_req'] = kwargs.get( 'async_req', False ) <NEW_LINE> kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) <NEW_LINE> kwargs['_preload_content'] = kwargs.get( '_preload_content', Tr... | Report whether you initiated an ACH transaction # noqa: E501
After calling `/signal/evaluate`, call `/signal/decision/report` to report whether the transaction was initiated. This endpoint will return an `INVALID_REQUEST` error if called a second time with a different value for `initiated`. # noqa: E501
This method ... | 625941ea45492302aab5e78e |
def test_name(self): <NEW_LINE> <INDENT> base4 = BaseModel() <NEW_LINE> base4.name = "Holberton" <NEW_LINE> self.assertEqual(type(base4.name), str) <NEW_LINE> self.assertEqual(base4.name, "Holberton") | Check name in BaseModel | 625941ea92d797404e304652 |
@login_required <NEW_LINE> def add_form_handler_entry(request, form_entry_id, form_handler_plugin_uid, theme=None, template_name=None): <NEW_LINE> <INDENT> print('From handler', form_entry_id) <NEW_LINE> try: <NEW_LINE> <INDENT> form_entry = Event._default_manager.get(pk=form_entry_id) <NEW_LINE> <DEDENT> except Object... | Add form handler entry.
:param django.http.HttpRequest request:
:param int form_entry_id:
:param int form_handler_plugin_uid:
:param fobi.base.BaseTheme theme: Theme instance.
:param string template_name:
:return django.http.HttpResponse: | 625941ea31939e2706e4d329 |
def type_into(self, element_spec, text, clear_first=False, start_with=None): <NEW_LINE> <INDENT> e = self.find_the(element_spec, self.tracker.Record.DEFERRED, start_with=None) <NEW_LINE> if clear_first: <NEW_LINE> <INDENT> e.clear() <NEW_LINE> self.tracker.track(self.tracker.Record.CLEAR, message=str(element_spec), lo... | Find text field, optionally clear it first, then type into it. | 625941ea21bff66bcd684e14 |
def on_playback_error(self, event, player, message): <NEW_LINE> <INDENT> pass | Override | 625941ea8e7ae83300e4b494 |
def explore_numerics(df): <NEW_LINE> <INDENT> drop_list = [] <NEW_LINE> low_std = [] <NEW_LINE> for col in df.columns: <NEW_LINE> <INDENT> print(col) <NEW_LINE> print(df[col].head(10)) <NEW_LINE> print(df[col].isnull().value_counts()) <NEW_LINE> print(df[col].describe()) <NEW_LINE> action_input = input() <NEW_LINE> if ... | :param df: takes in a dataframe with only numeric features
:return:
- loops throw each column and provides view of top 10 rows, number of nulls, descriptive stats
- asks if you want to add column to list of columns to drop later (drop_list)
- asks if you want to add column to list of columns with low std (l... | 625941ea3cc13d1c6d3c783e |
def raw_stat (self): <NEW_LINE> <INDENT> return self.__measured_values | :return: Return the list of raw measured values
:rtype: list | 625941ea287bf620b61d3f26 |
def get_similar_documents(document_index, document_embeddings, distance_measure='cosine'): <NEW_LINE> <INDENT> reverse = {'euclidian': False, 'cosine': True, 'cosine_abs': True} <NEW_LINE> similarities = list() <NEW_LINE> for n in range(document_embeddings.shape[1]): <NEW_LINE> <INDENT> if n != document_index: <NEW_LIN... | :param document_index:
:param document_embeddings:
:param distance_measure:
:return: | 625941ea187af65679ca55e6 |
def __init__(self, links=None, data=None): <NEW_LINE> <INDENT> self._links = None <NEW_LINE> self._data = None <NEW_LINE> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> if data is not None: <NEW_LINE> <INDENT> self.data = data | TripResourceRelationshipsService - a model defined in Swagger | 625941ea6aa9bd52df03726d |
def __init__(self): <NEW_LINE> <INDENT> self.dane_dla_miesiaca = {} | DaneWspolneDlaRoku: | 625941ea1b99ca400220af79 |
def _create_sale_order(self, uid, customer, product, pricelist, operating_unit): <NEW_LINE> <INDENT> sale = self.sale_model.sudo(uid).create({ 'partner_id': customer.id, 'partner_invoice_id': customer.id, 'partner_shipping_id': customer.id, 'pricelist_id': pricelist.id, 'operating_unit_id': operating_unit.id }) <NEW_LI... | Create a sale order. | 625941ea8a43f66fc4b54526 |
def string_to_list(string): <NEW_LINE> <INDENT> args = [] <NEW_LINE> if string: <NEW_LINE> <INDENT> string = str(string) <NEW_LINE> if ',' not in string: <NEW_LINE> <INDENT> string += ',' <NEW_LINE> <DEDENT> for arg in string.split(','): <NEW_LINE> <INDENT> arg = arg.strip() <NEW_LINE> if arg == '': continue <NEW_LINE>... | Usage::
{{ url|thumbnail:"width,height" }} | 625941ea566aa707497f4a28 |
def TheRepairSquare_InsideRepairListData(self,effect=True,location_office=None): <NEW_LINE> <INDENT> list_workOrder=None;JSESSIONID = self.FilterParameters["登录用户JSESSIONID"] <NEW_LINE> startDate = self.FilterParameters["开始日期"] <NEW_LINE> if type(startDate)==type(["1"]): <NEW_LINE> <INDENT> startDate=startDate[0] <NEW_L... | 报修广场--内部--数据查询接口,返回编译过的数据
:return: | 625941ea56b00c62f0f14b22 |
def __init__( self, *, storage_account_ids: Optional[List[str]] = None, **kwargs ): <NEW_LINE> <INDENT> super(LinkedStorageAccountsResource, self).__init__(**kwargs) <NEW_LINE> self.data_source_type = None <NEW_LINE> self.storage_account_ids = storage_account_ids | :keyword storage_account_ids: Linked storage accounts resources ids.
:paramtype storage_account_ids: list[str] | 625941ea7d847024c06be786 |
def test_correctCount(self): <NEW_LINE> <INDENT> suite = self.makeDocSuite(mockdoctest) <NEW_LINE> self.assertEqual(7, suite.countTestCases()) | L{countTestCases} returns the number of doctests in the module. | 625941eaac7a0e7691ed4589 |
def set_flag(self, flag): <NEW_LINE> <INDENT> self.flag = flag | Set flag.
Args:
flag(str): Flag. | 625941eae1aae11d1e74a182 |
def send(self, email_to, subject, body, attachment_file=False, attachment_name=False): <NEW_LINE> <INDENT> msg = MIMEMultipart() <NEW_LINE> msg["Subject"] = subject <NEW_LINE> msg.attach(MIMEText(body, 'html')) <NEW_LINE> if attachment_file and attachment_name: <NEW_LINE> <INDENT> if isinstance(attachment_file, list) a... | Sends an email.
TODO: refactor.
Parameters:
@email_to: a [list] of email address strings.
@subject: a string that will appear in the Subject line.
@body: what will appear in the body of the email.
@attachment_file (optional): a string as a path to a file, or a [list] of
paths as strings.... | 625941ead268445f265b5335 |
def login(self, username=None, password=None, load_cookies=True): <NEW_LINE> <INDENT> if load_cookies and self.load_cookies(): <NEW_LINE> <INDENT> if self.check_login(): <NEW_LINE> <INDENT> print("登录信息从cookie获取,已登录") <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("cookie 失效") <NEW_LINE> self... | 模拟登录知乎
:param username: 登录手机号
:param password: 登录密码
:param load_cookies: 是否读取上次保存的 Cookies
:return: bool | 625941ea236d856c2ad44ca7 |
def twentythree(): <NEW_LINE> <INDENT> def divisors(n): <NEW_LINE> <INDENT> return sum([i for i in range(1, ceil(n/2)+1) if n//i == n/i]) <NEW_LINE> <DEDENT> abundants = list(i for i in range(28124) if divisors(i) > i) <NEW_LINE> abundant_sums = [] <NEW_LINE> print("{}\n{}\n{}\n..." .format(abundants[:10], abundants[10... | A perfect number is one for which the sum of its proper divisors is
equal to the number. A deficient number is one for which the sum is
less than the number, and a number is abundant if the sum exceeds the
number. As 12 is the smallest abundant number, the smallest number that
can be written as the sum of two abundant ... | 625941ea32920d7e50b2869a |
def gen_tasks(self): <NEW_LINE> <INDENT> kw = { 'redirections': self.site.config['REDIRECTIONS'], 'output_folder': self.site.config['OUTPUT_FOLDER'], 'filters': self.site.config['FILTERS'], } <NEW_LINE> yield self.group_task() <NEW_LINE> if kw['redirections']: <NEW_LINE> <INDENT> for src, dst in kw["redirections"]: <NE... | Generate redirections tasks. | 625941ea6fb2d068a760f56b |
def find_min(tree): <NEW_LINE> <INDENT> if 'leaf' in tree.keys(): <NEW_LINE> <INDENT> return tree['leaf'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mapped = list(map(lambda t: find_min(t), tree['children'])) <NEW_LINE> return min(mapped) | Finds the minimum leaf value in a tree
Parameters
----------
tree : dict
parsed model | 625941ea1f5feb6acb0c500f |
def replace(self, name, newobject, send_events=True, registry=None): <NEW_LINE> <INDENT> if registry is None: <NEW_LINE> <INDENT> registry = get_current_registry() <NEW_LINE> <DEDENT> if name in self: <NEW_LINE> <INDENT> self.remove(name, send_events=send_events) <NEW_LINE> <DEDENT> self.add(name, newobject, send_event... | Replace an existing object named ``name`` in this folder with a
new object ``newobject``. If there isn't an object named ``name`` in
this folder, an exception will *not* be raised; instead, the new
object will just be added.
This operation is done in terms of a remove and an add. The Removed
and WillBeRemoved events... | 625941ea8c3a873295158887 |
def weight_variable(shape): <NEW_LINE> <INDENT> return tf.get_variable(name='weights',shape=shape, initializer=tf.truncated_normal_initializer(0.0,0.1)) | # Variable Initializing Functions
# function for initializing with better values for W
:param shape:
:return: tf.Variable | 625941ea5fcc89381b1e1b89 |
def _wait_for_asm_ready(self): <NEW_LINE> <INDENT> nops = 0 <NEW_LINE> restarted_asm = False <NEW_LINE> while nops < 3: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> policies = self.client.api.tm.asm.policies_s.get_collection() <NEW_LINE> if len(policies) >= 0: <NEW_LINE> <INDENT> nops += 1 <NEW_LINE> <DEDENT> else: <NE... | Waits specifically for ASM
On older versions, ASM can take longer to actually start up than
all the previous checks take. This check here is specifically waiting for
the Policies API to stop raising errors
:return: | 625941ea85dfad0860c3b322 |
def testCtrns(self): <NEW_LINE> <INDENT> r = Reader(bytes=_pngsuite['tbrn2c08']) <NEW_LINE> x,y,pixels,meta = r.asRGBA8() <NEW_LINE> row0 = list(pixels)[0] <NEW_LINE> self.assertEqual(tuple(row0[0:4]), (0x7f, 0x7f, 0x7f, 0x00)) | Test colour type 2 and tRNS chunk. | 625941ea3317a56b8693a113 |
def testHardwareFcportsNode(self): <NEW_LINE> <INDENT> pass | Test HardwareFcportsNode | 625941ea8a349b6b435e8639 |
def get_instance(): <NEW_LINE> <INDENT> return IMPL | Return a DB API instance. | 625941eabe7bc26dc91cdabd |
def generateNormal(self,n): <NEW_LINE> <INDENT> utilities.msg("DeformableObj realizations for x,y: dist 'normal'",'v') <NEW_LINE> self._lastDistr=None <NEW_LINE> self._realizationsPolygons=[] <NEW_LINE> self._realizations=distributions.generateNormal(np.concatenate((self._x,self._y)), self._cov,n) <NEW_LINE> numvars=np... | Generates a set of realizations for a deformable object using a multivariate normal.
- *n*: the number of realizations to generate | 625941ea925a0f43d254a342 |
def getPoFiles(product, all=False): <NEW_LINE> <INDENT> files = os.listdir(os.curdir) <NEW_LINE> if all: <NEW_LINE> <INDENT> files = [file for file in files if file.startswith('%s-' % product) and file.endswith('.po')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files = [file for file in files if file.startswith('%s-... | Returns all product*.po files in the current folder.
| 625941ea97e22403b379d462 |
def get_struct_name(code, start_subexpr, end_subexpr): <NEW_LINE> <INDENT> struct_name = "" <NEW_LINE> prev_expr = code.rfind(';', 0, start_subexpr) <NEW_LINE> if prev_expr != -1: <NEW_LINE> <INDENT> name_start = prev_expr + 1 <NEW_LINE> struct_name += code[name_start : start_subexpr - 1] <NEW_LINE> <DEDENT> elif start... | Get the name of a structure given the positions of its open & close parentheses. | 625941eabd1bec0571d90af5 |
def find_kmers(params): <NEW_LINE> <INDENT> string, k, addTo = params <NEW_LINE> kmerCounts = collections.Counter() if addTo is None else addTo <NEW_LINE> n = len(string) <NEW_LINE> for i in range(0, n-k+1): <NEW_LINE> <INDENT> kmerCounts[ string[i:i+k] ] += 1 <NEW_LINE> <DEDENT> return kmerCounts | Count kmer abundance in sequence | 625941eabde94217f36832b3 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SpendingImportForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['account'].widget = forms.HiddenInput() <NEW_LINE> self.fields['ach_payment'].label = "ACH" <NEW_LINE> self.fields['amount'].widget = forms.TextInput( attrs={'size': 10, 'maxlength':... | Hide the ``account`` input, fix field labels. | 625941ea8e7ae83300e4b495 |
def function(self, simulation, period): <NEW_LINE> <INDENT> period = period.start.period(u'month').offset('first-of') <NEW_LINE> salaire_imposable = simulation.calculate('salaire_imposable', period) <NEW_LINE> crds_salaire = simulation.calculate('crds_salaire', period) <NEW_LINE> csg_imposable_salaire = simulation.calc... | Calcul du salaire net d'après définition INSEE
net = net de csg et crds | 625941eafb3f5b602dac3b5f |
def main(): <NEW_LINE> <INDENT> description = 'A dotfile management and synchronisation tool.' <NEW_LINE> parser = argparse.ArgumentParser(description=description) <NEW_LINE> subparsers = parser.add_subparsers() <NEW_LINE> subparsers.required = True <NEW_LINE> subparsers.dest = 'subcommand' <NEW_LINE> def add(func): <N... | Execute the main command line interface. | 625941ea45492302aab5e78f |
def test_get_recent_resolved_bugs(transactional_db, sample_bugs): <NEW_LINE> <INDENT> search_term = "Recently modified resolved bugs should be returned in all_others" <NEW_LINE> exp_bugs = [100001] <NEW_LINE> bug_list = sample_bugs['bugs'] <NEW_LINE> fifty_days_ago = datetime.now() - timedelta(days=50) <NEW_LINE> for b... | Test that we retrieve recent, but fixed bugs for a search term. | 625941ea099cdd3c635f111f |
def set_axis_label_font_size(ax, size): <NEW_LINE> <INDENT> t = ax.get_xaxis().get_label() <NEW_LINE> t.set_fontsize(size) <NEW_LINE> t = ax.get_yaxis().get_label() <NEW_LINE> t.set_fontsize(size) | Convenience function for changing font size of x- and y-axis labels. | 625941ea596a897236089f81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.