code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __process_before_request(self): <NEW_LINE> <INDENT> before_request_class_funcs = get_class_registered_funcs(self.api_obj, BEFORE_REQUEST_FUNC_NAME) <NEW_LINE> before_request_global_funcs = get_global_registered_funcs(BEFORE_REQUEST_FUNC_NAME) <NEW_LINE> for before_request_global_func in before_request_global_funcs:... | 执行已注册的请求前置函数 | 625941c57cff6e4e8111797c |
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None): <NEW_LINE> <INDENT> if extra_args is None: extra_args = [ None for i in range(num_nodes) ] <NEW_LINE> return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ] | Start multiple catthisds, return RPC connections to them | 625941c592d797404e30417f |
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> index = 0 <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> if nums[index] != nums[i]: <NEW_LINE> <INDENT> index = index + 1 <NEW_LINE> nums[index] = nums[i] <NEW_LINE> <DEDENT> <DEDENT> return index+1 | :type nums: List[int]
:rtype: int | 625941c5ac7a0e7691ed40c5 |
def erase(self): <NEW_LINE> <INDENT> return self.cmd("2J") | Erase.
Erase.
Returns:
string: string of the command. | 625941c53617ad0b5ed67eef |
def set(self, value): <NEW_LINE> <INDENT> self.contents.set(value) | Set the value of the checkbox. | 625941c54e4d5625662d43d0 |
def is_x_alumni(self): <NEW_LINE> <INDENT> return self.roles.filter(hrid__in=Role.ALUMNI_ROLES_HRID).exists() | The user is an alumni of Ecole Polytechnique (not an external account) | 625941c5fff4ab517eb2f431 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Word_Counter.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you... | Run administrative tasks. | 625941c507f4c71912b11477 |
def execute(env): <NEW_LINE> <INDENT> env['site_prefix'] = os.path.splitext(env['rti_file'])[0] <NEW_LINE> env['case_prefix'] = 'scenario' <NEW_LINE> if env['pixel_file'] == 'off': <NEW_LINE> <INDENT> file_list.remove('pixel_file') <NEW_LINE> env['pixel_file'] = '_outlets.txt' <NEW_LINE> <DEDENT> assign_parameter_type_... | Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT. | 625941c5090684286d50ecda |
def Method_3(f,a,y0,b,n): <NEW_LINE> <INDENT> h = (b-a)/n <NEW_LINE> yk = [np.array([a,y0])] <NEW_LINE> yk.append([a + h, exp(-(a + h)**2)*(2+sin(5*(a + h)))]) <NEW_LINE> yk.append([a + 2*h, exp(-(a + 2*h)**2)*(2+sin(5*(a + 2*h)))]) <NEW_LINE> while yk[-1][0] < b: <NEW_LINE> <INDENT> yk.append( [ yk[-1][0] + h, (1/2)*y... | Three-step method 3 | 625941c526068e7796caecd2 |
def countPrimeSetBits(self, L, R): <NEW_LINE> <INDENT> prime_list = [2,3,5,7,11,13,17,19] <NEW_LINE> count = 0 <NEW_LINE> for i in range(L,R+1): <NEW_LINE> <INDENT> if (str(bin(i))).count('1') in prime_list: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return count | :type L: int
:type R: int
:rtype: int | 625941c54a966d76dd551005 |
def collect_timestamp(self): <NEW_LINE> <INDENT> most_significant_units = 'minutes' <NEW_LINE> if self.position >= len(self.input): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.input[self.position] not in DIGITS: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> string = self.collect_characters(lambda ... | collect a WebVTT timestamp | 625941c555399d3f055886a9 |
def test_available_ride(self): <NEW_LINE> <INDENT> response = self.app.post("{}auth/signup".format(BASE_URL), data=json.dumps(self.user_1), content_type=content_type) <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> self.assertEqual(response.json, {"message": "Account successfully created"}) <NEW_LINE>... | Create a user , login and then create a ride | 625941c555399d3f055886aa |
def is_leaf(self,v): <NEW_LINE> <INDENT> return not bool(self.children[v]) | 頂点 v は葉? | 625941c58c3a8732951583af |
def residual_degrees_of_freedom(self, train=False, valid=False, xval=False): <NEW_LINE> <INDENT> if xval: raise H2OValueError("Cross-validation metrics are not available.") <NEW_LINE> if not train and not valid: train = True <NEW_LINE> if train and valid: train = True <NEW_LINE> if train: <NEW_LINE> <INDENT> re... | Retreive the residual degress of freedom if this model has the attribute, or None otherwise.
:param train: Get the residual dof for the training set. If both train and valid are False, then train
is selected by default.
:param valid: Get the residual dof for the validation set. If both train and valid are True, th... | 625941c58a43f66fc4b5405d |
def copy_file_to_device(self, host_path, device_path): <NEW_LINE> <INDENT> self._bot_info.run( [os.path.join(self.ios_bin, 'ios_push_file'), host_path, device_path], ) | Like shutil.copyfile, but for copying to a connected device. | 625941c5435de62698dfdc42 |
def test_parser_template_verbose_true(self): <NEW_LINE> <INDENT> parser_template = self._call_fut() <NEW_LINE> args = parser_template.parse_args(['-v']) <NEW_LINE> self.assertTrue(args.verbose) | parser template sets verbose to True when -v in args
| 625941c56aa9bd52df036d99 |
def featurize(self, data): <NEW_LINE> <INDENT> deduped = data.drop_duplicates(subset=['assetID'], inplace=False) <NEW_LINE> print('Vectorizing assets...') <NEW_LINE> asset_vecs = self.vectr.vectorize(deduped['assetBody'], train=True) <NEW_LINE> print('Mapping assets...') <NEW_LINE> asset_map = {} <NEW_LINE> asset_ids =... | Calculate asset relevance by cosine distance.
The vectorizer is trained on the assets rather than the comments. | 625941c5bf627c535bc131c5 |
def list( self, location, **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 = "2020-03-01" <NEW_LINE> accept = "appl... | Gets all of the available subnet delegations for this subscription in this region.
:param location: The location of the subnet.
:type location: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AvailableDelegationsResult or the res... | 625941c5b830903b967e9903 |
def create(dir=None): <NEW_LINE> <INDENT> if not dir: <NEW_LINE> <INDENT> dir = tempfile.mkdtemp() <NEW_LINE> <DEDENT> logger.info("Using %s as base dir." % dir) <NEW_LINE> fs = LocalSubFileSystem(dir) <NEW_LINE> def write(path, contents): <NEW_LINE> <INDENT> f = fs.open(path, "w") <NEW_LINE> f.write(contents) <NEW_LIN... | Creates a "filesystem" in a new temp dir and creates one file in it. | 625941c5a934411ee375168a |
def detect_corners_from_contour(canvas:np.array, cnt:np.array) -> list: <NEW_LINE> <INDENT> epsilon = 0.01 * cv2.arcLength(cnt, True) <NEW_LINE> approx_corners = cv2.approxPolyDP(cnt, epsilon, True) <NEW_LINE> cv2.drawContours(canvas, approx_corners, -1, (255, 255, 0), 10) <NEW_LINE> approx_corners = sorted(np.concaten... | Detecting corner points from contours using cv2.approxPolyDP()
Args:
canvas: np.array()
cnt: list
Returns:
approx_corners: list | 625941c56fb2d068a760f092 |
def specification_v1_add_related_pks(self, obj): <NEW_LINE> <INDENT> if not hasattr(obj, '_history_pks'): <NEW_LINE> <INDENT> obj._history_pks = list( obj.history.all().values_list('history_id', flat=True)) <NEW_LINE> <DEDENT> if not hasattr(obj, '_section_pks'): <NEW_LINE> <INDENT> obj._section_pks = list( obj.section... | Add related primary keys to a Specification instance. | 625941c5b7558d58953c4f0d |
def parseCommandLine( width = 0, height = 0, renderer = "p3d", fullscreen = 0 ): <NEW_LINE> <INDENT> opts, pargs = getopt.getopt(sys.argv[1:], "w:h:f:r:") <NEW_LINE> for (opt, val) in opts: <NEW_LINE> <INDENT> if opt == '-w': <NEW_LINE> <INDENT> width = int(val) <NEW_LINE> <DEDENT> elif opt == '-h': <NEW_LINE> <INDENT>... | Get and validate command line args. | 625941c544b2445a3393208d |
def _on_exchange_declareok(self, unused_frame): <NEW_LINE> <INDENT> log.info('Exchange declared') <NEW_LINE> self._setup_queue(self.queue_name) | Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame | 625941c5925a0f43d2549e6c |
def inner(*args,**kwargs): <NEW_LINE> <INDENT> ret = func <NEW_LINE> return ret | 执行被装饰函数之前的操作 | 625941c5851cf427c661a507 |
def _spectra_comparison(density1, density2, a, b, measure): <NEW_LINE> <INDENT> if measure == "jensen-shannon": <NEW_LINE> <INDENT> M = lambda x: (density1(x) + density2(x)) / 2 <NEW_LINE> jensen_shannon = ( _kullback_leiber(density1, M, a, b) + _kullback_leiber(density2, M, a, b) ) / 2 <NEW_LINE> dist = np.sqrt(jensen... | Apply a metric to compare the continuous spectra
Parameters
----------
density1, density2 (function): one argument functions for the continuous
spectral densities.
a,b (float): lower and upper bounds of the support for the eigenvalues.
measure (str): metric between the two continuous spectra.
Returns
-------
dist... | 625941c556ac1b37e62641c8 |
def create_certificate(urn, issuer_key=None, issuer_cert=None, is_ca=False, public_key=None, life_days=1825, email=None, uuidarg=None, serial_number=0): <NEW_LINE> <INDENT> pub_key_param = None <NEW_LINE> if public_key: <NEW_LINE> <INDENT> fh, pub_key_param = tempfile.mkstemp(); os.write(fh, public_key); os.close(fh) <... | Creates a certificate.
{issuer_key} private key of the issuer. can either be a string in pem format or None.
{issuer_cert} can either be a string in pem format or None.
If either {issuer_cert} or {issuer_key} is None, the cert becomes self-signed
{public_key} contains the pub key which will be embedded in the certifica... | 625941c523849d37ff7b3086 |
def parse_abstract(self, abs_str): <NEW_LINE> <INDENT> return ' '.join(abs_str).encode('utf-8') | Abstracts may contain multiple elements, convert to string and return joined string | 625941c5711fe17d82542365 |
def store_commit_map(cmap: CommitMap, output_file_path: str) -> None: <NEW_LINE> <INDENT> mkdir("-p", Path(output_file_path).parent) <NEW_LINE> with open(output_file_path, "w") as c_map_file: <NEW_LINE> <INDENT> cmap.write_to_file(c_map_file) | Store commit map to file. | 625941c56aa9bd52df036d9a |
def _countNodes(self): <NEW_LINE> <INDENT> prev = self.mru <NEW_LINE> if not prev: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> count = 1 <NEW_LINE> while prev: <NEW_LINE> <INDENT> if prev.older is self.mru: <NEW_LINE> <INDENT> return count <NEW_LINE> <DEDENT> prev = prev.older <NEW_LINE> count+=1 | much slower than len(self.nodeDict) -- exists for diagnostic use
| 625941c563f4b57ef0001114 |
def find_duplicate_tags(self): <NEW_LINE> <INDENT> return self.all_tags.duplicate_names | Finds all tags that are not unique.
Returns
-------
duplicate_tag_dict: {str: [str]}
A dictionary of all duplicate short tags as keys, with the values being a list of
long tags sharing that short tag | 625941c5a8ecb033257d30c4 |
@app.route("/api/v1.0/tobs") <NEW_LINE> def tobs(): <NEW_LINE> <INDENT> Range = date_calc() <NEW_LINE> End_date = Range[1] <NEW_LINE> Start_date = Range[0] <NEW_LINE> tobs = session.query(Measurement.date,Measurement.tobs). filter(Measurement.date <= End_date). filt... | Return a JSON list of Temperature Observations (tobs) for the previous year. | 625941c5460517430c39417f |
def node_tuple(): <NEW_LINE> <INDENT> return {}, {} | :returns: The tuple that defines a node
:rtype: :class:`tuple_(dict, dict)` | 625941c596565a6dacc8f6c2 |
def _getForteClass(self): <NEW_LINE> <INDENT> self._updateChordTablesAddress() <NEW_LINE> return chordTables.addressToForteName(self._chordTablesAddress, 'tn') | Return a forte class name w/ inversions represented distinctly (Tn space)
| 625941c58e71fb1e9831d7a0 |
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/monoeciCore/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "monoeciCore") <NEW_LINE> <DED... | Return the default location of the monoeci Core data directory | 625941c599cbb53fe6792bdd |
def _get_threatbus_entity(self) -> int: <NEW_LINE> <INDENT> if self.threatbus_entity is not None: <NEW_LINE> <INDENT> return self.threatbus_entity <NEW_LINE> <DEDENT> threatbus_entity = ( self.opencti_helper.api.stix_domain_object.get_by_stix_id_or_name( name=self.entity_name ) ) <NEW_LINE> if threatbus_entity is not N... | Get the Threat Bus OpenCTI entity. Creates a new entity if it does not
exist yet. | 625941c5e1aae11d1e749cac |
def __init__(self, label='root'): <NEW_LINE> <INDENT> super(LayerGroup, self).__init__() <NEW_LINE> self.label = label | Parameters
----------
label : str, optional(defaul='root')
the label of the layer group
Examples
--------
>>> lg = LayerGroup()
>>> lg.label
'root' | 625941c563d6d428bbe444e6 |
def build(): <NEW_LINE> <INDENT> sh('%s -c "import setuptools"' % PYTHON) <NEW_LINE> cmd = [PYTHON, "setup.py", "build"] <NEW_LINE> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> try: <NEW_LINE> <INDENT> for line in iter(p.stdout.readline, b''): <NEW_LINE> <INDENT> if PY3: <NEW_L... | Build / compile | 625941c567a9b606de4a7eb2 |
def get_protocolinfo_response(**attributes): <NEW_LINE> <INDENT> protocolinfo_response = get_message("250-PROTOCOLINFO 1\n250 OK") <NEW_LINE> stem.response.convert("PROTOCOLINFO", protocolinfo_response) <NEW_LINE> for attr in attributes: <NEW_LINE> <INDENT> protocolinfo_response.__dict__[attr] = attributes[attr] <NEW_L... | Provides a ProtocolInfoResponse, customized with the given attributes. The
base instance is minimal, with its version set to one and everything else
left with the default.
Arguments:
attributes (dict) - attributes to customize the response with
Returns:
stem.response.protocolinfo.ProtocolInfoResponse instance | 625941c5f8510a7c17cf96f2 |
def setup_mic(self, num_samples=50): <NEW_LINE> <INDENT> print("Getting intensity values from mic.") <NEW_LINE> p = pyaudio.PyAudio() <NEW_LINE> stream = p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) <NEW_LINE> values = [math.sqrt(abs(audioop.avg(stream.rea... | Gets average audio intensity of your mic sound. You can use it to get
average intensities while you're talking and/or silent. The average
is the avg of the .2 of the largest intensities recorded. | 625941c53346ee7daa2b2d62 |
def get_suggestions(client, num=5): <NEW_LINE> <INDENT> qstring = "/suggestions/{}.json".format(num) <NEW_LINE> return query(client, qstring) | HTTQ Request: Get podcast suggestions from gpodder. | 625941c516aa5153ce362470 |
def findLengthOfLCIS(self, nums): <NEW_LINE> <INDENT> if nums: <NEW_LINE> <INDENT> max1 = 0 <NEW_LINE> flag = nums[0] <NEW_LINE> cont = 1 <NEW_LINE> for i in nums[1:]: <NEW_LINE> <INDENT> if flag < i: <NEW_LINE> <INDENT> cont +=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> max1 = max(max1,cont) <NEW_LINE> cont = 1 <N... | :type nums: List[int]
:rtype: int | 625941c5656771135c3eb864 |
def load_data(filename): <NEW_LINE> <INDENT> f = open(filename,'rb') <NEW_LINE> data = pickle.load(f) <NEW_LINE> f.close() <NEW_LINE> return data | Loads saved data from a file
Args:
filename: The name of the file to load from | 625941c5566aa707497f4562 |
def _visit_method_call_long_node(self, node): <NEW_LINE> <INDENT> children = node.children <NEW_LINE> class_name = children[0].value <NEW_LINE> method_name = children[1].value <NEW_LINE> args_list = children[-1] <NEW_LINE> is_static = True <NEW_LINE> if children[0].value not in self._t_env.types: <NEW_LINE> <INDENT> cl... | Generate code for a extended method call where the method is held
in another class. | 625941c53539df3088e2e341 |
def simulation(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> init_steps = int(self.steps_edit.text()) <NEW_LINE> init_sim = int(self.simulations_edit.text()) <NEW_LINE> init_plots = int(self.visible_plots_edit.text()) <NEW_LINE> init_price = float(self.price_edit.text()) <NEW_LINE> init_rate = float(self.rate_edi... | This function is triggered whenever simulate button is pressed. It performs plotting of simulation and
histogram plots. Inputs are validated first and error handling is imposed in the form of warning boxes. | 625941c53317a56b86939c53 |
def get_measurement_columns(self, pipeline): <NEW_LINE> <INDENT> return [ ("Image", x % self.cropped_image_name.value, "integer",) for x in (FF_AREA_RETAINED, FF_ORIGINAL_AREA) ] | Return information on the measurements made during cropping | 625941c566656f66f7cbc1a1 |
@routes.route('/<id_trav>', methods=['GET']) <NEW_LINE> @json_resp <NEW_LINE> @check_auth(groups=[ 'tizoutis-travaux-batiments-admin', 'tizoutis-travaux-batiments-user']) <NEW_LINE> def get_one_trav_batiment(id_trav): <NEW_LINE> <INDENT> result = _db.session.query(TravauxBatiment).get(id_trav) <NEW_LINE> return Travaux... | Retourne le détail d'une fiche de demande de travaux | 625941c596565a6dacc8f6c3 |
def axResRed(img,newres,ax): <NEW_LINE> <INDENT> if ax == 1: <NEW_LINE> <INDENT> img =rot90(img) <NEW_LINE> newres =[newres[1],newres[0]] <NEW_LINE> <DEDENT> dim = shape(img) <NEW_LINE> tempImg = zeros([newres[0],dim[1]]) <NEW_LINE> xalt = (dim[0]/newres[0]) <NEW_LINE> leftDec = 0.0 <NEW_LINE> rightDec = xalt-int(xalt)... | Overview:
This is the rebinning algorithm used to downgrade the resolution of a
.png file. It keeps track of the fractional values as it reads across the
axis and scales each pixel accordingly.
Parameters:
img:(array,[]) = The image array that is being rebinned.
newres:(array,[2]|count) = The new size of the [0... | 625941c5c4546d3d9de72a2a |
def get_trend_kweeks(authorized_username, trend_id, last_retrieved_kweek_id): <NEW_LINE> <INDENT> return get_kweeks(authorized_username=authorized_username, last_retrieved_kweek_id=last_retrieved_kweek_id, db_kweeks_fetcher=query_factory.get_trend_kweeks, args=[trend_id]) | Gets the kweeks that belong to a trend.
*Parameters:*
- *authorized_username (string)*: The username of the authorized user.
- *last_retrieved_kweek_id (string)*: The id of the last retrieved kweek (used to fetch more). Nullable.
- *trend_id (string)*: The id of the trend whose kweeks are to be fetched.
... | 625941c5004d5f362079a32b |
def execute(sock, call_on_completion: callable, **kwargs) -> object: <NEW_LINE> <INDENT> if kwargs['operation'] == 'get-electro': <NEW_LINE> <INDENT> Catalog.gather(['pwr.phase1.voltage', 'pwr.phase2.voltage', 'pwr.phase3.voltage', 'pwr.phase1.power', 'pwr.phase2.power', 'pwr.phase3.power', 'pwr.phase1.apparent_power',... | Do what it takes to serve the request.
Call call_on_completion with JSONable argument when you finish | 625941c597e22403b379cf90 |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> devices = [] <NEW_LINE> for (_, gateway) in hass.data[PY_XIAOMI_GATEWAY].gateways.items(): <NEW_LINE> <INDENT> for device in gateway.devices['binary_sensor']: <NEW_LINE> <INDENT> model = device['model'] <NEW_LINE> if model in ['moti... | Perform the setup for Xiaomi devices. | 625941c53c8af77a43ae3796 |
def get_identifiers(soup): <NEW_LINE> <INDENT> resp = {} <NEW_LINE> article_doi = soup.findAll(attrs={'scheme': 'doi'}) <NEW_LINE> if article_doi: <NEW_LINE> <INDENT> resp["doi"] = article_doi[0]['content'] <NEW_LINE> <DEDENT> return resp | this function get identifiers from html.
:params soup: instance of BeautifulSoup class | 625941c52ae34c7f2600d129 |
def test_remove(self): <NEW_LINE> <INDENT> c = DynamicArray() <NEW_LINE> c.append(1) <NEW_LINE> c.append(2) <NEW_LINE> c.append(3) <NEW_LINE> c.append(4) <NEW_LINE> c.append(5) <NEW_LINE> c.remove(1) <NEW_LINE> self.assertEquals(8, c._capacity) <NEW_LINE> self.assertEquals(4, c._count) <NEW_LINE> self.assertEquals(4, l... | Test DynamicArray remove. | 625941c5ff9c53063f47c1eb |
@hooks.before("Copyright > Event Copyright Details > Event Copyright Details") <NEW_LINE> def copyright_get_detail(transaction): <NEW_LINE> <INDENT> with stash['app'].app_context(): <NEW_LINE> <INDENT> copyright = EventCopyrightFactory() <NEW_LINE> db.session.add(copyright) <NEW_LINE> db.session.commit() | GET /event-copyrights/1
:param transaction:
:return: | 625941c5293b9510aa2c328f |
def testFlashWidget(self): <NEW_LINE> <INDENT> pass | Test FlashWidget | 625941c5cb5e8a47e48b7aa3 |
def test_get_keep_target_standalone(self, keep_manager): <NEW_LINE> <INDENT> keep_manager.keep_backup(test_backup_id, KeepManager.TARGET_STANDALONE) <NEW_LINE> assert ( keep_manager.get_keep_target(test_backup_id) == KeepManager.TARGET_STANDALONE ) | Verify we can set and retrieve the standalone target | 625941c5a8370b7717052898 |
def get(self, request, **kwargs): <NEW_LINE> <INDENT> format = kwargs.get("format", None) <NEW_LINE> pagetypes = CMSContents.objects.all() <NEW_LINE> content_id = self.request.query_params.get("resource_id", None) <NEW_LINE> contents = CMSContents.objects.all() <NEW_LINE> if content_id is not None: <NEW_LINE> <INDENT> ... | Get a list of all available PageTypes | 625941c5d99f1b3c44c67588 |
def _count_points(lons, lats, func, sigma, gridsize=(100,100), weights=None): <NEW_LINE> <INDENT> lons = np.atleast_1d(np.squeeze(lons)) <NEW_LINE> lats = np.atleast_1d(np.squeeze(lats)) <NEW_LINE> if weights in (None, False): <NEW_LINE> <INDENT> weights = 1 <NEW_LINE> <DEDENT> weights = np.asarray(weights, dtype=np.fl... | This function actually calculates the point density of the input ("lons"
and "lats") points at a series of counter stations. Creates "gridsize"
regular grid of counter stations in lat-long space, calculates the distance
to all input points at each counter station, and then calculates the
density using "func". Each inp... | 625941c5711fe17d82542366 |
def neighbours(i, j): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for (x, y) in [ (i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)]: <NEW_LINE> <INDENT> if x in range(g.HEIGHT) and y in range(g.WIDTH): <NEW_LINE> <INDENT> l.append((x, y)) <NEW_LINE> <DEDENT> <DEDENT> return l | Return the list of coordinates of the neighbours of the (i, j) cell | 625941c53617ad0b5ed67ef0 |
def test_autosample_particle_generation(self): <NEW_LINE> <INDENT> self.assert_initialize_driver(DriverProtocolState.AUTOSAMPLE) <NEW_LINE> self.assert_async_particle_generation( DataParticleType.HPIES_DATA_HEADER, self.assert_data_header_particle, timeout=20) <NEW_LINE> self.assert_async_particle_generation( DataParti... | Test that we can generate particles when in autosample.
To test status particle instrument must be off and powered on will test is waiting | 625941c5bde94217f3682dea |
def hasUpvoted(self, userId): <NEW_LINE> <INDENT> if userId in self.upvoteUserSet: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | :type userId: str
:rtype: bool | 625941c5dd821e528d63b1a2 |
def insert_into_logs(username, text, is_bot=False): <NEW_LINE> <INDENT> sql_query = ( """INSERT into conversation_log(username,is_bot,convo) VALUES(%s,%s,%s)""" ) <NEW_LINE> run_query(sql_query, [username, is_bot, text]) | :param username:
:param text:
:param: is_bot:
:return: | 625941c5cb5e8a47e48b7aa4 |
def create_if_none(self, worksheet_name): <NEW_LINE> <INDENT> if worksheet_name not in self.celltables: <NEW_LINE> <INDENT> if self.on_create is None: <NEW_LINE> <INDENT> raise ValueError( "Trying to create Celltable '%s' without specifying details in on_create" % worksheet_name) <NEW_LINE> <DEDENT> worksheet = self.wo... | Create worksheet and add to cell_tables if there's no such worksheet. It is first called in every data
accessing methods like query, insert, update, etc.
:param worksheet_name: Name of worksheet to inspect or create if required
:type worksheet_name: str | 625941c521bff66bcd68494c |
def evaluate(split, verbose=False, n_batches=None): <NEW_LINE> <INDENT> model.eval() <NEW_LINE> loss = 0 <NEW_LINE> acc = 0 <NEW_LINE> correct = 0 <NEW_LINE> n_examples = 0 <NEW_LINE> if split == 'val': <NEW_LINE> <INDENT> loader = val_loader <NEW_LINE> <DEDENT> elif split == 'test': <NEW_LINE> <INDENT> loader = test_l... | Compute loss on val or test data. | 625941c5bd1bec0571d90626 |
def wonderfulSubstrings(self, word: str) -> int: <NEW_LINE> <INDENT> count = [1] + [0] * 1023 <NEW_LINE> mask = 0 <NEW_LINE> result = 0 <NEW_LINE> for char in word: <NEW_LINE> <INDENT> mask ^= 1 << (ord(char) - ord('a')) <NEW_LINE> result += count[mask] <NEW_LINE> for n in range(10): <NEW_LINE> <INDENT> result += count... | https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1299525/Bitmask-Hashmap | 625941c521a7993f00bc7ce5 |
def simSetKinematics(self, state, ignore_collision, vehicle_name = ''): <NEW_LINE> <INDENT> self.client.call('simSetKinematics', state, ignore_collision, vehicle_name) | Set the kinematics state of the vehicle
If you don't want to change position (or orientation) then just set components of position (or orientation) to floating point nan values
Args:
state (KinematicsState): Desired Pose pf the vehicle
ignore_collision (bool): Whether to ignore any collision or not
vehicl... | 625941c5187af65679ca5116 |
def forward(self, feat): <NEW_LINE> <INDENT> output = None <NEW_LINE> self.meta = feat <NEW_LINE> return output | Some comments | 625941c5bd1bec0571d90627 |
def test_save_alignment_adds_created_timestamp(self): <NEW_LINE> <INDENT> Alignment.objects.create_alignment(self.name, self.data) <NEW_LINE> alignment = Alignment.objects.all() <NEW_LINE> self.assertTrue( datetime.now(timezone.utc) - alignment[0].created < timedelta(minutes=1), 'alignment was not created within the la... | Tests that when an alignment is saved to the database it contains a created time stamp | 625941c5a17c0f6771cbe049 |
def test_wrapper_fun(self): <NEW_LINE> <INDENT> resp_status = dict() <NEW_LINE> if self.wait_seconds_list[self.__class__.index] is not None: <NEW_LINE> <INDENT> time.sleep(int(self.wait_seconds_list[self.__class__.index])) <NEW_LINE> <DEDENT> resp = None <NEW_LINE> req_time = datetime.datetime.now().strftime('%Y-%m-%d ... | :description: 测试用例的包装方法
:return: | 625941c5be383301e01b5480 |
def sentences(self): <NEW_LINE> <INDENT> for sentid, ys in enumerate(self.yield_sentences()): <NEW_LINE> <INDENT> sent, context_sent, context_doc, inst2ans, textid = ys <NEW_LINE> instances = {} <NEW_LINE> for instance in sent.findAll('instance'): <NEW_LINE> <INDENT> instid = instance['id'] <NEW_LINE> lemma = instance[... | Returns the instances by sentences, and yields a list of tokens,
similar to the pywsd.semcor.sentences.
>>> coarse_wsd = SemEval2007_Coarse_WSD()
>>> for sent in coarse_wsd.sentences():
>>> for token in sent:
>>> print token
>>> break
>>> break
word(id=None, text=u'Your', offset=None, sentid=0,... | 625941c538b623060ff0ade5 |
def make_next_range_block_function(iterator): <NEW_LINE> <INDENT> def f(this_start, this_name, next_start, next_name, timeslot): <NEW_LINE> <INDENT> while next_start <= timeslot.start: <NEW_LINE> <INDENT> this_start, this_name = next_start, next_name <NEW_LINE> next_start, next_name = next(iterator) <NEW_LINE> <DEDENT>... | Makes a function that takes a timeslot and gets its range block.
The function returned here is a slightly strange function, in that
it returns not only the range block for a timeslot but another
function, which will return the range block for the next timeslot.
This is because each function records the block that was ... | 625941c55fcc89381b1e16b5 |
def _send_monitor(self, data_bytes, port_bytes, direction): <NEW_LINE> <INDENT> payload_length_bytes = bytes(len(data_bytes).to_bytes(2, byteorder='little', signed=False)) <NEW_LINE> if self.seq_num == 255: <NEW_LINE> <INDENT> self.seq_num = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.seq_num += 1 <NEW_LINE> <... | Send a packet in monitor mode using DroneBridge raw protocol v2. Return None on success | 625941c507d97122c4178880 |
def _api_search_mime(self, entropy, q, filter_cb = None): <NEW_LINE> <INDENT> data = [] <NEW_LINE> valid_repos = self._api_get_valid_repositories(entropy) <NEW_LINE> for repository_id, arch, branch, product in valid_repos: <NEW_LINE> <INDENT> if self._is_source_repository(repository_id): <NEW_LINE> <INDENT> continue <N... | Search packages in repositories using given query string
(mimetype strategy).
@param q: query string
@type q: string
@keyword filter_cb: callback used to filter results, the function
must have this signature:
bool filter_cb(entropy_repository, package_id)
and return True if package is valid, False othe... | 625941c5f9cc0f698b1405f5 |
def rabin_miller(n, target=128): <NEW_LINE> <INDENT> def calculate_t(n): <NEW_LINE> <INDENT> n = n - 1 <NEW_LINE> t = 0 <NEW_LINE> while n % 2 == 0: <NEW_LINE> <INDENT> n = n / 2 <NEW_LINE> t += 1 <NEW_LINE> <DEDENT> return t <NEW_LINE> <DEDENT> if n % 2 == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> t = ca... | returns True if prob(`n` is composite) <= 2**(-`target`) | 625941c53346ee7daa2b2d63 |
def update_request_validator(restApiId=None, requestValidatorId=None, patchOperations=None): <NEW_LINE> <INDENT> pass | Updates a RequestValidator of a given RestApi .
See also: AWS API Documentation
:example: response = client.update_request_validator(
restApiId='string',
requestValidatorId='string',
patchOperations=[
{
'op': 'add'|'remove'|'replace'|'move'|'copy'|'test',
'path': 'string'... | 625941c5283ffb24f3c558fb |
def calcular_combinacion(self): <NEW_LINE> <INDENT> carta_alta = es_carta_alta() <NEW_LINE> pareja = es_pareja() <NEW_LINE> doble_pareja = es_doble_pareja() <NEW_LINE> trio = es_trio() <NEW_LINE> escalera = es_escalera() <NEW_LINE> color = es_color() <NEW_LINE> full = es_full() <NEW_LINE> poker = es_poker() <NEW_LINE> ... | Calcula la mejor combinacion que hay en las cartas | 625941c5b830903b967e9904 |
def PyReadCSV(self, inputUrl): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> hdfs = self._get_HDFS_connection() <NEW_LINE> with hdfs.open(inputUrl) as reader: <NEW_LINE> <INDENT> df = pd.read_csv(reader, encoding='utf-8') <NEW_LINE> <DEDENT> return df | Standalone version for reading from CSV file
@param inputUrl: String
@return: Pandas.DataFrame | 625941c5fbf16365ca6f61b9 |
def __getitem__(self, i): <NEW_LINE> <INDENT> value = self.lst[i] <NEW_LINE> return value | Return the i-th element of the vector (allows you to use the indexing operator [] on a Vector object) | 625941c5be383301e01b5481 |
def set_parameters(self,params): <NEW_LINE> <INDENT> self.parameters.velocity = params.velocity <NEW_LINE> self.parameters.gains = params.gains <NEW_LINE> self.avoidobstacles.set_parameters(self.parameters) | Set parameters for itself and the controllers | 625941c53cc13d1c6d3c7373 |
def _onMessageResponse(self, error_message, response_id): <NEW_LINE> <INDENT> if response_id == gtk.ResponseType.APPLY: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif response_id == gtk.ResponseType.CLOSE: <NEW_LINE> <INDENT> error_message.destroy() | Standard response callback for error messages.
@param error_message: Message that emitted this response.
@type error_message: L{PluginErrorMessage}
@param response_id: response ID
@type response_id: integer | 625941c591f36d47f21ac4e9 |
@app.post('/v1/agents/<name>/config') <NEW_LINE> @app.get('/v1/agents/<name>/config') <NEW_LINE> def get_config(name): <NEW_LINE> <INDENT> proxy_support = urllib2.ProxyHandler({}) <NEW_LINE> opener = urllib2.build_opener(proxy_support) <NEW_LINE> location = urljoin( AGENT_CONFIG_SERVER, '/v1/agents/%s/config' % bidders... | redirects the call to the agent configuration service
on /v1/agents/<name>/config for the given name
return map_and_redirect('/v1/agents/%s/config', name) | 625941c526068e7796caecd4 |
def __init__(self): <NEW_LINE> <INDENT> self.registration = ['cloudtrail'] <NEW_LINE> self.priority = 5 | takes an incoming message and checks for dots at the
start or end of the key and removes them | 625941c5a934411ee375168b |
def rename(self, dry_run: bool, **kwargs) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> imdb_movie = self._determine_movie(self._info['title'], self._info['year']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> imdb_movie = self._determine_movie(self._info['title']) <NEW_LINE> <DEDENT> if imdb_movie i... | See super class. | 625941c5442bda511e8be412 |
def test_excel_conversion_convert_to_oenorm(self): <NEW_LINE> <INDENT> pass | Test case for excel_conversion_convert_to_oenorm
Converts Excel files to Oenorm files. # noqa: E501 | 625941c5377c676e912721a1 |
def rgb_oversample(image, crop_dims): <NEW_LINE> <INDENT> im_shape = np.array(image.shape) <NEW_LINE> crop_dims = np.array(crop_dims) <NEW_LINE> im_center = im_shape[:2] / 2.0 <NEW_LINE> h_indices = (0, im_shape[0] - crop_dims[0]) <NEW_LINE> w_indices = (0, im_shape[1] - crop_dims[1]) <NEW_LINE> crops_ix = np.empty((5,... | Crop images into the four corners, center, and their mirrored versions.
Adapted from Caffe
Parameters
----------
image : (H x W x K) ndarray
crop_dims : (height, width) tuple for the crops.
Returns
-------
crops : (10 x H x W x K) ndarray of crops. | 625941c555399d3f055886ac |
def check_token(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args,**kw): <NEW_LINE> <INDENT> err = False <NEW_LINE> params = yield from kw['request'].json() <NEW_LINE> kws = dict(**params) <NEW_LINE> key = kws['token'] <NEW_LINE> if key is None: <NEW_LINE> <INDENT> err = True <NEW_LINE> <DE... | 检查token是否过期 | 625941c5379a373c97cfab3c |
def two_dim(self, fronts: List[list], labels: List[str] = None, filename: str = None, format: str = 'eps'): <NEW_LINE> <INDENT> n = int(np.ceil(np.sqrt(len(fronts)))) <NEW_LINE> fig = plt.figure() <NEW_LINE> fig.suptitle(self.plot_title, fontsize=16) <NEW_LINE> reference = None <NEW_LINE> if self.reference_front: <NEW_... | Plot any arbitrary number of fronts in 2D.
:param fronts: List of fronts (containing solutions).
:param labels: List of fronts title (if any).
:param filename: Output filename. | 625941c550485f2cf553cd91 |
def __init__(self, grid: Grid): <NEW_LINE> <INDENT> super().__init__(grid) | Initialise. Not different from Model. | 625941c5d486a94d0b98e13d |
def get_pipeline(self, uid): <NEW_LINE> <INDENT> return (Pipeline(self.conf.get('api'))).get( uid, cache='{}/json/workflow.{}.json'.format(self.scratch, uid) if self.use_cache else False, ) | Get resource | 625941c530bbd722463cbdbd |
def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_txt(os.path.join(data_dir, "KFRval.txt")), 'dev') | See base class | 625941c5a219f33f34628964 |
def post_fact(self, fact_sentence): <NEW_LINE> <INDENT> return self.app.post('/animals/facts', data=json.dumps({'fact': fact_sentence}), content_type='application/json') | Helper method to call post fact API with provided fact sentence.
| 625941c5b830903b967e9905 |
def test_get_rename_dict__ENV_1(self): <NEW_LINE> <INDENT> self.assertEqual(SConsArguments.Declarations._ArgumentDeclarations().get_rename_dict(SConsArguments.ENV), dict()) | _ArgumentDeclarations().get_rename_dict(ENV) should return empty dict | 625941c58c0ade5d55d3e9b2 |
def method2jpg(output, mx, raw=False): <NEW_LINE> <INDENT> buff = raw <NEW_LINE> if not raw: <NEW_LINE> <INDENT> buff = method2dot(mx) <NEW_LINE> <DEDENT> method2format(output, "jpg", mx, buff) | Export method to a jpg file format
:param output: output filename
:type output: string
:param mx: specify the MethodAnalysis object
:type mx: :class:`MethodAnalysis` object
:param raw: use directly a dot raw buffer (optional)
:type raw: string | 625941c54f88993c3716c061 |
def load(self, objects=None, namespaces=None, **kwargs): <NEW_LINE> <INDENT> logger.debug(u'Loading: {0}'.format(self.transferPath())) <NEW_LINE> self.transferObject().load(objects=objects, namespaces=namespaces, **kwargs) <NEW_LINE> logger.debug(u'Loading: {0}'.format(self.transferPath())) | Load the data from the transfer object.
:type namespaces: list[str] or None
:type objects: list[str] or None
:rtype: None | 625941c5507cdc57c6306cd0 |
def avg_length(tree, freq_dict): <NEW_LINE> <INDENT> dict_codes = get_codes(tree) <NEW_LINE> freq_sum = 0 <NEW_LINE> codes_sum = 0 <NEW_LINE> for symbol in freq_dict: <NEW_LINE> <INDENT> freq_sum += freq_dict[symbol] <NEW_LINE> codes_sum += freq_dict[symbol] * len(dict_codes[symbol]) <NEW_LINE> <DEDENT> assert freq_sum... | Return the number of bits per symbol required to compress text
made of the symbols and frequencies in freq_dict, using the Huffman tree.
@param HuffmanNode tree: a Huffman tree rooted at node 'tree'
@param dict(int,int) freq_dict: frequency dictionary
@rtype: float
>>> freq = {3: 2, 2: 7, 9: 1}
>>> left = HuffmanNode... | 625941c5435de62698dfdc45 |
def get_console_output(self, console_log, node_id): <NEW_LINE> <INDENT> node_ip = self.get_ip_by_id(node_id) <NEW_LINE> log_path = "/tftpboot/log_" + str(node_id) <NEW_LINE> kmsg_cmd = (CONF.tile_monitor + " --resume --net " + node_ip + " -- dmesg > " + log_path) <NEW_LINE> subprocess.Popen(kmsg_cmd, shell=True) <NEW_L... | Gets console output of the given node. | 625941c5498bea3a759b9aa8 |
def _updateThreshold(self): <NEW_LINE> <INDENT> noise = scipy.mean(self.noise_peak_buffer) <NEW_LINE> signal = scipy.mean(self.signal_peak_buffer) <NEW_LINE> self.threshold = noise + 0.3125 * (signal - noise) <NEW_LINE> self.threshold = self.threshold*2 | Calculate threshold based on amplitudes of last
8 signal and noise peaks | 625941c5aad79263cf390a37 |
def get_s3_client(): <NEW_LINE> <INDENT> import boto3 <NEW_LINE> from botocore import UNSIGNED <NEW_LINE> from botocore.client import Config <NEW_LINE> s3_client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) <NEW_LINE> return s3_client | Return a boto3 s3 client
Returns
-------
s3_client : boto3.client('s3') | 625941c5a8ecb033257d30c6 |
def snapshot(self): <NEW_LINE> <INDENT> snap = super(WidgetComponent, self).snapshot() <NEW_LINE> get = getattr <NEW_LINE> attrs = dict((attr, get(self, attr)) for attr in _WIDGET_ATTRS) <NEW_LINE> snap.update(attrs) <NEW_LINE> return snap | Return the initial properties for a widget component.
| 625941c5d268445f265b4e67 |
def setup_preprocessing(self): <NEW_LINE> <INDENT> self.setup_datafind() <NEW_LINE> if self.error_code != 0: return <NEW_LINE> if self.engine == 'heterodyne': <NEW_LINE> <INDENT> self.setup_heterodyne() <NEW_LINE> if self.error_code != 0: return <NEW_LINE> <DEDENT> if self.engine == 'splinter': <NEW_LINE> <INDENT> self... | Setup the preprocessing analysis: data finding, segment finding and heterodyne/splinter data processing | 625941c58e05c05ec3eea36c |
def __call__(self): <NEW_LINE> <INDENT> islist = isinstance(self.queries, list) <NEW_LINE> if islist: <NEW_LINE> <INDENT> queries = self.queries <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queries = [self.queries] <NEW_LINE> <DEDENT> items = [] <NEW_LINE> for query in queries: <NEW_LINE> <INDENT> thisquery = deepcopy... | class instance behaves as a function f, use f() to call | 625941c58da39b475bd64f6b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.