code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def control(self): <NEW_LINE> <INDENT> return self._control
Returns the control.
625941de287bf620b61d3d9f
def typeof(obj): <NEW_LINE> <INDENT> if isinstance(obj, _simple_types): <NEW_LINE> <INDENT> return type(obj) <NEW_LINE> <DEDENT> if isinstance(obj, tuple): <NEW_LINE> <INDENT> return Tuple[tuple(typeof(elem) for elem in obj)] <NEW_LINE> <DEDENT> if isinstance(obj, (list, dict, set)) and not obj: <NEW_LINE> <INDENT> rai...
Compute the Transonic type corresponding to a Python object Supports: - simple Python types (int, float, complex, str) - homogeneous list, dict and set - tuple - numpy scalars - numpy arrays
625941de29b78933be1e59e4
def placeholder_inputs(batch_size): <NEW_LINE> <INDENT> images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, mnist1HiddenLayer.IMAGE_PIXELS)) <NEW_LINE> labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size)) <NEW_LINE> return images_placeholder, labels_placeholder
Generate placeholder variables to represent the input tensors. These placeholders are used as inputs by the rest of the model building code and will be fed from the downloaded data in the .run() loop, below. Args: batch_size: The batch size will be baked into both placeholders. Returns: images_placeholder: Image...
625941decad5886f8bd27316
def motar(df: DataFrame, num_matches: int, num_misses: int, num_switches: int, num_false_positives: int, num_objects: int, alpha: float = 1.0) -> float: <NEW_LINE> <INDENT> recall = num_matches / num_objects <NEW_LINE> nominator = (num_misses + num_switches + num_false_positives) - (1 - recall) * num_objects <NEW_LINE>...
Initializes a MOTAR class which refers to the modified MOTA metric at https://www.nuscenes.org/tracking. Note that we use the measured recall, which is not identical to the hypothetical recall of the AMOTA/AMOTP thresholds. :param df: Motmetrics dataframe that is required, but not used here. :param num_matches: The num...
625941de1f5feb6acb0c4e88
def decrypt(self, text): <NEW_LINE> <INDENT> output = [] <NEW_LINE> text = text.upper() <NEW_LINE> for char in text: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> index = self.letters_list.index(char) <NEW_LINE> decryption = ((self.a_inverse*(index-self.b)) % self.m) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <IN...
This is the method for decryption. The formula for decryption is (a_inverse*(x-b)) where a_inverse is the modular inverse of the number co prime with m. For this program the modular inverse has been calculated as 9 as has been set. The variable decryption holds the calculated answer after applying the formula.
625941de851cf427c661a849
def zscaleHist( hist2d, cAv, cSd ): <NEW_LINE> <INDENT> hist2d -= cAv <NEW_LINE> hist2d /= cSd <NEW_LINE> return hist2d
Histogram will be subtracted by cAv and divided by cSd
625941de67a9b606de4a81f4
def getHint(self, secret, guess): <NEW_LINE> <INDENT> s = [0] * 10 <NEW_LINE> g = [0] * 10 <NEW_LINE> l = len(secret) <NEW_LINE> b = 0 <NEW_LINE> for i in range(0, l): <NEW_LINE> <INDENT> if secret[i] == guess[i]: <NEW_LINE> <INDENT> b += 1 <NEW_LINE> <DEDENT> s[int(secret[i])] += 1 <NEW_LINE> g[int(guess[i])] += 1 <NE...
:type secret: str :type guess: str :rtype: str
625941deadb09d7d5db6cacb
def _dae(self, name, x, num_hidden, activation, noise_std=0.1): <NEW_LINE> <INDENT> if self.init_layers: <NEW_LINE> <INDENT> ae = Autoencoder(num_hidden, activation=activation) <NEW_LINE> ae.name = name <NEW_LINE> self.layers += [ae] <NEW_LINE> input_shape_ = tuple(dim2int(v) for v in x.shape) <NEW_LINE> ae.set_input_s...
DAE.
625941deb545ff76a8914153
@app.route('/4-hbnb') <NEW_LINE> def hbnb_filters(the_id=None): <NEW_LINE> <INDENT> state_objs = storage.all('State').values() <NEW_LINE> states = dict([state.name, state] for state in state_objs) <NEW_LINE> amens = storage.all('Amenity').values() <NEW_LINE> places = storage.all('Place').values() <NEW_LINE> users = dic...
handles request to custom template with states, cities & amentities
625941de7047854f462a1743
def p_logical(p): <NEW_LINE> <INDENT> p[0] = Node('logical', None, p[0], desig=p[1])
logical : AND | OR | XOR
625941de07d97122c4178bcf
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GetUniverseTypesTypeIdDogmaAttribute): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941de60cbc95b062c6881
def bprop(self, inputs, outputs, grads_wrt_outputs): <NEW_LINE> <INDENT> raise NotImplementedError()
Back propagates gradients through a layer. Given gradients with respect to the outputs of the layer calculates the gradients with respect to the layer inputs. This should correspond to default stochastic forward-propagation. Args: inputs: Array of layer inputs of shape (batch_size, input_dim). outputs: Array ...
625941deac7a0e7691ed4404
def get_rhs(current_pops, time): <NEW_LINE> <INDENT> environment["time"] = Expression.num_expression(time) <NEW_LINE> for (species, _), population in zip(gradients, current_pops): <NEW_LINE> <INDENT> environment[species] = Expression.num_expression(population) <NEW_LINE> <DEDENT> result = [expr.get_value(environment=en...
The main function passed to the solver, it calculates from the current populations of species, the rate of change of each species. Also given a 'time' which may be used in the equations Essentially then, solves for each ODE the right hand side of the ode at the given populations and time.
625941de2eb69b55b151cbf0
def opencv_image(self, size=400, grayscale=True): <NEW_LINE> <INDENT> filename = self.source_file.file.name <NEW_LINE> color_mode = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED <NEW_LINE> cv2img = cv2.imread(filename, color_mode) <NEW_LINE> self.source_file.close() <NEW_LINE> width, height = cv2img.shape...
Convert ImageFile into a cv2 image for image processing.
625941dea17c0f6771cbe38d
def over(self, alias) -> 'Expression': <NEW_LINE> <INDENT> return _binary_op("over")(self, alias)
Defines an aggregation to be used for a previously specified over window. Example: :: >>> tab.window(Over >>> .partition_by(col('c')) >>> .order_by(col('rowtime')) >>> .preceding(row_interval(2)) >>> .following(CURRENT_ROW) >>> .alias("w")) \ >>> ...
625941decc0a2c11143dd1ce
def test_client_merge_different_descr(): <NEW_LINE> <INDENT> r1 = Client(clientId="client", description="test1", scopes=["a"]) <NEW_LINE> r2 = Client(clientId="client", description="test2", scopes=["b"]) <NEW_LINE> with pytest.raises(RuntimeError) as exc: <NEW_LINE> <INDENT> r1.merge(r2) <NEW_LINE> <DEDENT> assert "Des...
Descriptions must match to merge
625941de090684286d50f026
def get_list(package): <NEW_LINE> <INDENT> user = package.get('user') <NEW_LINE> params = package.get('params') <NEW_LINE> target_schoolid = int(params.get(ParamType.SchoolId)) <NEW_LINE> page = params.get(ParamType.Page) <NEW_LINE> if page is None: <NEW_LINE> <INDENT> page = 1 <NEW_LINE> <DEDENT> page = int(page) <NEW...
get theme list
625941de50812a4eaa59c65c
def test_header_extend_unique(self): <NEW_LINE> <INDENT> hdu = fits.PrimaryHDU() <NEW_LINE> hdu2 = fits.ImageHDU() <NEW_LINE> hdu.header['MYKEY'] = ('some val', 'some comment') <NEW_LINE> hdu2.header['MYKEY'] = ('some other val', 'some other comment') <NEW_LINE> hdu.header.extend(hdu2.header) <NEW_LINE> assert len(hdu....
Test extending the header with and without unique=True.
625941de6fb2d068a760f3df
@login_required <NEW_LINE> @mission_is_member <NEW_LINE> def mission_asset_json(request, mission_user): <NEW_LINE> <INDENT> assets = MissionAsset.objects.filter(mission=mission_user.mission, removed__isnull=True) <NEW_LINE> assets_json = [] <NEW_LINE> for mission_asset in assets: <NEW_LINE> <INDENT> assets_json.append(...
List Assets in a Mission
625941de167d2b6e31218ed2
def dllf_dscale(scale, decay, history, sum_less_equal=True): <NEW_LINE> <INDENT> sum_part = np.count_nonzero(history) / scale <NEW_LINE> int_part = 0 <NEW_LINE> for i in range(len(history) - 1): <NEW_LINE> <INDENT> int_part += np.sum( np.exp(-decay * (history[i] - history[:i + 1])) - np.exp(-decay * (history[i + 1] - h...
Parameters ---------- scale decay history sum_less_equal : bool This argument does not affect the derivative w.r.t. the scale parameter. Thus, the return value does not depend on it. Returns ------- derivative_wrt_scale : float The derivative (w.r.t. the scale parameter) of the log-likelihood function ...
625941debe8e80087fb20f7c
def update_room_view(self, room) : <NEW_LINE> <INDENT> for neighbour_room in self.world_view[room.x][room.y][0] : <NEW_LINE> <INDENT> for a in self.open_list : <NEW_LINE> <INDENT> if(not self.world_view[a.x][a.y][1] in (-1,0,1) and a in get_coords(self.cave.grid[neighbour_room.x][neighbour_room.y].neighbours)) : <NEW_L...
Updates the bots view of the room
625941de3c8af77a43ae3ae1
def configure_python_packages() -> dict: <NEW_LINE> <INDENT> return { 'packages': reduce(lambda acc, pkg: acc + [d[0][len(_abs(SRC_DIR)) + 1:].replace(os.sep, '.') for d in sorted(os.walk(_abs(SRC_DIR, pkg))) if '__pycache__' not in d[0] and '__init__.py' in d[2]], PY_PACKAGES, []), 'package_dir': {'': SRC_DIR} }
Process python packages configuration
625941deb7558d58953c524c
def silence_transaction_logger(): <NEW_LINE> <INDENT> txn_handler = NullHandler() <NEW_LINE> txn_filter = MappingFilter( {logging.DEBUG: (8, 'DEBUG3')}, 'txn') <NEW_LINE> txn_handler.addFilter(txn_filter) <NEW_LINE> logging.getLogger('txn').addHandler(txn_handler)
Lower level of DEBUG messages from the transaction module.
625941de3d592f4c4ed1d3a3
def get_commitment(self, cpf, url='https://challenge.noverde.name/commitment'): <NEW_LINE> <INDENT> r = requests.post(url, headers={'x-api-key':'SnAB7jQEFs1Ai8XtZdssa14gORT3jWPI7TWdXN97'}, json={'cpf':cpf}) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> stream = io.BytesIO(r.content) <NEW_LINE> data = JSONPars...
Colocar validacao para caso o servico não estiver funcionando, ele tentar rodar a task depois
625941de63f4b57ef000144f
def _validate_params(self, for_partial_fit=False): <NEW_LINE> <INDENT> if not isinstance(self.shuffle, bool): <NEW_LINE> <INDENT> raise ValueError("shuffle must be either True or False") <NEW_LINE> <DEDENT> if not isinstance(self.early_stopping, bool): <NEW_LINE> <INDENT> raise ValueError("early_stopping must be either...
Validate input params.
625941de2eb69b55b151cbf1
def generate_slug(self, force=False): <NEW_LINE> <INDENT> if not self.slug: <NEW_LINE> <INDENT> self.slug = suggest_slug(self.slug_objects(), self.name)
Auto-generate the slug as needed.
625941de627d3e7fe0d6918f
def getLine(self, viter=None, giter=None, which_major=1): <NEW_LINE> <INDENT> if viter is None: <NEW_LINE> <INDENT> viter = self.variants <NEW_LINE> <DEDENT> if giter is None: <NEW_LINE> <INDENT> giter = self.cur <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> locus = next(viter) <NEW_LINE> genotypes = next(giter) <NEW_LI...
a line of validated genotypes for a locus
625941de3346ee7daa2b30ab
def _apirunner(self, apifunction, args=None): <NEW_LINE> <INDENT> if apifunction not in self.callbacks: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not args: args = {} <NEW_LINE> resultmaxprio = None <NEW_LINE> for plugin_and_priority in self.callbacks[apifunction]: <NEW_LINE> <INDENT> plugin = plugin_and_priorit...
Pass all calls to plugin callbacks through this method, they are checked whether they should be executed or not. Example C{self._apirunner("privmsg", {"user":user,"channel":channel,"msg":msg})} @type apifunction: string @param apifunction: the name of the callback function @type args: dict @param args: ...
625941de63d6d428bbe4482e
def load_data(): <NEW_LINE> <INDENT> (XT, YT), (x_test, y_test) = mnist.load_data() <NEW_LINE> X_train, y_train = XT[:N_TRAIN], YT[:N_TRAIN] <NEW_LINE> X_valid, y_valid = XT[N_TRAIN:], YT[N_TRAIN:] <NEW_LINE> X_test, y_test = x_test, y_test <NEW_LINE> return dict( X_train=X_train, y_train=y_train, X_valid=X_valid, y_va...
Get data with labels, split into training, validation and test set.
625941de7b180e01f3dc4b35
def inference_predict_span( self, select_on_vec: torch.Tensor, memory_tokens: torch.Tensor, valid_for_copy_mask: torch.LongTensor ) -> List[Tuple[int, int, float]]: <NEW_LINE> <INDENT> start_preds, end_preds = self._get_copy_span_weights( select_on_vec, memory_tokens, valid_for_copy_mask) <NEW_LINE> starts = torch.argm...
Given a copy is valid, finds the most likely (start, end, log_confidence) span
625941deeab8aa0e5d26de97
def _start_trace_internal(preamble=None): <NEW_LINE> <INDENT> Trace.reset() <NEW_LINE> if preamble: <NEW_LINE> <INDENT> Trace.Output.append(preamble) <NEW_LINE> <DEDENT> Trace.Output.append([ "#### import the simple module from the paraview", "from paraview.simple import *"]) <NEW_LINE> if not _get_skip_renderin...
**internal** starts tracing. Called by vtkSMTrace::StartTrace().
625941def548e778e58cd8bd
def pop(self): <NEW_LINE> <INDENT> return _swigibpy.ComboLegList_pop(self)
pop(ComboLegList self) -> std::vector< shared_ptr< ComboLeg > >::value_type
625941de8a349b6b435e84b1
def async_to_sync(cls): <NEW_LINE> <INDENT> def create_method(async_method_name): <NEW_LINE> <INDENT> @class_or_instance <NEW_LINE> def newmethod(self, *args, **kwargs): <NEW_LINE> <INDENT> if 'verbose' in kwargs: <NEW_LINE> <INDENT> verbose = kwargs.pop('verbose') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> verbose ...
Convert all query_x_async methods to query_x methods (see http://stackoverflow.com/questions/18048341/add-methods-to-a-class-generated-from-other-methods for help understanding)
625941de91af0d3eaac9bd59
def get_posts(db: Session, *, parent_resub_id: int, offset: int = 0, limit: int = 100) -> List[Post]: <NEW_LINE> <INDENT> return db.query(Post).filter_by(parent_resub_id=parent_resub_id).order_by(Post.created.desc()).offset(offset).limit( limit).all()
Get all posts in a resub.
625941de4e696a04525c978a
def delete_project(self, conn, name): <NEW_LINE> <INDENT> project = conn.identity.find_project(name, ignore_missing=False) <NEW_LINE> conn.identity.delete_project(project, ignore_missing=False)
Deletes the project
625941de71ff763f4b5499cf
def save(dictionary, path): <NEW_LINE> <INDENT> def json_serial(obj): <NEW_LINE> <INDENT> if isinstance(obj, dt.date): <NEW_LINE> <INDENT> serial = obj.strftime("%m/%d/%Y") <NEW_LINE> return serial <NEW_LINE> <DEDENT> raise TypeError("Type not serializable: " + str(obj)) <NEW_LINE> <DEDENT> with open(path, 'wb') as f: ...
utils.dump.save Writes dictionary to given path. Overwrites any data that is already there. Can save: Everything json.dumps can do by default datetime.date
625941deb7558d58953c524d
def check_can_sign_masternode(self, alias): <NEW_LINE> <INDENT> mn = self.get_masternode(alias) <NEW_LINE> if not mn: <NEW_LINE> <INDENT> raise Exception('Nonexistent masternode') <NEW_LINE> <DEDENT> if not mn.vin.get('prevout_hash'): <NEW_LINE> <INDENT> raise Exception('Collateral payment is not specified') <NEW_LINE>...
Raise an exception if alias can't be signed and announced to the network.
625941dedd821e528d63b4e5
def diagnose_car(): <NEW_LINE> <INDENT> user_input = raw_input('Is the car silent when you turn the key? (Y/N):') <NEW_LINE> if user_input == "Y": <NEW_LINE> <INDENT> user_input = raw_input('Are the battery terminals corroded? (Y/N):') <NEW_LINE> if user_input == "Y": <NEW_LINE> <INDENT> print('Clean terminals and try ...
Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Y or N Expected Outputs: Display proceeding diagnosis until final solution is provided Errors: Any other entry besides Y and N will result in an error Test Case: #Input:Y #Expected Output: Display Are the battery t...
625941de0c0af96317bb8526
def name(self): <NEW_LINE> <INDENT> return self._pycard.getType()
@return: the name of the iCalendar type of this component.
625941de711fe17d825426a2
def _calculate_physical_pixel_size(coord_min: Number, coord_max: Number, num_pixels: int) -> Number: <NEW_LINE> <INDENT> return (coord_max - coord_min) / num_pixels
Calculate the size of a pixel in physical space
625941de5f7d997b87174dd9
def _exit(error: str) -> None: <NEW_LINE> <INDENT> sys.exit(error)
A simple exit wrapper for testing.
625941de462c4b4f79d1da0e
def item_description(self, item): <NEW_LINE> <INDENT> return truncatewords(item.body,30)
返回正文前30个字符 :param item: :return:
625941de8e71fb1e9831dae6
def _remoteRemove(self, obj=None): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> if obj not in self._objects: <NEW_LINE> <INDENT> raise ObjectNotFound("object %s not found on relation %s" % ( obj.getPrimaryId(), self.getPrimaryId())) <NEW_LINE> <DEDENT> objs = [obj] <NEW_LINE> <DEDENT> else: objs = self.objectValuesA...
remove an object from the far side of this relationship if no object is passed in remove all objects
625941dea8ecb033257d340a
def GetFriendsTimeline(self, since=None): <NEW_LINE> <INDENT> url = 'http://twitter.com/statuses/friends_timeline/' <NEW_LINE> parameters = {} <NEW_LINE> if since: <NEW_LINE> <INDENT> parameters['since'] = since <NEW_LINE> <DEDENT> json = self._FetchUrl(url, parameters=parameters) <NEW_LINE> data = simplejson.loads(jso...
Fetch the sequence of twitter.Status messages for a user's friends The twitter.Api instance must be authenticated if the user is private. Args: user: Specifies the ID or screen name of the user for whom to return the friends_timeline. If unspecified, the username and password must be set in the twitter...
625941dee64d504609d74b7e
def savefig(path, fig=None, close=True, **kwargs): <NEW_LINE> <INDENT> if fig is None: <NEW_LINE> <INDENT> fig = plt.gcf() <NEW_LINE> <DEDENT> path = os.path.abspath(path) <NEW_LINE> kwargs["dpi"] = kwargs.get("dpi", 300) <NEW_LINE> kwargs["transparent"] = kwargs.get("transparent", False) <NEW_LINE> kwargs["pad_inches"...
Save a figure. Note, that this method defaults to transparent background (``facecolor`` kwarg) and to 300 dpi. Parameters ---------- path : str Path to save figure at. fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. close : bool (optiona...
625941de0fa83653e46572f7
def hmsToS(h, m, s): <NEW_LINE> <INDENT> return (h * 60 + m) * 60 + s
Convert hours, minutes, seconds to seconds. @param h: hours @type h: int @param m: minutes @type m: int @param s: seconds @type s: int @return: seconds @rtype: int
625941de442bda511e8be752
def getdata(nslicenum): <NEW_LINE> <INDENT> train = loadmat('./train_32x32.mat') <NEW_LINE> print ('train ', train['X'].shape, train['y'].shape) <NEW_LINE> print (type(train['X']), type(train['y'])) <NEW_LINE> train_samples = train['X'][:, :, :, 0:nslicenum].copy() <NEW_LINE> train_labels = train['y'][0:nslicenum, :].c...
get data from mat
625941de30dc7b7665901ca2
def resetAll(self): <NEW_LINE> <INDENT> if len(self.docks)==0: <NEW_LINE> <INDENT> self.index=None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for q in self.docks: <NEW_LINE> <INDENT> q.setWindowTitle('') <NEW_LINE> q.show() <NEW_LINE> <DEDENT> self.index=0
Reset the window titles of All the QDockWidgets in self.docks and set self.index=0 Returns: None
625941de796e427e537b0906
def new_table(session, name, ft_space, ann_space, metadesc, coldesc, parent=None): <NEW_LINE> <INDENT> ft = FeatureTable(session, name, ft_space, ann_space) <NEW_LINE> ft.new_table(metadesc, coldesc) <NEW_LINE> if parent: <NEW_LINE> <INDENT> otype, oid = parent.split(':') <NEW_LINE> oid = long(oid) <NEW_LINE> ft.create...
Create a new table, optionally attach it to an existing object :param session: An OMERO session :param name: The name of the table :param ft_space: The feature table namespace :param ann_space: The feature annotation namespace :param metadesc, coldesc: Create a new table with this list of metadata and feature n...
625941de4e696a04525c978b
def test_some_groups3_nam(some_groups3): <NEW_LINE> <INDENT> ent.assert_each_passwd_by_name(dict( user1=dict(name="user1", uid=1001, shell="/bin/sh1"), user2=dict(name="user2", uid=1002, shell="/bin/sh2"), user3=dict(name="user3", uid=1003, shell="/bin/sh3"), user4=dict(name="user4", uid=1004, shell=config.SESSION_RECO...
Test "some" scope with group list and getpwnam
625941de4f6381625f114d7a
def main(args=None, **kwargs): <NEW_LINE> <INDENT> return run((SKALogger,), args=args, **kwargs)
Main entry point of the module.
625941de5fc7496912cc3cbc
def adjust_mod_follow(business_date, holidays=()): <NEW_LINE> <INDENT> month = business_date.month <NEW_LINE> new = adjust_follow(business_date, holidays) <NEW_LINE> if month != new.month: <NEW_LINE> <INDENT> new = adjust_previous(business_date, holidays) <NEW_LINE> <DEDENT> business_date = new <NEW_LINE> return busine...
adjusts to Business Day Convention "Modified [Following]".
625941de7d847024c06be5fd
def upsample_flow(self, flow_lr, guidance): <NEW_LINE> <INDENT> flow_lr = F.interpolate(flow_lr, scale_factor=2, mode='nearest') <NEW_LINE> flow_hr = self.upsampler(flow_lr, guidance) <NEW_LINE> return flow_hr
Upsample flow field [H/8, W/8, 2] -> [H, W, 2] using nconv upsampler
625941de63b5f9789fde7424
def match_with_gaps(my_word, other_word): <NEW_LINE> <INDENT> my_word = my_word.replace(' ', '') <NEW_LINE> if len(my_word) != len(other_word): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for index in range(len(my_word)-1): <NEW_LINE> <INDENT> if my_word[index] == '_': <NEW_LINE> <INDENT> continue <NEW_LINE> <...
my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol _ , and my_word and other_word are of the same length; Fals...
625941de6aa9bd52df0370e4
def report_reservations( client: bigquery_reservation_v1.ReservationServiceClient, project_id: str, location: str, ) -> None: <NEW_LINE> <INDENT> print("Reservations in project {} in location {}".format(project_id, location)) <NEW_LINE> req = bigquery_reservation_v1.ListReservationsRequest( parent=client.common_locatio...
Prints details and summary information about reservations defined within a given admin project and location.
625941de462c4b4f79d1da0f
def add_variable_attribute(self, variable, key, value, type_='String'): <NEW_LINE> <INDENT> item = OrderedDict({'@name': key, '@type': type_, '@value': value}) <NEW_LINE> variables = self.ncroot['netcdf'].get('variable', []) <NEW_LINE> if isinstance(variables, OrderedDict): <NEW_LINE> <INDENT> variables = [variables] <...
Add variable attribute Parameters ---------- variable : str variable name key : str attribute name value : object attribute value. Must be a serializable Python Object type_ : str, default: 'String' string describing attribute type.
625941de94891a1f4081bde9
@register.function <NEW_LINE> @jinja2.contextfunction <NEW_LINE> def media(context, url, key='MEDIA_URL'): <NEW_LINE> <INDENT> if url.endswith('.js'): <NEW_LINE> <INDENT> build = context['BUILD_ID_JS'] <NEW_LINE> <DEDENT> elif url.endswith('.css'): <NEW_LINE> <INDENT> build = context['BUILD_ID_CSS'] <NEW_LINE> <DEDENT>...
Get a MEDIA_URL link with a cache buster querystring.
625941de287bf620b61d3da0
def set_target_by_name(self, device): <NEW_LINE> <INDENT> if device is None or self.__devices is None or device not in list(self.__devices.values()): <NEW_LINE> <INDENT> self.__error = 'Must get device list first' <NEW_LINE> print("[!] Device not found in device list") <NEW_LINE> return False <NEW_LINE> <DEDENT> self._...
Specify the device name to target example: set_target_device('emulator-5554')
625941defff4ab517eb2f77c
def update_flowspec_global_table(self, flowspec_family, rules, actions=None, is_withdraw=False): <NEW_LINE> <INDENT> from ryu.services.protocols.bgp.core import BgpCoreError <NEW_LINE> from ryu.services.protocols.bgp.api.prefix import ( FLOWSPEC_FAMILY_IPV4, FLOWSPEC_FAMILY_IPV6, FLOWSPEC_FAMILY_L2VPN, ) <NEW_LINE> src...
Update a BGP route in the Global table for Flow Specification. ``flowspec_family`` specifies one of the Flow Specification family name. ``rules`` specifies NLRIs of Flow Specification as a dictionary type value. `` actions`` specifies Traffic Filtering Actions of Flow Specification as a dictionary type value. If `...
625941de7d847024c06be5fe
def top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1): <NEW_LINE> <INDENT> if top_k > 0: <NEW_LINE> <INDENT> top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) <NEW_LINE> indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] <NEW_LINE> logit...
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (batch size, vocabulary size) if top_k > 0: keep only top k tokens with highest probability (top-k filtering). if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleu...
625941debe383301e01b57bf
def compute_products(self, vectors): <NEW_LINE> <INDENT> n_old = self.product_cache.count() <NEW_LINE> n_new = len(vectors) <NEW_LINE> if n_new <= n_old: <NEW_LINE> <INDENT> self.product_cache.reset() <NEW_LINE> compute_vectors = vectors <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> compute_vectors = vectors[n_old:] <N...
Compute Products for a list of guess vectors (X). if ptype == 'rpa': H1 , H2 returns pair (A+B)X, (A-B)X products if ptype == 'tda': returns Ax products.
625941de9c8ee82313fbbab4
def handle(self, *args, **options): <NEW_LINE> <INDENT> for song in Music.objects.all(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = urlopen(song.mp3.url) <NEW_LINE> local_file = NamedTemporaryFile() <NEW_LINE> local_file.write(response.read()) <NEW_LINE> audio = MP3(local_file.name) <NEW_LINE> song.length ...
Description: download all songs (to temporary local files), extract song length (in seconds) and save this info to db. Arguments: *args, **options Return: None Author: Nnoduka Eruchalu
625941de31939e2706e4d1a4
def parse_page(self, response): <NEW_LINE> <INDENT> item = TencentCrawlSpiderItem() <NEW_LINE> item['position_duty'] = response.xpath('//ul[@class="squareli"]')[0].xpath('./li/text()').extract() <NEW_LINE> item['position_requirement'] = response.xpath('//ul[@class="squareli"]')[1].xpath('./li/text()').extract() <NEW_LI...
解析提取到的详情链接 :param response: :return:
625941dee1aae11d1e749ff9
@pytest.mark.xfail <NEW_LINE> def test_consultar_cuits_paises(auth): <NEW_LINE> <INDENT> wsct=auth <NEW_LINE> consulta = wsct.ConsultarCUITsPaises() <NEW_LINE> assert consulta
Test consultar cuit paises.
625941dea17c0f6771cbe38e
def get_start_dir(self,last_dir,start_dir): <NEW_LINE> <INDENT> if start_dir is None: <NEW_LINE> <INDENT> return last_dir <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> last_dir_int = re.sub("[^0-9]", "",str(last_dir)) <NEW_LINE> start_dir_int = re.sub("[^0-9]", "",str(start_dir)) <NEW_LINE> if (last_dir_int < start_dir...
:param last_dir: :param start_dir: :return:
625941de0fa83653e46572f8
def obtenir_longueur_bras(scorpion): <NEW_LINE> <INDENT> return scorpion[1]
Fonction qui renvoie la longueur du bras d'un scorpion en m :param scorpion: liste contenant les paramètres du scorpion :type scorpion: float[10] :return: Longueur du bras :rtype: float
625941de44b2445a339323d3
def get_label(self, text, null_character=u'\u2591'): <NEW_LINE> <INDENT> batch_size = text.shape[0].value <NEW_LINE> lexicon_size = text.shape[1].value <NEW_LINE> text = tf.reshape(text, [-1]) <NEW_LINE> sp_text = tf.string_split(text, delimiter='') <NEW_LINE> sp_text = tf.sparse_reset_shape(sp_text, [batch_size*lexico...
Returns the ids of the corresponding text, Args: text: a tensor with shape [batch_size, lexicon_size] and type string null_character: a unicode character used to replace '<null>' character. the default value is a light shade block '░'.
625941ded7e4931a7ee9e25d
def regenerate_key( self, resource_group_name, account_name, key_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> regenerate_key1 = models.StorageAccountRegenerateKeyParameters(key_name=key_name) <NEW_LINE> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers...
Regenerates one of the access keys for the specified storage account. :param resource_group_name: The name of the resource group within the user's subscription. The name is case insensitive. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Stora...
625941de23849d37ff7b33cc
def abort_merge(): <NEW_LINE> <INDENT> git.read_tree('HEAD', reset=True, u=True, v=True) <NEW_LINE> merge_head = git.git_path('MERGE_HEAD') <NEW_LINE> if core.exists(merge_head): <NEW_LINE> <INDENT> core.unlink(merge_head) <NEW_LINE> <DEDENT> merge_msg_path = merge_message_path() <NEW_LINE> while merge_msg_path: <NEW_L...
Abort a merge by reading the tree at HEAD.
625941de796e427e537b0907
def session_to_s3(prefix, bucket_name, timestamp=True, **kwargs): <NEW_LINE> <INDENT> if timestamp: <NEW_LINE> <INDENT> now_str = str(datetime.now()) <NEW_LINE> date_time_str = re.sub('[^0-9a-zA-Z]+', '_', now_str) <NEW_LINE> filename = prefix + "_" + date_time_str + ".pkl" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
Save session to S3 bucket. Login via ~/.aws/credentials as per boto3.
625941deb57a9660fec33bc7
def testattrval(self, attr, val, node=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__lgh.testattrval(attr, val, node) <NEW_LINE> <DEDENT> except SystemError: <NEW_LINE> <INDENT> raise Genders.__find_exception(self)
Returns 1 if the specified node has the specified attribute and value, 0 if it does not. If the node is not specified, the local node is checked.
625941de5fcc89381b1e1a00
def extract_number(txt): <NEW_LINE> <INDENT> txt = _NUMERIC_ENTITIES.sub(lambda m: unichr(int(m.groups()[0])), txt) <NEW_LINE> numbers = _NUMBER_RE.findall(txt) <NEW_LINE> if len(numbers) == 1: <NEW_LINE> <INDENT> return numbers[0]
Extract a numeric value. This will fail if more than one numeric value is present. >>> extract_number(' 45.3') '45.3' >>> extract_number(' 45.3, 7') It will handle unescaped entities: >>> extract_number(u'&#163;129&#46;99') u'129.99'
625941de5fcc89381b1e19ff
@cli.command() <NEW_LINE> @click.argument('deployment_id') <NEW_LINE> @click.argument('node', required=False) <NEW_LINE> def supportconfig(deployment_id, node): <NEW_LINE> <INDENT> dep = seslib.Deployment.load(deployment_id) <NEW_LINE> _node = 'master' if node is None else node <NEW_LINE> dep.supportconfig(_print_log, ...
Runs supportconfig on a node within an already-deployed cluster. Dumps the resulting tarball in the current working directory. If the node is not specified, it defaults to "master". NOTE: supportconfig is only available in deployments running on SUSE Linux Enterprise.
625941ded6c5a1020814438c
def test_user_registration_invalid_json_keys_no_username(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> response = self.client.post( '/api/v1/auth/register', data=json.dumps(dict( email='test@test.com', password='test' )), content_type='application/json', ) <NEW_LINE> data = json.loads(response.data.d...
Ensure error is thrown if no username is included.
625941de8e05c05ec3eea6b6
def stock_mgt_search_by_type(query_params): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stock_code = query_params.get("stock_code") <NEW_LINE> query_type = query_params.get("query_type") <NEW_LINE> if stock_code is None or stock_code == "": <NEW_LINE> <INDENT> raise APIException(detail="Provide stock code for search")...
Return list of all stockmanagement to current stock :param query_params: query parameters on the url :return: list of all stock management by type
625941de046cf37aa974d084
def send_mail(receiver_address, mail_subject, mail_text, smtphost, sender_address): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = MIMEText(mail_text) <NEW_LINE> msg['Subject'] = mail_subject <NEW_LINE> msg['From'] = sender_address <NEW_LINE> msg['To'] = receiver_address <NEW_LINE> with smtplib.SMTP(smtphost) as sm...
Sends a mail to the user.
625941dedd821e528d63b4e6
def test_validate_all_fields_are_filled(self): <NEW_LINE> <INDENT> form = ContactForm( sender_name="Virginia", sender_email="virginia@gmail.com", sender_message="Some long message" ) <NEW_LINE> self.assertTrue(form.validate())
Tests to check data is not submitted with empty fields
625941de10dbd63aa1bd2ee1
def filter__names(): <NEW_LINE> <INDENT> db = MySQLdb.connect(host="localhost", port=3306, user=argv[1], passwd=argv[2], db=argv[3], charset="utf8" ) <NEW_LINE> cur = db.cursor() <NEW_LINE> cur.execute("SELECT * FROM states WHERE name LIKE BINARY 'N%' ORDER BY id") <NEW_LINE> query_rows = cur.fetchall() <NEW_LINE> for ...
Takes arguments argv to list from database Only lists with states that start with N argv[1]: mysql username argv[2]: mysql password argv[3]: database name
625941de99cbb53fe6792f25
def load_datarun_method_config(datarun_id, method=None): <NEW_LINE> <INDENT> with datarun_config(datarun_id): <NEW_LINE> <INDENT> config_path = get_datarun_config_path(datarun_id, method) <NEW_LINE> if method is not None: <NEW_LINE> <INDENT> with open(config_path) as f: <NEW_LINE> <INDENT> return json.load(f) <NEW_LINE...
Load the method configs (e.g., adaboost.json) of a datarun. If method is None, a dict of {method: config} will be returned :param datarun_id: :param method: method string (the keys of atm.constants.METHODS_MAP) :return:
625941de7d43ff24873a2fe1
def test_create_dir(tdir, label, simulation=False): <NEW_LINE> <INDENT> if os.path.isdir(tdir): <NEW_LINE> <INDENT> if not os.access(tdir, os.W_OK): <NEW_LINE> <INDENT> msg = "Cannot write to pipeline {l} directory '{d}'".format(l=label, d=tdir) <NEW_LINE> log.critical(msg) <NEW_LINE> raise ONEFluxPipelineError(msg) <N...
Tests if directory exists, if not creates it. If yes, tests if readable/writable. Returns True if directory created, False if already exists :param tdir: path to directory to be tested/created :type tdir: str :param label: label for type of directory being tested/created :type label: str :rtype: bool
625941dee8904600ed9f2270
def find_ijk(x, f, ws, wave_dist=0.045): <NEW_LINE> <INDENT> n = len(ws) <NEW_LINE> waves = sgnl.find_peaks(np.abs(x), distance=int(wave_dist*f))[0] <NEW_LINE> if len(waves) < n: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> maxi = np.argmax(np.correlate(x[waves], ws, mode="valid")) <NEW_LINE> return np.asarray(w...
Find IJK indices in small window around peaks in coarse signal Args: x (`1d array-like`): BCG signal f (float): in Hz; sampling rate of BCG signal ws (`tuple(float)`): weights for waves wave_dist (float): in seconds; minimum distance between peaks Returns: `1d array`: locations of one peak tuple
625941de3eb6a72ae02ec824
def isPalindrome(self, head): <NEW_LINE> <INDENT> if not head or not head.next: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> fast = slow = head <NEW_LINE> while fast and fast.next: <NEW_LINE> <INDENT> fast = fast.next.next <NEW_LINE> slow = slow.next <NEW_LINE> <DEDENT> stack = [slow.val] <NEW_LINE> while slow.n...
:type head: ListNode :rtype: bool
625941de66656f66f7cbc4ec
def test_empty(self): <NEW_LINE> <INDENT> self.assertRaises( chrono.error.NoDateTimeError, chrono.Date().get_datetime )
Date.get_datetime() raises NoDateTimeError on empty date
625941de236d856c2ad44b1d
def update(self,**karg): <NEW_LINE> <INDENT> if len(karg)>0: <NEW_LINE> <INDENT> self.CGF.virgin=True <NEW_LINE> for subsystem in self.subsystems.values(): <NEW_LINE> <INDENT> subsystem.update(**karg) <NEW_LINE> <DEDENT> super(ED.ED,self).update(**karg) <NEW_LINE> data=self.data <NEW_LINE> self.pthgenerator.update(**da...
Update the engine.
625941de3617ad0b5ed68235
def apply_parameters(self): <NEW_LINE> <INDENT> key = self.myname() <NEW_LINE> if key not in self._params: <NEW_LINE> <INDENT> self._params[key] = {} <NEW_LINE> <DEDENT> basevalue = str <NEW_LINE> act = 'store' <NEW_LINE> loc = ['headers', 'values'] <NEW_LINE> trim = True <NEW_LINE> self._params[key][PERPAGE_KEY] = (in...
Use parameters received via decoration
625941decb5e8a47e48b7de5
@log_call(namespace=__xmlrpc_namespace__) <NEW_LINE> @user_passes_test(lambda u: u.has_perm('testcases.change_testcase')) <NEW_LINE> def notification_add_cc(request, case_ids, cc_list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_cc_list(cc_list) <NEW_LINE> <DEDENT> except (TypeError, ValidationError): <NEW_L...
Description: Add email addresses to the notification CC list of specific TestCases Params: $case_ids - Integer/Array: one or more TestCase IDs $cc_list - Array: one or more Email addresses, which will be added to each TestCase indicated by the case_ids. Returns: JSON. Wh...
625941ded268445f265b51ae
def store_diff(self): <NEW_LINE> <INDENT> for config in self: <NEW_LINE> <INDENT> try: config.store_diff() <NEW_LINE> except AttributeError: pass
Finds the differences and saves them Assumptions: N/A Source: N/A Inputs: N/A Outputs: N/A Properties Used: N/A
625941deb545ff76a8914155
def run_pylint(repository): <NEW_LINE> <INDENT> with log.indent(): <NEW_LINE> <INDENT> log.info("Running Pylint for the repository " + repository) <NEW_LINE> script = path_to_qa_file(repository, "run-linter.sh") <NEW_LINE> command = ("pushd repositories/{repo} >> /dev/null;" + "{script} > ../../{repo}.linter.txt;" + "p...
Run Pylint checker against the selected repository.
625941de004d5f362079a671
def evaluate_moves(self, board, legal_moves, players): <NEW_LINE> <INDENT> matrix = self.export_matrix_for_cnn(board) <NEW_LINE> tensor = self.dqn.game_matrix_to_tensor(matrix) <NEW_LINE> inference = self.dqn.forward(tensor) <NEW_LINE> inference = inference.detach().numpy() <NEW_LINE> index = np.argmax(inference) <NEW_...
Calculates and selects the optimal move. Args: board: A nested array of Blocks. legal_moves: A list of legal moves. players: A list of players. Returns: i: An integer representing the x position of the chosen move. j: An integer representing the y position of the chosen move.
625941dede87d2750b8600d5
def test_multi_coverage_diff_region(self): <NEW_LINE> <INDENT> self._mock_function(['france'], ['peru']) <NEW_LINE> with pytest.raises(RegionNotFound): <NEW_LINE> <INDENT> compute_regions(self.args)
orig and dest are in different region
625941de8da39b475bd652b6
def SetFocalDistance(self, *args): <NEW_LINE> <INDENT> return _ITKRigidPerspectiveTransformPython.itkRigid3DPerspectiveTransformD_SetFocalDistance(self, *args)
SetFocalDistance(self, double focalDistance)
625941de2eb69b55b151cbf2
def next_state(self): <NEW_LINE> <INDENT> s = self.states[-1] <NEW_LINE> self.states.remove(s) <NEW_LINE> return s
overrides next_move method inherited from Searcher.
625941deaad79263cf390d85
def generate_ab_sequence(number_min=1, number_max=100): <NEW_LINE> <INDENT> sequence = '' <NEW_LINE> for number in range(number_min, number_max + 1): <NEW_LINE> <INDENT> letters = "" <NEW_LINE> if number % 2 == 0: <NEW_LINE> <INDENT> letters = "a" <NEW_LINE> <DEDENT> if number % 3 == 0: <NEW_LINE> <INDENT> letters += "...
Function for generate ab sequence. :param number_min: number for start sequence. number_max: number for finish sequence.
625941de3617ad0b5ed68236
def _get_rss_fetcher(self): <NEW_LINE> <INDENT> headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'} <NEW_LINE> def fetch_rss(pl): <NEW_LINE> <INDENT> self.event_listener.inform('feed is fetching', pl.title, capture='RSS') <NEW_LINE> try: <NEW_LINE> <INDENT> req = urllib.request.Request(pl.url, headers...
make and return a function to get RSS
625941de01c39578d7e7517b
def wheel(self, pos): <NEW_LINE> <INDENT> if pos < 85: <NEW_LINE> <INDENT> return Color(pos * 3, 255 - pos * 3, 0) <NEW_LINE> <DEDENT> elif pos < 170: <NEW_LINE> <INDENT> pos -= 85 <NEW_LINE> return Color(255 - pos * 3, 0, pos * 3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pos -= 170 <NEW_LINE> return Color(0, pos ...
Generate rainbow colors across 0-255 positions.
625941de67a9b606de4a81f7
def __set_temperature(self, args: list) -> bool: <NEW_LINE> <INDENT> if not (0 < len(args) <= 3): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for parameter, value in [(arg[0], arg[1:]) for arg in args]: <NEW_LINE> <INDENT> if parameter not in ['B', 'F', 'I', 'S', 'T']: <NEW_LINE> <INDENT> raise MCODEUnkownPara...
Set the temperature See documentation of the MCODE
625941de4f6381625f114d7b
def preprocess_image(img, do_crop_car_hood=True): <NEW_LINE> <INDENT> if do_crop_car_hood: <NEW_LINE> <INDENT> img = crop_car_hood(img) <NEW_LINE> <DEDENT> img = img[50:,:,:] <NEW_LINE> img = img / 255 <NEW_LINE> img -= np.mean(img) <NEW_LINE> img = cv2.resize(img, NETWORK_IMAGE_SIZE , cv2.INTER_CUBIC) <NEW_LINE> retur...
Preprocess the image to prepare it for the network We are removing the top to remove the sky We are removing the bottom to remove the car hood if requested We are normalizing the image We are resizing the image for the network input
625941de8c3a8732951586fd
def extract(self): <NEW_LINE> <INDENT> if os.path.isdir(self._input): <NEW_LINE> <INDENT> for path, _, files in os.walk(self._input): <NEW_LINE> <INDENT> for item in files: <NEW_LINE> <INDENT> self._list.append(os.path.join(path, item)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif os.path.isfile(self._input): <NEW_LINE> ...
Perform extraction of firmware updates from input to tarballs in output directory using a thread pool.
625941de6fb2d068a760f3e1
def _loadCrystalSpecsGroupBox(self, inPmGroupBox): <NEW_LINE> <INDENT> latticeChoices = ["Diamond", "Lonsdaleite"] <NEW_LINE> self.latticeCBox = PM_ComboBox( inPmGroupBox, label = 'Lattice:', labelColumn = 0, choices = latticeChoices, index = 0, setAsDefault = True, spanWidth = False )...
Load widgets in the Crystal Specifications group box. @param inPmGroupBox: The Crystal Specifications groupbox in the PM @type inPmGroupBox: L{PM_GroupBox}
625941decc0a2c11143dd1d1
def testFootprints(self): <NEW_LINE> <INDENT> level = 0x2 <NEW_LINE> ds = afwDetect.FootprintSet(self.mim.getMask(), afwDetect.createThreshold(level, "bitmask")) <NEW_LINE> objects = ds.getFootprints() <NEW_LINE> if 0 and display: <NEW_LINE> <INDENT> afwDisplay.Display(frame=0).mtv(self.mim, title=self._testMethodName ...
Check that we found the correct number of objects using FootprintSet
625941de50812a4eaa59c65e