code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@app.cli.command('resetdb') <NEW_LINE> @click.pass_context <NEW_LINE> def reset_db(ctx): <NEW_LINE> <INDENT> ctx.invoke(drop_db) <NEW_LINE> ctx.invoke(init_db) <NEW_LINE> ctx.invoke(seed_db) | Drops, initializes, then seeds tables with data | 625941be07d97122c417879e |
def text_features_grouped(file_name): <NEW_LINE> <INDENT> print("--------Grouped Features---------\n") <NEW_LINE> from sklearn.feature_extraction.text import CountVectorizer <NEW_LINE> with open(os.getcwd() + "/data/datafinal_60-16.json") as data_file: <NEW_LINE> <INDENT> data = json.load(data_file) <NEW_LINE> <DEDENT> keyWords = [] <NEW_LINE> budgets = [] <NEW_LINE> revenues = [] <NEW_LINE> for movie in data: <NEW_LINE> <INDENT> if len(movie["keywords"]["keywords"]) > 0 and int(movie["inf_revenue"]) > 1000000 and int(movie["inf_budget"]) > 1000000: <NEW_LINE> <INDENT> stringKeywords = "" <NEW_LINE> for kw in movie["keywords"]["keywords"]: <NEW_LINE> <INDENT> stringKeywords = stringKeywords + " " + kw["name"] <NEW_LINE> <DEDENT> keyWords.append(stringKeywords) <NEW_LINE> budgets.append(float(movie["inf_budget"])) <NEW_LINE> revenues.append(float(movie["inf_revenue"])) <NEW_LINE> <DEDENT> <DEDENT> count_vectorizer = CountVectorizer() <NEW_LINE> counts = count_vectorizer.fit_transform(keyWords) <NEW_LINE> bd = np.array(budgets) <NEW_LINE> rev = np.array(revenues) <NEW_LINE> rev = rev[:,np.newaxis] <NEW_LINE> ca = counts.toarray() <NEW_LINE> regr = lm.LinearRegression() <NEW_LINE> regr.fit(ca, rev) <NEW_LINE> print("REV SHAPE: ", rev.shape) <NEW_LINE> print("Count Array Shape: ", ca.shape) | - Open JSON file and get unique set of words
Parameters
----------
file_name: String
Returns
-------
None
Examples
--------
>>> text_features_grouped(file_name)
tuple(X, Y) | 625941be4a966d76dd550f25 |
def _ConvertMapFieldValue(self, value, message, field): <NEW_LINE> <INDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> raise ParseError( 'Map field {0} must be in a dict which is {1}.'.format( field.name, value)) <NEW_LINE> <DEDENT> key_field = field.message_type.fields_by_name['key'] <NEW_LINE> value_field = field.message_type.fields_by_name['value'] <NEW_LINE> for key in value: <NEW_LINE> <INDENT> key_value = _ConvertScalarFieldValue(key, key_field, True) <NEW_LINE> if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: <NEW_LINE> <INDENT> self.ConvertMessage(value[key], getattr( message, field.name)[key_value]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getattr(message, field.name)[key_value] = _ConvertScalarFieldValue( value[key], value_field) | Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
Raises:
ParseError: In case of convert problems. | 625941be507cdc57c6306bed |
def init_model_(model, init_method): <NEW_LINE> <INDENT> get_initializer(init_method) <NEW_LINE> model.apply(_init) <NEW_LINE> logger.info("Init params with: {}".format(init_method)) | Usage:
from initializer import init_model_
model = Model()
init_method = hoge
init_model_(model, init_method) | 625941be6fb2d068a760efb3 |
def hasCalibration(self, thermistors): <NEW_LINE> <INDENT> if not self.calibration: <NEW_LINE> <INDENT> print("Missing calibration file") <NEW_LINE> return False <NEW_LINE> <DEDENT> missing = [] <NEW_LINE> for name in thermistors: <NEW_LINE> <INDENT> if not self.calibration[name]: <NEW_LINE> <INDENT> missing.append(name) <NEW_LINE> <DEDENT> <DEDENT> if len(missing) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> print('\n'.join(map(str, missing))) <NEW_LINE> return False | checks if a list of thermistors (names) have calibration data | 625941be8da39b475bd64e89 |
def test_tuple_normalized_rgb(self): <NEW_LINE> <INDENT> colour1 = colourettu.Colour( (0.5656023325553875, 0.8070789468680986, 0.8006291331865334), normalized_rgb=True, ) <NEW_LINE> self.assertEqual(colour1.hex(), "#90CDCC") | Get value of colour given as a tuple of normalized rgb values | 625941be7d847024c06be1d1 |
def success(self, *args: Any, **kwargs: Any) -> None: <NEW_LINE> <INDENT> super(WolfLogger, self).log(SUCCESS, *args, **kwargs) | Logs a success message. | 625941be23e79379d52ee47f |
def _equ(s, P, Q): <NEW_LINE> <INDENT> return P[0] * Q[1] == P[1] * Q[0] | Is P equals to Q? | 625941bed486a94d0b98e05d |
def _resize_columns(self): <NEW_LINE> <INDENT> self.table.column('#0', width=36) <NEW_LINE> for head, width in self.headings.items(): <NEW_LINE> <INDENT> self.table.column(head, width=width) | Resize columns in treeview. | 625941bede87d2750b85fca8 |
def walk_up(start, sentinel): <NEW_LINE> <INDENT> from os.path import abspath, exists, isdir, join, dirname <NEW_LINE> current = abspath(start) <NEW_LINE> if not exists(current) or not isdir(current): <NEW_LINE> <INDENT> raise OSError('Invalid directory "%s"' % current) <NEW_LINE> <DEDENT> previouspath = None <NEW_LINE> found = False <NEW_LINE> while not found and current is not previouspath: <NEW_LINE> <INDENT> clue = join(current, sentinel) <NEW_LINE> if exists(clue): <NEW_LINE> <INDENT> found = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> previouspath = current <NEW_LINE> current = dirname(current) <NEW_LINE> <DEDENT> <DEDENT> return current if found else None | Given a `start` directory walk-up the file system tree until either the
FS root is reached or the `sentinel` is found.
The `sentinel` must be a string containing the file name to be found.
.. warning:: If `sentinel` is an absolute path that exists this will return
`start`, no matter what `start` is (in windows this could be even
different drives).
If `start` path exists but is not a directory an OSError is raised. | 625941be4c3428357757c242 |
def set_gpu_fraction(sess=None, gpu_fraction=0.3): <NEW_LINE> <INDENT> print(" tensorlayer: GPU MEM Fraction %f" % gpu_fraction) <NEW_LINE> gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction) <NEW_LINE> sess = tf.Session(config = tf.ConfigProto(gpu_options = gpu_options)) <NEW_LINE> return sess | Set the GPU memory fraction for the application.
Parameters
----------
sess : a session instance of TensorFlow
TensorFlow session
gpu_fraction : a float
Fraction of GPU memory, (0 ~ 1]
References
----------
- `TensorFlow using GPU <https://www.tensorflow.org/versions/r0.9/how_tos/using_gpu/index.html>`_ | 625941be9f2886367277a7a8 |
def scrape(self) -> List[Article]: <NEW_LINE> <INDENT> content = self.content_provider(self.URL) <NEW_LINE> return self._parse(content) | Scrapes the first page of Hacker News. | 625941bee64d504609d74758 |
def opposite(self, v): <NEW_LINE> <INDENT> if not isinstance(v, Graph.Vertex): <NEW_LINE> <INDENT> raise TypeError('v must be a Vertex') <NEW_LINE> <DEDENT> if v is self._origin: <NEW_LINE> <INDENT> return self._destination <NEW_LINE> <DEDENT> elif v is self._destination: <NEW_LINE> <INDENT> return self._origin <NEW_LINE> <DEDENT> raise ValueError('v not incident to edge') | Return the vertex that is opposite v on this edge. | 625941bed58c6744b4257b79 |
def Substract(*args): <NEW_LINE> <INDENT> return _ParaMEDMEM.DataArrayInt_Substract(*args) | Substract(DataArrayInt a1, DataArrayInt a2) -> DataArrayInt
1 | 625941be91af0d3eaac9b92e |
def object_vault(self, function_name): <NEW_LINE> <INDENT> def wrapper(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def nested_f(*args, **kwargs): <NEW_LINE> <INDENT> vault = Vault() <NEW_LINE> return_values = func(vault, *args, **kwargs) <NEW_LINE> if self.handle_multiple_calls: <NEW_LINE> <INDENT> n = self.call_counter_vault[function_name] <NEW_LINE> self.call_counter_vault[function_name] += 1 <NEW_LINE> function_id = '{}_{}'.format(function_name, n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> function_id = function_name <NEW_LINE> <DEDENT> self.vaults[function_id] = vault <NEW_LINE> return return_values <NEW_LINE> <DEDENT> return nested_f <NEW_LINE> <DEDENT> return wrapper | Decorator to provide a vault to store multiple objects.
args:
- function_name (str): name of the function
- chat_id (str): ID of group or user
**** Note that the function being decorated must have
as its first argument the vault. All variables
must be stored to this vault **** | 625941be7b180e01f3dc471b |
def move_lat(val, steps, flag): <NEW_LINE> <INDENT> bit_len = steps * 2 <NEW_LINE> lat_val = val & int('aaaaaaaaaaaaaaaa', 16) <NEW_LINE> lon_val = val & int('5555555555555555', 16) <NEW_LINE> step_val = int('5555555555555555', 16) >> (64 - bit_len) <NEW_LINE> if flag > 0: <NEW_LINE> <INDENT> lat_val += (step_val + 1) <NEW_LINE> <DEDENT> elif flag < 0: <NEW_LINE> <INDENT> lat_val |= step_val <NEW_LINE> lat_val -= (step_val + 1) <NEW_LINE> <DEDENT> lat_val &= int('aaaaaaaaaaaaaaaa', 16) >> (64 - bit_len) <NEW_LINE> return lat_val | lon_val | Move latitude to different direction based on flag | 625941be498bea3a759b99c8 |
def infocalypse_setupfms(ui_, **opts): <NEW_LINE> <INDENT> execute_setupfms(ui_, opts) | Setup or modify the fms configuration. | 625941bed6c5a10208143f61 |
def intersect_lines(line1, line2): <NEW_LINE> <INDENT> homogeneous = np.cross(line1, line2) <NEW_LINE> homogeneous = homogeneous.astype(float) <NEW_LINE> homogeneous /= homogeneous[2] <NEW_LINE> return homogeneous[0:2] | Finds intersection of 2 lines
:param line1: 3-tuple ax+by+c=0
:param line2: 3-tuple ax+by+c=0
:return: x,y, the intersection of the lines | 625941be3d592f4c4ed1cf8d |
def get_object(self): <NEW_LINE> <INDENT> lookup_args = {} <NEW_LINE> for field_name, mapping_name in self.get_fields.items(): <NEW_LINE> <INDENT> lookup_args[field_name] = self.kwargs.get(mapping_name, None) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.get_queryset().get(**lookup_args) <NEW_LINE> <DEDENT> except self.document_class.DoesNotExist: <NEW_LINE> <INDENT> abort(404) | Retrieve the object from the database.
:return:
An instance of the model class containing the retrieved object.
:raise:
:py:exc:`!werkzeug.exceptions.NotFound` when the document does not
exist. | 625941be6e29344779a6252d |
def threeSum(self, nums): <NEW_LINE> <INDENT> res = list() <NEW_LINE> length = len(nums) <NEW_LINE> nums.sort() <NEW_LINE> i = 0 <NEW_LINE> while i < length-2 and nums[i] <= 0: <NEW_LINE> <INDENT> if i > 0 and nums[i-1] == nums[i]: <NEW_LINE> <INDENT> i = i+1 <NEW_LINE> continue <NEW_LINE> <DEDENT> j = i+1 <NEW_LINE> k = length-1 <NEW_LINE> while j<k and nums[k] >= 0: <NEW_LINE> <INDENT> t = nums[i] + nums[j] <NEW_LINE> if t > -nums[k]: <NEW_LINE> <INDENT> k = k - 1 <NEW_LINE> <DEDENT> elif t < -nums[k]: <NEW_LINE> <INDENT> j = j + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res.append([nums[i], nums[j], nums[k]]) <NEW_LINE> j = j+1 <NEW_LINE> k = k-1 <NEW_LINE> <DEDENT> <DEDENT> i = i+1 <NEW_LINE> <DEDENT> return list(set([tuple(t) for t in res])) | :type nums: List[int]
:rtype: List[List[int]] | 625941bef548e778e58cd495 |
def test3_RI(self): <NEW_LINE> <INDENT> self.failUnless(not self.s.ri, "RI -> 0") | Test RI | 625941bebe7bc26dc91cd51e |
def load_json_data(file_name): <NEW_LINE> <INDENT> with open(f"data/{file_name}.json") as jf: <NEW_LINE> <INDENT> content = json.load(jf) <NEW_LINE> <DEDENT> return content | Loads the data from a json file, returns it.
r-type: dict | 625941bef7d966606f6a9f1a |
def get_classifiers(filename=None): <NEW_LINE> <INDENT> assert filename is not None <NEW_LINE> return readconfig(filename, conffile=False) | Reads python classifiers from a file.
:param filename: a filename containing python classifiers
(one classifier per line).
:return: a list with each classifier.
:rtype: ``list``
.. versionadded:: 0.1 | 625941be0fa83653e4656ed5 |
def get_model(self): <NEW_LINE> <INDENT> return 'NA' | Retrieves the part number of the component
Returns:
string: Part number of component | 625941be435de62698dfdb65 |
def propstat_by_status(propstat): <NEW_LINE> <INDENT> bystatus = {} <NEW_LINE> for propstat in propstat: <NEW_LINE> <INDENT> ( bystatus.setdefault( (propstat.statuscode, propstat.responsedescription), [] ).append(propstat.prop) ) <NEW_LINE> <DEDENT> return bystatus | Sort a list of propstatus objects by HTTP status.
:param propstat: List of PropStatus objects:
:return: dictionary mapping HTTP status code to list of PropStatus objects | 625941bed7e4931a7ee9de35 |
def OR_Query(arglist): <NEW_LINE> <INDENT> line = "','".join(arglist) <NEW_LINE> Data = "('" + line + "')" <NEW_LINE> if CON=='ALL': <NEW_LINE> <INDENT> Query = "select distinct FileName from jsoncallworddata where Keyword in " + Data <NEW_LINE> <DEDENT> elif CON=='START50WORD': <NEW_LINE> <INDENT> Query = "select distinct FileName from jsoncallworddata where wordSeq<=50 and Keyword in " + Data <NEW_LINE> <DEDENT> elif CON=='LAST50WORD': <NEW_LINE> <INDENT> Query = "select distinct T2.FileName from (select FileName,max(wordSeq) m from " "jsoncallworddata group by FileName) T1 inner join (select * from jsoncallworddata) as T2 where " "T1.FileName=T2.FileName and T2.wordSeq>(T1.m-50) and T2.Keyword in " + Data <NEW_LINE> <DEDENT> elif CON=='START50SECOND': <NEW_LINE> <INDENT> Query = "select distinct FileName from jsoncallworddata where startTime<=50 and Keyword in " + Data <NEW_LINE> <DEDENT> elif CON=='LAST50SECOND': <NEW_LINE> <INDENT> Query = "select distinct T2.FileName from " "(select FileName,max(startTime) m from jsoncallworddata group by FileName) T1 inner join " "(select * from jsoncallworddata) as T2 where T1.FileName=T2.FileName and T2.startTime>(T1.m-50);" + Data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('No Operation.') <NEW_LINE> <DEDENT> datalist=Get_Result(Query) <NEW_LINE> return datalist | This function perform OR Operation.
arglist : data item in List.
return : Call_id as data. | 625941bed99f1b3c44c674ae |
def get(self, block=True, timeout=None): <NEW_LINE> <INDENT> self.not_empty.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if not block: <NEW_LINE> <INDENT> if self._empty(): <NEW_LINE> <INDENT> raise Empty <NEW_LINE> <DEDENT> <DEDENT> elif timeout is None: <NEW_LINE> <INDENT> while self._empty(): <NEW_LINE> <INDENT> self.not_empty.wait() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if timeout < 0: <NEW_LINE> <INDENT> raise ValueError("'timeout' must be a positive number") <NEW_LINE> <DEDENT> endtime = _time() + timeout <NEW_LINE> while self._empty(): <NEW_LINE> <INDENT> remaining = endtime - _time() <NEW_LINE> if remaining <= 0.0: <NEW_LINE> <INDENT> raise Empty <NEW_LINE> <DEDENT> self.not_empty.wait(remaining) <NEW_LINE> <DEDENT> <DEDENT> item = self._get() <NEW_LINE> item._checkout() <NEW_LINE> self.not_full.notify() <NEW_LINE> return item <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.not_empty.release() | Remove and return an item from the queue.
If optional args `block` is True and `timeout` is None (the
default), block if necessary until an item is available. If
`timeout` is a positive number, it blocks at most `timeout`
seconds and raises the ``Empty`` exception if no item was
available within that time. Otherwise (`block` is false),
return an item if one is immediately available, else raise the
``Empty`` exception (`timeout` is ignored in that case). | 625941be31939e2706e4cd86 |
def put(self, key, value): <NEW_LINE> <INDENT> self.leveldb.Put(str(key), value) | Stores the object `value` named by `key` in leveldb.
Args:
key: Key naming `value`.
value: the object to store. | 625941be7b180e01f3dc471c |
def is_word_guessed(secret_word, letters_guessed): <NEW_LINE> <INDENT> return all(letter in letters_guessed for letter in secret_word) | secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in letters_guessed;
False otherwise | 625941be45492302aab5e1d9 |
def memText(self): <NEW_LINE> <INDENT> if self.debug: qDebug("[PTM] [main.py] [memText]") <NEW_LINE> line = self.ptm['vars']['formats']['mem'] <NEW_LINE> if (line.split('$memtotgb')[0] != line): <NEW_LINE> <INDENT> mem = "%4.1f" %((self.ptm['values']['mem']['free'] + self.ptm['values']['mem']['used']) / (1024.0 * 1024.0)) <NEW_LINE> line = line.split('$memtotgb')[0] + mem + line.split('$memtotgb')[1] <NEW_LINE> <DEDENT> if (line.split('$memtotmb')[0] != line): <NEW_LINE> <INDENT> mem = "%i" %((self.ptm['values']['mem']['free'] + self.ptm['values']['mem']['used']) / 1024.0) <NEW_LINE> line = line.split('$memtotmb')[0] + mem + line.split('$memtotmb')[1] <NEW_LINE> <DEDENT> if (line.split('$memgb')[0] != line): <NEW_LINE> <INDENT> mem = "%4.1f" % (self.ptm['values']['mem']['app'] / (1024.0 * 1024.0)) <NEW_LINE> line = line.split('$memgb')[0] + mem + line.split('$memgb')[1] <NEW_LINE> <DEDENT> if (line.split('$memmb')[0] != line): <NEW_LINE> <INDENT> mem = "%i" % (self.ptm['values']['mem']['app'] / 1024.0) <NEW_LINE> line = line.split('$memmb')[0] + mem + line.split('$memmb')[1] <NEW_LINE> <DEDENT> if (line.split('$mem')[0] != line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mem = 100 * self.ptm['values']['mem']['app'] / (self.ptm['values']['mem']['free'] + self.ptm['values']['mem']['used']) <NEW_LINE> mem = "%5.1f" % (round(mem, 1)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> mem = " N\\A" <NEW_LINE> <DEDENT> line = line.split('$mem')[0] + mem + line.split('$mem')[1] <NEW_LINE> <DEDENT> text = self.ptm['vars']['app']['format'][0] + line + self.ptm['vars']['app']['format'][1] <NEW_LINE> self.setText("mem", text) | function to set mem text | 625941be1f037a2d8b946118 |
def odds(string): <NEW_LINE> <INDENT> new_str = '' <NEW_LINE> for i in range(len(string)): <NEW_LINE> <INDENT> if i % 2 == 1: <NEW_LINE> <INDENT> new_str += string[i] <NEW_LINE> <DEDENT> <DEDENT> return new_str | This function takes one string argument (string) and returns
a new string consisting of all of the odd position
characters in the argument. | 625941be379a373c97cfaa5c |
def close(self): <NEW_LINE> <INDENT> self.fd.close() <NEW_LINE> self.fd = None | Close pid file *without* removing it. | 625941be7d847024c06be1d2 |
def testExportImageCloudApi(self): <NEW_LINE> <INDENT> with apitestcase.UsingCloudApi(): <NEW_LINE> <INDENT> region = ee.Geometry.Rectangle(1, 2, 3, 4) <NEW_LINE> config = dict( region=region['coordinates'], maxPixels=10**10, crs='foo', crs_transform='[9,8,7,6,5,4]', tiffCloudOptimized=True, fileDimensions=1024, ) <NEW_LINE> task = ee.batch.Export.image(ee.Image(1), 'TestDescription', config) <NEW_LINE> expected_expression = ee.Image(1).reproject( 'foo', crsTransform=[ 9.0, 8.0, 7.0, 6.0, 5.0, 4.0 ]).clip(region) <NEW_LINE> self.assertIsNone(task.id) <NEW_LINE> self.assertIsNone(task.name) <NEW_LINE> self.assertEqual('EXPORT_IMAGE', task.task_type) <NEW_LINE> self.assertEqual('UNSUBMITTED', task.state) <NEW_LINE> self.assertEqual({ 'expression': expected_expression, 'description': 'TestDescription', 'fileExportOptions': { 'fileFormat': 'GEO_TIFF', 'driveDestination': { 'filenamePrefix': 'TestDescription' }, 'geoTiffOptions': { 'cloudOptimized': True, 'tileDimensions': { 'width': 1024, 'height': 1024 } }, }, 'maxPixels': { 'value': '10000000000' }, }, task.config) | Verifies the task created by Export.image(). | 625941be3cc13d1c6d3c7294 |
def testDigitalIOStatus(self): <NEW_LINE> <INDENT> dummy = dwf.DigitalIOStatus(self.hdwf) | Test DigitalIOStatus | 625941be5510c4643540f304 |
def sendmsg(word, word_eol, userdata): <NEW_LINE> <INDENT> channel = hexchat.get_info("channel") <NEW_LINE> context = hexchat.find_context(channel=channel) <NEW_LINE> if not userdata and len(word) < 3: <NEW_LINE> <INDENT> context.emit_print("Channel Message", __module_name__, help_gpg) <NEW_LINE> return hexchat.EAT_ALL <NEW_LINE> <DEDENT> elif userdata and len(word) < 4: <NEW_LINE> <INDENT> context.emit_print("Channel Message", __module_name__, help_gpgs) <NEW_LINE> return hexchat.EAT_ALL <NEW_LINE> <DEDENT> if not userdata: <NEW_LINE> <INDENT> data = encrypt_message(word[1], None, word_eol[2], None) <NEW_LINE> <DEDENT> elif userdata and "s" in userdata: <NEW_LINE> <INDENT> data = encrypt_message(word[1], word[2], word_eol[3], userdata) <NEW_LINE> <DEDENT> data = data.split("\n") <NEW_LINE> for line in range(len(data)): <NEW_LINE> <INDENT> data[line] = data[line].replace("\r", "") <NEW_LINE> if data[line]: <NEW_LINE> <INDENT> context.emit_print( "Channel Message", hexchat.get_info("nick"), data[line] ) <NEW_LINE> context.command( "PRIVMSG {0} {1}".format(channel, data[line]) ) <NEW_LINE> <DEDENT> <DEDENT> return hexchat.EAT_ALL | Function called by /gpg. Parses user input, encrypts, and sends. | 625941bead47b63b2c509e99 |
def show_traffic(self): <NEW_LINE> <INDENT> traffic = {} <NEW_LINE> section = '' <NEW_LINE> for line in self.get_show_section('traffic'): <NEW_LINE> <INDENT> if len(line): <NEW_LINE> <INDENT> if line == line.lstrip(): <NEW_LINE> <INDENT> section = line <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if section not in traffic: <NEW_LINE> <INDENT> traffic[section] = [] <NEW_LINE> traffic[section].append(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if section not in traffic: <NEW_LINE> <INDENT> traffic[section] = {} <NEW_LINE> <DEDENT> if 'received' in line: <NEW_LINE> <INDENT> direction = 'receive' <NEW_LINE> <DEDENT> elif 'transmitted' in line: <NEW_LINE> <INDENT> direction = 'transmit' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if direction not in traffic[section]: <NEW_LINE> <INDENT> traffic[section][direction] = [] <NEW_LINE> <DEDENT> traffic[section][direction].append(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return json.dumps(traffic) | Parser for show traffic | 625941be24f1403a92600a82 |
def __init__(self): <NEW_LINE> <INDENT> self.model = MyModel() <NEW_LINE> self.model.setPath("data/file.csv") | :return: | 625941be4f88993c3716bf84 |
def random(self): <NEW_LINE> <INDENT> self._random = True <NEW_LINE> self.assign_node_pos() | Button handler to toggle random node distribution | 625941be96565a6dacc8f5e5 |
def pop(self): <NEW_LINE> <INDENT> return self._stack.pop() | Remove the last layer from the loop stack. | 625941be45492302aab5e1da |
def expand_sophisticated(src, dest, preds, mapping_data, msg): <NEW_LINE> <INDENT> logger.debug(msg) <NEW_LINE> for src_rule in src.rules_iter: <NEW_LINE> <INDENT> if src_rule.alloc: <NEW_LINE> <INDENT> for dest_rule in dest.rules_iter: <NEW_LINE> <INDENT> for pred_call in dest_rule.calles: <NEW_LINE> <INDENT> if set(mapping_data.get_aliases(src_rule.alloc)) & set(pred_call[1]): <NEW_LINE> <INDENT> logger.debug("Expanding {}".format(pred_call)) <NEW_LINE> dest.expand_current_call(preds, dest[0].expanded_rules[0]) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return False | Iterates over allocated nodes on src side and search for predicate call
containing node in arguments. Expands chosen predicate and
returns True on success, False otherwise | 625941be566aa707497f4486 |
def get_fuv_parameters(self): <NEW_LINE> <INDENT> return self.data["FUV"] | This function ...
:return: | 625941bed7e4931a7ee9de36 |
def urlretrieve(url, dest, timeout=300): <NEW_LINE> <INDENT> with open(dest, 'wb') as f: <NEW_LINE> <INDENT> r = requests.get(url, allow_redirects=True, timeout=timeout) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> f.write(r.content) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 | Download a file.
:param url: The url of the source file.
:param dest: destination file path. | 625941befff4ab517eb2f353 |
def get_pem_data(self): <NEW_LINE> <INDENT> return self.pki.do_get_pem_data() | Returns the fingerprint of CA | 625941be21bff66bcd68486e |
def register(self): <NEW_LINE> <INDENT> Storage().compile_sass() | Compile Sass.
Compile Sass if the libsass module is installed. Once installed, all
Sass files are compiled when the server is ran. This will only run
once when the server is first started. | 625941bee64d504609d74759 |
def dumpGustsFromTracks(self, trackiter, windfieldPath, timeStepCallback=None): <NEW_LINE> <INDENT> if timeStepCallback: <NEW_LINE> <INDENT> results = map(self.calculateExtremesFromTrack, trackiter, itertools.repeat(timeStepCallback)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = map(self.calculateExtremesFromTrack, trackiter) <NEW_LINE> <DEDENT> for track, result in results: <NEW_LINE> <INDENT> log.debug("Saving data for track {0:03d}-{1:05d}" .format(*track.trackId)) <NEW_LINE> gust, bearing, Vx, Vy, P, lon, lat = result <NEW_LINE> dumpfile = pjoin(windfieldPath, 'gust.{0:03d}-{1:05d}.nc'. format(*track.trackId)) <NEW_LINE> plotfile = pjoin(windfieldPath, 'gust.{0:03d}-{1:05d}.png'. format(*track.trackId)) <NEW_LINE> self.saveGustToFile(track.trackfile, (np.flipud(lat), lon, np.flipud(gust), np.flipud(Vx), np.flipud(Vy), np.flipud(P)), dumpfile) <NEW_LINE> <DEDENT> if self.multipliers is not None: <NEW_LINE> <INDENT> self.calcLocalWindfield(results) | Dump the maximum wind speeds (gusts) observed over a region to
netcdf files. One file is created for every track file.
:type trackiter: list of :class:`Track` objects
:param trackiter: a list of :class:`Track` objects.
:type windfieldPath: str
:param windfieldPath: the path where to store the gust output files.
:type filenameFormat: str
:param filenameFormat: the format string for the output file names. The
default is set to 'gust-%02i-%04i.nc'.
:type timeStepCallBack: function
:param timeStepCallback: optional function to be called at each
timestep to extract point values for
specified locations. | 625941be56b00c62f0f14571 |
def fixside(self, opts=None): <NEW_LINE> <INDENT> self._run_method('fixside', opts) | StructureChecking.fixside
Complete side chains (heavy atoms, protein only). Check only with no options. Options accepted as command-line string, or python dictionary.
Args:
opts (str | dict - Options dictionary):
* fix:
* **all** - Fix all residues
* **residue_list** - Fix indicated residues
* no_check_clashes (bool) - (False) Do not check for generated clashes
* rebuild (bool) - (False) Rebuild side chains using Modeller | 625941bec432627299f04b5d |
def get_language_count(self): <NEW_LINE> <INDENT> return self.get_languages().count() | Returns number of languages used in this project. | 625941be07d97122c417879f |
def print_handled_ex(ex): <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(ex, file=stderr) | Print the exception or traceback to terminal depending on whether we're in debug mode | 625941bed53ae8145f87a18d |
def tv_loss(self, input): <NEW_LINE> <INDENT> tv_loss = torch.sum(torch.abs(input[:, :, :, :-1] - input[:, :, :, 1:])) + torch.sum(torch.abs(input[:, :, :-1, :] - input[:, :, 1:, :])) <NEW_LINE> return tv_loss | Total Variation Loss. | 625941be1d351010ab855a36 |
def doesConflictingEventExist(event, context): <NEW_LINE> <INDENT> event_body = json.loads(event.get("body", "")) <NEW_LINE> print("event body:") <NEW_LINE> print(event_body) <NEW_LINE> table = dynamodb.Table(calendar_table_name) <NEW_LINE> user = event_body["user_id"] <NEW_LINE> site = event_body["site"] <NEW_LINE> time = event_body["time"] <NEW_LINE> events = getEventsDuringTime(time, site) <NEW_LINE> for event in events: <NEW_LINE> <INDENT> if event["creator_id"] != user: <NEW_LINE> <INDENT> return create_200_response(True) <NEW_LINE> <DEDENT> <DEDENT> return create_200_response(False) | Calendar reservations should only let the designated user use the observatory.
If there are no reservations, anyone can use it.
Args:
event.body.user_id: auth0 user 'sub' (eg. "google-oauth2|xxxxxxxxxxxxx")
event.body.site: site code (eg. "wmd")
event.body.time: UTC datestring (eg. '2020-05-14T17:30:00Z')
Returns:
True if a different user has a reservation at the specified time.
False otherwise. | 625941be0383005118ecf4fd |
def shift_vertical(self, n: int) -> None: <NEW_LINE> <INDENT> for cell in self.cells: <NEW_LINE> <INDENT> cell.set_y(cell.y + int(n)) <NEW_LINE> <DEDENT> self.reset_cell_coordinates() <NEW_LINE> return | Change the ``y`` coordinates of all :attr:`cells` by ``n``.
Args:
n (int): number to increment vertical position of cells | 625941be7d43ff24873a2bb7 |
def any_food(self, direction): <NEW_LINE> <INDENT> snake_head = self.snake.snake_body[0] <NEW_LINE> check_for_food = [] <NEW_LINE> if not self.game_over: <NEW_LINE> <INDENT> if direction == 'up': <NEW_LINE> <INDENT> for i in range(1, (BOARD_SIZE - (BOARD_SIZE - snake_head[0]) + 1)): <NEW_LINE> <INDENT> check_for_food.append(isinstance(self.board.board[snake_head[0]-i][snake_head[1]], Apple)) <NEW_LINE> <DEDENT> <DEDENT> elif direction == 'down': <NEW_LINE> <INDENT> for i in range(1, (BOARD_SIZE - (snake_head[0] + 1) + 1)): <NEW_LINE> <INDENT> check_for_food.append(isinstance(self.board.board[snake_head[0]+i][snake_head[1]], Apple)) <NEW_LINE> <DEDENT> <DEDENT> elif direction == 'right': <NEW_LINE> <INDENT> for i in range(1, (BOARD_SIZE - (snake_head[1] + 1) + 1)): <NEW_LINE> <INDENT> check_for_food.append(isinstance(self.board.board[snake_head[0]][snake_head[1]+i], Apple)) <NEW_LINE> <DEDENT> <DEDENT> elif direction == 'left': <NEW_LINE> <INDENT> for i in range(1, (BOARD_SIZE - (BOARD_SIZE - snake_head[1]) + 1)): <NEW_LINE> <INDENT> check_for_food.append(isinstance(self.board.board[snake_head[0]][snake_head[1]-i], Apple)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return any(check_for_food) | return True if there is any food in the given direction | 625941be5f7d997b871749ae |
def attack(c1,e1,c2,e2,n) : <NEW_LINE> <INDENT> l=egcd(e1,e2) <NEW_LINE> d={max(e1,e2) : l[1] , min(e1,e2) : l[2]} <NEW_LINE> if l[0]==0 : <NEW_LINE> <INDENT> print("Cant be attacked viz this method") <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> if d[e1] < 0 : <NEW_LINE> <INDENT> c1,c2=c2,c1 <NEW_LINE> e1,e2=e2,e1 <NEW_LINE> u=l[2] <NEW_LINE> v=l[1] <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> u=l[1] <NEW_LINE> v=l[2] <NEW_LINE> <DEDENT> c2_inv=inverse(c2,n) <NEW_LINE> m=pow((pow(c1,u,n)*pow(c2_inv,abs(v),n)),1,n) <NEW_LINE> <DEDENT> return long_to_bytes(m) | This function is used to decipher a message when the same message is sent by someone to two people but use the same modulus .One had in hand only the public key parameters and the cipher text :
attack(c1,e1,c2,e2,n) :
c1,c2 - ciphertext 1 and 2
e1,e2 - public key parameters 1 and 2
n - the common modulus | 625941be96565a6dacc8f5e6 |
@invoke.task <NEW_LINE> def serve(ctx): <NEW_LINE> <INDENT> docker_command = get_base_docker_command() <NEW_LINE> docker_command.extend(["jekyll", "serve", "--drafts", "--incremental"]) <NEW_LINE> ctx.run(" ".join(docker_command)) | Serves auto-reloading blog via Docker. | 625941be97e22403b379ceb2 |
def __str__( self, ): <NEW_LINE> <INDENT> return self.ascii_diagram(time_lines='both') | String representation of this Circuit (an ASCII circuit diagram). | 625941be92d797404e3040a3 |
def testMtoMeValues(self): <NEW_LINE> <INDENT> for m, me in self.knownValuesMtoMe: <NEW_LINE> <INDENT> result = conversions.convertMilesToMeters(m) <NEW_LINE> self.assertEqual(me, result) | convertMilesToMeters should return the correct F value | 625941beaad79263cf390956 |
def search(self, nums, target): <NEW_LINE> <INDENT> low, high = 0, len(nums) - 1 <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = (low + high) // 2 <NEW_LINE> if nums[mid] == target: <NEW_LINE> <INDENT> return mid <NEW_LINE> <DEDENT> if nums[mid] >= nums[low]: <NEW_LINE> <INDENT> if nums[low] <= target < nums[mid]: <NEW_LINE> <INDENT> high = mid - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> low = mid + 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if nums[mid] < target and nums[high] >= target: <NEW_LINE> <INDENT> low = mid + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> high = mid - 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return -1 | :type nums: List[int]
:type target: int
:rtype: int | 625941be85dfad0860c3ad73 |
def puzzle_01() -> None: <NEW_LINE> <INDENT> with open("src/day_02/input.txt", "r") as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> total = 0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> stripped = line.strip() <NEW_LINE> dimensions = stripped.split("x") <NEW_LINE> l = int(dimensions[0]) <NEW_LINE> w = int(dimensions[1]) <NEW_LINE> h = int(dimensions[2]) <NEW_LINE> box_surface = 2*l*w + 2*w*h + 2*h*l <NEW_LINE> extra = min((l*w, w*h, h*l)) <NEW_LINE> total += box_surface <NEW_LINE> total += extra <NEW_LINE> <DEDENT> <DEDENT> print(total) | The elves are running low on wrapping paper, and so they need to submit an
order for more. They have a list of the dimensions (length l, width w, and
height h) of each present, and only want to order exactly as much as they
need.
Fortunately, every present is a box (a perfect right rectangular prism),
which makes calculating the required wrapping paper for each gift a little
easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l.
The elves also need a little extra paper for each present: the area of the
smallest side.
All numbers in the elves' list are in feet. How many total square feet of
wrapping paper should they order?
:return: None; Answer should be 1606483. | 625941be0fa83653e4656ed6 |
def revoke_qualification(qual_id, worker_id): <NEW_LINE> <INDENT> check_keys() <NEW_LINE> operation_name = "RevokeQualification" <NEW_LINE> param_dict = {} <NEW_LINE> param_dict["Operation"] = operation_name <NEW_LINE> param_dict["SubjectId"] = worker_id <NEW_LINE> param_dict["QualificationTypeId"] = qual_id <NEW_LINE> result = issue_request(param_dict) <NEW_LINE> xmlroot = ET.fromstring(result) <NEW_LINE> revoke_result_node = xmlroot.findall("RevokeQualificationResult")[0] <NEW_LINE> request_node = revoke_result_node.findall("Request")[0] <NEW_LINE> is_valid = request_node.findall("IsValid")[0].text <NEW_LINE> if is_valid == "True": <NEW_LINE> <INDENT> return ("Success: Revoked qualification " + qual_id + " from worker " + worker_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ("Failure: Could not revoke qualification " + qual_id + " from worker " + worker_id) | Removes the qualification with id `qual_id` from the worker with id `worker_id`. | 625941beaad79263cf390957 |
def encode_huffman_tree(root, dtype): <NEW_LINE> <INDENT> converter = {'float32':float2bitstr, 'int32':int2bitstr} <NEW_LINE> code_list = [] <NEW_LINE> def encode_node(node): <NEW_LINE> <INDENT> if node.value is not None: <NEW_LINE> <INDENT> code_list.append('1') <NEW_LINE> lst = list(converter[dtype](node.value)) <NEW_LINE> code_list.extend(lst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code_list.append('0') <NEW_LINE> encode_node(node.left) <NEW_LINE> encode_node(node.right) <NEW_LINE> <DEDENT> <DEDENT> encode_node(root) <NEW_LINE> return ''.join(code_list) | Encodes a huffman tree to string of '0's and '1's | 625941be3346ee7daa2b2c84 |
def test2(self): <NEW_LINE> <INDENT> session=requests.Session() <NEW_LINE> login_res=session.post(url=self.TestData["login"]["login_url"],data=self.TestData["login"]["login_data"],headers=self.headers) <NEW_LINE> if login_res.status_code==200: <NEW_LINE> <INDENT> session.post(url=self.TestData["updateAgency"]["agency_url"],data=self.TestData["updateAgency"]["agency_data"]) <NEW_LINE> tailList_res=session.post(url=self.TestData["tailList"]["tailList_url"],data=self.TestData["tailList"]["tailList_data"]) <NEW_LINE> self.assertTrue(tailList_res.status_code==200) <NEW_LINE> Logger(self.TestData["name"]).Info(str(self.TestData["tailList"])+'\n'+tailList_res.text) <NEW_LINE> self.TestData["createSurplus"]["createSurplus_data"]["orderTime"]=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + 5 * 60)) <NEW_LINE> createSurplus_res=session.post(url=self.TestData["createSurplus"]["createSurplus_url"],data=self.TestData["createSurplus"]["createSurplus_data"]) <NEW_LINE> createSurplus_json=json.loads(allData().changeIntoStr(createSurplus_res.text)) <NEW_LINE> self.assertTrue(createSurplus_res.status_code==200 and createSurplus_json['tag']) <NEW_LINE> Logger(self.TestData["name"]).Info(str(self.TestData["createSurplus"])+'\n'+createSurplus_res.text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("登录不成功不进行单元测试") <NEW_LINE> <DEDENT> session.close() | 尾单波次列表信息显示 | 625941be23849d37ff7b2faa |
def json_resource_file(baseurl, jsondata, resource_info): <NEW_LINE> <INDENT> response_file = StringIO() <NEW_LINE> json.dump(jsondata, response_file, indent=2, separators=(',', ': '), sort_keys=True) <NEW_LINE> response_file.seek(0) <NEW_LINE> return response_file | Return a file object that reads out a JSON version of the supplied entity values data.
baseurl base URL for resolving relative URI references.
(Unused except for diagnostic purposes.)
jsondata is the data to be formatted and returned.
resource_info is a dictionary of values about the resource to be serialized.
(Unused except for diagnostic purposes.) | 625941be293b9510aa2c31b2 |
def process_parent_edges(self, edges): <NEW_LINE> <INDENT> assert len({e.parent for e in edges}) == 1 <NEW_LINE> parent = edges[0].parent <NEW_LINE> S = [] <NEW_LINE> for edge in edges: <NEW_LINE> <INDENT> x = self.A_head[edge.child] <NEW_LINE> while x is not None: <NEW_LINE> <INDENT> if x.right > edge.left and edge.right > x.left: <NEW_LINE> <INDENT> y = Segment( max(x.left, edge.left), min(x.right, edge.right), x.node ) <NEW_LINE> S.append(y) <NEW_LINE> <DEDENT> x = x.next <NEW_LINE> <DEDENT> <DEDENT> self.merge_labeled_ancestors(S, parent) <NEW_LINE> self.check_state() | Process all of the edges for a given parent. | 625941bea8370b77170527ba |
def rating(self): <NEW_LINE> <INDENT> return super(PikabuProfile, self).rating(self.settings["login"]) | Возвращает рейтинг пользователя | 625941be82261d6c526ab3b6 |
def hiving_swarms_ended(self): <NEW_LINE> <INDENT> pass | Called when the swarm hiving stage has completed. | 625941bebde94217f3682d0d |
def get_bldg_footprint_frm_bldg_occsolid(bldg_occsolid, tolerance = 1e-05, roundndigit = 6, distance = 0.1): <NEW_LINE> <INDENT> bounding_footprint = get_building_bounding_footprint(bldg_occsolid) <NEW_LINE> b_midpt = py3dmodel.calculate.face_midpt(bounding_footprint) <NEW_LINE> loc_pt = (b_midpt[0], b_midpt[1], b_midpt[2]+tolerance) <NEW_LINE> bounding_footprint = py3dmodel.fetch.topo2topotype(py3dmodel.modify.move(b_midpt, loc_pt, bounding_footprint)) <NEW_LINE> bldg_footprint_cmpd = py3dmodel.construct.boolean_section(bldg_occsolid, bounding_footprint, roundndigit = roundndigit, distance = distance) <NEW_LINE> bldg_footprint_cmpd = py3dmodel.fetch.topo2topotype(py3dmodel.modify.move(loc_pt, b_midpt, bldg_footprint_cmpd)) <NEW_LINE> bldg_footprint_list = py3dmodel.fetch.topo_explorer(bldg_footprint_cmpd, "face") <NEW_LINE> return bldg_footprint_list | This function gets the footprint of a building.
Parameters
----------
bldg_occsolid : OCCsolid
The OCCsolid that is a building to be analysed.
tolearnce : float, optional
The tolerance used for the analysis, the smaller the float it is more precise. Default = 1e-05.
roundndigit : int, optional
The number of decimal places of the xyz of the points for the boolean section function, Default = 6. The higher the number the more precise are the points.
Depending on the precision of the points, it will decide whether the edges are connected.
distance : float, optional
The smallest distance between two points from the edges for boolean section function, Default = 0.01.
The further the distance the less precise is the resultant faces.
Returns
-------
footprints : list of OCCfaces
List of OCCfaces identified as footprints. | 625941be0c0af96317bb8102 |
def ei_of_rho_p(self, rho, p): <NEW_LINE> <INDENT> return p / self._gm1 | Internal energy density as a function of density (rho) and pressure (p) | 625941becad5886f8bd26ef4 |
def open_menu(self, title): <NEW_LINE> <INDENT> if title != '': <NEW_LINE> <INDENT> menu = self.get_menu(title) <NEW_LINE> self.wait_elem_visible('.app_List span[title="' + title + '"]') <NEW_LINE> self.scroll_to_target_element(menu) <NEW_LINE> self.find_elem_is_clickable('.app_List span[title="' + title + '"]').click() | 打开菜单 | 625941bead47b63b2c509e9a |
def __init__(self, units, num_heads, use_bias=True, dtype='float32', weight_initializer=None, bias_initializer=None, prefix=None, params=None): <NEW_LINE> <INDENT> super().__init__(prefix=prefix, params=params) <NEW_LINE> if not isinstance(num_heads, (list, tuple)): <NEW_LINE> <INDENT> num_heads = (int(num_heads),) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_heads = tuple(num_heads) <NEW_LINE> <DEDENT> self._num_heads = num_heads <NEW_LINE> self._use_bias = use_bias <NEW_LINE> for ele in self._num_heads: <NEW_LINE> <INDENT> if ele <= 0: <NEW_LINE> <INDENT> raise ValueError('Invalid number of heads, all numbers need to be larger than 0.' ' num_heads={}'.format(num_heads)) <NEW_LINE> <DEDENT> <DEDENT> self._units = units <NEW_LINE> self._mult = np.prod(num_heads) <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.weight = self.params.get('weight', shape=(self._mult * units, 0), init=weight_initializer, dtype=dtype, allow_deferred_init=True) <NEW_LINE> if use_bias: <NEW_LINE> <INDENT> self.bias = self.params.get('bias', shape=(self._mult * units,), init=bias_initializer, dtype=dtype, allow_deferred_init=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bias = None | Multiple Dense with different parameters and the same number of units
The inner shapes of the weight and bias are
weight: (self._parallel_num[0] * ... * self._parallel_num[k] * units, in_units)
bias: (self._parallel_num[0] * ... * self._parallel_num[k],)
Parameters
----------
units : int
The basic units.
num_heads : int or tuple
use_bias : bool, default True
dtype : str, default 'float32'
The data type
weight_initializer : None or initialzer, default None
bias_initializer : None or initializer, default None
prefix : str or None
params : None | 625941bed6c5a10208143f62 |
def find_element(self, by: str = By.ID, value: Union[str, Dict] = None) -> T: <NEW_LINE> <INDENT> return self._execute(RemoteCommand.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value'] | Find an element given a By strategy and locator
Override for Appium
Prefer the find_element_by_* methods when possible.
Args:
by: The strategy
value: The locator
Usage:
element = element.find_element(By.ID, 'foo')
Returns:
`appium.webdriver.webelement.WebElement` | 625941bea8370b77170527bb |
def collide_widget_relative(self, widget): <NEW_LINE> <INDENT> self_x, self_y = self.to_window(*self.pos) <NEW_LINE> self_right = self_x + self.width <NEW_LINE> self_top = (self_y + self.height) <NEW_LINE> result = True <NEW_LINE> if self_x > widget.right: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> if self_right < widget.x: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> if self_y > widget.top: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> if self_top < widget.y: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result | Collide Widget test that takes into account relative layouts. | 625941bee1aae11d1e749bcf |
def set_quantity(self, quantity): <NEW_LINE> <INDENT> self.__quantity = quantity | set order last recently shares' qty | 625941be9b70327d1c4e0cee |
def talk_m10_15_x37(): <NEW_LINE> <INDENT> if GetEventFlag(205230) != 0 and GetEventFlag(102800) != 1 and GetEventFlag(104340) != 1: <NEW_LINE> <INDENT> assert talk_m10_15_x16(lot3=1771000, z7=102800, text4=77106000, text5=77106010) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert talk_m10_15_x1(text1=77102400, z20=0, z22=-1, z23=0) <NEW_LINE> <DEDENT> """State 2: Menu conversation: End""" <NEW_LINE> ClearNpcMenuSelection() <NEW_LINE> return 0 | Enclosed person: Menu conversation | 625941bebe8e80087fb20b61 |
def get_available_rewards(): <NEW_LINE> <INDENT> avail_rewards_script = "return document.getElementsByClassName('rewards-total-value')[0];" <NEW_LINE> avail_rewards = ba.driver.execute_script(avail_rewards_script).get_attribute('textContent').strip() <NEW_LINE> if avail_rewards != '$ 0': <NEW_LINE> <INDENT> return avail_rewards <NEW_LINE> <DEDENT> return None | Determines if any rewards are available | 625941be91f36d47f21ac40a |
def publish(self, link, data): <NEW_LINE> <INDENT> if(link in self.publishable_links): <NEW_LINE> <INDENT> self._mqtt_client.send_message(link, data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_msg = 'Link ({0}) not contained in publishable links ({1})'.format(link, self.publishable_links) <NEW_LINE> self._logger.error(error_msg) <NEW_LINE> raise ValueError(error_msg) | Publishes data on a particular link. Link should have been classified as STREAM in node descriptor.
Args:
link (str): Link on which data is published.
data (bytes): Bytes to be published over MQTT.
Raises:
ValueError: If the provided link is not classified as STREAM. | 625941be046cf37aa974cc64 |
def _vec_range_J(self, a): <NEW_LINE> <INDENT> ret = zeros(self.codim) <NEW_LINE> start = 0 <NEW_LINE> for r, s in sorted(a, reverse=True): <NEW_LINE> <INDENT> tp = a[r, s].reshape(-1) <NEW_LINE> ret[start:start+tp.shape[0]] = tp <NEW_LINE> start += tp.shape[0] <NEW_LINE> <DEDENT> return ret | vectorize an elememt of rangeJ
a.reshape(-1) | 625941bedd821e528d63b0c5 |
def test_iodu_get_descriptor(self): <NEW_LINE> <INDENT> obj_id, refr = create_descriptor(dal=self.dal) <NEW_LINE> self.assertEqual(obj_id, 1) <NEW_LINE> obj = self.dal.get(Descriptor, obj_id) <NEW_LINE> self.assertEqual(obj.descriptor_id, obj_id) <NEW_LINE> self.assertEqual(obj.ui, refr["ui"]) <NEW_LINE> self.assertEqual(obj.name, refr["name"]) <NEW_LINE> self.assertEqual(obj.created, refr["created"]) <NEW_LINE> self.assertEqual(obj.revised, refr["revised"]) <NEW_LINE> self.assertEqual(obj.established, refr["established"]) <NEW_LINE> self.assertEqual(obj.annotation, refr["annotation"]) <NEW_LINE> self.assertEqual(obj.history_note, refr["history_note"]) <NEW_LINE> self.assertEqual( obj.nlm_classification_number, refr["nlm_classification_number"], ) <NEW_LINE> self.assertEqual(obj.online_note, refr["online_note"]) <NEW_LINE> self.assertEqual(obj.public_mesh_note, refr["public_mesh_note"]) <NEW_LINE> self.assertEqual(obj.consider_also, refr["consider_also"]) | Tests the IODU insertion of a `Descriptor` record via the
`iodu_descriptor` method of the `DalMesh` class and its retrieval
via the `get` method. | 625941be56ac1b37e62640ee |
def encrypt(key, text): <NEW_LINE> <INDENT> result = split_text(key, text) <NEW_LINE> return hexlify(result) | Takes a key(string), text(string) and returns a hex
encoded string XOR encrypted against the key. | 625941be097d151d1a222d76 |
def jsonify(self, *args, **kwargs): <NEW_LINE> <INDENT> warnings.warn( 'Schema.jsonify is deprecated. Call jsonify on the ' 'output of Schema.dump instead.', category=DeprecationWarning ) <NEW_LINE> return jsonify(self.data, *args, **kwargs) | Return a JSON response of the serialized data.
.. deprecated:: 0.4.0 | 625941beb7558d58953c4e33 |
def get_background(array, mode = 'histogram'): <NEW_LINE> <INDENT> if mode == 'histogram': <NEW_LINE> <INDENT> x, y = histogram(array[::2,::2,::2], log = True, plot = False) <NEW_LINE> y = numpy.log(y + 1) <NEW_LINE> y = ndimage.filters.gaussian_filter1d(y, sigma=1) <NEW_LINE> air_index = numpy.argmax(y) <NEW_LINE> flat = x[air_index] <NEW_LINE> <DEDENT> elif mode == 'sides': <NEW_LINE> <INDENT> left = array[:, :, 0:10].mean(2) <NEW_LINE> right = array[:, :, 0:10].mean(2) <NEW_LINE> left = left.max(1) <NEW_LINE> right = left.max(1) <NEW_LINE> linfit = interp1d([0,1], numpy.vstack([left, right]).T, axis=1) <NEW_LINE> flat = linfit(numpy.linspace(0, 1, array.shape[2])) <NEW_LINE> flat = flat.astype(array.dtype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error('Unknown mode: ' + mode) <NEW_LINE> <DEDENT> return flat | Get the background intensity. | 625941beb545ff76a8913d30 |
def get_tfds_path(relative_path): <NEW_LINE> <INDENT> path = os.path.join(tfds_dir(), relative_path) <NEW_LINE> return path | Returns absolute path to file given path relative to tfds root. | 625941be009cb60464c632ce |
def zip_site_init(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> curdir = os.getcwd() <NEW_LINE> root = os.path.join(curdir, "blogofile", "site_init") <NEW_LINE> for d in os.listdir(root): <NEW_LINE> <INDENT> d = os.path.join(root, d) <NEW_LINE> if os.path.isdir(d): <NEW_LINE> <INDENT> os.chdir(root) <NEW_LINE> zf = d + ".zip" <NEW_LINE> z = zipfile.ZipFile(zf, "w") <NEW_LINE> os.chdir(d) <NEW_LINE> for dirpath, dirnames, filenames in os.walk(os.curdir): <NEW_LINE> <INDENT> if len(filenames) == 0: <NEW_LINE> <INDENT> z.writestr(zipfile.ZipInfo(dirpath+"/"), '') <NEW_LINE> <DEDENT> for fn in filenames: <NEW_LINE> <INDENT> z.write(os.path.join(dirpath, fn)) <NEW_LINE> <DEDENT> <DEDENT> z.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> os.chdir(curdir) | Zip up all of the subdirectories of site_init
This function should only be called by setuptools | 625941be956e5f7376d70d89 |
def apply_driver_hacks(self, app, info, options): <NEW_LINE> <INDENT> super(SQLAlchemy, self).apply_driver_hacks(app, info, options) <NEW_LINE> if info.drivername == 'sqlite': <NEW_LINE> <INDENT> connect_args = options.setdefault('connect_args', {}) <NEW_LINE> if 'isolation_level' not in connect_args: <NEW_LINE> <INDENT> connect_args['isolation_level'] = None <NEW_LINE> <DEDENT> if not event.contains(Engine, 'connect', do_sqlite_connect): <NEW_LINE> <INDENT> event.listen(Engine, 'connect', do_sqlite_connect) <NEW_LINE> <DEDENT> if not event.contains(Engine, 'begin', do_sqlite_begin): <NEW_LINE> <INDENT> event.listen(Engine, 'begin', do_sqlite_begin) <NEW_LINE> <DEDENT> from sqlite3 import register_adapter <NEW_LINE> def adapt_proxy(proxy): <NEW_LINE> <INDENT> return proxy._get_current_object() <NEW_LINE> <DEDENT> register_adapter(LocalProxy, adapt_proxy) <NEW_LINE> <DEDENT> elif info.drivername == 'postgresql+psycopg2': <NEW_LINE> <INDENT> from psycopg2.extensions import adapt, register_adapter <NEW_LINE> def adapt_proxy(proxy): <NEW_LINE> <INDENT> return adapt(proxy._get_current_object()) <NEW_LINE> <DEDENT> register_adapter(LocalProxy, adapt_proxy) <NEW_LINE> <DEDENT> elif info.drivername == 'mysql+pymysql': <NEW_LINE> <INDENT> from pymysql import converters <NEW_LINE> def escape_local_proxy(val, mapping): <NEW_LINE> <INDENT> return converters.escape_item( val._get_current_object(), self.engine.dialect.encoding, mapping=mapping, ) <NEW_LINE> <DEDENT> converters.conversions[LocalProxy] = escape_local_proxy <NEW_LINE> converters.encoders[LocalProxy] = escape_local_proxy | Call before engine creation. | 625941be656771135c3eb786 |
def init(self, userCmd=None, timeLim=3, getStatus=True): <NEW_LINE> <INDENT> log.info("%s.init(userCmd=%s, timeLim=%s, getStatus=%s)" % (self, userCmd, timeLim, getStatus)) <NEW_LINE> userCmd = expandCommand(userCmd) <NEW_LINE> return userCmd | Called automatically on startup after the connection is established.
Only thing to do is query for status or connect if not connected
getStatus ignored? | 625941be1f5feb6acb0c4a6e |
def create_date_frame_year(self, date): <NEW_LINE> <INDENT> b = datetime.date(date.year, 1, 1) <NEW_LINE> e = datetime.date(date.year, 12, 31) <NEW_LINE> index = pd.date_range(b, e, freq='D') <NEW_LINE> df = pd.DataFrame(index=index, columns=self.columns) <NEW_LINE> return df | Create Statistics Dataframe | 625941be21a7993f00bc7c05 |
def parse_bdist_wininst(name): <NEW_LINE> <INDENT> lower = name.lower() <NEW_LINE> base, py_ver, plat = None, None, None <NEW_LINE> if lower.endswith('.exe'): <NEW_LINE> <INDENT> if lower.endswith('.win32.exe'): <NEW_LINE> <INDENT> base = name[:-10] <NEW_LINE> plat = 'win32' <NEW_LINE> <DEDENT> elif lower.startswith('.win32-py', -16): <NEW_LINE> <INDENT> py_ver = name[-7:-4] <NEW_LINE> base = name[:-16] <NEW_LINE> plat = 'win32' <NEW_LINE> <DEDENT> elif lower.endswith('.win-amd64.exe'): <NEW_LINE> <INDENT> base = name[:-14] <NEW_LINE> plat = 'win-amd64' <NEW_LINE> <DEDENT> elif lower.startswith('.win-amd64-py', -20): <NEW_LINE> <INDENT> py_ver = name[-7:-4] <NEW_LINE> base = name[:-20] <NEW_LINE> plat = 'win-amd64' <NEW_LINE> <DEDENT> <DEDENT> return base, py_ver, plat | Return (base.css,pyversion) or (None,None) for possible .exe name | 625941be07d97122c41787a0 |
def cook_refs(refs, eff=None, n=4): <NEW_LINE> <INDENT> reflen = [] <NEW_LINE> maxcounts = dict() <NEW_LINE> for ref in refs: <NEW_LINE> <INDENT> rl, counts = precook(ref, n) <NEW_LINE> reflen.append(rl) <NEW_LINE> for (ngram,count) in counts.items(): <NEW_LINE> <INDENT> maxcounts[ngram] = max(maxcounts.get(ngram,0), count) <NEW_LINE> <DEDENT> <DEDENT> if eff == "shortest": <NEW_LINE> <INDENT> reflen = min(reflen) <NEW_LINE> <DEDENT> elif eff == "average": <NEW_LINE> <INDENT> reflen = float(sum(reflen))/len(reflen) <NEW_LINE> <DEDENT> return (reflen, maxcounts) | Takes a list of reference sentences for a single segment
and returns an object that encapsulates everything that BLEU
needs to know about them. | 625941be8c0ade5d55d3e8da |
def line(self, serie, rescale=False): <NEW_LINE> <INDENT> serie_node = self.svg.serie(serie) <NEW_LINE> if rescale and self.secondary_series: <NEW_LINE> <INDENT> points = [ (x, self._scale_diff + (y - self._scale_min_2nd) * self._scale) for x, y in serie.points if y is not None] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> points = serie.points <NEW_LINE> <DEDENT> view_values = list(map(self.view, points)) <NEW_LINE> if serie.show_dots: <NEW_LINE> <INDENT> for i, (x, y) in enumerate(view_values): <NEW_LINE> <INDENT> if None in (x, y): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (serie.show_only_major_dots and self.x_labels and i < len(self.x_labels) and self.x_labels[i] not in self._x_major_labels): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> metadata = serie.metadata.get(i) <NEW_LINE> classes = [] <NEW_LINE> if x > self.view.width / 2: <NEW_LINE> <INDENT> classes.append('left') <NEW_LINE> <DEDENT> if y > self.view.height / 2: <NEW_LINE> <INDENT> classes.append('top') <NEW_LINE> <DEDENT> classes = ' '.join(classes) <NEW_LINE> dots = decorate( self.svg, self.svg.node(serie_node['overlay'], class_="dots"), metadata) <NEW_LINE> val = self._get_value(serie.points, i) <NEW_LINE> self.svg.node(dots, 'circle', cx=x, cy=y, r=serie.dots_size, class_='dot reactive tooltip-trigger') <NEW_LINE> self._tooltip_data( dots, val, x, y) <NEW_LINE> self._static_value( serie_node, val, x + self.value_font_size, y + self.value_font_size) <NEW_LINE> <DEDENT> <DEDENT> line_view_values = [[]] <NEW_LINE> for view_value in view_values: <NEW_LINE> <INDENT> if None in view_value: <NEW_LINE> <INDENT> line_view_values.append([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> line_view_values[-1].append(view_value) <NEW_LINE> <DEDENT> <DEDENT> if serie.stroke: <NEW_LINE> <INDENT> if self.interpolate: <NEW_LINE> <INDENT> view_values = list(map(self.view, serie.interpolated)) <NEW_LINE> <DEDENT> if serie.fill: <NEW_LINE> <INDENT> view_values = self._fill(view_values) <NEW_LINE> <DEDENT> for row in line_view_values: <NEW_LINE> <INDENT> if not row: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.svg.line( serie_node['plot'], row, close=self._self_close, class_='line reactive' + ( ' nofill' if not serie.fill else '')) | Draw the line serie | 625941bed99f1b3c44c674af |
def getGenericLocation(self, *args): <NEW_LINE> <INDENT> return _libsbol.OwnedInteraction_getGenericLocation(self, *args) | Get the child object.
templateparam
-------------
* `SBOLClass` :
The type of the child object
* `SBOLSubClass` :
A derived class of SBOLClass. Use this type specialization when adding
multiple types of SBOLObjects to a container.
Parameters
----------
* `uri` :
The specific URI for a child object if this OwnedObject property contains
multiple objects,
Returns
-------
A reference to the child object Returns a child object from the OwnedObject
property. If no URI is specified, the first object in this OwnedObject property
is returned. | 625941be8da39b475bd64e8b |
def MultiOpen(self, urns, mode="rw", token=None, aff4_type=None, age=NEWEST_TIME, follow_symlinks=True): <NEW_LINE> <INDENT> if token is None: <NEW_LINE> <INDENT> token = data_store.default_token <NEW_LINE> <DEDENT> if mode not in ["w", "r", "rw"]: <NEW_LINE> <INDENT> raise RuntimeError("Invalid mode %s" % mode) <NEW_LINE> <DEDENT> symlinks = {} <NEW_LINE> aff4_type = _ValidateAFF4Type(aff4_type) <NEW_LINE> for urn, values in self.GetAttributes(urns, token=token, age=age): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = self.Open( urn, mode=mode, token=token, local_cache={urn: values}, age=age, follow_symlinks=False) <NEW_LINE> if aff4_type: <NEW_LINE> <INDENT> obj.aff4_type = aff4_type <NEW_LINE> <DEDENT> if follow_symlinks and isinstance(obj, AFF4Symlink): <NEW_LINE> <INDENT> target = obj.Get(obj.Schema.SYMLINK_TARGET) <NEW_LINE> if target is not None: <NEW_LINE> <INDENT> symlinks[target] = obj.urn <NEW_LINE> <DEDENT> <DEDENT> elif aff4_type: <NEW_LINE> <INDENT> if isinstance(obj, aff4_type): <NEW_LINE> <INDENT> yield obj <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield obj <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if symlinks: <NEW_LINE> <INDENT> for obj in self.MultiOpen( symlinks, mode=mode, token=token, aff4_type=aff4_type, age=age): <NEW_LINE> <INDENT> obj.symlink_urn = symlinks[obj.urn] <NEW_LINE> yield obj | Opens a bunch of urns efficiently. | 625941beb57a9660fec3379b |
def update_playlist_details(sp, playlist_id, playlist_name, playlist_description): <NEW_LINE> <INDENT> username = sp.me()['id'] <NEW_LINE> results = sp.user_playlist_change_details( username, playlist_id=playlist_id, name=playlist_name, description=playlist_description) <NEW_LINE> return results | Updates playlist details.
NOTE: There are several reports of issues when updating playlist descriptions in the Spotify community.
Currently, it seems the only solution is to wait for the server to update, which could take a day. | 625941bed486a94d0b98e05f |
def __init__(self, input_tensors, output_tensors, return_input=False, sess=None): <NEW_LINE> <INDENT> def normalize_name(t): <NEW_LINE> <INDENT> if isinstance(t, six.string_types): <NEW_LINE> <INDENT> return get_op_tensor_name(t)[1] <NEW_LINE> <DEDENT> return t <NEW_LINE> <DEDENT> self.return_input = return_input <NEW_LINE> self.input_tensors = [normalize_name(x) for x in input_tensors] <NEW_LINE> self.output_tensors = [normalize_name(x) for x in output_tensors] <NEW_LINE> self.sess = sess <NEW_LINE> if sess is not None: <NEW_LINE> <INDENT> self._callable = sess.make_callable( fetches=output_tensors, feed_list=input_tensors, accept_options=self.ACCEPT_OPTIONS) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._callable = None | Args:
input_tensors (list): list of names.
output_tensors (list): list of names.
return_input (bool): same as :attr:`PredictorBase.return_input`.
sess (tf.Session): the session this predictor runs in. If None,
will use the default session at the first call.
Note that in TensorFlow, default session is thread-local. | 625941be23e79379d52ee481 |
def __init__(self, indices, values, dense_shape): <NEW_LINE> <INDENT> with ops.name_scope(None, "SparseTensor", [indices, values, dense_shape]): <NEW_LINE> <INDENT> indices = ops.convert_to_tensor( indices, name="indices", dtype=dtypes.int64) <NEW_LINE> values = ops.internal_convert_to_tensor(values, name="values") <NEW_LINE> dense_shape = ops.convert_to_tensor( dense_shape, name="dense_shape", dtype=dtypes.int64) <NEW_LINE> <DEDENT> self._indices = indices <NEW_LINE> self._values = values <NEW_LINE> self._dense_shape = dense_shape <NEW_LINE> indices_shape = indices.shape.with_rank(2) <NEW_LINE> values_shape = values.shape.with_rank(1) <NEW_LINE> dense_shape_shape = dense_shape.shape.with_rank(1) <NEW_LINE> indices_shape.dims[0].merge_with(values_shape.dims[0]) <NEW_LINE> indices_shape.dims[1].merge_with(dense_shape_shape.dims[0]) | Creates a `SparseTensor`.
Args:
indices: A 2-D int64 tensor of shape `[N, ndims]`.
values: A 1-D tensor of any type and shape `[N]`.
dense_shape: A 1-D int64 tensor of shape `[ndims]`. | 625941bebf627c535bc130e9 |
def GetAssembly(self): <NEW_LINE> <INDENT> pass | GetAssembly(self: IAssemblable) -> Assembly | 625941bed164cc6175782c68 |
def onCreateConflict(self,index): <NEW_LINE> <INDENT> confEditorDialog = ConflictEditorDialog(self.parentWidget()) <NEW_LINE> if confEditorDialog.exec_() == QDialog.Accepted: <NEW_LINE> <INDENT> strParent = self.parent() <NEW_LINE> conflictNode = ConflictNode(confEditorDialog.conflict,strParent) <NEW_LINE> self.strModel.Conflict = confEditorDialog.conflict <NEW_LINE> numChildren = strParent.childCount() <NEW_LINE> self._view.model().insertRows(numChildren,1,index.parent()) | Slot raised when user selects to define new conflict information. | 625941beadb09d7d5db6c6ac |
def test_policy_set_gateway_for_vm_with_host_routes(self): <NEW_LINE> <INDENT> cidr = self._next_sequential_cidr(IP(self.base_cidr)) <NEW_LINE> allocation_pools = [{"start": str(IP(cidr[2].ip)), "end": str(IP(cidr[-2].ip))}] <NEW_LINE> net, subnet = self._create_network_with_subnet( 'hostroutes', str(cidr), allocation_pools=allocation_pools) <NEW_LINE> expected_gateway_ip = str(IP(cidr[1].ip)) <NEW_LINE> self.subnets_client.update_subnet( subnet.id, host_routes=[{"destination": "0.0.0.0/0", "nexthop": expected_gateway_ip}]) <NEW_LINE> vm = self._create_server('vm_with_default_route_hostroutes', [net, self.access_network], public_and_service=False) <NEW_LINE> time.sleep(240) <NEW_LINE> self.gateway.remote_client = self._get_remote_client(self.gateway) <NEW_LINE> ssh_cmd = '{}{} {}'.format(self.ssh_command_stub, getattr(vm, self.access_network.name), 'route | grep default') <NEW_LINE> output = self._execute_ssh_command( self.gateway.remote_client.ssh_client, ssh_cmd) <NEW_LINE> msg = ('Expected default route not found in VM connected to network ' 'with gateway_ip defined with host routes') <NEW_LINE> self.assertTrue(output, msg) <NEW_LINE> msg = ('Default route in VM connected to network does not point to ' 'the gateway defined in the network it is connected to') <NEW_LINE> self.assertIn(expected_gateway_ip, output, msg) | This test verifies that defining a host route 0.0.0.0/0 for a network
translates in a default route for vm's connected to that network | 625941be6fece00bbac2d657 |
def _handle_action_set_message(self, message): <NEW_LINE> <INDENT> self.session.message_change_succeed(message) <NEW_LINE> self.session.contacts.me.message = message <NEW_LINE> contact = self.session.contacts.me <NEW_LINE> account = Logger.Account.from_contact(contact) <NEW_LINE> self.session.log('message change', contact.status, message, account) | handle Action.ACTION_SET_MESSAGE
| 625941be85dfad0860c3ad74 |
def test_P_A_W_AA_Deps_Force(self): <NEW_LINE> <INDENT> doc = ISE(PAR(ACTION(tools.getMockActionCmd(ACTION_RC_WARNING, "A1.STD", "A1.ERR"), id="1"), ACTION(tools.getMockActionCmd(ACTION_RC_OK, "A2.STD", "A2.ERR"), id="2"), ACTION(tools.getMockActionCmd(ACTION_RC_OK, "A3.STD", "A3.ERR"), id="3", deps="1,2"), desc="P_A_W_AA_Deps_Force") ) <NEW_LINE> xml = lxml.etree.tostring(doc, pretty_print=True) <NEW_LINE> print(xml) <NEW_LINE> with io.StringIO(unicode(xml)) as reader: <NEW_LINE> <INDENT> execution = api.execute(reader, force=True) <NEW_LINE> self.assertEquals(ACTION_RC_WARNING, execution.rc) <NEW_LINE> actionsMap = execution.executed_actions <NEW_LINE> self.assertEquals(3, len(actionsMap), "actionsMap: %s" % actionsMap) <NEW_LINE> self.assertEquals(0, len(execution.error_actions)) <NEW_LINE> self.assertTrue("1" in actionsMap) <NEW_LINE> self.assertTrue("2" in actionsMap) <NEW_LINE> self.assertTrue("3" in actionsMap) <NEW_LINE> a1 = actionsMap["1"] <NEW_LINE> self.assertEquals(a1.rc, ACTION_RC_WARNING) <NEW_LINE> self.assertEquals(a1.stdout, "A1.STD") <NEW_LINE> self.assertEquals(a1.stderr, "A1.ERR") <NEW_LINE> a2 = actionsMap["2"] <NEW_LINE> self.assertEquals(a2.rc, ACTION_RC_OK) <NEW_LINE> self.assertEquals(a2.stdout, "A2.STD") <NEW_LINE> self.assertEquals(a2.stderr, "A2.ERR") <NEW_LINE> a3 = actionsMap["3"] <NEW_LINE> self.assertEquals(a3.rc, ACTION_RC_OK) <NEW_LINE> self.assertEquals(a3.stdout, "A3.STD") <NEW_LINE> self.assertEquals(a3.stderr, "A3.ERR") | A parallel with three actions. The last one has an explicit
dependency on first ones. The first one will fail with a
WARNING but with force mode. Therefore, the second one should
get executed, *and* also the third one. | 625941be004d5f362079a250 |
def _on_before_selection(self, widget, model_index, style_options): <NEW_LINE> <INDENT> self._on_before_paint(widget, model_index, style_options) <NEW_LINE> widget.set_selected(True) <NEW_LINE> sg_item = shotgun_model.get_sg_data(model_index) <NEW_LINE> num_actions = self._action_manager.populate_menu( widget.actions_menu, sg_item, self._action_manager.UI_AREA_MAIN ) <NEW_LINE> if num_actions > 0: <NEW_LINE> <INDENT> widget.actions_button.show() <NEW_LINE> <DEDENT> widget.set_up_work_area(sg_item["type"], sg_item["id"]) <NEW_LINE> widget.work_area_button.change_work_area.connect(self.change_work_area.emit) | Called when the associated widget is selected. This method
implements all the setting up and initialization of the widget
that needs to take place prior to a user starting to interact with it.
:param widget: The widget to operate on (created via _create_widget)
:param model_index: The model index to operate on
:param style_options: QT style options | 625941be01c39578d7e74d56 |
@spiceErrorCheck <NEW_LINE> def tpictr(sample, lenout=_default_len_out, lenerr=_default_len_out): <NEW_LINE> <INDENT> sample = stypes.stringToCharP(sample) <NEW_LINE> pictur = stypes.stringToCharP(lenout) <NEW_LINE> errmsg = stypes.stringToCharP(lenerr) <NEW_LINE> lenout = ctypes.c_int(lenout) <NEW_LINE> lenerr = ctypes.c_int(lenerr) <NEW_LINE> ok = ctypes.c_int() <NEW_LINE> libspice.tpictr_c(sample, lenout, lenerr, pictur, ctypes.byref(ok), errmsg) <NEW_LINE> return stypes.toPythonString(pictur), ok.value, stypes.toPythonString( errmsg) | Given a sample time string, create a time format picture
suitable for use by the routine timout.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html
:param sample: A sample time string.
:type sample: str
:param lenout: The length for the output picture string.
:type lenout: int
:param lenerr: The length for the output error string.
:type lenerr: int
:return:
A format picture that describes sample,
Flag indicating whether sample parsed successfully,
Diagnostic returned if sample cannot be parsed
:rtype: tuple | 625941be283ffb24f3c5581f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.