code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def future_trades_history(self, symbol, date, since): <NEW_LINE> <INDENT> params = { 'api_key': cfg.get_id(), 'symbol': symbol, 'date': date, 'since': since } <NEW_LINE> res = OKCoinBase.RESOURCES_URL['trades_history'] <NEW_LINE> return self._signed_request(params, res) | return:
amount:交易数量
date:交易时间(毫秒)
price:交易价格
tid:交易ID
type:交易类型(buy/sell) | 625941c4dc8b845886cb550d |
def get_artifact_manager(self, jobstep): <NEW_LINE> <INDENT> raise NotImplementedError | Return an artifacts.manager.Manager object for the given jobstep.
This manager should be created with all artifact handlers that apply.
For instance, in a collection JobStep, you might wish to have only a
handler for a collection artifact, whereas in JobSteps that run tests,
you may wish to have handlers for test resu... | 625941c41f5feb6acb0c4b2c |
def MessageHandlerDeletable(self, index): <NEW_LINE> <INDENT> return bool(_c.isDefmessageHandlerDeletable(self.__defclass, index)) | return True if specified MessageHandler can be deleted | 625941c48c3a873295158392 |
def changeUnit(self, unit): <NEW_LINE> <INDENT> unit = tounit( unit ) <NEW_LINE> myunit = self.unit() <NEW_LINE> try: unit + myunit <NEW_LINE> except: ValueError, "cannot set dataset of unit %s to new unit %s" % ( myunit, unit) <NEW_LINE> ratio = myunit/unit <NEW_LINE> self._storage *= ratio <NEW_LINE> self._setunit( u... | change unit. update data array accordingly | 625941c44e696a04525c9425 |
def test_put_wrong_sizes(client, db, bucket, multipart, multipart_url): <NEW_LINE> <INDENT> cases = [ b'a' * (multipart.chunk_size + 1), b'a' * (multipart.chunk_size - 1), b'', ] <NEW_LINE> for data in cases: <NEW_LINE> <INDENT> res = client.put( multipart_url + '&partNumber={0}'.format(1), input_stream=BytesIO(data), ... | Test invalid part sizes. | 625941c41f037a2d8b9461d7 |
def select(self, names): <NEW_LINE> <INDENT> sel = set() <NEW_LINE> if '*' in names: <NEW_LINE> <INDENT> for obj in self._universe.objectList(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sel.update([at for at in obj.atomList()]) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> ... | Returns the atoms that matches a given list of chain names.
@param universe: the universe
@type universe: MMTK.universe
@param names: the chain names list.
@type names: list | 625941c4cc0a2c11143dce69 |
def is_valid_address(host, port): <NEW_LINE> <INDENT> if not 0 < port < 65535: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> socket.gethostbyname(host) <NEW_LINE> <DEDENT> except socket.gaierror: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE... | Responsible for checking whether the given host port pair is valid.
Host can be given either as an ip address string or hostname.
Uses `socket.gethostbyname()` to check whether a hostname exists.
Else tries to create the `ipaddress.ip_address` our of a string.
Returns True or False | 625941c44428ac0f6e5ba7ca |
def compile_test_program(target_config, verbose, mname, source=None, debug=None): <NEW_LINE> <INDENT> metadata = MODULE_METADATA[mname] <NEW_LINE> name = 'cfgtest_' + mname <NEW_LINE> name_pro = name + '.pro' <NEW_LINE> name_makefile = name + '.mk' <NEW_LINE> name_source = name + '.cpp' <NEW_LINE> if source is None: <N... | Compile the source of a Qt program and return the name of the
executable or None if it couldn't be created. target_config is the target
configuration. verbose is set if the output is to be displayed. mname is
the name of the PyQt module being tested. source is the C++ source of the
program. If it is None then the ... | 625941c4cc0a2c11143dce6a |
def deleteNetworkSmTargetGroup(self, networkId: str, targetGroupId: str): <NEW_LINE> <INDENT> metadata = { 'tags': ['sm', 'configure', 'targetGroups'], 'operation': 'deleteNetworkSmTargetGroup' } <NEW_LINE> resource = f'/networks/{networkId}/sm/targetGroups/{targetGroupId}' <NEW_LINE> return self._session.delete(metada... | **Delete a target group from a network**
https://developer.cisco.com/meraki/api-v1/#!delete-network-sm-target-group
- networkId (string): (required)
- targetGroupId (string): (required) | 625941c4bf627c535bc131a8 |
def fail(self, message=None, offline=False): <NEW_LINE> <INDENT> if message is None: <NEW_LINE> <INDENT> message = "" <NEW_LINE> <DEDENT> if not self.live: <NEW_LINE> <INDENT> message = "Workspace is offline and this request is not cached. Call 'WorkspaceManager.sync()' to go online. " + message <NEW_LINE> <DEDENT> eli... | Call when the WorkspaceManager cannot fulfil a user request.
Raises an APIException based on the last request made.
Optionally provide a message describing the failure.
If offline is True, this will also switch to offline mode. | 625941c4d58c6744b4257c3a |
def eval(self, data): <NEW_LINE> <INDENT> func = any if self.logic == 'or' else all <NEW_LINE> return func(d.eval(data) for d in self.conditions) | Evaluate the provided data to determine whether it matches this set of conditions. | 625941c491f36d47f21ac4ca |
def ensureenv(): <NEW_LINE> <INDENT> if not os.path.exists("build/env"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with open("build/env", "r") as f: <NEW_LINE> <INDENT> env = dict(l.split("=", 1) for l in f.read().splitlines() if "=" in l) <NEW_LINE> <DEDENT> if all(os.environ.get(k) == v for k, v in env.items()):... | Load build/env's as environment variables.
If build/env has specified a different set of environment variables,
restart the current command. Otherwise do nothing. | 625941c40c0af96317bb81c1 |
def test_rasterize_fill_value_dtype_mismatch(basic_geometry): <NEW_LINE> <INDENT> with rasterio.Env(): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> rasterize( [basic_geometry], out_shape=DEFAULT_SHAPE, fill=1000000, default_value=2, dtype=np.uint8 ) | A fill value that doesn't match dtype should fail. | 625941c4283ffb24f3c558dc |
def test_default_docs_build(self): <NEW_LINE> <INDENT> with tests.working_directory(os.path.join(self.builtdir, 'docs')): <NEW_LINE> <INDENT> result = subprocess.check_call( shlex.split( 'sphinx-build -nW -b html -d _build/doctrees . _build/html' ) ) <NEW_LINE> self.assertEqual(result, 0) | Ensure default Sphinx docs build in rendered template | 625941c44c3428357757c302 |
def test_get_node_by_slot_random(self): <NEW_LINE> <INDENT> pool = self.get_pool(connection_kwargs={}) <NEW_LINE> pool.nodes.slots[0] = [ {'host': '172.20.0.2', 'port': 7000, 'name': '172.20.0.2:7000', 'server_type': 'master'}, {'host': '172.20.0.2', 'port': 7003, 'name': '172.20.0.2:7003', 'server_type': 'slave'}, ] <... | We can randomly get all nodes in readonly mode. | 625941c4293b9510aa2c3271 |
def compute_distance(pnt1: Tuple[float, float], pnt2: Tuple[float, float]) -> float: <NEW_LINE> <INDENT> lat1, lon1 = pnt1 <NEW_LINE> lat2, lon2 = pnt2 <NEW_LINE> if (lat1, lon1) == (lat2, lon2): <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> if max(abs(lat1 - lat2), abs(lon1 - lon2)) < 0.00001: <NEW_LINE> <INDENT>... | computes distance in Meters | 625941c4fbf16365ca6f619a |
def test_dict_getter_v1_2(self): <NEW_LINE> <INDENT> path = get_test_data_folder( version='1.2', which='wordnik' ) <NEW_LINE> path_resource_list = os.path.join(path, 'resource_list.json') <NEW_LINE> path_pet = os.path.join(path, 'pet.json') <NEW_LINE> path_store = os.path.join(path, 'store.json') <NEW_LINE> path_user =... | make sure 'DictGetter' works the same as 'LocalGetter'
for Swagger 1.2 | 625941c43eb6a72ae02ec4b2 |
def transformPrefs(prefs): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for person in prefs: <NEW_LINE> <INDENT> for item in prefs[person]: <NEW_LINE> <INDENT> result.setdefault(item, {}) <NEW_LINE> result[item][person] = prefs[person][item] <NEW_LINE> <DEDENT> <DEDENT> return result | Transform the recommendations into a mapping where persons are described
with interest scores for a given title e.g. {title: person} instead of
{person: title}. | 625941c4a79ad161976cc11f |
def applies(self, container): <NEW_LINE> <INDENT> raise NotImplementedError('applies') | All subclasses must implement the `applies(self, container)` method
:type container: Container
:param container: the caller
:return: True if condition applies, False otherwise | 625941c4bde94217f3682dcc |
def count_failures(runner): <NEW_LINE> <INDENT> return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ] | Count number of failures in a doctest runner.
Code modeled after the summarize() method in doctest. | 625941c4d53ae8145f87a24c |
def fl_set_browser_specialkey(ptr_flobject, specialkey): <NEW_LINE> <INDENT> _fl_set_browser_specialkey = library.cfuncproto( library.load_so_libforms(), "fl_set_browser_specialkey", None, [cty.POINTER(xfdata.FL_OBJECT), cty.c_int], """void fl_set_browser_specialkey(FL_OBJECT * ob, int specialkey)""") <NEW_LINE> librar... | fl_set_browser_specialkey(ptr_flobject, specialkey)
Changes the special character, used to change appearance, see
fl_add_browser_line(), to something other than '@'. In some cases
the character '@' might need to be placed at the beginning of the
lines without introducing the special meaning mentioned above. In
this ca... | 625941c491af0d3eaac9b9f1 |
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null', inetd=False): <NEW_LINE> <INDENT> if not inetd: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> sys.stderr.wr... | This forks the current process into a daemon.
The stdin, stdout, and stderr arguments are file names that
will be opened and be used to replace the standard file descriptors
in sys.stdin, sys.stdout, and sys.stderr.
These arguments are optional and default to /dev/null.
Note that stderr is opened unbuffered, so
if it s... | 625941c4e8904600ed9f1f04 |
def relative_rate(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_keep_m_in_n_sptr_relative_rate(self) | relative_rate(self) -> double | 625941c4167d2b6e31218b70 |
def sql_connect_db_io(table_name, value1, value2): <NEW_LINE> <INDENT> my_db = connect_db() <NEW_LINE> try: <NEW_LINE> <INDENT> my_cursor = my_db.cursor() <NEW_LINE> sql = f"INSERT INTO {table_name}(host, ioBytesSent, ioBytesRecv) VALUES (%s, %s, %s)" <NEW_LINE> val = ("192.168.64.2", value1, value2) <NEW_LINE> <DEDENT... | function takes three parameters:
insert value in IO tables | 625941c43617ad0b5ed67ed3 |
def to_list(cls): <NEW_LINE> <INDENT> cls._serialize_as = "json_list" <NEW_LINE> return cls | If your class instances should serialize into a JSON list decorate it with :func:`to_list`. The python built in
:class:`list` will be called with your class instance as its argument. ie **list(obj)**. This means your class needs to define
the ``__iter__`` method.
Here is an example::
@json_object(supress=["__... | 625941c4e5267d203edcdc79 |
def determine_browser_charset(self): <NEW_LINE> <INDENT> charset_match = _CHARSET_RE.search(self.headers.get('Content-Type', '')) <NEW_LINE> if charset_match: <NEW_LINE> <INDENT> return charset_match.group(1) | Determine the encoding as specified by the browser via the
Content-Type's charset parameter, if one is set | 625941c45fcc89381b1e1697 |
def user_groups(request): <NEW_LINE> <INDENT> context = {} <NEW_LINE> if request.user.is_authenticated() and request.user.is_active: <NEW_LINE> <INDENT> user = request.user.userprofile <NEW_LINE> expertA = user.is_expertA <NEW_LINE> expertB = user.is_expertB <NEW_LINE> organization = user.is_organization <NEW_LINE> con... | Checking users group. | 625941c4de87d2750b85fd6b |
def load_detailed_log(run_id): <NEW_LINE> <INDENT> fp = os.path.join( ocelot_base_dir(), "model-runs", run_id, "detailed.log.json" ) <NEW_LINE> assert os.path.isfile(fp), "Can't find detailed log file" <NEW_LINE> for line in open(fp, encoding='utf-8'): <NEW_LINE> <INDENT> yield json.loads(line) | Return the model run data | 625941c40a366e3fb873e7f3 |
@csrf_exempt <NEW_LINE> def class_select_all(request): <NEW_LINE> <INDENT> if request.method != "GET": <NEW_LINE> <INDENT> return JsonResponse(Response.get_error_status(401, CLASS_ERRORS)) <NEW_LINE> <DEDENT> if not get_user_logged_in(request): <NEW_LINE> <INDENT> return JsonResponse(Response.get_error_status(400, CLAS... | Function Summary: This function is used to get all the Class objects of a Student.
Path: '/api/class/select/all'
Request Type: GET
Required Login: True
Args:
request -- The request made to the server by the client
Required GET Parameters:
session_id -- The Session ID of the logged in user
Possible Error Code... | 625941c407d97122c4178862 |
def super_filter(names, inclusion_patterns=[], exclusion_patterns=[]): <NEW_LINE> <INDENT> included = multi_filter(names, inclusion_patterns) if inclusion_patterns else names <NEW_LINE> excluded = multi_filter(names, exclusion_patterns) if exclusion_patterns else [] <NEW_LINE> return list(set(included) - set(excluded)) | Super filter.
Enhanced version of fnmatch.filter() that accepts multiple inclusion and exclusion patterns.
- If only ``inclusion_patterns`` is specified, only the names which match one or more patterns are returned.
- If only ``exclusion_patterns`` is specified, only the names which do not match any pattern a... | 625941c4fb3f5b602dac366c |
def get_feed(self): <NEW_LINE> <INDENT> feed = memcache.get(self.key.id(), namespace=USER_FEED_NAMESPACE) <NEW_LINE> if feed is not None: <NEW_LINE> <INDENT> return feed <NEW_LINE> <DEDENT> return self.update_feed() | Returns and cache the users feed (last twisks from the users they follow) | 625941c431939e2706e4ce46 |
def request_del_by_host(self, host): <NEW_LINE> <INDENT> if host.mgmt_address in self.active_addresses: <NEW_LINE> <INDENT> for request in self.active_requests: <NEW_LINE> <INDENT> if request.host.mgmt_address == host.mgmt_address: <NEW_LINE> <INDENT> self.address_del(host.mgmt_address) <NEW_LINE> del(self.active_reque... | Delete all requests in waiting and active queue for the given host | 625941c4f7d966606f6a9fdd |
def test_update_oox(self): <NEW_LINE> <INDENT> data = self.tmp / 'test_update_oox.json' <NEW_LINE> self.update_xxx(True, data, 2) | Test overwriting the third of a set of three entries. | 625941c48c0ade5d55d3e993 |
def get_events( self, label, buffer_manager, placements, application_vertex, variable): <NEW_LINE> <INDENT> if variable == self.REWIRING: <NEW_LINE> <INDENT> return self._get_rewires( label, buffer_manager, placements, application_vertex, variable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = ( "Variable {} is n... | Read events mapped to time and neuron IDs from the SpiNNaker machine.
:param str label: vertex label
:param buffer_manager: the manager for buffered data
:type buffer_manager:
~spinn_front_end_common.interface.buffer_management.BufferManager
:param ~pacman.model.placements.Placements placements:
the... | 625941c43eb6a72ae02ec4b3 |
def ibn_densenet161(**kwargs): <NEW_LINE> <INDENT> return get_ibndensenet(num_layers=161, model_name="ibn_densenet161", **kwargs) | IBN-DenseNet-161 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretra... | 625941c4a4f1c619b28b0017 |
def read(self): <NEW_LINE> <INDENT> infile = open(self.attrs['file'], 'r') <NEW_LINE> self._parse_head(infile) <NEW_LINE> head = infile.readline() <NEW_LINE> raw = infile.readlines() <NEW_LINE> self['epot'] = dmarray(np.zeros(len(raw)),{'units':'keV'}) <NEW_LINE> self['l'] = dmarray(np.zeros(len(raw)),{'units':'Re'}... | Load and parse the information in the file. | 625941c460cbc95b062c651d |
def __init__(self, repo_id, details=None): <NEW_LINE> <INDENT> Repository.__init__(self, repo_id, details) <NEW_LINE> self.poller = TaskPoller(self.binding) | :param repo_id: The repository ID.
:type repo_id: str
:param details: The repositories details.
:type details: dict | 625941c499fddb7c1c9de36c |
def _output_pins(self, pins): <NEW_LINE> <INDENT> [self._validate_channel(pin) for pin in pins.keys()] <NEW_LINE> for pin, value in iter(pins.items()): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> self.gpio[int(pin/8)] |= 1 << (int(pin%8)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.gpio[int(pin/8)] &= ~(1 ... | Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values. | 625941c415baa723493c3f4e |
@pytest.fixture(scope="session") <NEW_LINE> def skip_report_list(skip_report_file_path): <NEW_LINE> <INDENT> with open(skip_report_file_path) as file: <NEW_LINE> <INDENT> return file.readlines() | List of skip report entries from the associated file. | 625941c4293b9510aa2c3272 |
@permission_required("core.manage_shop") <NEW_LINE> def set_cart_page(request): <NEW_LINE> <INDENT> cart_id = request.GET.get("cart-id") <NEW_LINE> result = simplejson.dumps({ "html": ( ("#cart-inline", cart_inline(request, cart_id)), ("#cart-filters-inline", cart_filters_inline(request, cart_id)), ("#selectable-carts-... | Sets the page of the selectable carts within cart view.
| 625941c4be8e80087fb20c1f |
def initiateImmediateSystemShutdown(self): <NEW_LINE> <INDENT> _logger.info("%s: Initiating immediate system shutdown", type(self).__name__) <NEW_LINE> result = subprocess.call(["/usr/bin/sudo", "-n", "/sbin/shutdown", "-P", "now"]) | Initiate an immediate system shutdown. | 625941c44a966d76dd550fe9 |
def anls(x, k, *, distance_type='eu', use_fcnnls=False, lambda_w=0, lambda_h=0, min_iter=10, max_iter=1000, tol1=1e-3, tol2=1e-3, nndsvd_init=(True, 'zero'), save_dir='./results/'): <NEW_LINE> <INDENT> Experiment = namedtuple('Experiment', 'method components distance_type nndsvd_init max_iter tol1 tol2 lambda_w lambda_... | Non-negative matrix factorization using alternating non-negative least squares
Following paper:
- Kim, Park: Non-negative matrix factorization based on alternating non-negativity
constrained least squares and active set method
FCNNLS paper:
- Benthem, Keenan: Fast algorithm for the solution of large-scale non-neg... | 625941c4379a373c97cfab1e |
def get_energy_step_qe(energy_step_data, current_id, work_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(work_path+rin.qe_outfile, 'r') as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> <DEDENT> energy_step = [] <NEW_LINE> final_flag = False <NEW_LINE> vc_flag = False <NEW_LINE> for line in line... | get energy step data in eV/atom
energy_step_data[ID][stage][step]
energy_step_data[ID][0] <-- stage 1
energy_step_data[ID][1] <-- stage 2 | 625941c485dfad0860c3ae35 |
def test_map_view(self): <NEW_LINE> <INDENT> if self.db.version < 90300: <NEW_LINE> <INDENT> self.skipTest('Only available on PG 9.3') <NEW_LINE> <DEDENT> stmts = [CREATE_TABLE, CREATE_STMT] <NEW_LINE> dbmap = self.to_map(stmts) <NEW_LINE> expmap = {'definition': VIEW_DEFN, 'with_data': True, 'depends_on': ['table t1']... | Map a created materialized view | 625941c467a9b606de4a7e95 |
def oxygen(modules): <NEW_LINE> <INDENT> node_dict = {} <NEW_LINE> for m in modules: <NEW_LINE> <INDENT> visited = set() <NEW_LINE> for n in m: <NEW_LINE> <INDENT> if n.parent_index in visited or n.weight < _MIN_NODE_WEIGHT: <NEW_LINE> <INDENT> visited.add(n.index) <NEW_LINE> continue <NEW_LINE> <DEDENT> node_dump = _d... | Run basic type 1 code duplication check based on AST.dump() function.
Arguments:
modules (list[list[TreeNode]): Modules in locally standardized format.
Returns:
DetectionResult -- Result of the code clone detection. | 625941c450485f2cf553cd74 |
def test_fg_getitem(tfg): <NEW_LINE> <INDENT> assert tfg[0] | Check indexing, from custom __getitem__, in FOOOFGroup. | 625941c4a4f1c619b28b0018 |
def train_word2vec(datalength, sentence_matrix, vocabulary_inv, num_features=300, min_word_count=1, context=10): <NEW_LINE> <INDENT> model_dir = 'models' <NEW_LINE> model_name = "{:d}features_{:d}minwords_{:d}context_{:d}datalength".format(num_features, min_word_count, context, datalength) <NEW_LINE> model_name = join(... | Trains, saves, loads Word2Vec model
Returns initial weights for embedding layer.
inputs:
sentence_matrix # int matrix: num_sentences x max_sentence_len
vocabulary_inv # dict {int: str}
num_features # Word vector dimensionality
min_word_count # Minimum word count
conte... | 625941c4cc40096d6159592b |
def setUp(self): <NEW_LINE> <INDENT> user = create_test_user() <NEW_LINE> self.tms = mock_up_TMS(user) <NEW_LINE> self.tms.save() <NEW_LINE> self.project_name = "etabot" <NEW_LINE> self.project_mode = "scrum" <NEW_LINE> self.project_open_status = "ToDo" <NEW_LINE> self.project_grace_period = "24" <NEW_LINE> self.projec... | Define the test client and other test variables. | 625941c4462c4b4f79d1d6ab |
def map_coral(X_train_df, X_test_df, gene_features, coral_lambda, samples=None): <NEW_LINE> <INDENT> from transfertools.models import CORAL <NEW_LINE> if samples is None: <NEW_LINE> <INDENT> samples = np.ones(X_train_df.shape[0]).astype('bool') <NEW_LINE> <DEDENT> transform = CORAL(scaling='none', tol=1e-3, lambda_val=... | Run CORAL domain adaptation on training dataset.
TODO document | 625941c4e1aae11d1e749c90 |
def getfilepath(title = "Select File"): <NEW_LINE> <INDENT> filename = filedialog.askopenfilenames(initialdir="os.path.abspath(__file__))", title=title) <NEW_LINE> print(filename) <NEW_LINE> if filename == "": <NEW_LINE> <INDENT> print("No file was selected") <NEW_LINE> quit(0) <NEW_LINE> <DEDENT> return filename | Generates a Popup window for the user to choose the filepath. If no file is selected,
the program will stop.
:param title: Title displayed in the Popupwindow (only in LINUX and Windows)
:return: tuple, complete filepath | 625941c4ab23a570cc25015c |
def degree(self): <NEW_LINE> <INDENT> return len(self) - 1 | The degree of the series.
.. versionadded:: 1.5.0
Returns
-------
degree : int
Degree of the series, one less than the number of coefficients. | 625941c4d8ef3951e3243518 |
def test_DSSP_noheader_file(self): <NEW_LINE> <INDENT> dssp, keys = make_dssp_dict("PDB/2BEG_noheader.dssp") <NEW_LINE> self.assertEqual(len(dssp), 130) | Test parsing of pregenerated DSSP missing header information | 625941c40383005118ecf5be |
def set_leds(self, hue=0.0, saturation=1.0, value=1.0): <NEW_LINE> <INDENT> r, g, b = hsv_to_rgb(hue, saturation, value) <NEW_LINE> write_led_value(self.device_unique_name, 'red', r * 255.0) <NEW_LINE> write_led_value(self.device_unique_name, 'green', g * 255.0) <NEW_LINE> write_led_value(self.device_unique_name, 'blue... | The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this
bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored.
:param hue:
The hue of the colour, defaults to 0, specified as a floating point value between ... | 625941c4aad79263cf390a19 |
def create_output_directory(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.isdir(XMLS_PATH_DOWNLOAD): <NEW_LINE> <INDENT> return os.makedirs(XMLS_PATH_DOWNLOAD) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> print(Colors.FAIL + 'Error during creating output directory --> {}'.f... | General method to create output directory. | 625941c40a50d4780f666e6c |
def flatten(self): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for k, v in self.stats.items(): <NEW_LINE> <INDENT> d[k] = self.to_dict(v) <NEW_LINE> <DEDENT> return d | return a dict + native datatypes only representation of this StatsTree | 625941c4d10714528d5ffcbc |
def get_covariate_name(self, idx): <NEW_LINE> <INDENT> return self.datasource.covariate_labels[idx] | Return label for a specific covariate
:param idx: which covariate?
:return: string label | 625941c430dc7b7665901943 |
def test_string_with_percent_encoded_equals_signs_is_decoded(): <NEW_LINE> <INDENT> base64_string = 'R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D' <NEW_LINE> decode(base64_string) | Some base64 strings have their padding characters (=) percent
encoded so they appear as %3D. We should be able to decode them.
At the moment, we will trust the decoding is correct, we just want
to make sure no errors are raised. | 625941c44d74a7450ccd419e |
def equivalent(self, other): <NEW_LINE> <INDENT> return self.iff(other).is_tautology() | Determine if two formulas are semantically equivalent.
INPUT:
- ``self`` -- calling object
- ``other`` -- instance of BooleanFormula class.
OUTPUT:
A boolean value to be determined as follows:
True - if the two formulas are logically equivalent
False - if the two formulas are not logically equivalent
EXAMPLES:
... | 625941c4d268445f265b4e49 |
def floor(self): <NEW_LINE> <INDENT> return ComplexDecimal(self.real.to_integral(), self.imaginary.to_integral()) | Floors a number | 625941c47d847024c06be295 |
def is_group_valid(group_): <NEW_LINE> <INDENT> global b, f, s, t <NEW_LINE> for val_, constraint in zip(group_, [b, f, s, t]): <NEW_LINE> <INDENT> if val_ > constraint: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Tests if a group is valid. | 625941c48e71fb1e9831d785 |
def derive_key(secret, salt, iterations=1000, keylen=32): <NEW_LINE> <INDENT> assert(type(secret) in [six.text_type, six.binary_type]) <NEW_LINE> assert(type(salt) in [six.text_type, six.binary_type]) <NEW_LINE> assert(type(iterations) in six.integer_types) <NEW_LINE> assert(type(keylen) in six.integer_types) <NEW_LINE... | Computes a derived cryptographic key from a password according to PBKDF2.
.. seealso:: http://en.wikipedia.org/wiki/PBKDF2
:param secret: The secret.
:type secret: bytes or unicode
:param salt: The salt to be used.
:type salt: bytes or unicode
:param iterations: Number of iterations of derivation algorithm to run.
:t... | 625941c4009cb60464c6338e |
def run_strategy(strategy_name, time, strategy): <NEW_LINE> <INDENT> state = simulate_clicker(BuildInfo(), time, strategy) <NEW_LINE> print (strategy_name, ":", state) | Run a simulation for the given time with one strategy. | 625941c4cad5886f8bd26fb5 |
def _install(mpt): <NEW_LINE> <INDENT> _check_resolv(mpt) <NEW_LINE> boot_, tmppath = (prep_bootstrap(mpt) or salt.syspaths.BOOTSTRAP) <NEW_LINE> arg = 'stable {0}'.format('.'.join(salt.version.__version__.split('.')[:2])) <NEW_LINE> cmd = 'if type salt-minion; then exit 0; ' <NEW_LINE> cmd += 'else sh {0} -c /tmp {1};... | Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed. | 625941c48e05c05ec3eea34e |
def test_repr(self): <NEW_LINE> <INDENT> bn = BotanicalName(name='Asclepias incarnata') <NEW_LINE> assert bn.__repr__() == '<BotanicalName "Asclepias incarnata">' | Return a string in format <BotanicalName '<botanical_name>'> | 625941c4aad79263cf390a1a |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = len(self.positions) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> pattern = '<%sd'%length <NEW_LINE> buff.write(struct.pack(pattern, *self.positions)) <NEW_LINE> length = len(self.velocities) <NEW_LINE> buff.write(_struct_I.pack... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941c4d4950a0f3b08c32b |
def execute_wbemcli(args, verbose=False): <NEW_LINE> <INDENT> cli_cmd = u'wbemcli.bat' if os.name == 'nt' else u'wbemcli' <NEW_LINE> assert isinstance(args, (list, tuple)) <NEW_LINE> cmd_args = [cli_cmd] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if not isinstance(arg, six.text_type): <NEW_LINE> <INDENT> arg = arg... | Invoke the 'wbemcli' command as a child process.
This requires that the 'wbemcli' command is installed in the current
Python environment.
Parameters:
args (iterable of :term:`string`): Command line arguments, without the
command name.
Each single argument must be its own item in the iterable; combining
... | 625941c4090684286d50ecbf |
def read_image(filename, representation): <NEW_LINE> <INDENT> if( representation < GRAY_REPR or representation > RGB_REPR): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> img = imread(filename) <NEW_LINE> if len(img.shape) == RGB_SHAPE and representation == GRAY_REPR: <NEW_LINE> <INDENT> return rgb2gray(img) <NEW_LI... | read the image and convert it to gray scale if necessary
:param filename: the image
:param representation: gray scale or RGB format to which the image is to be converted
:return: A image whose values are normalized and in the given representation | 625941c41f5feb6acb0c4b2e |
def name_id(): <NEW_LINE> <INDENT> return ['819800560', 'Lakshmiprabha', 'Sudersanan'] | Please return your REDID followed by your first and last name as separate elements in a list.
:return: a list of [redID, first_name, last_name] | 625941c4d99f1b3c44c6756c |
def get_egressmatrixcell(self, emc, src_sgt=None, dst_sgt=None): <NEW_LINE> <INDENT> self.ise.headers.update( {'ACCEPT': 'application/json', 'Content-Type': 'application/json'}) <NEW_LINE> result = { 'success': False, 'response': '', 'error': '', } <NEW_LINE> if self._oid_test(emc): <NEW_LINE> <INDENT> result = self.ge... | Get TrustSec Egress Matrix Cell Policy details.
:param emc: name or Object ID of the TrustSec Egress Matrix Cell Policy
:param src_sgt: name or Object ID of the Source SGT in the Policy
:param src_sgt: name or Object ID of the Dest SGT in the Policy
:return: result dictionary | 625941c494891a1f4081ba84 |
def projection_to_tangent_space(self, vector, base_point): <NEW_LINE> <INDENT> vector = gs.to_ndarray(vector, to_ndim=2) <NEW_LINE> base_point = gs.to_ndarray(base_point, to_ndim=2) <NEW_LINE> sq_norm = self.embedding_metric.squared_norm(base_point) <NEW_LINE> inner_prod = self.embedding_metric.inner_product(base_point... | Project a vector in Minkowski space
on the tangent space of the Hyperbolic space at a base point. | 625941c4b57a9660fec3385e |
def download_clean_sample( host, token, sample_pk, filename=None, directory=None, method=METHOD['https']): <NEW_LINE> <INDENT> url = "%s%s/api/repository/samples/%d/fcs_clean/" % ( method, host, sample_pk ) <NEW_LINE> if filename is None: <NEW_LINE> <INDENT> filename = str(sample_pk) + '_clean.fcs' <NEW_LINE> <DEDENT> ... | Download clean sample as FCS | 625941c43c8af77a43ae377a |
def agg_fun_chooser(agg_fun, db_scale=False): <NEW_LINE> <INDENT> if (agg_fun == np.nanmedian) or not db_scale: <NEW_LINE> <INDENT> return agg_fun <NEW_LINE> <DEDENT> return lambda x: lin_agg(x, agg_fun=agg_fun) | aggregation of db-scale variables | 625941c4b5575c28eb68dfda |
def _set_auxiliary_attr(col, attr, key, value): <NEW_LINE> <INDENT> attr_node = attr.get_node() <NEW_LINE> aux_name = _get_auxiliary_attr_name(col, attr, key) <NEW_LINE> plug_name = '{0}.{1}'.format(attr_node, aux_name) <NEW_LINE> exists = node_utils.attribute_exists(aux_name, attr_node) <NEW_LINE> if exists is False: ... | Look up the auxiliary attribute, and set a value on it.
If no auxiliary attribute exists, a new attribute is created and
initialized.
:param col: The Collection object to set data for.
:type col: Collection
:param attr: The Attribute object to set data for.
:type attr: Attribute
:param key: The unique 'key name' to... | 625941c4187af65679ca50f9 |
def _verify_openstack_metadata(self, ssh, mount_path): <NEW_LINE> <INDENT> openstackdata_dir = mount_path + "/openstack/latest/" <NEW_LINE> openstackdata_files = ["meta_data.json", "vendor_data.json", "network_data.json"] <NEW_LINE> for file in openstackdata_files: <NEW_LINE> <INDENT> res = ssh.execute("cat %s" % opens... | verify existence of metadata and user data files
in OpenStack format
:param ssh: SSH connection to the VM
:param mount_path: mount point of the config drive
:type ssh: marvin.sshClient.SshClient
:type mount_path: str | 625941c4dd821e528d63b185 |
def deleteNode(self, node): <NEW_LINE> <INDENT> node.val = node.next.val <NEW_LINE> node.next = node.next.n | :type node: ListNode
:rtype: void Do not return anything, modify node in-place instead. | 625941c4ff9c53063f47c1cf |
def put(self, request, id, format=None): <NEW_LINE> <INDENT> return Response(services.update_fabric_profiles(int(id), request.data, self.username)) | to edit a fabric profile
---
request_serializer: "FabricProfilesPutSerializer"
response_serializer: "FabricSerializer"
| 625941c466673b3332b9206c |
def quickselect(self, begin, end, k): <NEW_LINE> <INDENT> if k<=0 or begin >= end: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> i = begin <NEW_LINE> j = end <NEW_LINE> sa = 0 <NEW_LINE> tmp = self.pop[self.indexes[begin]].fitness <NEW_LINE> tmp_index = self.indexes[begin] <NEW_LINE> while i != j: <NEW_LINE> <INDENT... | 快速选出population中indexes从begin到end之间的前K个元素
:param begin:
:param end:
:param k:
:return: | 625941c45e10d32532c5ef02 |
def bulk(self, is_bulk=True): <NEW_LINE> <INDENT> self._bulk_insert = is_bulk <NEW_LINE> return self | Flag for a type of insert: bulk inserts or not.
@param is_bulk: Flag value.
@type is_bulk: bool
@return: Self instance.
@rtype: InsertQuery | 625941c48e7ae83300e4afa7 |
def privacy(): <NEW_LINE> <INDENT> return base.render(u'home/privacy.html', extra_vars={}) | display privacy page | 625941c44e4d5625662d43b5 |
def add_solution(self, sol): <NEW_LINE> <INDENT> assert isinstance(sol, Solution) <NEW_LINE> if self.representative == None: <NEW_LINE> <INDENT> self.representative = sol <NEW_LINE> <DEDENT> self.members.append(sol.solnum) <NEW_LINE> self.count += 1 | Add a solution to this stack. | 625941c47047854f462a13e7 |
def average_shortest_path_length(G, weight=None, method='dijkstra'): <NEW_LINE> <INDENT> method = 'unweighted' if weight is None else method <NEW_LINE> n = len(G) <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> msg = ('the null graph has no paths, thus there is no average' 'shortest path length') <NEW_LINE> raise nx.NetworkX... | Returns the average shortest path length.
The average shortest path length is
.. math::
a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}
where `V` is the set of nodes in `G`,
`d(s, t)` is the shortest path from `s` to `t`,
and `n` is the number of nodes in `G`.
Parameters
----------
G : NetworkX graph
weight : None ... | 625941c4d58c6744b4257c3c |
def write(self, cmd): <NEW_LINE> <INDENT> if isinstance(cmd, (tuple, list)): <NEW_LINE> <INDENT> self.device.write(';'.join(cmd)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.device.write(cmd) | Send one or multiple commands to the device | 625941c44d74a7450ccd419f |
def skip_if_no_arcpy(self): <NEW_LINE> <INDENT> if not arcpy: <NEW_LINE> <INDENT> self.skipTest("arcpy is not installed.") | Skips the current test if arcpy is not available.
| 625941c44c3428357757c304 |
def create_obstacles(self) -> list: <NEW_LINE> <INDENT> obstacles = [] <NEW_LINE> for i in range(100, 800, 50): <NEW_LINE> <INDENT> obstacles.append(Obstacle(Position(400, i))) <NEW_LINE> obstacles.append(Obstacle(Position(520, i))) <NEW_LINE> <DEDENT> return obstacles | Create obstacles for level 2
:return: list of obstacles for level 2 | 625941c4293b9510aa2c3273 |
def __or__(self, other): <NEW_LINE> <INDENT> if isinstance(other, (float, int, long)): <NEW_LINE> <INDENT> self.default_string = float(other) <NEW_LINE> <DEDENT> elif isinstance(other, basestring): <NEW_LINE> <INDENT> if other not in STRENGTHS: <NEW_LINE> <INDENT> raise ValueError('Invalid strength %r' % other) <NEW_LI... | Set the strength of all of the constraints to a common
strength. | 625941c4d7e4931a7ee9def8 |
def system(command, input=None): <NEW_LINE> <INDENT> if VERBOSE: <NEW_LINE> <INDENT> print('[%s] %s' % (os.getcwd(), command)) <NEW_LINE> <DEDENT> p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=MUST_CLOSE_FDS) <NEW_LINE> if input: <NEW_LINE> <I... | commands.getoutput() replacement that also works on windows
Code copied from zc.buildout. | 625941c4a17c0f6771cbe02d |
def _loading_finished_cb(self, *args): <NEW_LINE> <INDENT> self.load_ready = True <NEW_LINE> while not self.pending.empty() and self.load_ready: <NEW_LINE> <INDENT> function, args = self.pending.get(False) <NEW_LINE> function(*args) <NEW_LINE> <DEDENT> self.ready = self.load_ready | callback called when the content finished loading
| 625941c43617ad0b5ed67ed4 |
def token(self): <NEW_LINE> <INDENT> print("Retrieving access token from authorization server for kafka connection") <NEW_LINE> return self.oauth2_requests.access_token.token | Retrieves access token from authorization server
:return: access_token
:rtype: str | 625941c423e79379d52ee541 |
def find(self): <NEW_LINE> <INDENT> pass | find() -> bool
Finds from the last known location. Returns True if found or False otherwise. | 625941c4a17c0f6771cbe02e |
def mean(self, *args, **kwargs): <NEW_LINE> <INDENT> return np.array(self, copy=False, subok=False).mean(*args, **kwargs) | overide np.ndarray.mean() | 625941c4167d2b6e31218b72 |
def __init__(self, value: Number, meta: Optional[dict] = None): <NEW_LINE> <INDENT> self.value: Number = value <NEW_LINE> self._meta: Optional[dict] = meta | Create a new Task Result.
:param value: The numeric value of the result.
:param meta: Additional metadata about the TaskResult. | 625941c4046cf37aa974cd25 |
def gen_c(name, bpf_fn, filter_value="", placeholder=None): <NEW_LINE> <INDENT> bpf = BPF(text=bpf_text_template.replace("FILTER", filter_value)) <NEW_LINE> bytecode = bpf.dump_func(bpf_fn) <NEW_LINE> bpf.cleanup() <NEW_LINE> return ( generate_c_function(name, bytecode, placeholder=placeholder), len(bytecode) / 8, ) | Returns the C code for the function and the number of instructions in
the array the C function generates. | 625941c421bff66bcd684930 |
def init(): <NEW_LINE> <INDENT> global _multiprocessing <NEW_LINE> read_config(CONFIG_FILE) <NEW_LINE> create_log_directory() <NEW_LINE> try: <NEW_LINE> <INDENT> import multiprocessing <NEW_LINE> if config.PROCESS_COUNT > 1: <NEW_LINE> <INDENT> _multiprocessing = multiprocessing <NEW_LINE> <DEDENT> <DEDENT> except (Imp... | Performs sensor initialization | 625941c4442bda511e8be3f6 |
def fix_yaml_loader() -> None: <NEW_LINE> <INDENT> def construct_yaml_str(self, node): <NEW_LINE> <INDENT> return self.construct_scalar(node) <NEW_LINE> <DEDENT> yaml.Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) <NEW_LINE> yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_... | Ensure that any string read by yaml is represented as unicode. | 625941c44e4d5625662d43b6 |
def umfpack_dl_triplet_to_col(*args): <NEW_LINE> <INDENT> return __umfpack.umfpack_dl_triplet_to_col(*args) | umfpack_dl_triplet_to_col(UF_long n_row, UF_long n_col, UF_long nz, UF_long const [] Ti, UF_long const [] Tj,
double const [] Tx, UF_long [] Ap, UF_long [] Ai, double [] Ax, UF_long [] Map) -> UF_long | 625941c43317a56b86939c38 |
def forwards(self, orm): <NEW_LINE> <INDENT> model = "ecr.ECRUserLink" <NEW_LINE> orm[model].objects.filter(role="sign_3rd_level").update(role="sign_4th_level") <NEW_LINE> orm[model].objects.filter(role="sign_3th_level").update(role="sign_3rd_level") <NEW_LINE> orm["ECR.ECRHistory"].objects.filter(action="New sign_3rd_... | Write your forwards methods here. | 625941c43617ad0b5ed67ed5 |
def getScore(self): <NEW_LINE> <INDENT> raise NotImplementedError("Please override this method") | Return the current score of the game.
Returns
-------
int
The current reward the agent has received since the last init() or reset() call. | 625941c4d99f1b3c44c6756d |
def connect(host="localhost", port=5432, user=None, name=None, password=None, **kwargs): <NEW_LINE> <INDENT> global engine <NEW_LINE> url = _build_url(host, port, name, user, password) <NEW_LINE> engine = create_engine(url, **kwargs) <NEW_LINE> Session.configure(bind=engine) <NEW_LINE> Base.metadata.bind = engine | Establish a connection to the Postgres database.
After running :func:`connect`, sessions can be established.
>> import starplex
>> starplex.database.connect(**args)
>> session = starplex.database.Session()
Parameters
----------
host : str
Hostname
port : int
Server port
user : str
Username for server
pas... | 625941c4b830903b967e98e9 |
def get_shepherds(program_generator_config, feature_set_names): <NEW_LINE> <INDENT> del program_generator_config <NEW_LINE> shepherd_sets = dict( human_readable=[ shepherds_lib.DenseTensorShepherd("human_readable_code", dtype=tf.string, element_shape=[]), shepherds_lib.DenseTensorShepherd("human_readable_target_output"... | Gets the shepherds to use for supergraph-batching the features. | 625941c430bbd722463cbda0 |
def circular_path(center, radius, theta_start, theta_end): <NEW_LINE> <INDENT> center = np.array(center) <NEW_LINE> def path(s): <NEW_LINE> <INDENT> R = np.sign(theta_end - theta_start)*radius <NEW_LINE> result = center + radius*np.c_[np.cos(theta_start + s/R), np.sin(theta_start + s/R)] <NEW_LINE> if np.isscalar(s): <... | A constructor that returns a circular path.
If `C is the circle defined by `center and `radius, this path joins the point of angle
`theta_start to the point of angle `theta_end. | 625941c455399d3f0558868f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.