code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def swing(self, containers): <NEW_LINE> <INDENT> fail_msg = 'Failed to kill container: {0}' <NEW_LINE> complete_msg = 'Killed {0} of {1} containers.' <NEW_LINE> i = 0 <NEW_LINE> for container in containers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.debug('Killing container: {0}'.format(container)) <NEW_L... | Kills a list of containers.
Args:
containers (mixed, iterable): An iterable object of container ids.
Returns:
None
Examples:
>>> swordsman = Damocles()
>>> swordsman.swing(['xxxxxxxxxx', 'yyyyyyyyyyy']) | 625941c1167d2b6e31218b1d |
def __init__(self, base_arbitration_id, module_name=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(base_arbitration_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError( 'unable to represent given base_arbitration_id as an integer: ', base_arbitration_id) <NEW_LINE> <DEDENT> self.magic_word = [... | Initialize CAN data specific to OSCC module. | 625941c1498bea3a759b9a37 |
def parse_values_from_lines(self,lines): <NEW_LINE> <INDENT> assert len(lines) == len(CONTROL_VARIABLE_LINES), "ControlData error: len of lines not equal to " + str(len(CONTROL_VARIABLE_LINES)) <NEW_LINE> for iline,line in enumerate(lines): <NEW_LINE> <INDENT> vals = line.strip().split() <NEW_LINE> names ... | cast the string lines for a pest control file into actual inputs
Parameters:
----------
lines: strings from pest control file
Returns:
-------
None | 625941c1435de62698dfdbd4 |
def convert_tg_mean(mu, scale, step=1e-7): <NEW_LINE> <INDENT> X = np.arange(0, 1, step) <NEW_LINE> return (X * sc.norm.pdf(X, loc=mu, scale=scale)).mean()+ 1 - sc.norm.cdf(1, loc=mu, scale=scale) | :param mu: mean of the underlying gaussian r.v
:param scale: scale of the underlying gaussian r.v
:param step: precision of the numerical integration
:return: compute the mean of the Truncated Gaussian r.v knowing the parameters of its
associated Gaussian r.v | 625941c13617ad0b5ed67e80 |
def main(argv): <NEW_LINE> <INDENT> args, opts = oss.gopt(argv[1:], [], [('o', 'output')], main.__doc__ + __doc__) <NEW_LINE> outfile = 'cmd_help.html' if opts.output is None else opts.output <NEW_LINE> if len(args) == 0: <NEW_LINE> <INDENT> args = oss.ls('*.py') <NEW_LINE> <DEDENT> title = oss.pwd() <NEW_LINE> print("... | usage: mk_cmd_help.py [options] [<file_name> ...]
options:
-o | --output : html file output <default: 'cmd_help.html'
generate an html output file of the help strings from the specified
commands | 625941c196565a6dacc8f653 |
def trained_estimator_from_hyperparams(s3_train_data, hyperparams, output_path, s3_test_data=None): <NEW_LINE> <INDENT> knn = sagemaker.estimator.Estimator(get_image_uri(boto3.Session().region_name, "knn"), get_execution_role(), train_instance_count=1, train_instance_type='ml.c4.xlarge', output_path=output_path, sagema... | Create an Estimator from the given hyperparams, fit to training data,
and return a deployed predictor | 625941c1e76e3b2f99f3a797 |
def svd(data): <NEW_LINE> <INDENT> N, D = data.shape <NEW_LINE> data = data - np.mean(data, axis=0) <NEW_LINE> Veig_val, Veig_vector = np.linalg.eigh(np.dot(data.T, data)) <NEW_LINE> VT = Veig_vector[:, np.argsort(-abs(Veig_val))].T <NEW_LINE> Ueig_val, Ueig_vector = np.linalg.eigh(np.dot(data, data.T)) <NEW_LINE> U = ... | :param data:
:return: U, Sigma, VT | 625941c18da39b475bd64ef9 |
def discriminator_loss(self, D, y, fake_y, label, use_lsgan=True): <NEW_LINE> <INDENT> if use_lsgan: <NEW_LINE> <INDENT> error_real = tf.reduce_mean(tf.squared_difference(D(y), label)) <NEW_LINE> error_fake = tf.reduce_mean(tf.square(D(fake_y))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_real = -tf.reduce_mean... | Note: default: D(y).shape == (batch_size,5,5,1),
fake_buffer_size=50, batch_size=1
Args:
G: generator object
D: discriminator object
y: 4D tensor (batch_size, image_size, image_size, 3)
Returns:
loss: scalar | 625941c163b5f9789fde706d |
def _on_change_pos(self, editable): <NEW_LINE> <INDENT> if self.__updating: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__updating = True <NEW_LINE> el = False <NEW_LINE> if self._notebook.get_current_page() == 0: <NEW_LINE> <INDENT> el = self._get_active_bg() <NEW_LINE> <DEDENT> elif self._notebook.get_current... | Update the position on change.
`pos.right` will be updated to be larger than `pos.left`. Same for
top and bottom. | 625941c18e71fb1e9831d732 |
def isTitleVisible(self): <NEW_LINE> <INDENT> return self.titleVisible | True if the title is configured to be visible, False otherwise. | 625941c1293b9510aa2c321f |
def subscribe(self, channel, *clients): <NEW_LINE> <INDENT> active_subscribers = self._get_active_subscribers_idx(channel) <NEW_LINE> for client in clients: <NEW_LINE> <INDENT> ch_logger.debug('Subscribe client {} on channel {}'.format( client.address, channel)) <NEW_LINE> active_subscribers.update({client.address: wea... | Subscribe client for a channel.
Method supports multiple subscriptions.
:param channel: string channel name
:param clients: geventwebsocket.handler.Client list | 625941c1009cb60464c6333b |
def listening(port, shortened=False, pid_only=False, proc_only=False, kill=False): <NEW_LINE> <INDENT> if platform.system() != 'Linux': <NEW_LINE> <INDENT> sys.stderr.write('listeningPort available only under Linux!\n') <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> proc = subprocess.Popen('/usr/sbin/fuser %s/tcp' % str(p... | The return code may seem to be reversed, but
it exists for the common command line version:
return N # Indicate found N listeners
return 0 # Indicates nobody listening | 625941c10a50d4780f666e18 |
def build_map_dict_by_name(gdpinfo, plot_countries, year): <NEW_LINE> <INDENT> return_dict = {} <NEW_LINE> return_set1,return_set2 = set(), set() <NEW_LINE> gdpdata = read_csv_as_nested_dict(gdpinfo['gdpfile'], gdpinfo['country_name'], gdpinfo['separator'], gdpinfo['quote']) <NEW_LINE> for country_code in plot_countrie... | Inputs:
gdpinfo - A GDP information dictionary
plot_countries - Dictionary whose keys are plot library country codes
and values are the corresponding country name
year - String year to create GDP mapping for
Output:
A tuple containing a dictionary and two sets. The dictiona... | 625941c199fddb7c1c9de31a |
@api.route('/mapreduce', methods=['POST','GET']) <NEW_LINE> @auto.doc() <NEW_LINE> def mapreduce(): <NEW_LINE> <INDENT> collection = request.args.get('collection', 'revisions') <NEW_LINE> full_response = request.args.get('full_response', False) <NEW_LINE> db = RevisionDB(config={'host': config['default'].MONGO_HOST, 'p... | Use a json payload to query map reduce results
Params:
<ul class="params">
<li>collection.Required. Collection name</li>
<li>map. Required. map function code</li>
<li>reduce. Required. reduce function code</li>
</ul>
<i>Example: <a href="mapreduce?map=function(){emit(this.user,this.size);}&reduce=function(... | 625941c14e696a04525c93d4 |
def param_type(param): <NEW_LINE> <INDENT> if isinstance(param, Mixed) and len(param): <NEW_LINE> <INDENT> subtypes = [param_type(subparam) for subparam in param] <NEW_LINE> return " or ".join(subtypes) <NEW_LINE> <DEDENT> elif isinstance(param, (list, tuple, set)) and len(param): <NEW_LINE> <INDENT> return "array of "... | Return the XML-RPC type of a parameter. | 625941c1ec188e330fd5a72b |
def testOffset(self): <NEW_LINE> <INDENT> encoder = RandomDistributedScalarEncoder(name="encoder", resolution=1.0) <NEW_LINE> encoder.encode(23.0) <NEW_LINE> self.assertEqual(encoder._offset, 23.0, "Offset not specified and not initialized to first input") <NEW_LINE> encoder = RandomDistributedScalarEncoder(name="encod... | Test that offset is working properly | 625941c156ac1b37e626415b |
def test_if_excel_generator_adds_content_correctly(self): <NEW_LINE> <INDENT> path_of_excel_workbook_exemplar = ( CURRENT_PATH + '/exemplar_data/expected_excel_sheet_outcome.xlsx') <NEW_LINE> xlsx_file = generate_test_data_excel_workbook() <NEW_LINE> df1 = pd.read_excel(xlsx_file) <NEW_LINE> df2 = pd.read_excel(open(pa... | Test if an excel workbook generated by the linkchecker does not
differ an exemplar workbook containing the expected data. | 625941c171ff763f4b549610 |
def testCookerCommandEvent(self, command, params): <NEW_LINE> <INDENT> pattern = params[0] <NEW_LINE> command.cooker.testCookerCommandEvent(pattern) <NEW_LINE> command.finishAsyncCommand() | Dummy command used by OEQA selftest to test tinfoil without IO | 625941c167a9b606de4a7e43 |
def template_wrapping_substitute(line, dict): <NEW_LINE> <INDENT> for key, value in dict.items(): <NEW_LINE> <INDENT> splits = line.split(key) <NEW_LINE> l = len(splits) <NEW_LINE> if l > 1: <NEW_LINE> <INDENT> for i in range(1, l, 2): <NEW_LINE> <INDENT> word = value.replace(key, splits[i]) <NEW_LINE> splits[i] = word... | substitutes in a line expressions from a dict
expressions are of the sort : wrapperKEYwrapper -> blaKEYblo
For instance :
dict = { "_" : "A[:,_]" }
line = "_1_ + _2_"
will return "A[:,1] + A[:,2]" | 625941c1e8904600ed9f1eb3 |
def toggle_left_pane(self): <NEW_LINE> <INDENT> enabled = config.get('enable_vertical_tab_list') <NEW_LINE> if not config.silent_set('enable_vertical_tab_list', str(not enabled)): <NEW_LINE> <INDENT> self.information('Unable to write in the config file', 'Error') <NEW_LINE> <DEDENT> self.call_for_resize() | Enable/disable the left panel. | 625941c16fb2d068a760f023 |
def simplify_unit_impulse(self): <NEW_LINE> <INDENT> result = simplify_unit_impulse(self.expr, self.var) <NEW_LINE> return self.__class__(result, **self.assumptions) | Simplify UnitImpulse(4 * k + 8) to UnitImpulse(k + 2), etc. | 625941c1956e5f7376d70df6 |
def findLongestChain(self, pairs): <NEW_LINE> <INDENT> n = len(pairs) <NEW_LINE> pairs.sort(key = lambda x:(x[0],x[1])) <NEW_LINE> chain_len, chain_end = 1, pairs[0][1] <NEW_LINE> for p in range(1,n) : <NEW_LINE> <INDENT> if pairs[p][0] <= chain_end: <NEW_LINE> <INDENT> chain_end = min(chain_end, pairs[p][1]) <NEW_LINE... | :type pairs: List[List[int]]
:rtype: int | 625941c1baa26c4b54cb10aa |
def calculateHandlen(hand): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for key, value in hand.items(): <NEW_LINE> <INDENT> count += hand.get(key, 0) <NEW_LINE> <DEDENT> return count | Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer | 625941c1d99f1b3c44c6751c |
def test_exact_fscore_agreement(): <NEW_LINE> <INDENT> for nprobs in range(1, 9): <NEW_LINE> <INDENT> probs = np.random.rand(nprobs) <NEW_LINE> thresh = np.random.rand() <NEW_LINE> naive = fsc.exact_expected_fscore_naive(probs, thresh) <NEW_LINE> clever = cfsc.efscore(probs, thresh) <NEW_LINE> assert naive == pytest.ap... | Test whether the naive and 'clever' implementations of exact expected fscore
agree on a bunch of randomly generated examples of different sizes. | 625941c13346ee7daa2b2cf2 |
def formatLine(self, line): <NEW_LINE> <INDENT> line = line.split("] ", 1)[1] <NEW_LINE> line = line.replace("[Server]", '', 1) <NEW_LINE> line = line.replace('[Server thread/INFO]:', '', 1) <NEW_LINE> line = line.strip() <NEW_LINE> return line | Cut unwanted parts from given line.
- :param line: Line to be formatted
- :type line: string
- :returns string: | 625941c1be383301e01b5411 |
def put_HelpContextID(self, contextID): <NEW_LINE> <INDENT> return super(ICommandItem, self).put_HelpContextID(contextID) | Method ICommandItem.put_HelpContextID
INPUT
contextID : long | 625941c1c432627299f04bcc |
def test_shell_show_selected_sorted(): <NEW_LINE> <INDENT> resp = run_cmd("show selected sortby sender asc limit 2") <NEW_LINE> assert "Preview of first 2" in resp <NEW_LINE> assert len(resp.split('\n')) == 3 <NEW_LINE> resp = run_cmd("show selected sortby sender desc limit 2") <NEW_LINE> assert "Preview of first 2" in... | Test 'show selected sortby sender limit 2' command | 625941c15e10d32532c5eeaf |
def configure_for_kubernetes(): <NEW_LINE> <INDENT> pass | Configures Baker Street for a Kubernetes deployment | 625941c1287bf620b61d39ed |
def check_scm(domain_str, gittree_str): <NEW_LINE> <INDENT> global _message <NEW_LINE> _message = [] <NEW_LINE> try: <NEW_LINE> <INDENT> domains_data = parse_blocks(domain_str, MAPPING) <NEW_LINE> trees_data = parse_blocks(gittree_str, MAPPING) <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> error(str... | check domain and gittree file.
The return value: zero means everything is ok, non-zero means something
is wrong, and the number is the error num in total. | 625941c1d8ef3951e32434c5 |
@wraps('lazy') <NEW_LINE> def relu_forward(x): <NEW_LINE> <INDENT> out = np.maximum(0, x) <NEW_LINE> return out | Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x | 625941c18a43f66fc4b53fef |
def read_json(file, *_args, **_kwargs): <NEW_LINE> <INDENT> if sys.version_info >= (3, 6): <NEW_LINE> <INDENT> _json = json.load(file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_content_str = file.read().decode() <NEW_LINE> _json = json.loads(file_content_str) <NEW_LINE> <DEDENT> flattened = json_normalize(_jso... | Read a semi-structured JSON file into a flattened dataframe.
Args:
file: file-like object
_args: positional arguments receiver; not used
_kwargs: keyword arguments receiver; not used
Returns:
Dataframe with single column level; original JSON hierarchy is
expressed as dot notation in column nam... | 625941c157b8e32f52483422 |
def check(com, user): <NEW_LINE> <INDENT> if com == user: <NEW_LINE> <INDENT> print("I chose same :", com) <NEW_LINE> print("A DRAW. AGAIN...") <NEW_LINE> return 2 <NEW_LINE> <DEDENT> elif com == "rock" and user == "paper": <NEW_LINE> <INDENT> print("YOU WIN!! I chose", com) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif... | Logic of the entire game.
returns 2 for a DRAW, 1 if USER WINS, 0 IF COM WINS | 625941c155399d3f0558863b |
def get_insn(self): <NEW_LINE> <INDENT> return self.insn | Get the insn buffer
:rtype: bytes | 625941c1b5575c28eb68df87 |
def parse_tile(text: str) -> Tuple[int, List[List[str]]]: <NEW_LINE> <INDENT> id_tile, image = text.split(":\n") <NEW_LINE> return int(id_tile.replace("Tile ", "")), [list(i) for i in image.split("\n")] | Given 'Tile 1567:
.####.##.#
.......#..
.###..###.
.....#..#.
..#....#..
#......###
#..#.....#
#....##...
...###...#
#.#.#..##.'
return (1567, [['.', '#', '#', '#', '#', '.', '#', '#', '.', '#'], ['.', '.', '.', '.', '.', '.', '.', '#', '.', '.'], ...] | 625941c17b25080760e393e2 |
def SetFixedImageIndexes(self, *args): <NEW_LINE> <INDENT> return _itkImageToImageMetricPython.itkImageToImageMetricIUL2IUL2_SetFixedImageIndexes(self, *args) | SetFixedImageIndexes(self, std::vector<(itkIndex2,std::allocator<(itkIndex2)>)> indexes) | 625941c1be7bc26dc91cd58c |
def summary(self): <NEW_LINE> <INDENT> print("\nSummary") <NEW_LINE> print("=" * 79) <NEW_LINE> cmd = "All repositories are updated." <NEW_LINE> if self.count_repo == 1: <NEW_LINE> <INDENT> cmd = "Repository is updated." <NEW_LINE> <DEDENT> if self.count_news > 0: <NEW_LINE> <INDENT> cmd = "Run the command 'slpkg updat... | Print summary
| 625941c13317a56b86939be6 |
def nsmallest(n, iterable, key=None): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> it = iter(iterable) <NEW_LINE> sentinel = object() <NEW_LINE> if key is None: <NEW_LINE> <INDENT> result = min(it, default=sentinel) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = min(it, default=sentinel, key=key) <NEW_LIN... | Find the n smallest elements in a dataset.
Equivalent to: sorted(iterable, key=key)[:n] | 625941c18c0ade5d55d3e941 |
def rightButton(autohotpy,event): <NEW_LINE> <INDENT> stroke = InterceptionMouseStroke() <NEW_LINE> stroke.state = InterceptionMouseState.INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN <NEW_LINE> autohotpy.sendToDefaultMouse(stroke) <NEW_LINE> stroke.state = InterceptionMouseState.INTERCEPTION_MOUSE_RIGHT_BUTTON_UP <NEW_LINE> au... | This function simulates a right click | 625941c19f2886367277a817 |
def print_first_and_last(sentence): <NEW_LINE> <INDENT> words = break_words(sentence) <NEW_LINE> print_first_world(words) <NEW_LINE> print_last_world(words) | prints the first and last words of the sentence | 625941c1e1aae11d1e749c3e |
def butConnHandler(self): <NEW_LINE> <INDENT> if not validIp(self.serverIp): <NEW_LINE> <INDENT> QMessageBox.critical(self, 'Invalid Ip', f"Invalid IP address: {self.serverIp}", QMessageBox.Ok) <NEW_LINE> self.tIp.setFocus() <NEW_LINE> return <NEW_LINE> <DEDENT> if not validPort(self.serverPorta): <NEW_LINE> <INDENT> Q... | button逻辑,判断输入是否合法 | 625941c1627d3e7fe0d68dd7 |
def _parse_line_with_compiled_regexes(self, line): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for item, reg in self.mapping.compiled_regexes: <NEW_LINE> <INDENT> if reg.search(line): <NEW_LINE> <INDENT> line, _count = reg.subn(self.mapping.get(item.lower()), line) <NEW_LINE> count += _count <NEW_LINE> <DEDENT> <DEDENT> r... | Check the provided line against known items we have encountered
before and have pre-generated regex Pattern() objects for.
:param line: The line to parse for possible matches for obfuscation
:type line: ``str``
:returns: The obfuscated line and the number of changes made
:rtype: ``str``, ``int`` | 625941c115baa723493c3efc |
def __init__(self, format_maps): <NEW_LINE> <INDENT> if format_maps is None: <NEW_LINE> <INDENT> format_maps = [{}] <NEW_LINE> <DEDENT> if not isinstance(format_maps, (list, tuple)): <NEW_LINE> <INDENT> raise GenestackException('Format map should be list or tuple') <NEW_LINE> <DEDENT> map(self.validate, format_maps) <N... | Format pattern is a list of format maps.
You can specify all required formats in constructor or add them from other format pattern with ``add`` method
:param format_maps: list of dicts
:return: | 625941c1a8370b7717052829 |
def close(self): <NEW_LINE> <INDENT> if self.logger is not None: <NEW_LINE> <INDENT> logger.close() | Stop crawling and close any additional running functionalities. | 625941c1851cf427c661a49a |
def expand_query(query_str): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> word_index = -1 <NEW_LINE> index_reset = False <NEW_LINE> for ch in query_str: <NEW_LINE> <INDENT> global full_word_query <NEW_LINE> if ch == " ": <NEW_LINE> <INDENT> if index == len(query_str) - 1: <NEW_LINE> <INDENT> global last_word <NEW_LINE> las... | Expand the raw query string to generate term queries that can be used to search the documents
:param query_str: the raw input query that needs to be expanded.
UpperCased query if raw query contains only lower case characters.
:return: all possible term queries that include
* upper_case_query - the sequence of upper cas... | 625941c1a934411ee375161b |
def get_a_action(base, action_id): <NEW_LINE> <INDENT> res = base.client.get_obj('actions', action_id) <NEW_LINE> return res['body'] | Utility function that gets a Senlin action. | 625941c107d97122c4178810 |
def __init__(self, nodes , activationFunction = "ReLU"): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.learning_rate = 0.02 <NEW_LINE> self.gene_off = 0 <NEW_LINE> self.nodes = nodes <NEW_LINE> self.layer = len(self.nodes) <NEW_LINE> self.five_fold_count = 1 <NEW_LINE> self.activationFunction = activationFunct... | :param
1. nodes: nodes list of Deep neural network.
2. activationFunction : choice of activation function , default is ReLU | 625941c12eb69b55b151c835 |
def mixer_s32_256(**kwargs): <NEW_LINE> <INDENT> model = MLP_Mixer(patch_size = 32, num_layers = 8 , dim = 512, token_dim = 256, channel_dim = 2048, **kwargs) <NEW_LINE> return model | Mixer-S/32 256x256
| 625941c15510c4643540f372 |
def __itruediv__(self, arg): <NEW_LINE> <INDENT> return self._binary_operator_inplace(arg, lambda l, r: l / r) | _CPP_:
MO__VEC_OP_INPLACE(l /= r) | 625941c14e696a04525c93d5 |
def file_util_is_exists(path): <NEW_LINE> <INDENT> return os.path.exists(path) | 判断文件或目录是否存在 | 625941c14a966d76dd550f96 |
def send_file_service(service): <NEW_LINE> <INDENT> send_file(device_id, url=service.data.get('url'), api_key=api_key) | Service to send files to devices. | 625941c192d797404e304112 |
def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"): <NEW_LINE> <INDENT> if (sys.platform == "win32" or not LocateBinary(tool)): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if (tool == "pkg-config"): <NEW_LINE> <INDENT> handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)... | Returns a list of library paths for the package, NOT prefixed by -L. | 625941c16fb2d068a760f024 |
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close() | Activated at the end of the with statement. | 625941c1656771135c3eb7f5 |
def get_instrument_info(self,instrument,granularity,number_of_candles,start_time=None,end_time=None): <NEW_LINE> <INDENT> if start_time == None and end_time == None: <NEW_LINE> <INDENT> params = {'granularity':granularity,'count':number_of_candles,'price':'BA'} <NEW_LINE> <DEDENT> elif end_time == None: <NEW_LINE> <IND... | gets number_of_candles from start_time (if specified) for instrument at granularity
returns dictionary of lists dictionary keys are 'time','bid_open','bid_high','bid_low','bid_close','ask_open','ask_high','ask_low','ask_close'
volume list for each are of length number of candles, and represent the values for each of th... | 625941c176e4537e8c3515f9 |
def add_controller( self, controller_name, controller ): <NEW_LINE> <INDENT> self.controllers[ controller_name ] = controller | Add a controller class to this application. A controller class has
methods which handle web requests. To connect a URL to a controller's
method use `add_route`. | 625941c1bf627c535bc13157 |
def evaluate_left(self, eval_scope={}): <NEW_LINE> <INDENT> return self.left_size.evaluate(**eval_scope) | Evaluate left side size. | 625941c11d351010ab855aa5 |
def robust_rmtree(path: Union[str, bytes]) -> None: <NEW_LINE> <INDENT> if not isinstance(path, bytes): <NEW_LINE> <INDENT> path = path.encode('utf-8') <NEW_LINE> <DEDENT> if not os.path.exists(path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not os.path.islink(path) and os.path.isdir(path): <NEW_LINE> <INDENT>... | Robustly tries to delete paths.
Continues silently if the path to be removed is already gone, or if it
goes away while this function is executing.
May raise an error if a path changes between file and directory while the
function is executing, or if a permission error is encountered. | 625941c12eb69b55b151c836 |
def powerset(iterable): <NEW_LINE> <INDENT> s = list(iterable) <NEW_LINE> return itertools.chain.from_iterable( itertools.combinations(s, r) for r in range(len(s)+1)) | powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) | 625941c14d74a7450ccd414c |
def mk_cgroup_cgcreate(self, pwd=None, cgroup=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parent_cgroup = self.get_cgroup_name(pwd) <NEW_LINE> if cgroup is None: <NEW_LINE> <INDENT> range = "abcdefghijklmnopqrstuvwxyz0123456789" <NEW_LINE> sub_cgroup = "cgroup-" + "".join(random.sample(range + range.upper(), 6)... | Make a cgroup by executing the cgcreate command
:params: cgroup: name of the cgroup to be created
:return: last cgroup index | 625941c1377c676e91272132 |
def __init__(self, model, memory_size=1024, Batch_size=32, Gamma=0.99, Epsilon=rangefloat(1.0,0.1,1e6), K=1, name='Agent'): <NEW_LINE> <INDENT> self.Memory = PrioritizedReplay(memory_size) <NEW_LINE> self.Batch_size = Batch_size <NEW_LINE> self.Gamma = Gamma <NEW_LINE> if type(Epsilon) is float or type(Epsilon) is int:... | Create Agent from model description file. | 625941c116aa5153ce362401 |
def verifyPreorder(self, preorder): <NEW_LINE> <INDENT> lower = -sys.maxint <NEW_LINE> i = 0 <NEW_LINE> for e in preorder: <NEW_LINE> <INDENT> if e < lower: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> while i > 0 and e > preorder[i-1]: <NEW_LINE> <INDENT> lower = preorder[i-1] <NEW_LINE> i -= 1 <NEW_LINE> <DED... | :type preorder: List[int]
:rtype: bool | 625941c1507cdc57c6306c5f |
def format(self): <NEW_LINE> <INDENT> return Table([[v] for v in self._values]).format(alignment="r") | Format the vector for human consumption | 625941c1fb3f5b602dac361a |
@nox.session(python=False) <NEW_LINE> def sign(session): <NEW_LINE> <INDENT> def sign_darwin(cert_name): <NEW_LINE> <INDENT> session.run('security', 'find-identity', external=True) <NEW_LINE> session.run( 'codesign', '--deep', '--force', '--verbose', '--timestamp', '--identifier', OSX_BUNDLE_IDENTIFIER, '--entitlements... | Sign the bundled distribution (macOS and Windows only). | 625941c199cbb53fe6792b70 |
def dispose(self, v): <NEW_LINE> <INDENT> key = self._value_to_key.pop(v) <NEW_LINE> pool = self._pools[key] <NEW_LINE> return pool.dispose(v) | Dispose a previously acquired value. | 625941c145492302aab5e24a |
def render_simple_tray_divider(self, width, height, move): <NEW_LINE> <INDENT> if self.move(height, width, move, True): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> t = self.thickness <NEW_LINE> self.polyline( height - t, 90, t, -90, t, 90, width - 2 * t, 90, t, -90, t, 90, height - t, 90, width, 90, ) <NEW_LINE> sel... | Simple movable divider. A wall with small feet for a little more stability. | 625941c1711fe17d825422f9 |
def _set_capacities_proportionally(topology, capacities, metric, capacity_unit='Mbps'): <NEW_LINE> <INDENT> if not capacity_unit in capacity_units: <NEW_LINE> <INDENT> raise ValueError("The capacity_unit argument is not valid") <NEW_LINE> <DEDENT> if any((capacity < 0 for capacity in capacities)): <NEW_LINE> <INDENT> r... | Set link capacities proportionally to the value of a given edge metric.
Parameters
----------
topology : Topology
The topology to which link capacities will be set
capacities : list
A list of all possible capacity values
metric : dict
A dictionary with all values of the given edge metric, keyed by edge
... | 625941c1fff4ab517eb2f3c4 |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(self.angles.tostring()) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <NEW_LINE> except TypeError as te: sel... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941c116aa5153ce362402 |
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/PeepCoin/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "PeepCoin") <NEW_LINE> <DEDENT> r... | Return the default location of the peepcoin data directory | 625941c1460517430c394113 |
def peekFirst(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.deque[len(self.deque) -1] | Returns but does not remove the first item of the deque. | 625941c115fb5d323cde0a96 |
def get_parameters(self): <NEW_LINE> <INDENT> strategy_parameters = {} <NEW_LINE> for name in self.parameters: <NEW_LINE> <INDENT> strategy_parameters[name] = getattr(self, name) <NEW_LINE> <DEDENT> return strategy_parameters | Get strategy parameters dict. | 625941c15166f23b2e1a50e2 |
def getProject(self, pid): <NEW_LINE> <INDENT> return self.request(Endpoints.PROJECTS + '/{0}'.format(pid)) | return all projects that are visable to a user | 625941c1b5575c28eb68df88 |
def __init__(self,n_input,n_hidden,transfer_function = tf.nn.softplus,optimizer = tf.train.AdamOptimizer(),scale = 0.1): <NEW_LINE> <INDENT> self.n_input = n_input <NEW_LINE> self.n_hidden = n_hidden <NEW_LINE> self.transfer = transfer_function <NEW_LINE> self.scale = tf.placeholder(tf.float32) <NEW_LINE> self.training... | 构造器
Args:
n_input:输入变量数
n_hidden:隐含层节点数量
transfer_function:隐含层激活函数
optimizer:优化器
scale:高斯噪声系数 | 625941c160cbc95b062c64cc |
def candidates(word, WORDS): <NEW_LINE> <INDENT> return (known([word], WORDS) or known(edits1(word), WORDS) or known(edits2(word), WORDS) or [word]) | Generate possible spelling corrections for word. | 625941c1cc40096d615958da |
@pytest.mark.xfail <NEW_LINE> def test_convert_scalar(): <NEW_LINE> <INDENT> foo = Value(scalars=1.2) <NEW_LINE> assert foo.scalars[0].value == 1.2 | Test that scalars are made rigid | 625941c17d847024c06be243 |
def refresh(self): <NEW_LINE> <INDENT> self.__plugins = {} <NEW_LINE> return self | Clean-up plugin cache
This will force to reinitialize each plugin when asked | 625941c19f2886367277a818 |
def __init__(self): <NEW_LINE> <INDENT> self.OrderId = None <NEW_LINE> self.PkgId = None <NEW_LINE> self.Status = None <NEW_LINE> self.StartTime = None <NEW_LINE> self.EndTime = None | :param OrderId: 定单唯一性ID
:type OrderId: str
:param PkgId: 云存套餐ID
:type PkgId: str
:param Status: 定单服务状态
:type Status: int
:param StartTime: 定单服务生效时间
:type StartTime: int
:param EndTime: 定单服务失效时间
:type EndTime: int | 625941c163f4b57ef00010a8 |
def reset( self, resource_group_name, workflow_name, trigger_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version... | Resets a workflow trigger.
:param resource_group_name: The resource group name.
:type resource_group_name: str
:param workflow_name: The workflow name.
:type workflow_name: str
:param trigger_name: The workflow trigger name.
:type trigger_name: str
:keyword callable cls: A custom type or function that will be passed t... | 625941c16fece00bbac2d6c6 |
def add_package_menu_items(self, pkg_id, pkg_name, items): <NEW_LINE> <INDENT> if len(self._package_menu_items) == 0: <NEW_LINE> <INDENT> self.packagesMenu.menuAction().setEnabled(True) <NEW_LINE> <DEDENT> if not self._package_menu_items.has_key(pkg_id): <NEW_LINE> <INDENT> pkg_menu = self.packagesMenu.addMenu(str(pkg_... | add_package_menu_items(pkg_id: str,pkg_name: str,items: list)->None
Add a pacckage menu entry with submenus defined by 'items' to
Packages menu. | 625941c130bbd722463cbd4d |
def maxTurbulenceSize(self, A): <NEW_LINE> <INDENT> pass | :type A: List[int]
:rtype: int | 625941c18e05c05ec3eea2fc |
@app.route('/shutdown') <NEW_LINE> def shutdown(): <NEW_LINE> <INDENT> func = request.environ.get('werkzeug.server.shutdown') <NEW_LINE> if func is None: <NEW_LINE> <INDENT> return jsonify({'status': 'error - Not running with the Werkzeug Server'}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func() <NEW_LINE> return ... | Shutdown server | 625941c14f88993c3716bff2 |
def glInitPlatformX11KHR(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME ) | Return boolean indicating whether this extension is available | 625941c1a17c0f6771cbdfdc |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941c11f037a2d8b946188 |
def __getitem__(self, item): <NEW_LINE> <INDENT> return self._expense[item] | returns payment with index of item
:param item: payment index
:return: payment | 625941c199fddb7c1c9de31b |
def test_nrows_ncols_ndepths_sum(self): <NEW_LINE> <INDENT> self.assertModule('r3.mapcalc', expression='nrows_ncols_ndepths_sum = nrows() + ncols() + ndepths()') <NEW_LINE> self.to_remove.append('nrows_ncols_ndepths_sum') <NEW_LINE> self.assertRaster3dMinMax('nrows_ncols_ndepths_sum', refmin=2160, refmax=2160) | Test if sum of nrows, ncols and ndepths matches one
expected from current region settigs | 625941c1bde94217f3682d7c |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'markethink.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you s... | Run administrative tasks. | 625941c123e79379d52ee4ef |
def remove(self, widget): <NEW_LINE> <INDENT> path = self.removable_list[self.remove_item[0]][self.remove_item[1]] <NEW_LINE> self.current_collection.remove(path) <NEW_LINE> self.removable_list[self.remove_item[0]].pop(self.remove_item[1]) <NEW_LINE> self.show_update() <NEW_LINE> self.show_remove_button(False) | remove an extension | 625941c15fcc89381b1e1646 |
def _data_dialog(self): <NEW_LINE> <INDENT> self.progress_processing.setHidden(True) <NEW_LINE> self.progress_processing.setMinimum(0) <NEW_LINE> self.progress_processing.setValue(0) <NEW_LINE> self.tasks = transport.get_result_files(self.work_dir, self.substances) <NEW_LINE> n_tas = len(self.tasks) <NEW_LINE> self.sol... | a dialog for data processing | 625941c1ad47b63b2c509f09 |
def check_job_successful(job): <NEW_LINE> <INDENT> job_dir = job_file(job.uuid) <NEW_LINE> html = job_file(job.uuid, 'STEME.html') <NEW_LINE> meme = job_file(job.uuid, 'meme.txt') <NEW_LINE> successful = ( os.path.exists(job_dir) and os.path.exists(html) and os.stat(html).st_size and os.path.exists(meme) ) <NEW_LINE> r... | Check that the job finished successfully. | 625941c1cc0a2c11143dce19 |
def stop(self) -> None: <NEW_LINE> <INDENT> for upload in self.active_uploads.values(): <NEW_LINE> <INDENT> upload[1].cancel() <NEW_LINE> <DEDENT> if self.observer: <NEW_LINE> <INDENT> self.observer.stop() <NEW_LINE> <DEDENT> self.loop.stop() | Stop the client. | 625941c15fdd1c0f98dc01bc |
def where_parse(where_l): <NEW_LINE> <INDENT> res=[] <NEW_LINE> key=['and','or','not'] <NEW_LINE> char='' <NEW_LINE> for i in where_l: <NEW_LINE> <INDENT> if i in key: <NEW_LINE> <INDENT> if len(char) != 0: <NEW_LINE> <INDENT> char=three_parse(char) <NEW_LINE> res.append(char) <NEW_LINE> <DEDENT> res.append(i) <NEW_LIN... | 对用户输入的where子句后的条件格式化,每个子条件都改成列表形式
where_l: ['id>', '4', 'and', 'id<', '10'] ---> ['id', >', '4', 'and', 'id', '<', '10']
:param where_l: 用户输入where后对应的过滤条件列表
:return: | 625941c1ff9c53063f47c17e |
def add_application_vertices(self, application_graph): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import sqlite3 as sqlite <NEW_LINE> connection = sqlite.connect(self._database_path) <NEW_LINE> cur = connection.cursor() <NEW_LINE> cur.execute( "CREATE TABLE Application_vertices(" "vertex_id INTEGER PRIMARY KEY AUTOIN... | :param application_graph:
:return: | 625941c1167d2b6e31218b1f |
def __init__(self, data): <NEW_LINE> <INDENT> self._data = pickle.load(data) <NEW_LINE> self._v_label = _('Time') <NEW_LINE> self._h_label = '' | Import chart data from file. | 625941c13617ad0b5ed67e82 |
def _cleanup_remote_target( self, array, volume, remote_array, device_id, target_device, rdf_group, volume_name, rep_extra_specs): <NEW_LINE> <INDENT> self.masking.remove_and_reset_members( remote_array, volume, target_device, volume_name, rep_extra_specs, False) <NEW_LINE> are_vols_paired, local_vol_state, pair_state ... | Clean-up remote replication target after exception or on deletion.
:param array: the array serial number
:param volume: the volume object
:param remote_array: the remote array serial number
:param device_id: the source device id
:param target_device: the target device id
:param rdf_group: the RDF group
:param volume_n... | 625941c1b7558d58953c4ea2 |
@login_required <NEW_LINE> def project_gene_list_settings(request, project_id): <NEW_LINE> <INDENT> project = get_object_or_404(Project, project_id=project_id) <NEW_LINE> if not project.can_view(request.user): <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return render(request, 'project/project_gene_li... | Manager can edit project settings | 625941c157b8e32f52483423 |
def get_submission_count(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return obj.submission_count <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return obj.submissions | Add a custom method to get submission count | 625941c1460517430c394114 |
def authenticate(self, name, password=None, source=None, mechanism='MONGODB-CR'): <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError("name must be an instance " "of %s" % (str.__name__,)) <NEW_LINE> <DEDENT> if password is not None and not isinstance(password, str): <NEW_LINE> <INDENT... | Authenticate to use this database.
Raises :class:`TypeError` if either `name` or `password` is not
an instance of :class:`basestring` (:class:`str` in python 3).
Authentication lasts for the life of the underlying client
instance, or until :meth:`logout` is called.
The "admin" database is special. Authenticating on "... | 625941c194891a1f4081ba32 |
def test_api_root_endpoint(app): <NEW_LINE> <INDENT> assert 'application/json' == app.get('/api/').content_type | Make sure the api root (/api/) works | 625941c16fece00bbac2d6c7 |
def isPalindrome(self, s): <NEW_LINE> <INDENT> if len(s) == 0: return True <NEW_LINE> result = re.subn('[^0-9A-Za-z]', '', s)[0].lower() <NEW_LINE> reverse = result[-1:-len(result) - 1:-1] <NEW_LINE> return result == reverse | :type s: str
:rtype: bool | 625941c1167d2b6e31218b20 |
@app.route("/apperror") <NEW_LINE> def appError(): <NEW_LINE> <INDENT> flash('Something happened in the system !!! ','error') <NEW_LINE> return render_template('general_error.html'), 404 | In order to manage the unexpected error | 625941c17c178a314d6ef3e5 |
def HermeticZipInfo(*args, **kwargs): <NEW_LINE> <INDENT> date_time = None <NEW_LINE> if len(args) >= 2: <NEW_LINE> <INDENT> date_time = args[1] <NEW_LINE> <DEDENT> elif 'date_time' in kwargs: <NEW_LINE> <INDENT> date_time = kwargs['date_time'] <NEW_LINE> <DEDENT> if not date_time: <NEW_LINE> <INDENT> kwargs['date_time... | Creates a zipfile.ZipInfo with a constant timestamp and external_attr.
If a date_time value is not provided in the positional or keyword arguments,
the default value from HermeticDateTime is used.
Args:
See zipfile.ZipInfo.
Returns:
A zipfile.ZipInfo. | 625941c10a50d4780f666e1a |
def toggle_anim(self, toggling): <NEW_LINE> <INDENT> if toggling: <NEW_LINE> <INDENT> self.anim.setDirection(QAbstractAnimation.Forward) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.anim.setDirection(QAbstractAnimation.Backward) <NEW_LINE> <DEDENT> self.anim.start() | Toggle the animation to be play forward or backward
Parameters
----------
toggling: bool
True for forward, False for backward | 625941c16aa9bd52df036d2c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.