code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def initialize_chain(test_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join("cache", "node0")): <NEW_LINE> <INDENT> devnull = open("/dev/null", "w+") <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> datadir=initialize_datadir("cache", i) <NEW_LINE> args = [ os.getenv("BITCOIND", "expediad"), "-keypool=1", "-... | Create (or copy from cache) a 200-block-long chain and
4 wallets.
expediad and expedia-cli must be in search path. | 625941e5b5575c28eb68e42a |
def get_lib(backend): <NEW_LINE> <INDENT> if backend in libs: <NEW_LINE> <INDENT> lib=libs[backend] <NEW_LINE> lib.initlib() <NEW_LINE> return lib <NEW_LINE> <DEDENT> raise ValueError("unrecognized backend '{}'; available backends are {}".format(backend,list(libs))) | Get and initialize library with the corresponding backend | 625941e58a43f66fc4b54487 |
def unquote(string): <NEW_LINE> <INDENT> return html.unescape(urllib.parse.unquote(string)) | Remove html escaping and urlencoding. | 625941e58da39b475bd6539f |
def charge(self): <NEW_LINE> <INDENT> if self.bet <= self.credit: <NEW_LINE> <INDENT> self.credit -= self.bet <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> machine.still() <NEW_LINE> print('\n\t Not enough credit to place a bet') <NEW_LINE> time.sleep(2) <NEW_LINE> return True | Checks if player has enough credit to place a bet
if not gives prompt and returns True so player will be able to lower bet
else it subtracts bet from player's credits | 625941e560cbc95b062c6969 |
def two_sum(nums, target): <NEW_LINE> <INDENT> my_dict = {} <NEW_LINE> for i in range(0, len(nums)): <NEW_LINE> <INDENT> complement = target - nums[i] <NEW_LINE> if complement in my_dict: <NEW_LINE> <INDENT> return [my_dict.get(complement), i] <NEW_LINE> <DEDENT> my_dict[nums[i]] = i <NEW_LINE> <DEDENT> return -1 | Problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
:type nums: List[int]
:type target: int
:rtype: List[int]
Solution:
Enroll all the nums in a d... | 625941e563f4b57ef0001533 |
def evaluate_linemod(generator, model, threshold=0.05): <NEW_LINE> <INDENT> results = [] <NEW_LINE> image_ids = [] <NEW_LINE> image_idx = [] <NEW_LINE> idx = 0 <NEW_LINE> for index in progressbar.progressbar(range(generator.size()), prefix='COCO evaluation: '): <NEW_LINE> <INDENT> image = generator.load_image(index) <N... | Use the pycocotools to evaluate a COCO model on a dataset.
Args
generator : The generator for generating the evaluation data.
model : The model to evaluate.
threshold : The score threshold to use. | 625941e5bde94217f3683213 |
def _leftMouseDragged(self, stopCoord, strCoord, speed): <NEW_LINE> <INDENT> app_psn = self._getPsnForPid(self._getPid()) <NEW_LINE> if strCoord == (0, 0): <NEW_LINE> <INDENT> loc = AppKit.NSEvent.mouseLocation() <NEW_LINE> strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y) <NEW_LINE> <DEDENT> app_psn = self._ge... | Private method to handle generic mouse left button dragging and
dropping.
Parameters: stopCoord(x,y) drop point
Optional: strCoord (x, y) drag point, default (0,0) get current
mouse position
speed (int) 1 to unlimit, simulate mouse moving
action from some special requirement
Returns: None | 625941e5009cb60464c637d4 |
def test_DSP1(self): <NEW_LINE> <INDENT> assert(True) | Test the DSP1 instruction | 625941e52eb69b55b151ccdb |
def sub_dict(d): <NEW_LINE> <INDENT> r = {} <NEW_LINE> for k in d: <NEW_LINE> <INDENT> if type(d[k]) in prims: <NEW_LINE> <INDENT> r[k] = d[k] <NEW_LINE> <DEDENT> elif type(d[k]) is list: <NEW_LINE> <INDENT> r[k] = sub_list(d[k]) <NEW_LINE> <DEDENT> elif type(d[k]) is dict: <NEW_LINE> <INDENT> r[k] = sub_dict(d[k]) <NE... | Recursively walk a data-structure sorting any lists along the way.
Any unknown types get mapped to string representation
:param d: dict
:return: dict where any lists, even those buried deep in the structure, have been sorted. | 625941e5091ae3566866737d |
def IsApplicable(self): <NEW_LINE> <INDENT> return 1 | PingFests are always applicable ;-)
| 625941e5d4950a0f3b08c76f |
def test_create_member(self): <NEW_LINE> <INDENT> logging.info("test_create_member start....") <NEW_LINE> driver = self.driver <NEW_LINE> driver.get(self.base_url) <NEW_LINE> driver.find_element_by_id("account").clear() <NEW_LINE> driver.find_element_by_id("account").send_keys("admin") <NEW_LINE> driver.find_element_by... | 添加成员测试用例 | 625941e5e5267d203edce0bd |
def is_tree(self, x): <NEW_LINE> <INDENT> return self.size(x)==self.edges[self.find(x)]+1 | 要素 x が属する族が木かどうかを判定する.
x: 要素 | 625941e596565a6dacc8faf0 |
def check_spelling(text): <NEW_LINE> <INDENT> incorrect = [] <NEW_LINE> length = 0 <NEW_LINE> words = tokenizer.tokenize(text) <NEW_LINE> for element in words: <NEW_LINE> <INDENT> length += 1 <NEW_LINE> if not hobj.spell(element): <NEW_LINE> <INDENT> incorrect.append(element) <NEW_LINE> <DEDENT> <DEDENT> return incorre... | creates a list of misspelled words in text
:param text: the text
:return: list of errors | 625941e5498bea3a759b9ed4 |
def get_facts_for_cluster(self, cluster_index): <NEW_LINE> <INDENT> return self.clusters_facts["clusters"][cluster_index]["facts"] | Gets all facts for a cluster identified by its index. Returns a list of dicts
:rtype: list | 625941e555399d3f05588add |
def __del__(self): <NEW_LINE> <INDENT> logger.debug("Destroying PCAP Writer.") <NEW_LINE> if self.pcap_writer is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.pcap_writer.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | Try to close our file nicely | 625941e599fddb7c1c9de7b5 |
@tf_export("random_crop") <NEW_LINE> def random_crop(value, size, seed=None, name=None): <NEW_LINE> <INDENT> with ops.name_scope(name, "random_crop", [value, size]) as name: <NEW_LINE> <INDENT> value = ops.convert_to_tensor(value, name="value") <NEW_LINE> size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="siz... | Randomly crops a tensor to a given size.
Slices a shape `size` portion out of `value` at a uniformly chosen offset.
Requires `value.shape >= size`.
If a dimension should not be cropped, pass the full size of that dimension.
For example, RGB images can be cropped with
`size = [crop_height, crop_width, 3]`.
Args:
va... | 625941e53317a56b8693a074 |
def load(self, dataset_path='datasets/CINIC-10', in_memory=True): <NEW_LINE> <INDENT> self.train_x = [] <NEW_LINE> self.train_y = [] <NEW_LINE> self.valid_x = [] <NEW_LINE> self.valid_y = [] <NEW_LINE> self.test_x = [] <NEW_LINE> self.test_y = [] <NEW_LINE> for idx, cls in enumerate(self.classes): <NEW_LINE> <INDENT> x... | load from dataset dir
:param dataset_path:
:param in_memory: true if you want to load all image in memory.
false only load images path. | 625941e5d8ef3951e3243964 |
def checkio(n, m): <NEW_LINE> <INDENT> return bin(n ^ m).count('1') | i = bin(n ^ m)
count = i.count('1')
return count | 625941e563d6d428bbe44917 |
def cut_depth(self): <NEW_LINE> <INDENT> zmax = 500 <NEW_LINE> shp = self.Vl.shape <NEW_LINE> if shp[0] >= zmax: <NEW_LINE> <INDENT> self.Vl = self.Vl[:500, :, :] <NEW_LINE> self.Vh = self.Vh[:500, :, :] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ext = zmax - shp[0] <NEW_LINE> self.Vl = np.concatenate([self.Vl, np.z... | cut Vl and Vh to 500 x 171 x 333 | 625941e5925a0f43d254a2a1 |
def select_next(self): <NEW_LINE> <INDENT> row = min(self.get_selected() + 1, len(self._store) - 1) <NEW_LINE> selection = self._view.get_selection() <NEW_LINE> selection.unselect_all() <NEW_LINE> selection.select_path(row) <NEW_LINE> self._moved = True <NEW_LINE> self._view.scroll_to_cell(row) | Select the next complete word. | 625941e53eb6a72ae02ec90e |
def my_documents(request, pk): <NEW_LINE> <INDENT> return render(request, 'library/my_documents_list.html', {'user': CustomUser.objects.get(id=pk)}) | View for listing document of user with given id.
:param request: HTTP request.
:param pk: user id.
:return: rendered page with list of user's documents. | 625941e51f5feb6acb0c4f6f |
def get_detection_zone_limits(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.PyX4M210_get_detection_zone_limits(self) | get_detection_zone_limits(PyX4M210 self) -> DetectionZoneLimits | 625941e5566aa707497f4989 |
def calculate_bldg_height(bldg_occsolid): <NEW_LINE> <INDENT> xmin,ymin,zmin,xmax,ymax,zmax = py3dmodel.calculate.get_bounding_box(bldg_occsolid) <NEW_LINE> height = zmax - zmin <NEW_LINE> return round(height,2) | This function calculates the building height of this building OCCsolid.
Parameters
----------
bldg_occsolid : OCCsolid
The OCCsolid that is a building to be analysed.
Returns
-------
height : float
The building height. | 625941e573bcbd0ca4b2c49b |
def test_setup_101_projects(self): <NEW_LINE> <INDENT> vlan = self._ou.get_next_free_vlan() <NEW_LINE> for i in range(101): <NEW_LINE> <INDENT> self.setup_project("seq%s" % i, vlan) | With new logic for more than 100 projects, setup 101 | 625941e582261d6c526ab8cc |
def clear_cache(self): <NEW_LINE> <INDENT> self._proc._init(self._proc.pid, _ignore_nsp=True) | Clear the cache of a Process instance. | 625941e5d6c5a10208144474 |
def network_lopf(network, snapshots=None, solver_name="glpk", solver_io=None, skip_pre=False, extra_functionality=None, solver_logfile=None, solver_options={}, keep_files=False, formulation="angles", ptdf_tolerance=0., free_memory={}): <NEW_LINE> <INDENT> snapshots = _as_snapshots(network, snapshots) <NEW_LINE> network... | Linear optimal power flow for a group of snapshots.
Parameters
----------
snapshots : list or index slice
A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
solver_name : string
Must be a solver name that pyomo recognises and that is
installed, e.g. "g... | 625941e51f5feb6acb0c4f70 |
def __init__(self, data): <NEW_LINE> <INDENT> self.data = data | Defines a waveform, with functions allowing calculation of
various degradation features.
:param data: | 625941e52ae34c7f2600d557 |
def set_rate(self,data_rate): <NEW_LINE> <INDENT> if data_rate == 0: <NEW_LINE> <INDENT> self.set_read_mode(1) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not data_rate in self.ADS1115_CONFIG_DATARATE: <NEW_LINE> <INDENT> raise ValueError("The data rate must be 0 or one from the list {}".format(s... | Set the reading rate for continuous conversion mode.
Does not change the mode unless data_rate =0, which sets mode to 1 (single conversion)
Parameters:
-----------
data_rate: int
Set the data rate for continuous mode. Must be one of
0, 8,16,32,64,128,250,475,860, with 0 forcing mode=1 | 625941e5bf627c535bc135f6 |
def zip_files(source_dir, dest_dir): <NEW_LINE> <INDENT> valid_plugins = get_valid_plugins(dest_dir) <NEW_LINE> for dirname in next(os.walk(source_dir))[1]: <NEW_LINE> <INDENT> if ((valid_plugins and dirname in valid_plugins) or not valid_plugins): <NEW_LINE> <INDENT> archive_path = os.path.join(dest_dir, dirname) <NEW... | Zip up plugin folders | 625941e51b99ca400220aeda |
def stdev_outliers(self, column_name, deviations=3, reject=False): <NEW_LINE> <INDENT> mean = self.columns[column_name].mean() <NEW_LINE> sd = self.columns[column_name].stdev() <NEW_LINE> lower_bound = mean - (sd * deviations) <NEW_LINE> upper_bound = mean + (sd * deviations) <NEW_LINE> if reject: <NEW_LINE> <INDENT> f... | A wrapper around :meth:`where` that filters the dataset to
rows where the value of the column are more than some number
of standard deviations from the mean.
This method makes no attempt to validate that the distribution
of your data is normal.
There are well-known cases in which this algorithm will
fail to identify ... | 625941e5379a373c97cfaf6d |
def combinationSum(self, candidates, target): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for i, num in enumerate(candidates): <NEW_LINE> <INDENT> self.backtrack(candidates, [num], i, target-num, result) <NEW_LINE> <DEDENT> return result | :type candidates: List[int]
:type target: int
:rtype: List[List[int]] | 625941e5de87d2750b8601bd |
def filter_listings(request, filter_term=None): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> if any(filter_term in country for country in COUNTRY_CHOICES): <NEW_LINE> <INDENT> filtered_listings = Listing.objects.filter( country=filter_term, start_date__lte=now, end_date__gte=now ).exclude(disabled=True).order_by... | Returns the charity listings for the selected country.
@param request: HttpRequest
@type filter_term: unicode
@param filter_term: Country or Letter selected
@rtype: HttpResponse
@return: listings filtered by selected country | 625941e5be383301e01b58a4 |
def import_query(path, **kwargs): <NEW_LINE> <INDENT> with open(path, 'r', **kwargs) as query_file: <NEW_LINE> <INDENT> query = query_file.read() <NEW_LINE> <DEDENT> return query | Essa função realiza o import de uma query, onde pode ser passado vários argumentos de import (read()) | 625941e56fece00bbac2db6a |
def _unescape(self, value): <NEW_LINE> <INDENT> if isinstance(value, (str,unicode)): <NEW_LINE> <INDENT> return value.replace(self._escape_character, '.') <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> return { self._unescape(k) : self._unescape(v) for k,v in value.items() } <NEW_LINE> <DEDENT> e... | Recursively unescape values. Though slower, this doesn't require the user to
know anything about the escaping when writing their own custom fetch functions. | 625941e54428ac0f6e5bac1c |
def getConcentrationsLines(equationDataArray, constants, timeInterval, intregrationInterval, initialConcentrations): <NEW_LINE> <INDENT> def pend(y, tAxis, equationDataArray, constants): <NEW_LINE> <INDENT> args = {} <NEW_LINE> for i in range(0, len(constants)): <NEW_LINE> <INDENT> args["k" + str(i + 1)] = constants[i]... | Calculates and return concentration lines(concentration of reagent vs. time)
Parameters:
equationdataArray (Array): Array of objects each containing sign of reagent(A,B...), function to get the value of dC(A,B...)
constants (array): 2d-array. Each item contains a unique set of speed constants for the chemical process
... | 625941e5dd821e528d63b5cc |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetPointer(self) | GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF3IF3 | 625941e58e05c05ec3eea79f |
def __init__(self, bounds=None): <NEW_LINE> <INDENT> self.input_dim = 3 <NEW_LINE> if bounds is None: <NEW_LINE> <INDENT> self.bounds = [[0, 1], [0, 1], [0, 1]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bounds = bounds <NEW_LINE> <DEDENT> self.min = [0, 0, 0] <NEW_LINE> self.fmin = -4 <NEW_LINE> self.name = 'x... | :param bounds: 函数各维度的取值区间,用二维数组表示 | 625941e5ab23a570cc2505ac |
def get_detailed_submission_sets(self, place): <NEW_LINE> <INDENT> request = self.context['request'] <NEW_LINE> submission_sets = self.get_submission_sets(place) <NEW_LINE> details = {} <NEW_LINE> for set_name, submissions in submission_sets.iteritems(): <NEW_LINE> <INDENT> user = getattr(request, 'user', None) <NEW_LI... | Get a mapping from place id to a detiled submission set dictionary.
Get this for the entire dataset at once. | 625941e567a9b606de4a82de |
def _shorten_url(self, msg, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> return "You must provide a URL to shorten" <NEW_LINE> <DEDENT> params = {'signature': self._surl_sig, 'url': args, 'action': 'shorturl', 'format': 'json'} <NEW_LINE> request = requests.get(self._surl_api, params=params) <NEW_LINE> ... | Shorten a URL with the http://kurzma.ch URL shortener
shorturl http://myurl.com
| 625941e54f6381625f114e62 |
def poll(self): <NEW_LINE> <INDENT> self._logger.debug('[MonitoringMailbox]: entering poll') <NEW_LINE> self.poll_mailbox() | This Method is CRUX of system, it is called on every poll interval | 625941e54527f215b584c879 |
def p_else(p): <NEW_LINE> <INDENT> pass | else : ELSE BEGIN statement END SEMICOLON | 625941e55fcc89381b1e1ae8 |
def run(self): <NEW_LINE> <INDENT> print('Starting service.') <NEW_LINE> connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) <NEW_LINE> channel = connection.channel() <NEW_LINE> channel.queue_declare(queue='email_service') <NEW_LINE> print(' [*] Waiting for messages. Press CTRL+C to exit.') <N... | TODO Make this useful.
This is a method of Service. | 625941e53cc13d1c6d3c779f |
def countAndSay(self, n): <NEW_LINE> <INDENT> sequence = [1] <NEW_LINE> for _ in range(n-1): <NEW_LINE> <INDENT> next = [] <NEW_LINE> for num in sequence: <NEW_LINE> <INDENT> if not next or next[-1] != num: <NEW_LINE> <INDENT> next += [1, num] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> next[-2] += 1 <NEW_LINE> <DEDE... | :type n: int
:rtype: str | 625941e566673b3332b924b8 |
def SubscribeAllOptionTickByTick(self, exchange_id: XTP_EXCHANGE_TYPE): <NEW_LINE> <INDENT> return super().SubscribeAllOptionTickByTick(exchange_id) | 订阅全市场的期权逐笔行情
@remark 需要与全市场退订期权逐笔行情接口配套使用
:param exchange_id: 表示当前全订阅的市场,如果为XTP_EXCHANGE_UNKNOWN,表示沪深全市场,XTP_EXCHANGE_SH表示为上海全市场,XTP_EXCHANGE_SZ表示为深圳全市场
:return: 订阅全市场期权逐笔行情接口调用是否成功,“0”表示接口调用成功,非“0”表示接口调用出错 | 625941e51d351010ab855f42 |
def create_armor(self): <NEW_LINE> <INDENT> armor_name = input("What is the armor name?") <NEW_LINE> armor_health = input("What's the armor's max health?") <NEW_LINE> return Weapon(armor_name, armor_health) | Prompt user for Armor information
return Armor with values from user input. | 625941e5ec188e330fd5abbe |
@click.command() <NEW_LINE> @click.option( "shape", "--shape1", flag_value=shape1, default=True, help="Default small ship" ) <NEW_LINE> @click.option("shape", "--shape2", flag_value=shape2, help="Large ship, using colors") <NEW_LINE> @click.option( "shape", "--custom", type=str, ) <NEW_LINE> @click.option( "resolution"... | Quick example to navigate an string-defined shape through
the terminal using the arrow keys! Press <ESC> to exit.
Usage example:
$ terminedia-shapes --custom=" \n *** \n * * \n *** " | 625941e5be8e80087fb21063 |
def update(self, old_lines, new_lines): <NEW_LINE> <INDENT> LOG.debug('diff parser start') <NEW_LINE> self._module._used_names = None <NEW_LINE> self._parser_lines_new = new_lines <NEW_LINE> self._reset() <NEW_LINE> line_length = len(new_lines) <NEW_LINE> sm = difflib.SequenceMatcher(None, old_lines, self._parser_lines... | The algorithm works as follows:
Equal:
- Assure that the start is a newline, otherwise parse until we get
one.
- Copy from parsed_until_line + 1 to max(i2 + 1)
- Make sure that the indentation is correct (e.g. add DEDENT)
- Add old and change positions
Insert:
- Parse from parsed_until_line +... | 625941e58e7ae83300e4b3f5 |
def compute_graph_scores(dg): <NEW_LINE> <INDENT> graph_score_dict = {} <NEW_LINE> for node in dg.nodes(data=False): <NEW_LINE> <INDENT> out_weights_acc = 0 <NEW_LINE> in_weights_acc = 0 <NEW_LINE> for succ in dg.successors(node): <NEW_LINE> <INDENT> out_weights_acc += dg.get_edge_data(node,succ)['weight'] <NEW_LINE> <... | Computes score for each generated image (node in the graph)
based on the weight and direction of the edges | 625941e5b545ff76a891423c |
def getColors(self, colorSetName='None'): <NEW_LINE> <INDENT> pass | This method gets the color of the each vertex in the current face.
Parameters:
colorSetName : 'unicode'
Name of the color set.
Returns:
List['Color']
Derived from api method `maya.OpenMaya.MItMeshPolygon.getColors` | 625941e57cff6e4e81117dac |
def __init__(self, path, port, server, isv): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> self._port = port <NEW_LINE> self._server = server <NEW_LINE> self._isv = isv | Construction | 625941e5796e427e537b09f0 |
def parse_word(token_string): <NEW_LINE> <INDENT> if ' ' in token_string: <NEW_LINE> <INDENT> return token_string.split(' ', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return token_string, '' | Parse a single word from a token string. | 625941e5a79ad161976cc56c |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.mentor.profile is self.mentee.profile: <NEW_LINE> <INDENT> raise ValidationError("Mentor and Mentee cannot be same user.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(Pairing, self).save(*args, **kwargs) | Overwrite save method.
We want to prevent saving a Pairing if a mentor and mentee are the same
user. | 625941e5e64d504609d74c67 |
def get_language(obj): <NEW_LINE> <INDENT> if len([c for c in obj if c in GREEK_ALPHABET]) > 0: <NEW_LINE> <INDENT> return 'greek' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'latin' | Determines language of input text | 625941e5e8904600ed9f235a |
def get(self, _id=None, short_id=None): <NEW_LINE> <INDENT> if _id: <NEW_LINE> <INDENT> cur = self.mdb.find_one({'_id': _id}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur = self.mdb.find_one({'short_id': short_id}) <NEW_LINE> if not cur: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> _id = cur['_id'] <NEW_LIN... | if url is given, we need a reverse lookup in metadata. Returns
a GridOut/bookmark with additional metadata added. | 625941e57cff6e4e81117dad |
def sanitize_token(self, token): <NEW_LINE> <INDENT> if token['type'] in (tokenTypes['StartTag'], tokenTypes['EndTag'], tokenTypes['EmptyTag']): <NEW_LINE> <INDENT> if token['name'] in self.allowed_elements: <NEW_LINE> <INDENT> if 'data' in token: <NEW_LINE> <INDENT> if isinstance(self.allowed_attributes, dict): <NEW_L... | Sanitize a token either by HTML-encoding or dropping.
Unlike HTMLSanitizerMixin.sanitize_token, allowed_attributes can be
a dict of 'tag' => ['attribute', 'pairs'].
Also gives the option to strip tags instead of encoding. | 625941e582261d6c526ab8cd |
def write_remap_script(subst, output_folder): <NEW_LINE> <INDENT> subst = {k: v for k, v in subst.items() if k != v} <NEW_LINE> if len(subst) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> s = """find . -name "*.tex" -exec sed -i 's/{0}/{1}/g' {{}} \\;""" <NEW_LINE> outfile = os.path.join(output_folder, "remap.sh... | Write a bash script to replace old bibtex keys by new ones. | 625941e5711fe17d82542789 |
def clear_text(self): <NEW_LINE> <INDENT> self.part_entry.delete(0, tk.END) <NEW_LINE> self.customer_entry.delete(0, tk.END) <NEW_LINE> self.retailer_entry.delete(0, tk.END) <NEW_LINE> self.price_entry.delete(0, tk.END) <NEW_LINE> self.parts_list.select_clear(0, tk.END) | Clear all text fields | 625941e5cdde0d52a9e5345d |
def naive_longest_palindromic_substring(self, s): <NEW_LINE> <INDENT> longest_palindrome = "" <NEW_LINE> n = len(s) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> if i <= j: <NEW_LINE> <INDENT> substring_length = len(s[i:j+1]) <NEW_LINE> if substring_length == 1 and ... | Have a nested for loop to go through all possible substrings. Then use
another loop to verify that the substring is a palindrome,
Time Complexity: O(n^3) | 625941e5f548e778e58cd9a6 |
def set_geom_opt_coords_type(self, coords_type="internal_switch"): <NEW_LINE> <INDENT> coords_map = {"cartesian": 0, "internal": 1, "internal-switch": -1, "z-matrix": 2, "z-matrix-switch": -2} <NEW_LINE> if coords_type.lower() not in set(coords_map.keys()): <NEW_LINE> <INDENT> raise ValueError("Coodinate system " + coo... | Set the coordinates system used in geometry optimization.
"cartesian" --- always cartesian coordinates.
"internal" --- always internal coordinates.
"internal-switch" --- try internal coordinates first, if fails, switch
to cartesian coordinates.
"z-matrix" --- always z-matrix coordinates.
"z-matrix-s... | 625941e5956e5f7376d71293 |
def put(self, key, value): <NEW_LINE> <INDENT> if not self.capacity: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if key in self.key_node: <NEW_LINE> <INDENT> node = self.key_node[key] <NEW_LINE> node.val = value <NEW_LINE> self.update_node(node) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE... | :type key: int
:type value: int
:rtype: void | 625941e530bbd722463cc1ef |
def feed(self, pattern, datum): <NEW_LINE> <INDENT> if pattern in self.hooks[FILTER]: <NEW_LINE> <INDENT> if any(filter_(datum) for filter_ in self.hooks[FILTER][pattern]): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> if pattern not in self.data: <NEW_LINE> <INDENT> self.data[pattern] = tempfi... | Adds a new item to the data set | 625941e50a366e3fb873ec45 |
def get_empf(self): <NEW_LINE> <INDENT> return self.empf.reshape((-1,) + self.shape) | empirical distribution | 625941e5f7d966606f6aa430 |
def get_current_repo_name(): <NEW_LINE> <INDENT> repo = get_current_repo() <NEW_LINE> return re.match(u'git@git.sbis.ru:(.+)\.git', repo.remote().url).groups()[0] | Получить название текущего репозитория | 625941e523849d37ff7b34b3 |
def terminate(self, dry_run=False): <NEW_LINE> <INDENT> instance_id = self.instance_id <NEW_LINE> response = self.ec2_client.terminate_instances( InstanceIds=[ instance_id, ], DryRun=dry_run ) <NEW_LINE> instance = self.ec2_resource.Instance(instance_id) <NEW_LINE> instance.delete_tags(Tags=[{'Key': 'Name'}]) | Terminate the instance.
After triggering termination, removes the 'Name' tag from the instance, which allows you to immediately launch a
new node with the same Name.
Args:
dry_run (bool): Make EC2 API call as a test. | 625941e5a8370b7717052cc5 |
def state_machine(state_factory, transition_func): <NEW_LINE> <INDENT> def sm(ctx, s_id_vec=tuple(), evt=None): <NEW_LINE> <INDENT> state = None <NEW_LINE> state_id = s_id_vec[-1] if s_id_vec else None <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> next_state_id = transition_func(ctx, (state_id, ev... | Return a state machine generator function. | 625941e5d53ae8145f87a68f |
def is_ip_in_range(self, start_ip, end_ip, ip_to_test): <NEW_LINE> <INDENT> start = self.get_ip_as_number(start_ip) <NEW_LINE> end = self.get_ip_as_number(end_ip) <NEW_LINE> ip = self.get_ip_as_number(ip_to_test) <NEW_LINE> return start <= ip and ip <= end | Check whether ip_to_test belongs to IP range between start_ip and end_ip
| 625941e5d4950a0f3b08c770 |
def removeUser(self, username): <NEW_LINE> <INDENT> self.storage.remove(username) <NEW_LINE> self.storage.remove('lasso-' + username) | Clean ups storage data | 625941e566656f66f7cbc5d4 |
def search_app(): <NEW_LINE> <INDENT> keyboard.hotkey('ALT', 'F2') | Run an application by typing
:return: | 625941e5090684286d50f113 |
def prepend(self, item): <NEW_LINE> <INDENT> new_node = Node(item) <NEW_LINE> if self.head is not None: <NEW_LINE> <INDENT> new_node.next = self.head <NEW_LINE> self.head = new_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.head = new_node <NEW_LINE> self.tail = new_node | Insert the given item at the head of this linked list.
TODO: Running time: O(1) Why and under what conditions? | 625941e526068e7796caf10c |
def tick(self, framerate=0): <NEW_LINE> <INDENT> if self.pos < 9: <NEW_LINE> <INDENT> self.pos += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pos = 0 <NEW_LINE> <DEDENT> self.time = System.nanoTime()/1000000 <NEW_LINE> self.time_diff[self.pos] = (self.time-self.time_init) <NEW_LINE> self.time_init = self.time ... | Call once per program cycle, returns ms since last call.
An optional framerate will add pause to limit rate. | 625941e5236d856c2ad44c07 |
def __init__(self, low=0, high=0, name='', value=None, mutate=None): <NEW_LINE> <INDENT> self.low = low <NEW_LINE> self.high = high <NEW_LINE> self.name = name <NEW_LINE> self.value = value <NEW_LINE> self.immutable = True if value is not None else False <NEW_LINE> self.mutateCollections = {'mutateRandomRangedFloat': s... | ElementDescription initializer.
:param double low: minimum value for this element; OPTIONAL if immutable value specified.
:param double high: maximum value for this element; OPTIONAL if immutable value specified.
:param str name: OPTIONAL - the name of the element.
:param double value: OPTIONAL - immutable value for t... | 625941e5f9cc0f698b140a1f |
def unpack_batch(batch, use_cuda): <NEW_LINE> <INDENT> if use_cuda: <NEW_LINE> <INDENT> inputs = [b.cuda() if b is not None else None for b in batch[:4]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inputs = [b if b is not None else None for b in batch[:4]] <NEW_LINE> <DEDENT> orig_idx = batch[4] <NEW_LINE> return inp... | Unpack a batch from the data loader. | 625941e5d58c6744b4258085 |
def colorThreshFor(self, category, value): <NEW_LINE> <INDENT> if not self.thresholds.get(category): <NEW_LINE> <INDENT> return 'unknown category %s' % category <NEW_LINE> <DEDENT> if not self.thresholds[category].get('green'): <NEW_LINE> <INDENT> return 'missing entry green for %s' % category <NEW_LINE> <DEDENT> if no... | Return color for value and category, determined by threshold. | 625941e5eab8aa0e5d26df81 |
def put(self, enc_obs, actions, rewards, mus, dones): <NEW_LINE> <INDENT> if self.enc_obs is None: <NEW_LINE> <INDENT> self.enc_obs = np.empty([self.size] + list(enc_obs.shape), dtype=self.obs_dtype) <NEW_LINE> self.actions = np.empty([self.size] + list(actions.shape), dtype=np.int32) <NEW_LINE> self.rewards = np.empty... | Adds a frame to the buffer
:param enc_obs: ([float]) the encoded observation
:param actions: ([float]) the actions
:param rewards: ([float]) the rewards
:param mus: ([float]) the policy probability for the actions
:param dones: ([bool])
:param masks: ([bool]) | 625941e5d268445f265b5296 |
def pair(self, w1, w2): <NEW_LINE> <INDENT> return min(w1, w2), max(w1, w2) | Given two words, returns the words as a sorted tuple where w1 <= w2
:param w1: string
:param w2: string
:return: sorted word pair | 625941e59f2886367277acb1 |
def get_tweet_obj(tweet): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if 'quoted_status' in tweet: <NEW_LINE> <INDENT> return get_tweet_obj(tweet['quoted_status']) <NEW_LINE> <DEDENT> if 'retweeted_status' in tweet: <NEW_LINE> <INDENT> return get_tweet_obj(tweet['retweeted_status']) <NEW_LINE> <DEDENT> <DEDENT> except... | Retrieve the inner most tweet information.
Quoted tweet gets preference over retweeted status.
Args:
tweet: The current level of tweet obj.
Returns:
tweet (json obj): The inner most tweet obj. | 625941e526238365f5f0f29b |
def submit_offline_reports(self): <NEW_LINE> <INDENT> smtp_enabled = bool(self._smtp) <NEW_LINE> hq_enabled = bool(self._hq) <NEW_LINE> offline_reports = self.get_offline_reports() <NEW_LINE> logging.info('Submitting %d offline crash reports' % len(offline_reports)) <NEW_LINE> offline_reports = offline_reports[:self.se... | Submit offline reports using the enabled methods (SMTP and/or HQ)
Returns a tuple of (N sent reports, N remaining reports) | 625941e5bf627c535bc135f7 |
def selectJrand(i, m): <NEW_LINE> <INDENT> j = i <NEW_LINE> while (j == i): <NEW_LINE> <INDENT> j = int(random.uniform(0, m)) <NEW_LINE> <DEDENT> return j | Functions:
choose the alpha casually
:param i: alpha_i
:param m: alpha参数个数
:return:
j - alpha_j
Modify:
2018-09-13 | 625941e53c8af77a43ae3bcc |
def executa(self): <NEW_LINE> <INDENT> self.player.play(self.arquivo) | Executa o comando para tocar a música. | 625941e5de87d2750b8601be |
def testBuildArgumentList_014(self): <NEW_LINE> <INDENT> options = Options() <NEW_LINE> options.ignoreWarnings = True <NEW_LINE> argumentList = options.buildArgumentList(validate=False) <NEW_LINE> self.assertEqual(["--ignoreWarnings"], argumentList) | Test with ignoreWarnings set, validate=False. | 625941e597e22403b379d3c3 |
def __init__(self, *objects, **kwargs): <NEW_LINE> <INDENT> self.resources = [] <NEW_LINE> self.contexts = Contexts() <NEW_LINE> self.summary = Summary() <NEW_LINE> self.results = Results() <NEW_LINE> self.perfdata = [] <NEW_LINE> if 'name' in kwargs and kwargs['name'] != '': <NEW_LINE> <INDENT> self.name = kwargs['nam... | Creates and configures a check.
Specialized *objects* representing resources, contexts,
summary, or results are passed to the the :meth:`add` method.
Alternatively, objects can be added later manually.
If no *name* is given, the output prefix is set to the first
resource's name. If *name* is None, no prefix is set at ... | 625941e529b78933be1e5ace |
def generate(self, **kwargs): <NEW_LINE> <INDENT> namespace = { "escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "datetime": datetime, } <NEW_LINE> namespace.update(kwargs) <NEW_LINE> exec(self.compiled, namespace) <NEW_LINE> execute = namespa... | Generate this template with the given arguments. | 625941e515fb5d323cde0f3d |
def check_file_list_cache(opts, form, list_cache, w_lock): <NEW_LINE> <INDENT> refresh_cache = False <NEW_LINE> save_cache = True <NEW_LINE> serial = salt.payload.Serial(opts) <NEW_LINE> wait_lock(w_lock, list_cache, 5 * 60) <NEW_LINE> if not os.path.isfile(list_cache) and _lock_cache(w_lock): <NEW_LINE> <INDENT> refre... | Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written). | 625941e53c8af77a43ae3bcd |
def vitoria_bloqueio_123(t, l, c, i, p, j, res, fn): <NEW_LINE> <INDENT> if eh_posicao_livre(t, cria_posicao(c[i], l)): <NEW_LINE> <INDENT> possivel_pos = p[i] <NEW_LINE> del p[i] <NEW_LINE> if pecas_iguais( obter_peca(t, cria_posicao(c[p[0]], l)), obter_peca(t, cria_posicao(c[p[1]], l)), ): <NEW_LINE> <INDENT> if ( no... | tabuleiro x linha x coluna x inteiro x lista x peca x tuplo x str --> tuplo
devolve um tuplo com as possiveis posicoes de vitoria caso o argumento fn
seja 'vitoria' ou as posicoes de bloqueio caso fn seja 'bloqueio' | 625941e50a366e3fb873ec46 |
def add_child(self, value): <NEW_LINE> <INDENT> new_node = Tree(value) <NEW_LINE> self.children.append(new_node) <NEW_LINE> return new_node | Append new child node to the tree.
Creates new tree node with the specified value and appends it
to the current tree child nodes list.
Args:
value (any): appended tree root node value.
Returns:
Tree: created Tree instance. | 625941e55fcc89381b1e1ae9 |
def update_data(self): <NEW_LINE> <INDENT> self.episode_over = self.environment.get_done() <NEW_LINE> self.update_controller_data() <NEW_LINE> self.update_meta_controller_data() | Updates stored data for controller and meta-controller. It must occur in the order shown | 625941e5097d151d1a22327f |
def test_tags_view_updated_min_display_limit_page_links(self,tag_with_items): <NEW_LINE> <INDENT> self.tag_name = tag_with_items <NEW_LINE> po = self.catalog.load_pageobject('TagsPage') <NEW_LINE> po.goto_page() <NEW_LINE> po.search_for_content([self.tag_name]) <NEW_LINE> po = self.catalog.load_pageobject('TagsViewPage... | on /tags/view, change the display limit to min and
check footer for page links | 625941e5377c676e912725cf |
def fix_missing_remotefiles(localox, missing_remotefileparents): <NEW_LINE> <INDENT> log.error("Fixing remotes, since -f/--fix was specified") <NEW_LINE> log.error("WARNING: Oxygen needs to be running to have changes synced up") <NEW_LINE> log.debug("%s", missing_remotefileparents) <NEW_LINE> for dirname in missing_rem... | Given a list of dirs, try to 'fix' it. Oxygen remote may be missing things | 625941e529b78933be1e5acf |
def login(self, auth: str = 'multistep') -> None: <NEW_LINE> <INDENT> if auth == 'basic': <NEW_LINE> <INDENT> self.basic_login() <NEW_LINE> <DEDENT> elif auth == 'multistep': <NEW_LINE> <INDENT> self.get_session_id() <NEW_LINE> self.check_login() <NEW_LINE> self.check_password() <NEW_LINE> self.finish_auth() <NEW_LINE>... | Combined log-in method with both basic and multistep authentication
support.
:param auth: authentication type: "basic", "multistep"
:type auth: str | 625941e5d7e4931a7ee9e347 |
def __hash__(self): <NEW_LINE> <INDENT> return self._hash_value | Get the hash value of the lowercased string. | 625941e592d797404e3045b4 |
def copy_treemodel(orig): <NEW_LINE> <INDENT> column_types = [] <NEW_LINE> column_numbers = range(orig.get_n_columns()) <NEW_LINE> for i in column_numbers: <NEW_LINE> <INDENT> column_types.append(orig.get_column_type(i)) <NEW_LINE> <DEDENT> copy = Gtk.TreeStore(*column_types) <NEW_LINE> return copy | Create a new treemodel with the same columns as model | 625941e5b545ff76a891423d |
def calculate_end_of_barrel(self, player): <NEW_LINE> <INDENT> mouse_position = player.mouse_position <NEW_LINE> gun_position_vector = get_vector_to_position(mouse_position, self.window_position_center) <NEW_LINE> theta = self.roto_theta_conversion_tool_extreme(gun_position_vector) + 90 <NEW_LINE> x_offset = self.serve... | calculates the bullet's spawn location | 625941e571ff763f4b549aba |
@login_required <NEW_LINE> def messages(request, username): <NEW_LINE> <INDENT> userdata = get_object_or_404( UserData, user=UserModel.objects.get(username__iexact=username) ) <NEW_LINE> if not can_modify(request, userdata.id): <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> messages = userdata.get_messa... | Returns user messages.
Uses get_messages() method of Userdata model instead of accessing
messages directly. | 625941e560cbc95b062c696b |
def text(self): <NEW_LINE> <INDENT> return f"user_path_hash = {self.val}" | Predicate's representation. | 625941e5d4950a0f3b08c771 |
def show_properties(self): <NEW_LINE> <INDENT> pass | Override to show the page's properties dialog.
| 625941e5711fe17d8254278a |
def create_map_from_pdb_and_mtz ( pdb_file, mtz_file, output_file, fill=False, out=None, llg_map=False, remove_unknown_scatterering_type=False, assume_pdb_data=False) : <NEW_LINE> <INDENT> if (out is None) : out = sys.stdout <NEW_LINE> from iotbx import file_reader <NEW_LINE> from scitbx.array_family import flex <NEW_L... | Convenience function, used by phenix.fetch_pdb.
:param remove_unknown_scatterering_type: if True, atoms with unknown
scattering type will be removed before extracting the X-ray structure
(which would crash otherwise). | 625941e5ac7a0e7691ed44ec |
def test_from_operator(self): <NEW_LINE> <INDENT> for tup in it.product(['I', 'X', 'Y', 'Z'], repeat=2): <NEW_LINE> <INDENT> label = ''.join(tup) <NEW_LINE> with self.subTest(msg=label): <NEW_LINE> <INDENT> spp_op = SparsePauliOp.from_operator(Operator(pauli_mat(label))) <NEW_LINE> self.assertTrue(np.array_equal(spp_op... | Test from_operator methods. | 625941e510dbd63aa1bd2fca |
def excess(self): <NEW_LINE> <INDENT> def excess_odd(mono): <NEW_LINE> <INDENT> if not mono: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return len(mono[0]) + 2 * sum(mono[1]) <NEW_LINE> <DEDENT> <DEDENT> p = self.prime() <NEW_LINE> a = self.milnor() <NEW_LINE> if not self.parent()._gener... | Excess of element.
OUTPUT: ``excess`` - non-negative integer
The excess of a Milnor basis element `\text{Sq}(a,b,c,...)` is
`a + b + c + \cdots`. When `p` is odd, the excess of `Q_{0}^{e_0}
Q_{1}^{e_1} \cdots P(r_1, r_2, ...)` is `\sum e_i + 2 \sum r_i`.
The excess of a linear combination of Milnor basis elements is
... | 625941e58e71fb1e9831dbd0 |
def _read_molecule(stream, transform_unit): <NEW_LINE> <INDENT> line = stream.readline() <NEW_LINE> while not line.strip() and len(line): <NEW_LINE> <INDENT> line = stream.readline() <NEW_LINE> <DEDENT> n_atoms = int(line) <NEW_LINE> properties = re.split(r'\s+', stream.readline().strip()) <NEW_LINE> atoms = [] <NEW_LI... | Reads molecule structures in XYZ file stream.
Note: this function assumes XYZ file coordinates in Angstrom unit.
:param stream: Stream of XYZ file.
:param transform_unit: Transform values into different unit.
:return: A molecular structure. | 625941e5cad5886f8bd27401 |
def _process_autoclave(text, key, decrypt=False): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> res = [] <NEW_LINE> limit = len(key) <NEW_LINE> if decrypt: <NEW_LINE> <INDENT> nKey = list(key) <NEW_LINE> last = 0 <NEW_LINE> for c in text: <NEW_LINE> <INDENT> if c in WHITESMAP: <NEW_LINE> <INDENT> res.append(c) <NEW_LINE> <D... | cypher or decypher text with key using the autoclave-cypher | 625941e599fddb7c1c9de7b7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.