code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _normalize_lists(value_str): <NEW_LINE> <INDENT> parsed = re.match(r"^([^*=->\s]*)\s*(\*)\s*(.*)$", value_str) <NEW_LINE> if parsed is not None: <NEW_LINE> <INDENT> value_str = "".join(parsed.groups()) <NEW_LINE> <DEDENT> result = "" <NEW_LINE> inside_quotes = False <NEW_LINE> idx = 0 <NEW_LINE> while idx < len(val... | >>> _normalize_lists("'one two' 'three four'")
"'one two','three four'"
>>> _normalize_lists("'one two' 'three four'")
"'one two','three four'"
>>> _normalize_lists("'one two' , 'three four'")
"'one two','three four'"
>>> _normalize_lists("'one two'")
"'one two'"
>>> _normalize_lists("1 2 3, 4 , 5")
'1,2,3,4,5'
>>... | 625941c855399d3f0558871a |
def relu(z): <NEW_LINE> <INDENT> return np.maximum(0.0, z) | Apply rectified-linear-unit function element-wise to a numpy array.
Args:
z (numpy array of number)
Returns:
numpy array of float | 625941c85fdd1c0f98dc0299 |
def sample_ps(self, W): <NEW_LINE> <INDENT> outsamp = np.random.multivariate_normal(self.mean, self.cov, W) <NEW_LINE> return (outsamp, self.mean) | W samples directly from distribution | 625941c899fddb7c1c9de3f8 |
def get_following_list(self) -> list: <NEW_LINE> <INDENT> list_following = [] <NEW_LINE> try: <NEW_LINE> <INDENT> self.__reset_app() <NEW_LINE> self.d(resourceId="com.instagram.android:id/profile_tab").click(timeout=10) <NEW_LINE> self.d(resourceId="com.instagram.android:id/profile_tab").click(timeout=5) <NEW_LINE> uia... | Returns:
list: list of usernames | 625941c810dbd63aa1bd2c0a |
def __init__(self, titleOrMenu="", menu=None, state=ControlNormal, cmd=wx.ID_ANY): <NEW_LINE> <INDENT> if isinstance(titleOrMenu, six.string_types): <NEW_LINE> <INDENT> self._title = titleOrMenu <NEW_LINE> self._menu = menu <NEW_LINE> self._rect = wx.Rect() <NEW_LINE> self._state = state <NEW_LINE> if cmd == wx.ID_ANY:... | Default class constructor.
Used internally. Do not call it in your code!
:param `titleOrMenu`: if it is a string, it represents the new menu label,
otherwise it is another instance of :class:`MenuEntryInfo` from which the attributes
are copied;
:param `menu`: the associated :class:`FlatMenu` object;
:param integer ... | 625941c83539df3088e2e3b1 |
@app.route("/api/v1.0/<start>", defaults = {'end' : None}) <NEW_LINE> @app.route("/api/v1.0/<start>/<end>") <NEW_LINE> def tobs_stdt_enddt(start, end): <NEW_LINE> <INDENT> tmin,tavg,tmax = get_temps(start, end) <NEW_LINE> return ( f"Here are the Minimum, Maximum and Average observered Temperature between <b>{start}</b>... | Return Minimum, Average and Maximum Temperature Observered values for all months since the given start date | 625941c8236d856c2ad44840 |
def p_optional_elifs_epsilon( p ): <NEW_LINE> <INDENT> p[0] = [] | optional_elifs : epsilon | 625941c84f6381625f114aa2 |
def dali_converter(inputs, device=None): <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> for i in range(len(inputs)): <NEW_LINE> <INDENT> x = inputs[i].as_tensor() <NEW_LINE> if (isinstance(x, dali.backend_impl.TensorCPU)): <NEW_LINE> <INDENT> x = np.array(x) <NEW_LINE> if x.ndim == 2 and x.shape[1] == 1: <NEW_LINE> <INDEN... | Convert DALI arrays to Numpy/CuPy arrays | 625941c8e76e3b2f99f3a873 |
def __init__ (self, height, width, mode, shipNumb): <NEW_LINE> <INDENT> grid = [] <NEW_LINE> for i in range(height): <NEW_LINE> <INDENT> grid.append([]) <NEW_LINE> for j in range(width): <NEW_LINE> <INDENT> grid[i].append(0) <NEW_LINE> <DEDENT> <DEDENT> for i in range(shipNumb): <NEW_LINE> <INDENT> if mode == 0: <NEW_L... | " Ships will always be 3x1
" if mode == 0: ships will be filled randomly
" if mode == 1: player will select each ships placement | 625941c80a50d4780f666ef8 |
def open_file(): <NEW_LINE> <INDENT> opened = False <NEW_LINE> while not opened: <NEW_LINE> <INDENT> filename = input('Please input the name of file:(*.csv) ') <NEW_LINE> try: <NEW_LINE> <INDENT> file = read_data(filename) <NEW_LINE> opened = True <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print(... | a function that open the file | 625941c8f7d966606f6aa06a |
def setup_app(command, conf, vars): <NEW_LINE> <INDENT> load_environment(conf.global_conf, conf.local_conf) <NEW_LINE> log.debug("Trying to connect to Midgard") <NEW_LINE> connected = init_midgard_connection(conf["midgard.config_path"], conf["midgard.logger"]) <NEW_LINE> if not connected: <NEW_LINE> <INDENT> return <NE... | Place any commands to setup midgardmvc here | 625941c8b5575c28eb68e066 |
def _get_bilean_url(self, args): <NEW_LINE> <INDENT> if args.os_bilean_url: <NEW_LINE> <INDENT> return args.os_bilean_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Translate the available url-related options into a single string.
Return the endpoint that should be used to talk to Bilean if a
clear decision can be made. Otherwise, return None. | 625941c8ac7a0e7691ed4134 |
def test_post_order(self): <NEW_LINE> <INDENT> with self.client as client: <NEW_LINE> <INDENT> response = client.post(BASE_URL, json=dict(client='Bill', contact='0784318356', order_item="chips", price="2000")) <NEW_LINE> self.assertEqual(response.status_code, 201) | method tests if an order has been placed
asserts that response code is 201 | 625941c88c3a873295158420 |
def get_remaining_types(self): <NEW_LINE> <INDENT> return list(set([ingredients_dict[k]['type'] for k,v in self.ingredients.iteritems() if v > 0])) | gets the remaining type of ingredients to be added | 625941c87d43ff24873a2d07 |
def get_queryset(self): <NEW_LINE> <INDENT> if self.action == 'list': <NEW_LINE> <INDENT> return self.queryset.filter(status='active') <NEW_LINE> <DEDENT> return self.queryset | Restrict list to public-only. | 625941c873bcbd0ca4b2c0dd |
def __getitem__(self, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._certs[bytes_to_str(id)] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise SecurityError('Unknown certificate: {0!r}'.format(id)) | get certificate by id | 625941c82ae34c7f2600d198 |
def visitTerminal(self, node): <NEW_LINE> <INDENT> node_type = node.getSymbol().type <NEW_LINE> node_text = node.getText() <NEW_LINE> if node_type == RelayLexer.GLOBAL_VAR: <NEW_LINE> <INDENT> return expr.GlobalVar(node_text[1:]) <NEW_LINE> <DEDENT> elif node_type == RelayLexer.LOCAL_VAR: <NEW_LINE> <INDENT> name = nod... | Visit lexer tokens that aren't ignored or visited by other functions. | 625941c815fb5d323cde0b75 |
def get_allocator(self): <NEW_LINE> <INDENT> return _libvncxx.UInt32Vector_get_allocator(self) | get_allocator(UInt32Vector self) -> std::vector< unsigned int >::allocator_type | 625941c8d10714528d5ffd49 |
def test_listeners_hear_to_speakers(): <NEW_LINE> <INDENT> before = Speaker('before', ['file_created']) <NEW_LINE> @before.file_created <NEW_LINE> def obeyer(event, node): <NEW_LINE> <INDENT> node.received_successfully(True) <NEW_LINE> <DEDENT> node = Mock() <NEW_LINE> node.path = 'foo/bar' <NEW_LINE> before.shout('fil... | Listeners should hear to speaker | 625941c8d268445f265b4ed5 |
def set_coordinates(self, xyz, fractionals=True): <NEW_LINE> <INDENT> as_array = isinstance(xyz, numpy.ndarray) <NEW_LINE> x_column = self.get_column("x") <NEW_LINE> y_column = self.get_column("y") <NEW_LINE> z_column = self.get_column("z") <NEW_LINE> xs = [] <NEW_LINE> ys = [] <NEW_LINE> zs = [] <NEW_LINE> periodicity... | Set the coordinates to new values.
Parameters
----------
fractionals : bool = True
The coordinates are fractional coordinates for periodic
systems. Ignored for non-periodic systems.
Returns
-------
None | 625941c8a79ad161976cc1ac |
def _connect_to_rados(self, pool=None): <NEW_LINE> <INDENT> client = self.rados.Rados(rados_id=self._ceph_backup_user, conffile=self._ceph_backup_conf) <NEW_LINE> try: <NEW_LINE> <INDENT> client.connect() <NEW_LINE> pool_to_open = encodeutils.safe_encode(pool or self._ceph_backup_pool) <NEW_LINE> ioctx = client.open_io... | Establish connection to the backup Ceph cluster. | 625941c82eb69b55b151c915 |
def get_material(self, diffuse_color, night_color): <NEW_LINE> <INDENT> diffuse_color_int = color_to_rgb_int(diffuse_color) <NEW_LINE> diffuse_color = color_to_rgba(diffuse_color) <NEW_LINE> night_color_int = color_to_rgb_int(night_color) <NEW_LINE> night_color = color_to_rgba(night_color) <NEW_LINE> if night_color_int... | Gets a material with the given diffuse and night color, creating one if it does not exist yet, and adds it to the current mesh's materials | 625941c863b5f9789fde714c |
def _on_error ( self, errors ): <NEW_LINE> <INDENT> self.ok.enabled = (errors == 0) | Handles editing errors.
| 625941c876d4e153a657eb97 |
def deleted(cond): <NEW_LINE> <INDENT> a = {} <NEW_LINE> if cond: <NEW_LINE> <INDENT> del a <NEW_LINE> <DEDENT> return a | >>> deleted(False)
{}
>>> deleted(True)
Traceback (most recent call last):
...
UnboundLocalError: local variable 'a' referenced before assignment | 625941c850485f2cf553ce00 |
@patch("insights.client.collection_rules.InsightsUploadConf.get_conf_file") <NEW_LINE> @patch("insights.client.collection_rules.InsightsUploadConf.get_collection_rules", return_value=None) <NEW_LINE> def test_load_from_file(get_collection_rules, get_conf_file): <NEW_LINE> <INDENT> upload_conf = insights_upload_conf() <... | Falls back to file if collection rules are not downloaded. | 625941c87047854f462a1472 |
def to_transducer(self): <NEW_LINE> <INDENT> from sage.combinat.finite_state_machine import Transducer <NEW_LINE> transitions = [] <NEW_LINE> for (right, top, left, bottom) in self: <NEW_LINE> <INDENT> transition = (left, right, bottom, top) <NEW_LINE> transitions.append(transition) <NEW_LINE> <DEDENT> return Transduce... | EXAMPLES::
sage: from slabbe import WangTileSet
sage: tiles = [(0,0,0,2), (1,0,0,1), (2,1,0,0), (0,0,1,0),
....: (1,2,1,1), (1,1,2,0), (2,0,2,1)]
sage: T = WangTileSet(tiles)
sage: T.to_transducer()
Transducer with 3 states | 625941c830dc7b76659019ce |
def get_feed_response(self, feed, feed_url): <NEW_LINE> <INDENT> response = feedparser.parse(feed_url) <NEW_LINE> if isinstance(response.get('bozo_exception', None), urllib2.URLError): <NEW_LINE> <INDENT> raise response.bozo_exception <NEW_LINE> <DEDENT> return response | Returns a parsed response for this ``feed``. By default, this uses
:mod:`feedparser` to get a response for the ``feed_url`` and returns
the resulting structure. | 625941c87cff6e4e811179ed |
def substitution(xored_text): <NEW_LINE> <INDENT> encrypted_text = [] <NEW_LINE> i,j=0,0 <NEW_LINE> while(i < 48): <NEW_LINE> <INDENT> block = '' <NEW_LINE> block = xored_text[i:i+6] <NEW_LINE> row = int(block[0]+block[5],2) <NEW_LINE> column = int(block[1:5],2) <NEW_LINE> encrypted_text.append('{0:04b}'.format(sBox[j]... | This function choose give the excrypted text from one of the s-boxes | 625941c85fc7496912cc39e5 |
def execute(code='', kc=None, **kwargs): <NEW_LINE> <INDENT> from .test_message_spec import validate_message <NEW_LINE> if kc is None: <NEW_LINE> <INDENT> kc = KC <NEW_LINE> <DEDENT> msg_id = kc.execute(code=code, **kwargs) <NEW_LINE> reply = kc.get_shell_msg(timeout=TIMEOUT) <NEW_LINE> validate_message(reply, 'execute... | wrapper for doing common steps for validating an execution request | 625941c84f88993c3716c0cf |
def generate_matching_datasets(self, data_slug): <NEW_LINE> <INDENT> matching_datasets = Dataset.objects.filter( hub_slug=data_slug ).order_by('-date_uploaded') <NEW_LINE> if len(matching_datasets) > 0: <NEW_LINE> <INDENT> return matching_datasets <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Return datasets that match data_slug (hub_slug). | 625941c80383005118ecf64a |
def delete_object(self, container, obj, headers=None, query=None, cdn=False, body=None): <NEW_LINE> <INDENT> path = self._object_path(container, obj) <NEW_LINE> return self.request( 'DELETE', path, body or '', headers, query=query, cdn=cdn) | DELETEs the object and returns the results.
:param container: The name of the container.
:param obj: The name of the object.
:param headers: Additional headers to send with the request.
:param query: Set to a dict of query values to send on the
query string of the request.
:param cdn: If set True, the CDN manageme... | 625941c8b7558d58953c4f7d |
def vacate_slot(self, slot_number): <NEW_LINE> <INDENT> slot = self.slots.get(slot_number) <NEW_LINE> if slot and slot.get_occupied_car(): <NEW_LINE> <INDENT> self.occupied_slots_count = self.occupied_slots_count - 1 <NEW_LINE> slot.vacate_slot() <NEW_LINE> return slot <NEW_LINE> <DEDENT> return slot | :param slot_number: Slot to be vacte
:return: return the vacated slot | 625941c876e4537e8c3516d9 |
def to_dict(self): <NEW_LINE> <INDENT> return [item.to_dict() for item in self] | Convert self into a dictionary for BeerJSON storage. | 625941c8ad47b63b2c509fe6 |
def getGuessedWord(secretWord, lettersGuessed): <NEW_LINE> <INDENT> guessdict = {} <NEW_LINE> for i in secretWord: <NEW_LINE> <INDENT> guessdict[i] = ' _ ' <NEW_LINE> <DEDENT> for i in lettersGuessed: <NEW_LINE> <INDENT> if i in secretWord: <NEW_LINE> <INDENT> guessdict[i] = ' '+i+' ' <NEW_LINE> <DEDENT> <DEDENT> strin... | secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far. | 625941c8796e427e537b062c |
def __init__(self): <NEW_LINE> <INDENT> self.registration = ['auditd', 'audisp-json'] <NEW_LINE> self.priority = 2 | register our criteria for being passed a message
as a list of lower case strings or values to match with an event's dictionary of keys or values
set the priority if you have a preference for order of plugins to run. 0 goes first, 100 is assumed/default if not sent | 625941c8dc8b845886cb559b |
def loss(self, X, y=None, reg=0.0): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> N, D = X.shape <NEW_LINE> scores = None <NEW_LINE> z1 = X.dot(W1) + b1 <NEW_LINE> a1 = np.maximum(0, z1) <NEW_LINE> scores = a1.dot(W2) + b2 <NEW_LINE... | Compute the loss and gradients for a two layer fully connected neural
network.
Inputs:
- X: Input data of shape (N, D). Each X[i] is a training sample.
- y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
an integer in the range 0 <= y[i] < C. This parameter is optional; if it
is not passed... | 625941c86fb2d068a760f103 |
def Dispose(self): <NEW_LINE> <INDENT> pass | Dispose(self: VertexPair) | 625941c8462c4b4f79d1d738 |
def update_data_sources_and_targets(self): <NEW_LINE> <INDENT> l_wheel_speed = self.datatargets["engine_l"] <NEW_LINE> r_wheel_speed = self.datatargets["engine_r"] <NEW_LINE> if l_wheel_speed + r_wheel_speed > 2 * self.speed_limit: <NEW_LINE> <INDENT> f = 2 * self.speed_limit / (l_wheel_speed + r_wheel_speed) <NEW_LINE... | called on every world simulation step to advance the life of the agent | 625941c821bff66bcd6849bb |
def to_json(record, extraneous=True, prop=None): <NEW_LINE> <INDENT> if prop: <NEW_LINE> <INDENT> if isinstance(prop, basestring): <NEW_LINE> <INDENT> prop = type(record).properties[prop] <NEW_LINE> <DEDENT> val = prop.__get__(record) <NEW_LINE> if hasattr(prop, "to_json"): <NEW_LINE> <INDENT> return prop.to_json(val, ... | JSON conversion function: a 'visitor' function which implements marshall
out (to JSON data form), honoring JSON property types/hints but does not
require them. To convert to an actual JSON document, pass the return value
to ``json.dumps`` or a similar function.
args:
``record=``\ *anything*
This object ca... | 625941c88a349b6b435e81da |
def render_workflow_html_template(filename, subtemplate, filelists, **kwargs): <NEW_LINE> <INDENT> dirnam = os.path.dirname(filename) <NEW_LINE> makedir(dirnam) <NEW_LINE> try: <NEW_LINE> <INDENT> filenames = [f.name for filelist in filelists for f in filelist if f is not None] <NEW_LINE> <DEDENT> except TypeError: <NE... | Writes a template given inputs from the workflow generator. Takes
a list of tuples. Each tuple is a pycbc File object. Also the name of the
subtemplate to render and the filename of the output. | 625941c82c8b7c6e89b35828 |
def get_tgtids(dataset, regid, cfgid=None): <NEW_LINE> <INDENT> tgtids = set() <NEW_LINE> re_tgtid = re.compile(r'^([^-]+)-[a-zA-Z0-9]+\.csv$') <NEW_LINE> csvdir = get_csvdir(dataset, regid, cfgid=cfgid) <NEW_LINE> for d in os.listdir(csvdir): <NEW_LINE> <INDENT> m = re_tgtid.match(d) <NEW_LINE> if m: <NEW_LINE> <INDEN... | Get list of target image IDs. | 625941c8bd1bec0571d90696 |
def attack(self, player): <NEW_LINE> <INDENT> damage = random.randint(self.min_damage, self.max_damage) <NEW_LINE> is_critical = False <NEW_LINE> rand_num = random.randint(1, self.freq) <NEW_LINE> if rand_num % self.freq == 0: <NEW_LINE> <INDENT> is_critical = True <NEW_LINE> <DEDENT> print(self.name + "のこうげき!") <NEW_L... | 敵を攻撃する
Parameters
----------
player : Player
プレイヤーのオブジェクト
Returns
-------
bool
True:プレイヤーがまだ生きている、False:プレイヤーが死んでしまった | 625941c821a7993f00bc7d55 |
def get_fitness_value(self): <NEW_LINE> <INDENT> return self._fitness_value | Get the fitness value of the batch.
Returns
-------
:class:`float`
The fitness value. | 625941c8d6c5a102081440b1 |
def close_tab(self, index): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sender = self.sender() <NEW_LINE> if self.tab_paths.get(sender.tabText(index), None) is not None: <NEW_LINE> <INDENT> del self.tab_paths[sender.tabText(index)] <NEW_LINE> <DEDENT> widget = sender.widget(index) <NEW_LINE> if widget is not None: <NE... | Called when Tab close button is pressed
Closes tab at index
:param index: int | 625941c850812a4eaa59c38a |
def from_ExprOp(self, expr): <NEW_LINE> <INDENT> raise NotImplementedError("Abstract method") | Translate an ExprOp
@expr: ExprOp to translate | 625941c8e1aae11d1e749d1d |
def login_required(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated_function(*args, **kwargs): <NEW_LINE> <INDENT> if session.get("username") is None: <NEW_LINE> <INDENT> return redirect("/signin") <NEW_LINE> <DEDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> return decorated_function | decorate routes to require login_require | 625941c8aad79263cf390aa7 |
@pytest.fixture <NEW_LINE> def sqshelper(config): <NEW_LINE> <INDENT> return SQSHelper( access_key=config("crashmover_crashpublish_access_key", default=""), secret_access_key=config( "crashmover_crashpublish_secret_access_key", default="" ), endpoint_url=config("crashmover_crashpublish_endpoint_url", default=""), regio... | Generate and returns a PubSub helper using env config. | 625941c86fece00bbac2d7a5 |
def indexes(self): <NEW_LINE> <INDENT> return [v for k, v in list(self._indexes.items())] | Access a list of the current indexes registered
Returns:
(list): the indexes stored. | 625941c8d164cc6175782db4 |
def test_update_profile(self): <NEW_LINE> <INDENT> pass | Test case for update_profile
Update your own profile information # noqa: E501 | 625941c83d592f4c4ed1d0d7 |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_2i().pack(_x.return_code, _x.err_code)) <NEW_LINE> _x = self.err_msg <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941c826068e7796caed45 |
def get_all_regestered_legal_entities(self, connection): <NEW_LINE> <INDENT> return connection.get_all_regestered_legal_entities() | This can be a good legal entity distribution mechanism as long as the user
knows how to verify connect securely the first time they pull. See getConnection
for the technical explanation. Ultimately, the question is: do you trust the
server you logged into originally? | 625941c844b2445a339320fe |
def get_build_options(self, source_id: proto_source.SourceRepository.SourceIdentity) -> proto_source.BazelOption: <NEW_LINE> <INDENT> source = self.get_source_repository(source_id) <NEW_LINE> bazel_options = source.bazel_options <NEW_LINE> if not bazel_options: <NEW_LINE> <INDENT> source_name = proto_source.S... | Determine whether build options are specified in the control object
and return them
Args:
source_id: The identity of the source object we seek (eg.
SRCID_NIGHTHAWK or SRCID_ENVOY)
Return:
the Bazel Options defined in the source identified by the
specified source_id
Raises:
SourceManagerError: If no opt... | 625941c8b5575c28eb68e067 |
@opcode <NEW_LINE> def CSEL(cpu_context, instruction): <NEW_LINE> <INDENT> logger.debug("%s instruction not currently implemented.", instruction.mnem) | Conditional select | 625941c8c432627299f04cad |
def _configure(options): <NEW_LINE> <INDENT> if getattr(options, b'config', None) is not None: <NEW_LINE> <INDENT> config_path = options.config <NEW_LINE> del options.config <NEW_LINE> config.set_file(config_path) <NEW_LINE> <DEDENT> config.set_args(options) <NEW_LINE> if config['verbose'].get(int): <NEW_LINE> <INDENT>... | Amend the global configuration object with command line options.
| 625941c8a8370b7717052907 |
def countPlayers(): <NEW_LINE> <INDENT> conn = connect() <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute("SELECT count(*) FROM players;") <NEW_LINE> num_players_from_db = cur.fetchone() <NEW_LINE> conn.close() <NEW_LINE> return num_players_from_db[0] | Returns the number of players currently registered. | 625941c88e71fb1e9831d811 |
def get_output_validation_error(self, data_to_validate: typing.Any) -> ProcessValidationError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.serializer.dump(data_to_validate, validate=True, many=self._many) <NEW_LINE> raise WorkflowException("Serializer should raise an exception here") <NEW_LINE> <DEDENT> except Va... | Return a ProcessValidationError containing validation
detail error for output data | 625941c8442bda511e8be481 |
def fix_db(self, database): <NEW_LINE> <INDENT> self.logger.debug('CONVERTING DB') <NEW_LINE> temp_db = {} <NEW_LINE> for guild in database: <NEW_LINE> <INDENT> temp_date = {} <NEW_LINE> for date in database[guild]: <NEW_LINE> <INDENT> temp_emoji = {} <NEW_LINE> for emoji_id in database[guild][date]: <NEW_LINE> <INDENT... | Converts FireBase file content into proper manageable objects (datetime & EmojiStat)
@param database: Dictionary FireBase content
@return: Dictionary of FireBase content into proper objects | 625941c8097d151d1a222ec2 |
def history_all_product_inventory(self, cr, uid, current_date, context=None): <NEW_LINE> <INDENT> if not current_date: <NEW_LINE> <INDENT> _logger.error('No current data error!') <NEW_LINE> return False <NEW_LINE> <DEDENT> product_pool = self.pool.get('product.product') <NEW_LINE> product_ids = product_pool.search(cr, ... | Save all product status now
| 625941c8627d3e7fe0d68eb7 |
def destroy_process_group(group=group.WORLD): <NEW_LINE> <INDENT> global _pg_map <NEW_LINE> global _pg_names <NEW_LINE> global _pg_group_ranks <NEW_LINE> global _default_pg <NEW_LINE> global _default_pg_init_method <NEW_LINE> if group == GroupMember.NON_GROUP_MEMBER: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if gr... | Destroy a given process group, and deinitialize the distributed package
Arguments:
group (ProcessGroup, optional): The process group to be destroyed, if
group.WORLD is given, all process
groups including the default one will
... | 625941c8167d2b6e31218bfe |
def test_get_share_gateway(self): <NEW_LINE> <INDENT> vgw = self.user._gateway.get_share_gateway(self.r_share.id) <NEW_LINE> self.assertEqual(vgw.user, self.user) <NEW_LINE> self.assertEqual(vgw.owner.id, self.sharer.id) <NEW_LINE> self.assertEqual(vgw.root_id, self.r_share.subtree.id) | Test the get_share_gateway method of a StorageUserGateway. | 625941c8d6c5a102081440b2 |
def get_comparable_values(self): <NEW_LINE> <INDENT> return () | Return a tupple of values representing the unicity of the object
| 625941c832920d7e50b28237 |
def put(self, request, pk, format=None): <NEW_LINE> <INDENT> resource = self.get_object(pk) <NEW_LINE> serializer = ResourceSerializer(resource, data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> return Response(s... | When requested update the corresponding entry of the table | 625941c82c8b7c6e89b35829 |
def getCitiBikeCSV(datestring): <NEW_LINE> <INDENT> print ("Downloading", datestring) <NEW_LINE> if not os.path.isfile(os.getenv("PUIDATA") + "/" + datestring + "-citibike-tripdata.csv"): <NEW_LINE> <INDENT> if os.path.isfile(datestring + "-citibike-tripdata.csv"): <NEW_LINE> <INDENT> if os.system("mv " + datestring + ... | The function downloads a CSV file into the PUIDATA directory from the Citibike database for the given datestring
Author: vys217 lifting code from
https://github.com/fedhere/PUI2016_fb55/blob/master/HW3_fb55/citibikes_gender.ipynb | 625941c89b70327d1c4e0e3c |
def ECM(self): <NEW_LINE> <INDENT> self.kVecCumul = np.cumsum(self.kVec) <NEW_LINE> self.arule = [1.0*self.total_failures] <NEW_LINE> self.brule = [1.0*self.total_failures/self.total_time] <NEW_LINE> self.crule = [1.0] <NEW_LINE> self.ll_list = [self.logL(self.arule[0], self.brule[0], self.crule[0])] <NEW_LINE> self.ll... | ECM Algorithm implementation | 625941c8377c676e91272211 |
def test_delete_image(setup_provider, provider_crud, remove_test, set_grid, request): <NEW_LINE> <INDENT> image_name = remove_test['image'] <NEW_LINE> test_image = instance.Image(image_name, provider_crud) <NEW_LINE> test_image.delete() <NEW_LINE> test_image.wait_for_delete() <NEW_LINE> provider_crud.refresh_provider_r... | Tests delete image
Metadata:
test_flag: delete_object | 625941c863f4b57ef0001183 |
def validate_json_output(output_schema=None, output_example=None, validator_cls=None, format_checker=jsonschema.FormatChecker(), on_empty_404=False, write_json=True): <NEW_LINE> <INDENT> def _validate(rh_method): <NEW_LINE> <INDENT> @wraps(rh_method) <NEW_LINE> def _wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> o... | Parameterized decorator for schema validation
:type validator_cls: IValidator class
:type format_checker: jsonschema.FormatChecker or None
:type on_empty_404: bool
:param on_empty_404: If this is set, and the result from the
decorated method is a falsy value, a 404 will be raised.
:type use_defaults: bool
:param wr... | 625941c8a8ecb033257d3135 |
def Huffman2(symb2freq): <NEW_LINE> <INDENT> heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] <NEW_LINE> heapify(heap) <NEW_LINE> while len(heap) > 1: <NEW_LINE> <INDENT> lo = heappop(heap) <NEW_LINE> hi = heappop(heap) <NEW_LINE> for pair in lo[1:]: <NEW_LINE> <INDENT> pair[1] = '0' + pair[1] <NEW_LINE> <DEDE... | Huffman encode the given dict mapping symbols to frequency | 625941c88da39b475bd64fdb |
def subsetsWithDup(self, nums): <NEW_LINE> <INDENT> out = [[]] <NEW_LINE> for n in sorted(nums): <NEW_LINE> <INDENT> out += [i+[n] for i in out] <NEW_LINE> <DEDENT> rst = set([tuple(i) for i in out]) <NEW_LINE> return list([list(i) for i in rst]) | :type nums: List[int]
:rtype: List[List[int]] | 625941c88e05c05ec3eea3dc |
def support_schema_learning(topology_m1c1): <NEW_LINE> <INDENT> ent = topology_m1c1.cs["consumer1"].getEntry(DN_CONFIG, ldap.SCOPE_BASE, "(cn=config)", ['nsslapd-versionstring']) <NEW_LINE> if ent.hasAttr('nsslapd-versionstring'): <NEW_LINE> <INDENT> val = ent.getValue('nsslapd-versionstring') <NEW_LINE> version = ensu... | with https://fedorahosted.org/389/ticket/47721, the supplier and consumer can learn
schema definitions when a replication occurs.
Before that ticket: replication of the schema fails requiring administrative operation
In the test the schemaCSN (supplier consumer) differs
After that ticket: replication of the schema suc... | 625941c8a934411ee37516fb |
def detail_url(exam_sheet_id): <NEW_LINE> <INDENT> return reverse('exam:examsheet-detail', args=[exam_sheet_id]) | Return exam sheet detail url | 625941c81f037a2d8b946266 |
def add_data_from_jsonp(self, data_src, data_name='json_data', series_type="line", name=None, **kwargs): <NEW_LINE> <INDENT> if not self.jsonp_data_flag: <NEW_LINE> <INDENT> self.jsonp_data_flag = True <NEW_LINE> self.jsonp_data_url = json.dumps(data_src) <NEW_LINE> if data_name == 'data': <NEW_LINE> <INDENT> data_name... | set map data directly from a https source
the data_src is the https link for data
and it must be in jsonp format | 625941c81f5feb6acb0c4bb9 |
def goTo(self, goal, yaw, duration, groupMask = 0): <NEW_LINE> <INDENT> gp = arrayToGeometryPoint(goal) <NEW_LINE> self.goToService(groupMask, True, gp, yaw, rospy.Duration.from_sec(duration)) | Broadcasted goTo - Move smoothly to goal, then hover indefinitely.
Broadcast version of :meth:`Crazyflie.goTo()`. All robots that match the
groupMask start moving at exactly the same time. Use for synchronized
movement. Asynchronous command; returns immediately.
While the individual goTo() supports both relative and ... | 625941c8eab8aa0e5d26dbc0 |
def launchReportWindow(self): <NEW_LINE> <INDENT> self.ReportCanvas = ReportCanvas( self.samplePoints, self.filteredResistivity, self.voltageSpacing, self.apparentResistivity, self.voltageSpacingExtrapolated, self.newResistivity) <NEW_LINE> pp.pprint('tableDATA REPORT WINDOW:') <NEW_LINE> pp.pprint(tableData_reportWind... | Launches the ReportWindow class on launch of VES Inverse Analysis | 625941c866673b3332b920f9 |
def _create_chain(self, word_list): <NEW_LINE> <INDENT> for i, message in enumerate(word_list + word_list[:self.order]): <NEW_LINE> <INDENT> if i < self.order: <NEW_LINE> <INDENT> self.memory.enqueue(message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_state = self.memory.serialize() <NEW_LINE> self.memory.en... | Generate the internal markov chain that will be used by the sentence generator. | 625941c83eb6a72ae02ec543 |
def test_update_node_new(self): <NEW_LINE> <INDENT> dataset_id = unicode(uuid4()) <NEW_LINE> manifestation = Manifestation(dataset=Dataset(dataset_id=dataset_id), primary=True) <NEW_LINE> node = NodeState( hostname=u"node1.example.com", applications={Application( name=u'postgresql-clusterhq', image=DockerImage.from_str... | When doing ``update_node()``, if the given ``NodeState`` has hostname
not in the existing ``DeploymentState`` then just add new
``NodeState`` to new ``DeploymentState``. | 625941c830c21e258bdfa505 |
def get_version_str(git_only=False, is_post_release=False): <NEW_LINE> <INDENT> script_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> version_file_path = os.path.join(script_dir, 'version.txt') <NEW_LINE> if os.path.exists(version_file_path) and git_only == False: <NEW_LINE> <INDENT> with open(version_fil... | Returns the versions of the tools
If git_only is true, the version.txt file is ignored even
if it is present. | 625941c86e29344779a6267b |
def _extract(self): <NEW_LINE> <INDENT> self._create_folder(REVIEW_DIR) <NEW_LINE> self._clean_folder(REVIEW_DIR) <NEW_LINE> self._extract_package(self._path, REVIEW_DIR) | Extract the package in the REVIEW_DIR
- clean the REVIEW_DIR
- extract | 625941c87c178a314d6ef4c6 |
def audit_trail(self,temp_table = True): <NEW_LINE> <INDENT> if(temp_table): <NEW_LINE> <INDENT> self.write_sql("DELETE FROM METER_AUDIT_TEMP") <NEW_LINE> self.write_sql(("INSERT INTO METER_AUDIT_TEMP " "(MC_ID, CO_CODE, ADM_CODE, MC_YEAR, EM_FIG_OLD, MQ_ID_OLD, MG_ID_OLD, USER_NAME, SERIES) " "SELECT IND_ID, CO_CODE, ... | Records the changes of indicators in the INDICATORS_AUDIT_TRAIL SQL table. | 625941c892d797404e3041f2 |
def clean(self): <NEW_LINE> <INDENT> old_password = self.cleaned_data.get('old', None) <NEW_LINE> password1 = self.cleaned_data.get('new1', None) <NEW_LINE> password2 = self.cleaned_data.get('new2', None) <NEW_LINE> if not self.instance.check_password(old_password): <NEW_LINE> <INDENT> raise forms.ValidationError('Inva... | Do the global validation.
Raises:
ValidationError: If the old (current) password is wrong
or if the two others are not the identical.
Returns:
(dict): Return cleaned data. | 625941c821bff66bcd6849bc |
def calculate_score_instance(self, instance): <NEW_LINE> <INDENT> instance_cpu_utilization = self.get_instance_cpu_usage(instance) <NEW_LINE> if instance_cpu_utilization is None: <NEW_LINE> <INDENT> LOG.error( "No values returned by %(resource_id)s " "for %(metric_name)s" % dict( resource_id=instance.uuid, metric_name=... | Calculate Score of virtual machine
:param instance: the virtual machine
:return: score | 625941c816aa5153ce3624e1 |
def test_roots_generator(): <NEW_LINE> <INDENT> assert find_polymin_from_roots([0])[0] == 0 <NEW_LINE> assert find_polymin_from_roots([1])[0] == 1 <NEW_LINE> assert find_polymin_from_roots([-1])[0] == -1 <NEW_LINE> assert find_polymin_from_roots([0], scale=-1)[0] == -np.inf <NEW_LINE> assert find_polymin_from_roots([0]... | Test function to minimize integral of polynomial created from list of roots | 625941c8236d856c2ad44841 |
def dataReceived(self, data): <NEW_LINE> <INDENT> self.receive_buffer += data <NEW_LINE> while len(self.receive_buffer) > 0: <NEW_LINE> <INDENT> if not soupbin.has_complete_message(self.receive_buffer): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> msg, self.receive_buffer = soupbin.get_message(self.receive_buffer) <N... | Handle a received packet.
Override of Twisted method from base class. | 625941c85166f23b2e1a51c1 |
def initialize_command_dataframe(only_columns=False): <NEW_LINE> <INDENT> columns = ['participant_id', 'SSD', 'run_id', 'scenario', 'timestamp', 'type', 'value', 'ACID', 'timestamp_traffic'] <NEW_LINE> if only_columns: <NEW_LINE> <INDENT> command_list = pd.DataFrame(columns=columns) <NEW_LINE> <DEDENT> else: <NEW_LINE>... | INITIALIZE COMMAND DATAFRAME | 625941c8b57a9660fec338ec |
def boundingRect(self): <NEW_LINE> <INDENT> if self._bounding is None: <NEW_LINE> <INDENT> self._bounding = QtCore.QRectF(0, 0, 1, 1) <NEW_LINE> self._bounding.setSize(self.bounding_size()) <NEW_LINE> <DEDENT> return self._bounding | Return the bounding box of the page. | 625941c84f6381625f114aa3 |
def decode_header(self, nesheader): <NEW_LINE> <INDENT> self.prg_rom_bytes = nesheader[4] * 16384 <NEW_LINE> self.chr_rom_bytes = nesheader[5] * 8192 <NEW_LINE> self.mirror_pattern = self.MIRROR_HORIZONTAL if bit_low(nesheader[6], self.MIRROR_BIT) else self.MIRROR_VERTICAL <NEW_LINE> self.has_persistent = bi... | Decode the standard .nes file format header. Includes support for NES 2.0 format. | 625941c88c0ade5d55d3ea23 |
def test_process_fan_payload_invalid_length(self): <NEW_LINE> <INDENT> xknx = XKNX(loop=self.loop) <NEW_LINE> fan = Fan(xknx, name="TestFan", group_address_speed='1/2/3') <NEW_LINE> telegram = Telegram(GroupAddress('1/2/3'), payload=DPTArray((23, 24))) <NEW_LINE> with self.assertRaises(CouldNotParseTelegram): <NEW_LINE... | Test process wrong telegrams. (wrong payload length). | 625941c8be7bc26dc91cd66a |
def getBasis(self): <NEW_LINE> <INDENT> ops = self.getPendingOperations() <NEW_LINE> if len(ops) <= 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.logger.debug(u"Recomputing basis.") <NEW_LINE> skiplist = ProofManager._buildCommitSkipList(deepcopy(ops)) <NEW_LINE> return skiplist.getBasis() | Computes and returns basis for the whole current structure
made of added Operations.
If no operations were added, None is returned.
raise: UnexpectedBasisException if anything goes wrong while
computing basis. | 625941c8cad5886f8bd27042 |
def retrieve_mail_attachments( self, name: str, *, check_regex: bool = False, latest_only: bool = False, mail_folder: str = 'INBOX', mail_filter: str = 'All', not_found_mode: str = 'raise', ) -> List[Tuple]: <NEW_LINE> <INDENT> mail_attachments = self._retrieve_mails_attachments_by_name( name, check_regex, latest_only,... | Retrieves mail's attachments in the mail folder by its name.
:param name: The name of the attachment that will be downloaded.
:type name: str
:param check_regex: Checks the name for a regular expression.
:type check_regex: bool
:param latest_only: If set to True it will only retrieve the first matched attachment.
:typ... | 625941c882261d6c526ab506 |
def init_ground(self, lines): <NEW_LINE> <INDENT> self.ground = [] <NEW_LINE> for i in range(self.nb_lines): <NEW_LINE> <INDENT> lines[i] = list(lines[i]) <NEW_LINE> for j in range(self.nb_columns): <NEW_LINE> <INDENT> lines[i][j] = [lines[i][j], []] <NEW_LINE> <DEDENT> self.ground.append(lines[i]) | Fill the ground
Each cell is a list:
first element: the cell value
second element: states of Bender when he was on this cell (to detect loops)
Args:
lines -- list of strings -- the ground's lines | 625941c84c3428357757c391 |
def to_dict(self): <NEW_LINE> <INDENT> user_dict = { "user_id": self.id, "name": self.name, "mobile": self.mobile, "avatar": const.QINIU_URL_DOMAIN + self.avatar_url if self.avatar_url else "", "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S") } <NEW_LINE> return user_dict | 将对象转换为字典数据 | 625941c8b5575c28eb68e068 |
def add_in_co(self, tx): <NEW_LINE> <INDENT> self.in_co.append(tx) | add a transaction to confirmed incoming tx array
:param tx: | 625941c8187af65679ca5187 |
def chroot(args, argv): <NEW_LINE> <INDENT> argv.insert(0, args.argv) <NEW_LINE> c = Chroot(path=args.path, target=os.execvp, args=(argv[0], argv), newpid=args.pid, uid_map=args.uid, gid_map=args.gid, map_zero=args.id, newuts=args.uts, newipc=args.ipc, newnet=args.net) <NEW_LINE> c.start() <NEW_LINE> if args.verbose: <... | Run program in new root and namespaces.
$ space chroot --pid --uid '0 1000 1' ~/.local/share/lxc/ubuntu/rootfs/ /bin/ls /home/
Create a child process that executes a shell command in new
root directory, ns, user and additional namespaces; allow UID
and GID mappings to be specified when creating a user namespace.
An... | 625941c873bcbd0ca4b2c0df |
def set_desired_state(self, desired_state): <NEW_LINE> <INDENT> if isinstance(desired_state, str): <NEW_LINE> <INDENT> self.desired_state = STATE_STRING_TO_ENUM.get(desired_state.lower()) <NEW_LINE> if not self.desired_state: <NEW_LINE> <INDENT> raise InvalidState <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ... | Sets the desired state for all particles in the quasiparticle.
Args:
desired_state (str): one of running,stopped,terminated. | 625941c8ac7a0e7691ed4137 |
def FetchSizeOfSignedBinary( binary_id_or_urn: Union[rdf_objects.SignedBinaryID, rdfvalue.RDFURN]) -> int: <NEW_LINE> <INDENT> if isinstance(binary_id_or_urn, rdfvalue.RDFURN): <NEW_LINE> <INDENT> binary_id = SignedBinaryIDFromURN(binary_id_or_urn) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> binary_id = binary_id_or_... | Returns the size of the given binary (in bytes).
Args:
binary_id_or_urn: SignedBinaryID or RDFURN that uniquely identifies the
binary.
Raises:
SignedBinaryNotFoundError: If no signed binary with the given URN exists. | 625941c82eb69b55b151c917 |
def ingredients(apikey, fdc_id, url = 'https://api.nal.usda.gov/fdc/v1/food/'): <NEW_LINE> <INDENT> params = (('api_key', apikey),) <NEW_LINE> try: <NEW_LINE> <INDENT> r = requests.get(url+"%s" % fdc_id, params = params) <NEW_LINE> L = r.json()['inputFoods'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> warn... | Given fdc_id, return ingredients of food. | 625941c85e10d32532c5ef90 |
def post(self, request): <NEW_LINE> <INDENT> period = self.request.POST.get('period', False) <NEW_LINE> package_id = self.request.POST.get('package', False) <NEW_LINE> if not period: <NEW_LINE> <INDENT> messages.error(request, 'Не выбран период', 'danger') <NEW_LINE> return redirect(reverse('package:list')) <NEW_LINE> ... | Покупка или продления тарифного плана
:param request: | 625941c8be8e80087fb20cad |
def fetchmany(self, size=arraysize): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> result = [] <NEW_LINE> while i < size: <NEW_LINE> <INDENT> row = self.fetchone() <NEW_LINE> if row: <NEW_LINE> <INDENT> result.append(row) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> ... | Fetch the next set of rows of a query result, returning a sequence of
sequences (e.g. a list of tuples). An empty sequence is returned when no
more rows are available. The number of rows to fetch per call is specified
by the parameter. If it is not given, the cursor’s arraysize determines
the number of rows to be fetch... | 625941c850485f2cf553ce02 |
def mag2Jy(info_dict, Mag): <NEW_LINE> <INDENT> fluxJy=info_dict['Flux_zero_Jy']*10**(-0.4*Mag) <NEW_LINE> return fluxJy | Converts a magnitude into flux density in Jy
Parameters
-----------
info_dict: dictionary
Mag: array or float
AB or vega magnitude
Returns
-------
fluxJy: array or float
flux density in Jy | 625941c85fc7496912cc39e7 |
def download(url): <NEW_LINE> <INDENT> req = requests.get(url) <NEW_LINE> if req.status_code == 404: <NEW_LINE> <INDENT> print('No such file found at %s' % url) <NEW_LINE> return <NEW_LINE> <DEDENT> filename = url.split('/')[-1] <NEW_LINE> with open(filename, 'wb') as fobj: <NEW_LINE> <INDENT> fobj.write(req.content) <... | 从指定的URL中下载文件并存储到当前目录
:arg url:要下载的文件的URL | 625941c84d74a7450ccd422d |
def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp', proxy=None, num_retries=1, scrape_callback=None): <NEW_LINE> <INDENT> crawl_queue = [seed_url] <NEW_LINE> seen = {seed_url: 0} <NEW_LINE> num_urls = 0 <NEW_LINE> rp = get_robots(seed_url) <NEW_LINE> throttle... | Crawl from the given seed URL following links matched by link_regex
| 625941c830dc7b76659019d0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.