code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def build_timestamp_id(): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> localtime = time.localtime(now) <NEW_LINE> tstr = time.strftime('%Y%m%d%H%M%S', localtime) <NEW_LINE> msstr = "%03d"%((now%1)*1000) <NEW_LINE> return tstr + msstr | Builds a timestamp from the local clock | 625941eafbf16365ca6f6698 |
def hasCycle(self, head): <NEW_LINE> <INDENT> pointer = head <NEW_LINE> table = {} <NEW_LINE> while True: <NEW_LINE> <INDENT> if pointer == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if table.has_key(pointer): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> table[pointer] = True <NEW_LINE> pointer =... | :type head: ListNode
:rtype: bool | 625941ea460517430c394641 |
def serialize(self, outputStream): <NEW_LINE> <INDENT> super( TransmitterPdu, self ).serialize(outputStream) <NEW_LINE> self.radioReferenceID.serialize(outputStream) <NEW_LINE> outputStream.write_unsigned_short(self.radioNumber); <NEW_LINE> self.radioEntityType.serialize(outputStream) <NEW_LINE> outputStream.write_unsi... | serialize the class | 625941ea099cdd3c635f1122 |
def detailed_nutrition_lookup(): <NEW_LINE> <INDENT> url = 'https://trackapi.nutritionix.com/v2/natural/nutrients' <NEW_LINE> body = { "query": "for breakfast i ate 2 eggs, bacon, and french toast", "timezone": "US/Eastern" } <NEW_LINE> response = requests.post(url=url, headers=HEADERS, json=body) <NEW_LINE> content = ... | Natural language nutrition lookup API
References:
- https://gist.github.com/mattsilv/9dfb709e7609537ffd3b1b8c097e9bfb
- https://gist.github.com/mattsilv/95f94dd1378d4747fb68ebb2d042a4a6 | 625941ea3d592f4c4ed1d529 |
def nDimPoissonHists(rho, input_state, Us, P_j, trials, train_frac, mu=None, **simkwargs): <NEW_LINE> <INDENT> Us = np.array(Us) <NEW_LINE> rho = np.array(rho) <NEW_LINE> assert Us.shape[0] == rho.shape[0] <NEW_LINE> dim = P_j.shape[2] <NEW_LINE> num_sub = P_j.shape[1] <NEW_LINE> num_total = Us.shape[0] <NEW_LINE> P_ij... | Generates n-dimensional histograms for simulated examples.
Args:
rho: array of fiducial state for reference experiment and
target states for probing experiments
input_state: array of fiducial state for reference experiment and 1 for
probing experiment
Us: ... | 625941eaa79ad161976cc60f |
def player_input(): <NEW_LINE> <INDENT> marker = '' <NEW_LINE> while marker != 'X' and marker != 'O': <NEW_LINE> <INDENT> marker = input('Player1 choose "X" or "O" :').upper() <NEW_LINE> if marker == 'X': <NEW_LINE> <INDENT> return ('X', 'O') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('O', 'X') | OUTPUT : (PLAYER1_MARKER , PLAYER2_MARKER)
:return: | 625941ea566aa707497f4a2b |
def cookie_decode(data, key, digestmod=None): <NEW_LINE> <INDENT> data = tob(data) <NEW_LINE> if cookie_is_encoded(data): <NEW_LINE> <INDENT> sig, msg = data.split(tob('?'), 1) <NEW_LINE> digestmod = digestmod or hashlib.sha256 <NEW_LINE> hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest() <NEW_LINE> if _lsc... | Verify and decode an encoded string. Return an object or None. | 625941ea4e696a04525c9917 |
def resolve_conflicts(self): <NEW_LINE> <INDENT> neighbours = self.nodes <NEW_LINE> new_chain = None <NEW_LINE> max_length = len(self.chain) <NEW_LINE> for node in neighbours: <NEW_LINE> <INDENT> response = requests.get(f'http://{node}/chain') <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> length = resp... | This is our Consensus Algorithm, it resolves conflicts
by replacing our chain with the longest one in the network.
:return: <bool> True if our chain was replaced, False if not | 625941eaf9cc0f698b140ac0 |
def __init__(self, cli, logger, resource_config, api): <NEW_LINE> <INDENT> super(CiscoASAFirmwareRunner, self).__init__(logger) <NEW_LINE> self.cli = cli <NEW_LINE> self.api = api <NEW_LINE> self.resource_config = resource_config | Handle firmware upgrade process
:param CLI cli: Cli object
:param qs_logger logger: logger
:param CloudShellAPISession api: cloudshell api object
:param GenericNetworkingResource resource_config: | 625941ea73bcbd0ca4b2c53f |
def my_languages(results:dict): <NEW_LINE> <INDENT> dict_sorted_by_value = OrderedDict(sorted(results.items(), key=lambda x: x[1], reverse=True)) <NEW_LINE> my_lang = [] <NEW_LINE> for language, score in dict_sorted_by_value.items(): <NEW_LINE> <INDENT> if score >= 60: <NEW_LINE> <INDENT> my_lang.append(language) <NEW_... | Function returns the list of languages where
your test score is at least 60, in descending order of the results. | 625941ea711fe17d8254282a |
def add_new_weight(weight, user_info): <NEW_LINE> <INDENT> date_file = access_date_file(user_info, 'a') <NEW_LINE> snap_date_to_now() <NEW_LINE> date_file.write(f"weight:{weight}\n") | Adds new weight record on current set date
:param weight:
:param user_info:
:return: | 625941eaac7a0e7691ed458c |
def _single_resource_json_response(resource): <NEW_LINE> <INDENT> return jsonify(**resource.as_dict()) | Return the JSON representation of *resource*.
:param resource: :class:`sandman.model.Model` to render
:type resource: :class:`sandman.model.Model`
:rtype: :class:`flask.Response` | 625941ead6c5a10208144518 |
def testV1QuobyteVolumeSource(self): <NEW_LINE> <INDENT> pass | Test V1QuobyteVolumeSource | 625941eaa4f1c619b28b04f7 |
def close(self): <NEW_LINE> <INDENT> if self.read_fd is not None: <NEW_LINE> <INDENT> os.close(self.read_fd) <NEW_LINE> self.read_fd = None <NEW_LINE> <DEDENT> if self.write_fd is not None: <NEW_LINE> <INDENT> os.close(self.write_fd) <NEW_LINE> self.write_fd = None | close file if open | 625941ea63d6d428bbe449ba |
def find_column(token): <NEW_LINE> <INDENT> return find_column_by_lexpos(token.lexpos) | This function tells the column number for a token. | 625941ea56ac1b37e626468f |
def makeBuilding(objectslist=None,baseobj=None,name="Building"): <NEW_LINE> <INDENT> obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython",name) <NEW_LINE> _Building(obj) <NEW_LINE> if FreeCAD.GuiUp: <NEW_LINE> <INDENT> _ViewProviderBuilding(obj.ViewObject) <NEW_LINE> <DEDENT> if objectslist: <NEW_LIN... | makeBuilding(objectslist): creates a building including the
objects from the given list. | 625941eaeab8aa0e5d26e023 |
def patch_get_signal(mocker, value=(True, False)) -> None: <NEW_LINE> <INDENT> mocker.patch( 'freqtrade.freqtradebot.Analyze.get_signal', side_effect=lambda s, t: value ) | :param mocker: mocker to patch Analyze class
:param value: which value Analyze.get_signal() must return
:return: None | 625941ead8ef3951e3243a07 |
def main(): <NEW_LINE> <INDENT> test_factorial() | Decorator case study with factorial
The Decorator will be used to raise exception if the number is not positive and int | 625941eaa934411ee3751b5e |
def getDynamicSpectrum(self,window=None,template=None,mpw=None,align=None,windowsize=None,weight=True,verbose=False,snr=False): <NEW_LINE> <INDENT> fullshape = self.shape(squeeze=False) <NEW_LINE> if fullshape[0] != 1 and fullshape[1] == 1 and fullshape[2] != 1: <NEW_LINE> <INDENT> bw = self.getBandwidth() <NEW_LINE> d... | Return the dynamic spectrum
window: return the dynamic spectrum using only a certain phase bins
Should use a numpy array for this
When thrown into imshow, tranpose puts frequency on the y-axis, time on the x | 625941eabe8e80087fb21105 |
def __create_cams_draft(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> draft = get_object_or_404(Draft, slug='cam') <NEW_LINE> <DEDENT> except Http404: <NEW_LINE> <INDENT> draft = Draft(name="Cam", slug="cam") <NEW_LINE> draft.save() <NEW_LINE> <DEDENT> level1 = DesignerLevel(draft=draft, name="Foo", slug="foo", p... | Creates Cam's Draft smartgrid with two levels, three columns, three actions | 625941eadd821e528d63b66f |
def insertLink(self, linkLocation, box=None): <NEW_LINE> <INDENT> if linkLocation is None: <NEW_LINE> <INDENT> self.log.write("Linking cancelled.") <NEW_LINE> <DEDENT> elif linkLocation is False: <NEW_LINE> <INDENT> self.log.write("Back to note selection window") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if linkLoc... | Insert a link to linkLocation | 625941eab7558d58953c53d3 |
def api(self): <NEW_LINE> <INDENT> api = Api(self) <NEW_LINE> cherrypy.config.update({ 'tools.sessions.on': False, 'tools.sessions.locking': 'explicit', 'request.show_tracebacks': True, 'server.socket_port': self.config.get("api_port"), 'server.thread_pool': 1, 'server.socket_host': '0.0.0.0', 'server.show_tracebacks':... | Run the webhook listener and block | 625941ea7c178a314d6ef931 |
def mkdir(self, _sDirectory): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.isdir(_sDirectory): <NEW_LINE> <INDENT> self._mkdir(_sDirectory) <NEW_LINE> <DEDENT> <DEDENT> except EnvironmentError as e: <NEW_LINE> <INDENT> self._ERROR("%s; %s" % (e.strerror, _sDirectory)) <NEW_LINE> raise EnvironmentError(e.... | Create the given directory (recursively).
(including validation and exceptions handling)
@param string _sDirectory Directory path | 625941ea9f2886367277ad53 |
def shrink(body): <NEW_LINE> <INDENT> toremove = [] <NEW_LINE> for key, value in body.iteritems(): <NEW_LINE> <INDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> if key.endswith('url'): <NEW_LINE> <INDENT> if (value.startswith('https://api.github.com/') or value.startswith('https://avatars.githubusercontent.... | Recursively remove GitHub API urls from an object to make it more human-readable. | 625941eaf9cc0f698b140ac1 |
def get_welcome_response(): <NEW_LINE> <INDENT> session_attributes = {} <NEW_LINE> card_title = "Welcome" <NEW_LINE> speech_output = "Welcome to Hyvee Prices. " "Ask about groceries, deals, or news." <NEW_LINE> reprompt_text = "Please tell me what item's price you'd like to know by saying, " ... | If we wanted to initialize the session to have some attributes we could
add those here | 625941ea187af65679ca55e9 |
def test_trigonometric(): <NEW_LINE> <INDENT> est1 = SymbolicRegressor(random_state=0) <NEW_LINE> est1.fit(boston.data[:400, :], boston.target[:400]) <NEW_LINE> est1 = mean_absolute_error(est1.predict(boston.data[400:, :]), boston.target[400:]) <NEW_LINE> est2 = SymbolicRegressor(trigonometric=True, random_state=0) <NE... | Check that using trig functions work and that results differ | 625941ea92d797404e304656 |
def test_no_instantiation(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> NotificationUserScopeResolver() <NEW_LINE> <DEDENT> register_user_scope_resolver('bad_scope', BadTestScopeResolver()) <NEW_LINE> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> resolve_user_scope... | Asserts that NotificationScopeResolver is an abstract base clas | 625941ea379a373c97cfb010 |
def pca(self, implementation='smartpca', overwrite=False, normalize=True, args={}): <NEW_LINE> <INDENT> if implementation == 'smartpca': <NEW_LINE> <INDENT> self.make_ped() <NEW_LINE> pca = SmartPCA(dataset=self) <NEW_LINE> pca.run(overwrite=overwrite, args=args) <NEW_LINE> return pca <NEW_LINE> <DEDENT> elif implement... | Computes a Principal Components Analysis with the genotypes in this
dataset. Returns a PCA object that responds to #results and #plot(). | 625941ea7047854f462a18ce |
def get_person(self, person_id): <NEW_LINE> <INDENT> assert person_id in self.people <NEW_LINE> return self.people[person_id] | Retrieves person. | 625941ea379a373c97cfb011 |
def get_generic_path_information(paths, stat_prefix=''): <NEW_LINE> <INDENT> statistics = OrderedDict() <NEW_LINE> returns = [sum(path["rewards"]) for path in paths] <NEW_LINE> rewards = np.vstack([path["rewards"] for path in paths]) <NEW_LINE> statistics.update(create_stats_ordered_dict('Rewards', rewards, stat_prefix... | Get an OrderedDict with a bunch of statistic names and values. | 625941ea462c4b4f79d1db99 |
def shift_coordinates(old_latitude, old_longitude, displacement): <NEW_LINE> <INDENT> latitude = math.degrees( math.asin(math.sin(math.radians(old_latitude)) * math.cos(displacement.length() / EARTH_RADIUS) + math.cos(math.radians(old_latitude)) * math.sin(displacement.length() / EARTH_RADIUS) * math.cos( math.radians(... | displacement is a Vector2D | 625941ea2ae34c7f2600d5fa |
def begin_create_or_update( self, resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_int... | Creates or updates a security rule in the specified network security group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name o... | 625941ea8e7ae83300e4b498 |
def create_unit(self, unit_type): <NEW_LINE> <INDENT> unit = None <NEW_LINE> unit_type = unit_type.lower() <NEW_LINE> if unit_type == 'elfrider': <NEW_LINE> <INDENT> unit = ElfRider() <NEW_LINE> <DEDENT> elif unit_type == 'knight': <NEW_LINE> <INDENT> unit = Knight() <NEW_LINE> <DEDENT> elif unit_type == 'dwarffighter'... | The work horse method to create and return instances of a game unit.
:arg string unit_type: The ype of unit requestaed by the client.
:return: An instance of a game unit such as ElfRider, Knight, Dwarf, etc. | 625941ea6fece00bbac2dc0e |
def match(self, path, method='GET'): <NEW_LINE> <INDENT> rule_args = self.static_routes.get(path) <NEW_LINE> url_args = {} <NEW_LINE> if not rule_args: <NEW_LINE> <INDENT> for re_pattern in self.dynamic_patterns: <NEW_LINE> <INDENT> matched = re_pattern.match(path) <NEW_LINE> if matched: <NEW_LINE> <INDENT> url_args = ... | Return a (endpoint, url_args) tuple or raise HTTPException(400/404/405). | 625941ea287bf620b61d3f2a |
def statistics_dict(self): <NEW_LINE> <INDENT> raw_dict = self.raw_statistics_dict() <NEW_LINE> parsed_dict = {} <NEW_LINE> fields = (('hit_count', 'hit_count', r'^(\d+)$', int), ('miss_count', 'miss_count', r'^(\d+)$', int), ('hit_ratio', 'hit_ratio', r'^(\d+)%$', int), ('item_count', 'item_count', r'^(\d+) item\(s\)$... | A parsed representation of memcache statistics.
Raises ValueError if unable to parse elements of the raw
summary. For example if input like '1024 byte(s)' later changes
to '1 kilobyte(s)' a ValueError will be raised.
Returns:
A dict with fields like this:
{'hit_count': 12345,
'miss_count': 123,
'hit_ratio'... | 625941eaff9c53063f47c6bb |
def pre_optimal_ass_fifo(self): <NEW_LINE> <INDENT> opts = OptsClass() <NEW_LINE> pre_opt_ass = [] <NEW_LINE> for l in range(1000): <NEW_LINE> <INDENT> if not self.tasks_pool.empty(): <NEW_LINE> <INDENT> tl1 = self.tasks_pool.get() <NEW_LINE> et1 = opts.inputET(tl1, l) <NEW_LINE> ass1, f1, delays1 = opts.ass1_fifo(tl1,... | 生成pre_scheduling assignment
:return: pre_opt_ass | 625941ea24f1403a9260102c |
def generator_super_squid_square(width=1,inner_radius=4,arm_length=8, arm_width=2,delta=0.0,mag_field=0.0,fill=False): <NEW_LINE> <INDENT> g = geometry.squid_square(width=width,inner_radius=inner_radius, arm_length=arm_length, arm_width = arm_width,fill=fill) <NEW_LINE> g.dimensionality = 0 <NEW_LINE> g.celldis = None ... | Creates a function that returns a superconducting
squid made of square lattice,
central part is a normal system | 625941ea7cff6e4e81117e4f |
def TractionIntegrand(self, B, SpatialGradient, CauchyStressTensor, analysis_nature="nonlinear", has_prestress=True): <NEW_LINE> <INDENT> pass | Applies to displacement based formulation | 625941eac432627299f05113 |
def init_prime_bitarray(maxnum): <NEW_LINE> <INDENT> global primes_ba <NEW_LINE> maxnum += 1 <NEW_LINE> primes_ba = BitArray(maxnum) <NEW_LINE> primes_ba.set(1) <NEW_LINE> primes_ba[0], primes_ba[1] = [0, 0] <NEW_LINE> for i in [2] + list(range(3, maxnum, 2)): <NEW_LINE> <INDENT> if primes_ba[i]: <NEW_LINE> <INDENT> fo... | Initialize a bitarray with the supplied length, and find primes with
a prime sieve. | 625941ea1d351010ab855fe5 |
def get_path_by_id(self, _id): <NEW_LINE> <INDENT> attr = self.get_standard_attr_by_id(_id) <NEW_LINE> if attr._parent == 'None': <NEW_LINE> <INDENT> return '/' + attr._name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return joinp(self.get_path_by_id(attr._parent), attr._name) | returns a path on the DS from the uuid of an existing object | 625941ea498bea3a759b9f78 |
def _printPolygons(self, mesh, sprite): <NEW_LINE> <INDENT> if len(mesh.polygons) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> backface = mesh.polygon_layers_int["backface"].data <NEW_LINE> rlayer = mesh.polygon_layers_int["rlayer"].data <NEW_LINE> glayer = mesh.polygon_layers_int["glayer"].data <NEW_LINE> blay... | Print the selected (visible) polygons.
| 625941ea76d4e153a657effd |
def GetAbsPath(self, relPath): <NEW_LINE> <INDENT> path = self.absDirPath + relPath <NEW_LINE> return path | path = ""
if relPath.find("Fonts/") >= 0:
strDir = os.path.dirname(os.path.abspath(relPath))
fontPos = strDir.find("/Fonts")
strDir = strDir[:fontPos]
print(strDir)
if strDir.find("BEETFT") < 0:
strDir = strDir+ "/BEETFT/"
path = strDir + "/" + relPath
elif ... | 625941ea56b00c62f0f14b26 |
def worddist(self): <NEW_LINE> <INDENT> return (self.n_gl_z_w + 1) / (self.n_gl_z[:, numpy.newaxis] + 1), (self.n_loc_z_w + 1) / (self.n_loc_z[:, numpy.newaxis] + 1) | get topic-word distribution | 625941eaadb09d7d5db6cc56 |
def power(num1, num2): <NEW_LINE> <INDENT> return float(num1) ** float(num2) | Raises the first integer to the power of the second integer and returns the value. | 625941eaac7a0e7691ed458d |
def shop(request): <NEW_LINE> <INDENT> if request.session.get('is_login', None): <NEW_LINE> <INDENT> content = {} <NEW_LINE> shop_id = models.Shop.objects.filter(shop_owner=request.session['user_id'])[0].id <NEW_LINE> goods_set = models.Goods.objects.filter(shop_id=shop_id) <NEW_LINE> goods = [] <NEW_LINE> for item in ... | view my goods
:param request:
:return: | 625941ea57b8e32f52483968 |
def insertExtractPartSteps(self, mode, prerequisites): <NEW_LINE> <INDENT> self.newSteps = [] <NEW_LINE> self.newSteps.append(self._insertFunctionStep("extractParticles", mode, prerequisites= prerequisites)) <NEW_LINE> self.newSteps.append(self._insertFunctionStep("joinSetOfParticlesStep", mode, prerequisites= self.new... | Inserts the steps necessary for extracting the particles from the micrographs | 625941ea167d2b6e3121905f |
def player_getRandomRoleNames(self, male): <NEW_LINE> <INDENT> self.send(self.game_session, "player@getRandomRoleNames", male=male) | :function: 获取角色任意名称 male=2
:param male: 是否男性
:return: 不返回数据 | 625941ea460517430c394642 |
def reputation_to_score(rep): <NEW_LINE> <INDENT> if isinstance(rep, str): <NEW_LINE> <INDENT> rep = int(rep) <NEW_LINE> <DEDENT> if rep == 0: <NEW_LINE> <INDENT> return 25.0 <NEW_LINE> <DEDENT> score = max([math.log10(abs(rep)) - 9, 0]) <NEW_LINE> if rep < 0: <NEW_LINE> <INDENT> score *= -1 <NEW_LINE> <DEDENT> score =... | Copied from beem
Converts the account reputation value into the reputation score | 625941ead58c6744b4258128 |
def write_triplets_to_file(triplets: List[Triplet], path: str): <NEW_LINE> <INDENT> pass | SOMEONE
writes triplets to table, i might suggest xlwt library
:param triplets:
:param path:
:return: | 625941ea91f36d47f21ac9c2 |
def _traverse_prefix_nofill(self, request: HttpRequest) -> typing.Optional[typing.Dict[bytes, typing.Any]]: <NEW_LINE> <INDENT> path = request.url.path.strip(b'/').split(b'/') <NEW_LINE> followed = [b''] <NEW_LINE> current = self._prefix <NEW_LINE> for step in path: <NEW_LINE> <INDENT> if step == b'': <NEW_LINE> <INDEN... | Traverses the prefix trie and returns the resulting leaf.
This method does not fill in branches. Returns None if the leaf cannot be found.
This method also fills the request.match_info values.
:param request: HttpRequest to traverse the path for and fill in match_info values.
:return: Leaf node of the prefix trie. | 625941ea4e696a04525c9918 |
@as_var("pixie.ffi", "struct-size") <NEW_LINE> def struct_size(tp): <NEW_LINE> <INDENT> if not isinstance(tp, CStructType): <NEW_LINE> <INDENT> runtime_error(u"Expected a CStruct type to get the size of, got " + rt.name(rt.str(tp))) <NEW_LINE> <DEDENT> return rt.wrap(tp.get_size()) | (struct-size tp)
Gives the size of the given CStruct type tp, in bytes. | 625941ea66673b3332b9255b |
def __init__(self): <NEW_LINE> <INDENT> super(ChromeCacheIndexFileParser, self).__init__() <NEW_LINE> self.creation_time = None <NEW_LINE> self.index_table = [] | Initializes an index file. | 625941ea07d97122c4178d61 |
def ub(self, irc, msg, args, channel, optlist, items): <NEW_LINE> <INDENT> perm = False <NEW_LINE> for (option, arg) in optlist: <NEW_LINE> <INDENT> if option == 'perm': <NEW_LINE> <INDENT> perm = True <NEW_LINE> <DEDENT> <DEDENT> isMass = False <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if item == '*': <NEW_LIN... | [<channel>] [--perm] <nick|hostmask|*> [<nick|hostmask>]
sets -b on them; if * is given, remove them all,
--perm to remove them for permanent bans | 625941ea0fa83653e4657482 |
def get_recipe_local_files(d, patches=False, archives=False): <NEW_LINE> <INDENT> import oe.patch <NEW_LINE> uris = (d.getVar('SRC_URI') or "").split() <NEW_LINE> fetch = bb.fetch2.Fetch(uris, d) <NEW_LINE> archive_exts = ['.tar', '.tgz', '.tar.gz', '.tar.Z', '.tbz', '.tbz2', '.tar.bz2', '.tar.xz', '.tar.lz', '.zip', '... | Get a list of local files in SRC_URI within a recipe. | 625941eaec188e330fd5ac5f |
def validate(cfgdict): <NEW_LINE> <INDENT> status,message = validate_tftprootfolder(cfgdict["tftprootfolder"]) <NEW_LINE> if not status: <NEW_LINE> <INDENT> return status, message <NEW_LINE> <DEDENT> status,message = validate_logfolder(cfgdict["logfolder"]) <NEW_LINE> if not status: <NEW_LINE> <INDENT> return status, m... | Returns True, None if cfgdict ok
or False, message if there is an error | 625941ea32920d7e50b2869e |
def test_nextset(self): <NEW_LINE> <INDENT> self.checkMethod(self.c,'nextset') | CursorBase object nextset()-method | 625941ea0c0af96317bb86b2 |
def generate_even_helix_position_sq(rows=MAX_ROWS, cols=MAX_COLS): <NEW_LINE> <INDENT> n_rows = rows * 2 <NEW_LINE> for i in range(0, cols, 1): <NEW_LINE> <INDENT> for j in range(0, n_rows, 2): <NEW_LINE> <INDENT> m = 0 if i % 2 == 0 else 1 <NEW_LINE> yield (i, j + m) | Iterator to generate the next even helix position on a square lattice.
:param rows: number of rows in the lattice
:param cols: number of columns in the lattice
:return (row, col): tuple consisting of helix coordinates on the lattice | 625941ea3317a56b8693a116 |
def test_sanity_HashNode(self): <NEW_LINE> <INDENT> tx1 = 'a' <NEW_LINE> tx2 = 'b' <NEW_LINE> tx3 = 'c' <NEW_LINE> tx4 = 'd' <NEW_LINE> data1 = tx1 + tx2 <NEW_LINE> data1 = hash_data(data1, 'sha256') <NEW_LINE> data2 = tx3 + tx4 <NEW_LINE> data2 = hash_data(data2, 'sha256') <NEW_LINE> data = data1 + data2 <NEW_LINE> da... | Ensure HashNode structures work as intended | 625941ea99cbb53fe67930af |
def set_coupon_in_session(intent, session): <NEW_LINE> <INDENT> card_title = intent['name'] <NEW_LINE> session_attributes = {} <NEW_LINE> should_end_session = False <NEW_LINE> if 'Item' in intent['slots']: <NEW_LINE> <INDENT> item = intent['slots']['Item']['value'] <NEW_LINE> item_attributes = create_item_attributes(it... | Sets the aisle number in the session and prepares the speech to reply to the
user. | 625941ea5f7d997b87174f67 |
def test_uniqueness_topic(self): <NEW_LINE> <INDENT> self.flat3.follow('topic', self.topic1.user_id) <NEW_LINE> self.flat3.follow('user', self.user1.user_id) <NEW_LINE> now = datetime.datetime.now(tzlocal()) <NEW_LINE> tweet = 'My Way %s' % random_postfix <NEW_LINE> activity_data = { 'actor': 1, 'verb': 'tweet', 'objec... | In order for things to be considere unique they need:
a.) The same time and activity data, or
b.) The same time and foreign id | 625941ea63b5f9789fde75b0 |
def _patch_post(self, battle_patcher): <NEW_LINE> <INDENT> return self | 完成填充
| 625941ea01c39578d7e75306 |
def main_menu(): <NEW_LINE> <INDENT> build_menu() <NEW_LINE> print(colorizer.colorize('\nChoose a KILLER option.', colors.text_colors['WARNING'], '', '')) <NEW_LINE> choice = input("> ") <NEW_LINE> if choice == "1": <NEW_LINE> <INDENT> annex_habitat(keahua) <NEW_LINE> <DEDENT> if choice == "2": <NEW_LINE> <INDENT> rele... | Show Keahua Action Options
Arguments: None | 625941ea30c21e258bdfa96d |
def t400360_x9(): <NEW_LINE> <INDENT> assert t400360_x1() <NEW_LINE> return 0 | State 0,1,2,3 | 625941ea63d6d428bbe449bb |
def __init__(self, configParser=None): <NEW_LINE> <INDENT> self._logger = getLogger(__name__) <NEW_LINE> self._logger.info("Plugin Munin start") <NEW_LINE> self._configParser = configParser <NEW_LINE> self._munin_host = "127.0.0.1" <NEW_LINE> self._munin_port = 4949 <NEW_LINE> self._plugins_enable = ".*" <NEW_LINE> sel... | When numeter load a module, the only one parameter is the config
parser. It’s allow you to add section in numeter config file for
your own module. | 625941ea0a366e3fb873ece9 |
def _ParseHomeOrAway(symbol): <NEW_LINE> <INDENT> if symbol == '': <NEW_LINE> <INDENT> return HOME_TEAM_WON <NEW_LINE> <DEDENT> elif symbol == '@': <NEW_LINE> <INDENT> return HOME_TEAM_LOST <NEW_LINE> <DEDENT> elif symbol == 'N': <NEW_LINE> <INDENT> return NO_HOME_TEAM <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rais... | Parses the symbol that gives who was home/away. | 625941ea66673b3332b9255c |
@taskc.app.task(name="create-logs-summary") <NEW_LINE> def create_build_logs_summary(job, kernel, git_branch): <NEW_LINE> <INDENT> status, error = utils.logs.build.create_build_logs_summary( job, kernel, git_branch, taskc.app.conf.db_options) <NEW_LINE> return status | Task wrapper around the real function.
Create the build logs summary.
:param job: The tree value.
:type job: str
:param kernel: The kernel value.
:type kernel: str
:param git_branch: The branch name.
:type git_branch: str | 625941ea956e5f7376d71336 |
def __ge__(self, other): <NEW_LINE> <INDENT> return int(self) >= other | Return whether the square is greater than or equal to an other
other (int): the number to compare to | 625941eaad47b63b2c50a449 |
def check_notifications(self): <NEW_LINE> <INDENT> response = self._session_manager.send(self._create_request(self._session_manager)) <NEW_LINE> if not response: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._display_notifications( notification for notification in response.get('messagesImportants', ()) if notific... | Check for new notifications. | 625941ea91af0d3eaac9bee8 |
def read_ble(mac, handle,adpater="hci0",security="high", FloraDebug=0, retries=3, timeout=20): <NEW_LINE> <INDENT> global LOCK <NEW_LINE> attempt = 0 <NEW_LINE> delay = 10 <NEW_LINE> while attempt <= retries: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = "gatttool --adapter={} --device={} --char-read -a {} --sec-l... | Read from a BLE address
@param: mac - MAC address in format XX:XX:XX:XX:XX:XX
@param: handle - BLE characteristics handle in format 0xXX
@param: timeout - timeout in seconds | 625941eacc0a2c11143dd35d |
def isValidBST(self, root) -> bool: <NEW_LINE> <INDENT> return self.helper(root, None, None) | 关键是在于中序遍历的是一个升序数列
那么对于root左树来说,最大的节点就是root
左树的每个节点都要比最小节点还要小
那么对于root右树来说,最小的节点就是root
右树的每个节点都要比最大节点还要大 | 625941ea3c8af77a43ae3c71 |
def purge(self, chars): <NEW_LINE> <INDENT> return " ".join([ "PRG,00,Purge", format_int(len(chars) + 1, True, 5), "Characters", chars+"!" ]) | Responds any current input to the screen without executing it.
:param chars: Whatever characters are left over in the buffer
:return: Purge message including ignored input | 625941ea30dc7b7665901e2c |
def sahi_failed_report(release,build): <NEW_LINE> <INDENT> if iSIndexDotXmlFromHttpURL=="YES": <NEW_LINE> <INDENT> failuredata = {} <NEW_LINE> i=1 <NEW_LINE> count = 1 <NEW_LINE> version = release+"_"+build <NEW_LINE> source_file_name="" <NEW_LINE> while i < int(runtime): <NEW_LINE> <INDENT> source_file_name=str(result... | This will return Sahi run detailed based on
release : 4.0.0,4.2.0 ect.
build : 1,2,3,4,5 ect | 625941eae1aae11d1e74a187 |
def generateFeasible2(distrNNurses, hoursDay): <NEW_LINE> <INDENT> nNurses = distrNNurses.__next__() <NEW_LINE> nurses = [] <NEW_LINE> for _ in range(nNurses): <NEW_LINE> <INDENT> m = rnd.randint(6, 18) <NEW_LINE> start = min(max(0, int(rnd.gauss(m-5, 4))), hoursDay - 1) <NEW_LINE> end = min(max(start+1, int(rnd.gauss(... | It creates a feasible instance for the problem given a number of nurses
:param distrNNurses: Distribution of the number of nurses
:param hoursDay: Number of hours in a day
:return: The params of the problem and a solution for these params | 625941ead18da76e235329a7 |
def make_gaussian_fit(x_axis, data, estimator, units=None, add_params=None, **kwargs): <NEW_LINE> <INDENT> mod_final, params = make_gaussian_model() <NEW_LINE> error, params = estimator(x_axis, data, params) <NEW_LINE> params = gfm._substitute_params(initial_params=params, update_params=add_params) <NEW_LINE> try: <NEW... | Perform a 1D gaussian peak fit on the provided data.
@param numpy.array x_axis: 1D axis values
@param numpy.array data: 1D data, should have the same dimension as x_axis.
@param method estimator: Pointer to the estimator method
@param list units: List containing the ['horizontal', 'vertical'] units as strings
@param P... | 625941eabf627c535bc1369a |
def sigmoid(z): <NEW_LINE> <INDENT> return 1.0 / (1.0 + np.exp(-z)) | Apply sigmoid function element-wise to a numpy array.
Args:
z (numpy array of number)
Returns:
numpy array of float | 625941eaec188e330fd5ac60 |
@login_required <NEW_LINE> def edit_subsection(request, location): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> course = get_course_for_item(location) <NEW_LINE> <DEDENT> except InvalidLocationError: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> if not has_access(request.user, course.location)... | Edit the subsection of a course | 625941ea8e05c05ec3eea844 |
def OSGridZonetoNE (ossquare): <NEW_LINE> <INDENT> assert (len (ossquare) == 2) <NEW_LINE> lookup = {'S':[0,0], 'T':[1,0], 'N':[0,1], 'O':[1,1], 'H':[0,2], 'J':[1,2]} <NEW_LINE> key = ossquare[0] <NEW_LINE> assert (key in lookup),"'%s' is not an OSGB 500km square (1st char)" % key <NEW_LINE> offset = lookup[key] <NEW_L... | Convert an Ordinance Survey zone (2 letter code) to distances from the reference point. | 625941eab57a9660fec33d56 |
def get_or_load_image_at_index(self, index: int): <NEW_LINE> <INDENT> img = None <NEW_LINE> if index in self._images: <NEW_LINE> <INDENT> img = self._images[index] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if index < len(self._image_names): <NEW_LINE> <INDENT> image_file_name = self._image_names[index] <NEW_LINE> i... | Get image for requested index from cache or load it. | 625941ea1f037a2d8b9466c8 |
def per_dim_int_length(self, boxes: Tensor, _scaling_factor: Tensor = torch.ones(1)) -> Tensor: <NEW_LINE> <INDENT> if len(boxes.shape) == 2: <NEW_LINE> <INDENT> return boxes[1, :] <NEW_LINE> <DEDENT> first_box = boxes[..., [0], :, :] <NEW_LINE> if boxes.shape[ -3] == 1: <NEW_LINE> <INDENT> return _scaling_factor * fir... | :param boxes: Tensor(..., intersect_axis, min/delta, embedding_dim)
:param _scaling_factor: Used for recursion, will be set internally
:return: Tensor(..., embedding_dim) of intersection length in each dimension | 625941eaaad79263cf390f13 |
def effective_distance_zh(self, z): <NEW_LINE> <INDENT> z = mf.convert2array(z) <NEW_LINE> d_a = self.angular_distance_zh(z) <NEW_LINE> dv3 = d_a*d_a*z*ckms / (np.sqrt(self.c.E_z(z))*100.) <NEW_LINE> return np.power(dv3, 1./3.) | Compute the effective distance d_V(z) = [d_a^2(z) *c*z/ (H(z))]^(1/3) in Mpc/h
Parameters
----------
z: float, list, tuble, numpy array
redshift
output: float
effective distance evaluated in z | 625941eabd1bec0571d90afa |
@singledispatch <NEW_LINE> def bin(df, start_minute=0, freq=60, label='end', min_samples_leaf=1000): <NEW_LINE> <INDENT> t = np.array(df.index, dtype='datetime64[m]').astype(int) <NEW_LINE> dt = np.diff(t) <NEW_LINE> d = np.r_[dt[0], dt, dt, dt[-1]].reshape((2,-1)).min(0) <NEW_LINE> T = t.reshape((-1, 1)) <NEW_LINE> tr... | Average raw data from CEAZAMet stations (fetched by CEAZAMet.Downloader.fetch_raw) into true time intervals.
Points about the algorithm:
1) It is assumed that the logger's timestamp refers to the end of a sampling interval.
2) A decision tree is used to split the time series into parts with likely same sampling inte... | 625941eab5575c28eb68e4cf |
def ui_command_delete(self, name): <NEW_LINE> <INDENT> self.get_root().remove_vhost_controller(ctrlr=name) | Delete a Vhost controller from configuration.
Arguments:
name - Controller name. | 625941eab5575c28eb68e4d0 |
def request_suspend(self, fut): <NEW_LINE> <INDENT> if not self.resumable: <NEW_LINE> <INDENT> print("No checkpoint; cannot suspend. Aborting...") <NEW_LINE> self._exception = FailedPause() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Suspending....To get prompt hit Ctrl-C to pause the scan") <NEW_LINE> wait_ms... | Request that the run suspend itself until the future is finished.
Parameters
----------
fut : asyncio.Future | 625941ea7d847024c06be78b |
def train_test(image_root, train_ratio=0.5): <NEW_LINE> <INDENT> folder1 = os.path.join(image_root, 'sequences', 'cam1') <NEW_LINE> folder2 = os.path.join(image_root, 'sequences', 'cam2') <NEW_LINE> dataset = {} <NEW_LINE> for folder in os.listdir(folder1): <NEW_LINE> <INDENT> pid = folder[-3:] <NEW_LINE> dataset[pid] ... | split the ilids dataset into trainset and testset in dict form
dataset[pid][cam] = tracklet
tracklet in list form, consist of image filename
:param image_root: the root directory of ilids dataset
:param train_ratio: trainset person identities ratio
:return:trainset and testset | 625941eab830903b967e9dd1 |
def open(self): <NEW_LINE> <INDENT> self.printer = usb.core.find(idVendor=USB_PRINTER_VENDOR_ID, idProduct=USB_PRINTER_PRODUCT_ID) <NEW_LINE> if not self.printer: <NEW_LINE> <INDENT> raise RuntimeError('No hay impresora') <NEW_LINE> <DEDENT> if self.printer.is_kernel_driver_active(0): <NEW_LINE> <INDENT> self.printer.d... | Realiza la apertura del USB | 625941ea99cbb53fe67930b0 |
def get_bibentry_from_api(id_str, id_type, try_doi=True, ui=None, raw=False): <NEW_LINE> <INDENT> id_fns = { 'doi': doi2bibtex, 'isbn': isbn2bibtex, 'arxiv': arxiv2bibtex, } <NEW_LINE> id_type = id_type.lower() <NEW_LINE> if id_type not in id_fns.keys(): <NEW_LINE> <INDENT> raise ValueError('id_type must be one of `doi... | Return a bibtex string from various ID methods.
This is a wrapper around functions that will return a bibtex string given
one of:
* DOI
* IBSN
* arXiv ID
Args:
id_str: A string with the ID.
id_type: Name of the ID type. Must be one of `doi`, `isbn`, or `arxiv`.
rp: A `Repository` object.
ui: A UI ob... | 625941ea73bcbd0ca4b2c540 |
def join(self,*args): <NEW_LINE> <INDENT> pass | join(self: str,sequence: list) -> str
join(self: str,sequence: object) -> str
Return a string which is the concatenation of the strings
in the sequence seq. The
separator between elements is the
string providing this method | 625941ea8a43f66fc4b5452b |
def __enter__(self): <NEW_LINE> <INDENT> self.running = True | On entering the context, mark the event queue as running. | 625941ea099cdd3c635f1124 |
def sign_keydata_and_encrypt(keydata, error_cb=None, homedir=None): <NEW_LINE> <INDENT> tmpkeyring = TempKeyring() <NEW_LINE> tmpkeyring.import_data(keydata) <NEW_LINE> tmpkeyring.context.set_option('always-trust') <NEW_LINE> for (uid, signed_key) in sign_keydata(keydata, error_cb=error_cb, homedir=homedir): <NEW_LINE>... | Signs OpenPGP keydata with your regular GnuPG secret keys
and encrypts the result under the given key
error_cb can be a function that is called with any exception
occuring during signing of the key. | 625941ea9b70327d1c4e12a3 |
def parseOptions(): <NEW_LINE> <INDENT> parser=op.OptionParser(usage="Usage: %prog [options] JOBID" ,version="%prog 1.0",description="Run 'sacct --format=ALL' on the given job" +" and present the output in a row-based format instead of column-based so" +" it's easier to read.") <NEW_LINE> addParserOptions(parser) <NEW_... | Parses command line options
| 625941ea50485f2cf553d267 |
def label_new_product(df): <NEW_LINE> <INDENT> op = df.copy() <NEW_LINE> op['new_product'] = op.apply(lambda _: '', axis=1) <NEW_LINE> cols = op.columns <NEW_LINE> for i, row in df.iterrows(): <NEW_LINE> <INDENT> sku = row[cols.get_loc('MasterSKU')] <NEW_LINE> date = row[cols.get_loc('Requested_Date')].to_pydatetime().... | label orders of new product | 625941ea15fb5d323cde0fe2 |
@app.route('/anything') <NEW_LINE> @app.route('/anything/<path:anything>') <NEW_LINE> def view_anything(anything=None): <NEW_LINE> <INDENT> return jsonify(get_dict('url', 'args', 'headers', 'origin', 'method')) | Returns request data. | 625941ea7b25080760e39921 |
def _setUpStore(self): <NEW_LINE> <INDENT> self.siteStore = Store(filesdir=self.mktemp()) <NEW_LINE> Mantissa().installSite( self.siteStore, u"localhost", u"", generateCert=False) <NEW_LINE> site = self.siteStore.findUnique(SiteConfiguration) <NEW_LINE> ssls = list(site.store.query(SSLPort)) <NEW_LINE> ssls[0].portNumb... | Set up a store, install a L{HyperbolaPublicPresence} and its
dependencies, and create a role | 625941eaab23a570cc250652 |
def format_using_error(self, exc: Exception, _: str) -> str: <NEW_LINE> <INDENT> return str(exc) | Return string representation of the error. | 625941ea9c8ee82313fbbc42 |
def children(self, node): <NEW_LINE> <INDENT> if node.left != None: <NEW_LINE> <INDENT> yield node.left <NEW_LINE> <DEDENT> if node.right != None: <NEW_LINE> <INDENT> yield node.right | return children of node | 625941eae5267d203edce162 |
def load_data_and_labels(democrat_data_file, republican_data_file): <NEW_LINE> <INDENT> democrat_examples = list(open(democrat_data_file, "r", encoding='utf-8').readlines()) <NEW_LINE> democrat_examples = [s.strip() for s in democrat_examples] <NEW_LINE> republican_examples = list(open(republican_data_file, "r", encodi... | Loads Tweets from /data, splits the data into words and generates labels.
Returns split sentences and labels. | 625941ea925a0f43d254a347 |
@pytest.fixture() <NEW_LINE> def copydata(tmpdir, request): <NEW_LINE> <INDENT> srcpath = os.path.join(os.getenv("SAS_BASE_DIR"), request.param) <NEW_LINE> if not os.path.exists(srcpath): <NEW_LINE> <INDENT> pytest.skip('file does not exist cannot copy') <NEW_LINE> <DEDENT> sasdir = tmpdir / 'sas' <NEW_LINE> destpath =... | fixture to copy a file into a temporary directory | 625941ea56ac1b37e6264691 |
def test_dup_sim_hubs(self): <NEW_LINE> <INDENT> name = "dupsim" <NEW_LINE> mock = MockClusterConfigFile(self.cfgdir, name) <NEW_LINE> host = mock.add_host("host1") <NEW_LINE> _ = host.add_sim_hubs(15, 2, if_unused=True) <NEW_LINE> host.add_sim_hubs(10, 1) <NEW_LINE> mock.create() <NEW_LINE> if self.DEBUG: <NEW_LINE> <... | duplicate simHub lines at different priorities are allowed | 625941eade87d2750b860263 |
def getModulesToBeRigged(instanceList): <NEW_LINE> <INDENT> modulesToBeRiggedList = [] <NEW_LINE> allNamespaceList = cmds.namespaceInfo(listNamespace=True) <NEW_LINE> for guideModule in instanceList: <NEW_LINE> <INDENT> if guideModule.verifyGuideModuleIntegrity(): <NEW_LINE> <INDENT> guideNamespaceName = guideModule.gu... | Get all valid loaded modules to be rigged (They are valid instances with namespaces in the scene, then they are not deleted).
Return a list of modules to be rigged. | 625941ea5e10d32532c5f3f0 |
def column_set_table(column, table): <NEW_LINE> <INDENT> return column_from_parts(table, column_get_column(column)) | Given a string column, possibly containing a table, set the table.
>>> column_set_table('foo', 'bar')
'bar/@/foo'
>>> column_set_table('foo/@/bar', 'baz')
'baz/@/bar' | 625941ea07d97122c4178d62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.