code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get(self): <NEW_LINE> <INDENT> logs = MonLog.gql('WHERE time < :time', time=int(round(time.time()-30*24*60*60))) <NEW_LINE> for log in logs: <NEW_LINE> <INDENT> log.delete() <NEW_LINE> <DEDENT> self.write('ok')
docstring for get
625941e163f4b57ef00014bc
def compress_string_concatenation(string): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> compressed_string = "" <NEW_LINE> for i in range(len(string)): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> if i + 1 >= len(string) or string[i] != string[i + 1]: <NEW_LINE> <INDENT> compressed_string += string[i] + str(count) <NEW_LINE> c...
It creates a new string and traverse through original string, concatenate the characters and its count to new string. String concatenation is very expensive, as strings are immutable. Time Complexity: O(n^2) Space Complexity: O(n)
625941e196565a6dacc8fa78
def __init__(self, weights, bias): <NEW_LINE> <INDENT> self.weights = weights <NEW_LINE> self.bias = bias
weights is an np.array
625941e14e696a04525c97fb
def at_object_creation(self): <NEW_LINE> <INDENT> self.db.weight = 0 <NEW_LINE> self.db.cost = 0 <NEW_LINE> self.db.size = 0 <NEW_LINE> self.db.noise_modifier = 0 <NEW_LINE> self.db.breakable = 0 <NEW_LINE> self.db.hidden_in_room = 0 <NEW_LINE> self.locks.add("equip:false()")
Called only at initial creation.
625941e1d4950a0f3b08c6f8
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return Gtcmodify( gtcOrderNo = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return Gtcmodify( )
Test Gtcmodify include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941e15510c4643540f789
def observe(self, observation, gameState): <NEW_LINE> <INDENT> noisyDistance = observation <NEW_LINE> emissionModel = busters.getObservationDistribution(noisyDistance) <NEW_LINE> pacmanPosition = gameState.getPacmanPosition() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> allPossible = util.Counter() <NEW_LINE> noisyal...
Updates beliefs based on the distance observation and Pacman's position. The noisyDistance is the estimated manhattan distance to the ghost you are tracking. The emissionModel below stores the probability of the noisyDistance for any true distance you supply. That is, it stores P(noisyDistance | TrueDistance). self...
625941e1adb09d7d5db6cb3b
def convert_to_ds_id(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return derive_ds_id(self.dset) <NEW_LINE> <DEDENT> except InvalidProject: <NEW_LINE> <INDENT> raise Exception( f"The format of {self.dset} is not known and it could not be converted to a ds id." )
Converts the input dataset to a drs id form to use with the elasticsearch index.
625941e1090684286d50f098
@error_handler <NEW_LINE> @authorisation <NEW_LINE> @method_allow(['GET']) <NEW_LINE> @rest_json(JSON_OPTS) <NEW_LINE> def root_view(method, input_, user, **kwargs): <NEW_LINE> <INDENT> user_id = user.identifier <NEW_LINE> groups = [obj.identifier for obj in user.groups.all()] <NEW_LINE> sources = [ OrderedDict(( ("ide...
DAMATS user profile view.
625941e15fc7496912cc3d2c
def execute(width, height, data): <NEW_LINE> <INDENT> channels = len(data) // (width * height) <NEW_LINE> if channels in (3, 4): <NEW_LINE> <INDENT> return swap_channels(width, height, data, 0, 2) <NEW_LINE> <DEDENT> return width, height, data
Swaps the red and blue channels in an image. :Parameters: width : int The width of the image being converted height : int The height of the image being converted data : string A string containing the data for the image :rtype: tuple :returns: a tuple containing a width, height, and...
625941e1236d856c2ad44b8d
def getInspectorActionById(self, identifier): <NEW_LINE> <INDENT> for action in self.inspectorActionGroup.actions(): <NEW_LINE> <INDENT> if action.data() == identifier: <NEW_LINE> <INDENT> return action <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("No action found with ID: {!r}".format(identifier))
Sets the inspector and draw the contents Triggers the corresponding action so that it is checked in the menus.
625941e176d4e153a657eee0
def set_bold(self, bold=1): <NEW_LINE> <INDENT> self.bold = bold
Set the Format bold property. Args: bold: Default is 1, turns property on. Returns: Nothing.
625941e1d10714528d600095
def add_constraint(self, iatom, jatom, distance=True): <NEW_LINE> <INDENT> if (iatom, jatom) in self._constrained_atom_pairs: <NEW_LINE> <INDENT> existing_distance = self._constrained_atom_pairs[(iatom, jatom)] <NEW_LINE> if unit.is_quantity(existing_distance) and (distance is True): <NEW_LINE> <INDENT> raise Exception...
Mark a pair of atoms as constrained. Constraints between atoms that are not bonded (e.g., rigid waters) are permissible. Parameters ---------- iatom, jatom : Atom Atoms to mark as constrained These atoms may be bonded or not in the Topology distance : openmm.unit.Quantity, optional, default=True Constrain...
625941e1c4546d3d9de72de5
@BP.route("/edit", methods=("GET", "POST")) <NEW_LINE> def edit(): <NEW_LINE> <INDENT> return render_template("items/edit.html")
Edit an item by id
625941e115baa723493c4326
def __call__(self, input_img, target_img): <NEW_LINE> <INDENT> if self.padding is not None: <NEW_LINE> <INDENT> input_img = F.pad(input_img, self.padding, self.fill, self.padding_mode) <NEW_LINE> target_img = F.pad(target_img, self.padding, 0, self.padding_mode) <NEW_LINE> <DEDENT> if self.pad_if_needed and img.size[0]...
assuming the input_img and target_img has same size at this moment, I'm lazy to think if crop size has different value in w, h so consideringing as same size
625941e132920d7e50b28581
def setAnno(self,panno): <NEW_LINE> <INDENT> self.anno=panno
Función: Asigna el año Entrada: Año (int) Salida: Asigna el año como atributo del libro
625941e1d7e4931a7ee9e2cd
def load_tests(loader, tests, pattern): <NEW_LINE> <INDENT> return get_suit()
Enables (graphical) unit testing in PyDev.
625941e150485f2cf553d149
def __init__(self, name, human, variables): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.conditions = [] <NEW_LINE> self.n_conditions = 0 <NEW_LINE> self.human = human <NEW_LINE> self.variables = variables
:param name: (string) Name of the experiment :param human: (Human) Human class which :param variables: (dict) a dictionary that has as keys variable names and as values Variable objects. the same variables are shared across conditions just with different values. The val...
625941e13346ee7daa2b311c
def visualize_attention(image: torch.Tensor, word_seq: List[str], attention_scores: np.ndarray, max_length: int, file_name: str) -> None: <NEW_LINE> <INDENT> image = normalize_inverse(image).cpu().detach().numpy() <NEW_LINE> image = (image.transpose((1, 2, 0)) * 225).astype(np.uint8) <NEW_LINE> height = int(np.ceil((ma...
Generate one image out of all predicted word with their respective attention as an overlay. :param image: original image used for the prediction :param word_seq: predicted word sequence :param attention_scores: attention scores for eachpredictionn :param max_length: max_length of predicted words (this is to keep all i...
625941e196565a6dacc8fa79
def llikelihood(self, f1, f2): <NEW_LINE> <INDENT> llik = normlpdf(f1, f2, self.param["llik_sigma"]) <NEW_LINE> return llik
Inputs latent state, returns log prior probability.
625941e1bd1bec0571d909dd
def _segments(self) -> Tuple[np.ndarray, int]: <NEW_LINE> <INDENT> return self.trial_anchors - self._pre, self.trial_samples
returns timepoints and lengths in samples
625941e123e79379d52ee90d
def is_notstr_iterable(obj): <NEW_LINE> <INDENT> return not isinstance(obj, str) and isinstance(obj, abc.Iterable)
Checks if obj is iterable, but not a string
625941e1a219f33f34628d13
def is_office_hour_reserver(user): <NEW_LINE> <INDENT> reserver_roles = [UserRole.FINALIST, UserRole.AIR, UserRole.ALUM] <NEW_LINE> return user.programrolegrant_set.filter( program_role__user_role__name__in=reserver_roles, program_role__program__program_status=ACTIVE_PROGRAM_STATUS).exists()
Returns True iff user has an office-hour reserver user role with respect to an active program Office-hour reserver roles are FINALIST, AIR, ALUM
625941e129b78933be1e5a56
def load_dataset(dataset_id, partition, features): <NEW_LINE> <INDENT> cond1 = dataset_files["Dataset"] == dataset_id <NEW_LINE> cond2 = dataset_files["Partition"] == partition <NEW_LINE> cond3 = dataset_files["Features"] == features <NEW_LINE> df_row = dataset_files[cond1 & cond2 & cond3] <NEW_LINE> if df_row.empty: <...
Load dataset from any collection of csv files Parameters ---------- dataset_id: string Dataset ID partition: Partition can be "Train" or "Test" features: Feature type can be "CellProfiler" or "DeepLearning" Returns ------- dataframe All read selected features from the bucket with given ID and partitio...
625941e13d592f4c4ed1d412
def quad_loss(x: jnp.ndarray, u: jnp.ndarray) -> Real: <NEW_LINE> <INDENT> return jnp.sum(x.T @ x + u.T @ u)
Quadratic loss. Args: x (jnp.ndarray): u (jnp.ndarray): Returns: Real
625941e1498bea3a759b9e5d
def entrypoint(self, func): <NEW_LINE> <INDENT> assert func.__module__.startswith(self.prefix), ( '%r entrypoints must be below "%s"' % (self, self.prefix)) <NEW_LINE> assert getattr(func, _ENTRYPOINT_ATTR, None) is None, ( '%r is already associated with another PrivContext' % func) <NEW_LINE> f = functools.partial(sel...
This is intended to be used as a decorator.
625941e18e71fb1e9831db56
def main(all_files=None): <NEW_LINE> <INDENT> default_config = read_config(get_default_config()) <NEW_LINE> make_rc(default_config, PRODUCTION_RC, additions=_PRODUCTION_RC_ADDITIONS, replacements=_PRODUCTION_RC_REPLACEMENTS) <NEW_LINE> make_rc(default_config, TEST_RC, additions=_TEST_RC_ADDITIONS, replacements=_TEST_RC...
Script entry point. Lints both sets of files. Args: all_files (Optional[list]): A list of all files to consider.
625941e1d164cc61757830fd
def copy(self): <NEW_LINE> <INDENT> return copy.deepcopy(self)
Returns a copy of a design. This makes a deep copy to ensure designs are trully independent. Parameters ---------- Returns ------- design copied design
625941e18e7ae83300e4b37c
def getM2(m): <NEW_LINE> <INDENT> M = np.zeros((lmax+1, lmax+1)) <NEW_LINE> for l in range(abs(m)+2, lmax+1): <NEW_LINE> <INDENT> M[l, l-2] = alpha(l, m)*alpha(l-1, m)/alpha(2, 0) <NEW_LINE> <DEDENT> for l in range(abs(m), lmax+1): <NEW_LINE> <INDENT> M[l, l] = (alpha(l+1, m)**2 - alpha(1, 0)*Y00 +alpha(l, m)**2)/alpha...
Calculate the matrix \ind Y_{l_1,m}(u) Y_{2,0}(u) Y(l_2,m) du This matrix is referred to as J in the paper. The rows and colums correspond to l_1,l_2. Args: m (int): z-component eignvalue
625941e199fddb7c1c9de73e
def alias_tensors(*args): <NEW_LINE> <INDENT> def alias_if_tensor(a): <NEW_LINE> <INDENT> return array_ops.identity(a) if isinstance(a, ops.Tensor) else a <NEW_LINE> <DEDENT> if len(args) > 1: <NEW_LINE> <INDENT> return (alias_if_tensor(a) for a in args) <NEW_LINE> <DEDENT> elif len(args) == 1: <NEW_LINE> <INDENT> retu...
Wrap any Tensor arguments with an identity op. Any other argument, including Variables, is returned unchanged. Args: *args: Any arguments. Must contain at least one element. Returns: Same as *args, with Tensor instances replaced as described. Raises: ValueError: If args doesn't meet the requirements.
625941e15fc7496912cc3d2d
def status_fault(a_message, a_fault): <NEW_LINE> <INDENT> print(a_message +" [ fail ]") <NEW_LINE> print("A fault occurred") <NEW_LINE> print("Fault code: {0}".format(a_fault.faultCode)) <NEW_LINE> print("Fault string: {0}".format(a_fault.faultString)) <NEW_LINE> exit(-1)
Handle errors from xml-rpc calls.
625941e1d18da76e23532889
def show_ipsecpolicy(self, ipsecpolicy): <NEW_LINE> <INDENT> return self._fetch_ipsecpolicy(ipsecpolicy)
Fetches information of a specific IPsecPolicy
625941e166673b3332b92440
def read(self): <NEW_LINE> <INDENT> measurement = c_double(0) <NEW_LINE> status = self.nilcicapi.niVB_DMM_Read(self.instrument_handle, byref(measurement)) <NEW_LINE> if (status != Status.SUCCESS): <NEW_LINE> <INDENT> raise PyVirtualBenchException(status, self.nilcicapi, self.library_handle) <NEW_LINE> <DEDENT> return m...
Reads the data from the instrument.
625941e173bcbd0ca4b2c424
def test_heartbeat_404(self): <NEW_LINE> <INDENT> DUMMYNODEID = "90f7c2c0-cfa9-11e7-9b9d-2fe338e1e7ce" <NEW_LINE> a = Aggregator(mdns_updater=mock.MagicMock()) <NEW_LINE> a._node_data["registered"] = True <NEW_LINE> a._node_data["node"] = {"type": "node", "data": {"id": DUMMYNODEID}} <NEW_LINE> a.aggregator = "http://e...
Test heartbeat operation when heartbeat request returns HTTP 404 After HTTP 404, Node should mark itself as not registered and attempt re-registration
625941e11b99ca400220ae61
@route('/rclocal/:address') <NEW_LINE> def rclocal(address): <NEW_LINE> <INDENT> pxe_vars = settings.pxe_variables(cfg, address) <NEW_LINE> file_name = os.path.join(cfg['paths']['templates'], cfg['templates']['rc_local']) <NEW_LINE> result = utils.file_read(file_name) <NEW_LINE> result = utils.apply_template(result, px...
return the rc.local file
625941e1a934411ee3751a43
def _get_ike_profile(self): <NEW_LINE> <INDENT> self._log.info('get_ike_profile') <NEW_LINE> lines = _get_section_config(self, self.name) <NEW_LINE> line = [ line for line in lines.splitlines() if line.lstrip().startswith('tunnel protection ipsec profile') ] <NEW_LINE> line = line[0] <NEW_LINE> if line and len(line.spl...
get the ike profile name from tunnel
625941e132920d7e50b28582
def __init__(self, id=None, logo_file=None, logo_url=None, favicon_file=None, favicon_url=None, default_title=None, show_help_menu=None, show_docs=None, show_email_sub_options=None, allow_looker_mentions=None, allow_looker_links=None, can=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._logo_file = None <NEW...
WhitelabelConfiguration - a model defined in Swagger
625941e1b830903b967e9cb6
def open_tvshow_list(self, prev_window=None, listitems=None, filters=[], mode="filter", list_id=False, filter_label="", force=True, media_type="tv"): <NEW_LINE> <INDENT> from dialogs import DialogVideoList <NEW_LINE> if prev_window: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> color = prev_window.data["general"]['Image...
open video list, deal with window stack and color
625941e176e4537e8c351a24
@app.task <NEW_LINE> def morphy(doc): <NEW_LINE> <INDENT> nltk_download('wordnet') <NEW_LINE> tokens = pipe(doc, fetch, _tokenize_if_needed) <NEW_LINE> return map(nltk.WordNetLemmatizer().lemmatize, tokens)
Lemmatize tokens using morphy, WordNet's lemmatizer. Finds the morphological root of all words in ``doc``, which is assumed to be written in English. Returns ------- lemmas : list List of lemmas. See also -------- stem_snowball: simpler approach to lemmatization (stemming).
625941e110dbd63aa1bd2f51
def validate_virtual_network_rules(ns): <NEW_LINE> <INDENT> from azure.mgmt.cosmosdb.models import VirtualNetworkRule <NEW_LINE> if ns.virtual_network_rules is not None: <NEW_LINE> <INDENT> virtual_network_rules_list = [] <NEW_LINE> for item in ns.virtual_network_rules: <NEW_LINE> <INDENT> virtual_network_rules_list.ap...
Extracts multiple space-separated virtual network rules
625941e1596a897236089e6b
def test_admin_urls_are_configured(): <NEW_LINE> <INDENT> assert reverse("admin:index") == "/admin/", "admin urls are not configured"
Test that the admin urls exist.
625941e1e5267d203edce047
def __init__(self, function): <NEW_LINE> <INDENT> message = '{0} requires a AI'.format(function) <NEW_LINE> super(ValidAIRequired, self).__init__(message)
Construct a ValidAIRequired exception. :param function: The function that requires a valid AI.
625941e1fff4ab517eb2f7ed
def get_firewall_rules(self): <NEW_LINE> <INDENT> return self.cloud_manager.get_firewall_rules(self)
Return all FirewallRule instances that are associated with this server instance.
625941e121a7993f00bc80a5
@auth.s3_requires_membership(1) <NEW_LINE> def consent_option(): <NEW_LINE> <INDENT> def prep(r): <NEW_LINE> <INDENT> resource = r.resource <NEW_LINE> table = resource.table <NEW_LINE> editable = False <NEW_LINE> if not r.record: <NEW_LINE> <INDENT> editable = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctable =...
Consent Options: RESTful CRUD Controller
625941e1cc40096d61595cfe
def simple_version(self): <NEW_LINE> <INDENT> return 'ver %d, %d (Origin: ver %d, %d)' % ( self.revision, self.pub_year, self.revision_origin, self.pub_year_origin, )
return a simple version
625941e14f6381625f114dea
def add_param(params: dict, name: str, value: str): <NEW_LINE> <INDENT> if name == 'type': <NEW_LINE> <INDENT> params[name] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params[name] = int(value)
Add (name, value) params to dict. Value is converted to int value if needed
625941e115baa723493c4327
def hazard_plot(parameters, limit, density=1000, xbar_max=1, gain_boost=None): <NEW_LINE> <INDENT> radius_meters, freq_mhz, power_watts, efficiency, side_lobe_ratio, H, ffmin, ffpwrden, k = parameters <NEW_LINE> n = density <NEW_LINE> delta = np.linspace(1.0, 0.01, n) <NEW_LINE> xbarArray = np.ones(n) <NEW_LINE> Ep = n...
Hazard plot for parabolic dish. Receives user input parameters and hazard limit for parabolic dish. Computes and returns hazard distance plot. :param parameters: parameters tuple created with parameters function :param limit: power density limit :param density: (optional) number of points for plot, if none density=10...
625941e14a966d76dd5513c1
def __init__(self, cons: List[Consequent], impl_func: Tuple[Callable, str]): <NEW_LINE> <INDENT> super(DefaultFuzzyRule, self).__init__( ants=[], ant_act_func=None, cons=cons, impl_func=impl_func )
Define a default rule for a fuzzy system. It behaves the same as FuzzyRule but it does not require to define antecedents nor an activation function :param cons: see FuzzyRule's docstring :param impl_func: see FuzzyRule's docstring
625941e1fbf16365ca6f6579
def __decoder_worker(self): <NEW_LINE> <INDENT> self.log_handler.log_info('Worker thread started.') <NEW_LINE> while self.is_running: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> decoder = self.sub_processes['decoder'] <NEW_LINE> if decoder is None or decoder.stdout is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DED...
A worker thread handling output from the decoder sub-process.
625941e167a9b606de4a8266
def set_profile(self, name): <NEW_LINE> <INDENT> self.profile = name
Set the current profile.
625941e1287bf620b61d3e10
def dft_recursive(self, starting_vertex, visited=None): <NEW_LINE> <INDENT> if visited is None: <NEW_LINE> <INDENT> visited = set() <NEW_LINE> <DEDENT> print(starting_vertex) <NEW_LINE> visited.add(starting_vertex) <NEW_LINE> for edge in self.vertices[starting_vertex]: <NEW_LINE> <INDENT> if edge not in visited: <NEW_L...
depth-first traversal with recusion Print each vertex in depth-first order beginning from starting_vertex.
625941e1d10714528d600096
def getToken(self, tokenName): <NEW_LINE> <INDENT> return self.tokenDict.get(tokenName.lower(), None)
Returns the value of the indicated web token as a string, if it was set, or None if it was not.
625941e14428ac0f6e5baba4
def load(self, filePrefix): <NEW_LINE> <INDENT> self.nodes = list() <NEW_LINE> self.edges = list() <NEW_LINE> self.landmarks = list() <NEW_LINE> with open(filePrefix + "nodes.dat", "r") as f: <NEW_LINE> <INDENT> reader = csv.reader(f, delimiter=',') <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> if len(row) != 4: <N...
Load the nodes, edges, and landmarks from three separate files, given a file prefix. Parameters: filePrefix -- The prefix to append to the three input files.
625941e1f7d966606f6aa3b8
def detectCycle(self, head): <NEW_LINE> <INDENT> visited = set() <NEW_LINE> while head: <NEW_LINE> <INDENT> if head in visited: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> visited.append(head) <NEW_LINE> head = head.next <NEW_LINE> <DEDENT> <DEDENT> return None
:type head: ListNode :rtype: ListNode
625941e155399d3f05588a65
def get_project_condition(self, project_key, id_condition): <NEW_LINE> <INDENT> url = self._url_project_condition(project_key, id_condition) <NEW_LINE> return self.get(url) or {}
Request type: GET Return a specific condition with reviewers list that has been configured for this project. For further information visit: https://docs.atlassian.com/bitbucket-server/rest/5.16.0/bitbucket-default-reviewers-rest.html#idm52264901504 :projectKey: str - project key involved :idCondition: int - conditi...
625941e163d6d428bbe4489f
def search_by_extension(directory: Path, ext: str) -> Path: <NEW_LINE> <INDENT> ext = ext.lower() <NEW_LINE> names = [name for name in listdir(directory) if name.lower().endswith(ext)] <NEW_LINE> if not names: <NEW_LINE> <INDENT> raise FileNotFoundError("No `%s` file found in that directory (%s) ! " % (ext, directory))...
Search for a file with extension `ext` in given directory. Search is NOT case sensible. If no or more than one file is found, an error is raised.
625941e13617ad0b5ed682a5
def runYadePython(self, iterNO=-1): <NEW_LINE> <INDENT> paramsList = [] <NEW_LINE> for i in range(self.numSamples): <NEW_LINE> <INDENT> paramsForEach = {} <NEW_LINE> for j, name in enumerate(self.paramNames): <NEW_LINE> <INDENT> paramsForEach[name] = self.smcSamples[iterNO][i][j] <NEW_LINE> <DEDENT> paramsForEach['key'...
Run Yade interactive within GrainLearning using a thread pool
625941e18a349b6b435e8522
def items(self): <NEW_LINE> <INDENT> return [(key, self[key]) for key in self.keys()]
Return a copy of the StackedDict's list of (key, value) pairs. >>> s = StackedDict(a=1, b=2) >>> i = s.items() >>> i.sort() >>> i [('a', 1), ('b', 2)] >>> s.commit().update(c=3) >>> i = s.items() >>> i.sort() >>> i [('a', 1), ('b', 2), ('c', 3)]
625941e1851cf427c661a8bb
@then("we can return a Recordset") <NEW_LINE> def recordset_method(context): <NEW_LINE> <INDENT> sql = "SELECT id, testfield FROM {}".format(TEST_TABLE_NAME) <NEW_LINE> rst = context.manager.recordset(con_name="my-sqlite-database", sql=sql) <NEW_LINE> correct_data = [(1, "foo"), (2, "1")] <NEW_LINE> correct_dicts = [ {...
Test the various Recordset methods
625941e16aa9bd52df037155
def set_low_vel(self, arg0, arg1): <NEW_LINE> <INDENT> return self.sampler.execute(self.set_low_vel_cmd, (arg0, arg1, ))
Set Zone Low Velocity
625941e14527f215b584c802
def reverse(self, x): <NEW_LINE> <INDENT> bar=2**31 <NEW_LINE> def reverse_sub(x): <NEW_LINE> <INDENT> strs=str(x) <NEW_LINE> tempstr="" <NEW_LINE> for i in range(len(strs))[::-1]: <NEW_LINE> <INDENT> for j in range(len(strs))[::-1]: <NEW_LINE> <INDENT> if(strs[j]=='0'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT>...
:type x: int :rtype: int
625941e18da39b475bd65327
def iob2(tags): <NEW_LINE> <INDENT> for i, tag in enumerate(tags): <NEW_LINE> <INDENT> if tag.value == "O": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> split = tag.value.split("-") <NEW_LINE> if len(split) != 2 or split[0] not in ["I", "B"]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if split[0] == "B": ...
Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2.
625941e131939e2706e4d214
def compute_rtype_size(typ: RType) -> int: <NEW_LINE> <INDENT> if isinstance(typ, RPrimitive): <NEW_LINE> <INDENT> return typ.size <NEW_LINE> <DEDENT> elif isinstance(typ, RTuple): <NEW_LINE> <INDENT> return compute_aligned_offsets_and_size(list(typ.types))[1] <NEW_LINE> <DEDENT> elif isinstance(typ, RUnion): <NEW_LINE...
Compute unaligned size of rtype
625941e1f8510a7c17cf9aae
def stop(): <NEW_LINE> <INDENT> with cd(remote_app_dir): <NEW_LINE> <INDENT> with virtualenv(): <NEW_LINE> <INDENT> sudo('./csmserver stop', pty=False)
Stop CSM Server
625941e1be8e80087fb20fec
@rule("sheva", "sheva-merahef") <NEW_LINE> def sheva_merahef(last_vowel, guess, next_token): <NEW_LINE> <INDENT> if ( guess.has(vowel=T.NAME_SHEVA, dagesh=False) and NIQQUD_TYPES.get(last_vowel) in [NIQQUD_SHORT, NIQQUD_HATAF] and next_token.has(letter=T_BEGEDKEFET, dagesh=False) and next_token.vowel != T.POINT_SHEVA )...
`sheva` without `dagesh` between short vowel and BGDKFT without `dagesh` is `sheva-merahef` Source: [Wikipedia-Sheva] Shva Meraḥef > `sheva-merahef` is the grammatical designation of a `sheva` which does not comply > with all criteria characterizing a `sheva-na` (specifically, one marked under a > letter following a l...
625941e1507cdc57c6307092
def Write_File(s, file_path): <NEW_LINE> <INDENT> with open(file_path, 'wb') as file: <NEW_LINE> <INDENT> file.write(s.binary)
Write these contents to the target file_path.
625941e1a934411ee3751a44
def dispatch_stopped_events(self): <NEW_LINE> <INDENT> events = self.TasksStoppedEvents.pop(self.udid, []) <NEW_LINE> for event in events: <NEW_LINE> <INDENT> event.set() <NEW_LINE> events.remove(event)
去除已经停止的事件
625941e1a79ad161976cc4f5
def _discover_device(self, entry, snmp_comunity_strings): <NEW_LINE> <INDENT> snmp_handler, snmp_community = self._get_snmp_handler(device_ip=entry.ip, snmp_comunity_strings=snmp_comunity_strings) <NEW_LINE> snmp_comunity_strings.remove(snmp_community) <NEW_LINE> snmp_comunity_strings.insert(0, snmp_community) <NEW_LIN...
Discover device attributes via SNMP :param autodiscovery.reports.base.Entry entry: :param list snmp_comunity_strings: list of possible SNMP read community strings for the given devices :rtype: autodiscovery.reports.base.Entry
625941e1a8ecb033257d347b
def likelihood(param, D): <NEW_LINE> <INDENT> Aest_Cp = feval_Cp(param, D['Tt_Cp']) <NEW_LINE> Aest_H = feval_H(param, D['Tt_H']) <NEW_LINE> if param[0] <= 0: <NEW_LINE> <INDENT> return -np.inf <NEW_LINE> <DEDENT> prob_CP = ss.norm.logpdf(Aest_Cp, loc=D['At_Cp'], scale=D['Et_Cp']).sum() <NEW_LINE> prob_H = ss.norm.logp...
compute the log likelihood for a set of datapoints given a parameterization
625941e1099cdd3c635f1009
def download_result_data(result_id): <NEW_LINE> <INDENT> dirname = upload_dir_user(TEMPLATEDIR) <NEW_LINE> if not dirname: <NEW_LINE> <INDENT> dirname = TEMPLATEDIR <NEW_LINE> <DEDENT> result = load_result_by_id(result_id) <NEW_LINE> return result.export(folder=dirname)
Returns (dirname, basename) of the the result.csv on the server
625941e13539df3088e2e6fa
def create_port_postcommit(self, context): <NEW_LINE> <INDENT> port = context.current <NEW_LINE> body = self._prepare_crd_port(port) <NEW_LINE> self._crdclient.create_port(body=body) <NEW_LINE> LOG.debug("create_port update sent to CRD Server: %s", body)
Send create_port data to CRD service.
625941e1925a0f43d254a22a
def install_adapter(self, id, type, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.install_adapter_with_http_info(id, type, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.install_adapter_with_http_info(i...
Sets up the specified worker to install the specified type of adapter. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thr...
625941e1de87d2750b860145
def on_slope(p, slope, intercept=0): <NEW_LINE> <INDENT> from re import match <NEW_LINE> if isinstance(p, tuple) and len(p) == 2: <NEW_LINE> <INDENT> token = False <NEW_LINE> for i in p: <NEW_LINE> <INDENT> if not isinstance(i, (int, float)): <NEW_LINE> <INDENT> token = True <NEW_LINE> <DEDENT> <DEDENT> if token: <NEW_...
Determines if the given 'p' point is on a line with a slope of the 'slope' parameter. Note: The slope parameter must be in string form. There is also an optional 'intercept' parameter, which defaults to 0.
625941e1a17c0f6771cbe3ff
def test_valid_fig_config_default_mem_limit(self): <NEW_LINE> <INDENT> config = { 'postgres': { 'image': 'sample/postgres', 'environment': { 'PG_SCHEMA_NAME': 'example_database', 'PG_PGUSER_PASSWORD': 'clusterhq' }, } } <NEW_LINE> parser = FigConfiguration(config) <NEW_LINE> applications = parser.applications() <NEW_LI...
``FigConfiguration._parse`` creates an ``Application`` instance with a memory_limit of None if no mem_limit is specified in a valid Fig configuration.
625941e1bd1bec0571d909de
def exists(self, name): <NEW_LINE> <INDENT> return False
Django系统调用文件存储类中的_save保存文件之前,会先调用exists这个方法 来判断文件名是否跟文件系统中原有的文件发生了冲突 name: 1.jpg
625941e18c3a87329515876e
def set_cost(self, cost): <NEW_LINE> <INDENT> if cost > 0: <NEW_LINE> <INDENT> self.cost = cost <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('cost must be greater than 0')
Update the cost attribute Throw ValueError if cost is less than or equal to 0
625941e1bf627c535bc1357f
def pdf_to_text(path): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile(mode='r') as f: <NEW_LINE> <INDENT> code = subprocess.call(['pdftotext', '-layout', path, f.name]) <NEW_LINE> if code != 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return f.read()
Converts a PDF file to text. Depends on the external pdftotext command line tool.
625941e14e4d5625662d4783
def crim_Choice(q): <NEW_LINE> <INDENT> inf = i_R(q) / (i_R(q) + v_R(q)) <NEW_LINE> vil = v_R(q) / (i_R(q) + v_R(q)) <NEW_LINE> victimizer = np.random.choice(4, p=[0,inf,vil,0]) <NEW_LINE> return victimizer
Returns the index (1 or 2) for the next victimizer in the population arrray. Keyword arguments: q -- population array
625941e1dd821e528d63b556
def update(self,dt): <NEW_LINE> <INDENT> assert isinstance(dt, int) or isinstance(dt, float) <NEW_LINE> self._determineState() <NEW_LINE> if (self._state == STATE_NEWWAVE): <NEW_LINE> <INDENT> self._wave = Wave() <NEW_LINE> self._state = STATE_ACTIVE <NEW_LINE> <DEDENT> if (self._state == STATE_ACTIVE): <NEW_LINE> <IND...
Animates a single frame in the game. It is the method that does most of the work. It is NOT in charge of playing the game. That is the purpose of the class Wave. The primary purpose of this game is to determine the current state, and -- if the game is active -- pass the input to the Wave object _wave to play the game...
625941e197e22403b379d34b
def run_dfmp2_gradient(name, **kwargs): <NEW_LINE> <INDENT> optstash = p4util.OptionsState( ['DF_BASIS_SCF'], ['DF_BASIS_MP2'], ['SCF_TYPE']) <NEW_LINE> if not psi4.has_option_changed('SCF', 'SCF_TYPE'): <NEW_LINE> <INDENT> psi4.set_global_option('SCF_TYPE', 'DF') <NEW_LINE> psi4.print_out(""" SCF Algorithm Type (re...
Function encoding sequence of PSI module calls for a DFMP2 gradient calculation.
625941e1e76e3b2f99f3abb5
def dark(self): <NEW_LINE> <INDENT> return QBrush
QPalette.dark() -> QBrush
625941e1aad79263cf390df6
def add_solo_config(cfg): <NEW_LINE> <INDENT> cfg.MODEL.DEVICE = 'cpu' <NEW_LINE> cfg.MODEL.INS_SEG_HEAD = CN() <NEW_LINE> cfg.MODEL.INS_SEG_HEAD.NAME = "SemSegFPNHead" <NEW_LINE> cfg.MODEL.INS_SEG_HEAD.IN_FEATURES = ["p2", "p3", "p4", "p5"] <NEW_LINE> cfg.MODEL.INS_SEG_HEAD.IGNORE_VALUE = 255 <NEW_LINE> cfg.MODEL.INS_...
Add config for Solo.
625941e1a05bb46b383ecbce
def adjust_timestamps_in_record(record: Dict, schema: Dict) -> None: <NEW_LINE> <INDENT> def reset_new_value(record: Dict, key: str, _format: str): <NEW_LINE> <INDENT> if not isinstance(record[key], str): <NEW_LINE> <INDENT> raise UnexpectedValueTypeException( f'Value {record[key]} of key "{key}" is not a string.') <NE...
Goes through every field that is of type date/datetime/time and if its value is out of range, resets it to MAX value accordingly Args: record: record containing properties and values schema: json schema that has types of each property
625941e1baa26c4b54cb14cc
def _run_random_task(tupel, gdir, y0, mb_offset): <NEW_LINE> <INDENT> seed = tupel[0] <NEW_LINE> temp_bias = tupel[1] <NEW_LINE> fls = gdir.read_pickle('model_flowlines') <NEW_LINE> suffix = str(y0) + '_random_'+str(seed) + '_' + str(temp_bias) <NEW_LINE> path = os.path.join(gdir.dir, str(y0),'model_run'+suffix+'.nc') ...
Run random model to create lots of possible states
625941e156b00c62f0f14a0b
def effectuerControle(self,idEPI,nomControleur,prenomControleur,typeDeControle,dateControle,analyse="",remarque=""): <NEW_LINE> <INDENT> self.__curseur.execute('SELECT Id_EPI FROM EPI') <NEW_LINE> listeId = self.__curseur.fetchall() <NEW_LINE> typeDeControle = typeDeControle.lower() <NEW_LINE> if (idEPI,) not in listeI...
Fonction permetant d'ajouter un controle à un EPI arguments: idEPI -- Il s'agit de la clé primaire de l'EPI, indispensable pour l'identifier nomControleur -- on identife le controlleur prenomControleur -- son prenom typedeControle -- on notifie le type de controle (operationnel, maintenance ...) analyse -- dateContro...
625941e17b180e01f3dc4ba6
def Append(self,item): <NEW_LINE> <INDENT> pass
Append(self: ReferenceArrayArray,item: ReferenceArray)
625941e1bde94217f368319d
def get_divisions_by_company(self, company_id): <NEW_LINE> <INDENT> resource_path = DSS_321FORMS_API_RESOURCE_COMPANY_DIVISIONS % { 'company_id': company_id, } <NEW_LINE> request_url = self.get_request_url(resource_path=resource_path) <NEW_LINE> response = self.request_get(request_url) <NEW_LINE> try: <NEW_LINE> <INDEN...
Returns a JSON response with two elements. The companyID provided and an array of divisions
625941e1004d5f362079a6e1
def parse_multi_parameter_cli(self, cli, asa_gen_template = None): <NEW_LINE> <INDENT> if cli.startswith('no '): <NEW_LINE> <INDENT> status = 'disable' <NEW_LINE> result = self.parse_rates(cli[3:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status = 'enable' <NEW_LINE> result = self.parse_rates(cli) <NEW_LINE> <DEDE...
Parse parameters
625941e1566aa707497f4913
def request_xml(self, protocol, params, mode='tradeweb', headers={}, to=1): <NEW_LINE> <INDENT> if mode == 'tradeweb': <NEW_LINE> <INDENT> url = self.tradeweb_url <NEW_LINE> <DEDENT> elif mode == 'front': <NEW_LINE> <INDENT> url = self.front_url + '/common_front/checkneedless/user/logon/logon.action' <NE...
发送交易指令 - 拼接请求成xml - 发送 - 解析返回的请求
625941e1442bda511e8be7c3
def func103(): <NEW_LINE> <INDENT> x, y, z = (5, 2, 3, 4, 5)[2:]
should not warn
625941e1293b9510aa2c3642
def has_evidence_values(self): <NEW_LINE> <INDENT> return hasattr(self, 'lookup_evidence')
Checks whether the current formula contains information for evidence propagation.
625941e107d97122c4178c43
def render(self, path=''): <NEW_LINE> <INDENT> image = SLLDrawer.draw(self) <NEW_LINE> if path: <NEW_LINE> <INDENT> util.save_file(image, path, self.name) <NEW_LINE> <DEDENT> return image
Renders the current state of the linked list. Args: path: The path where the rendered image will be saved.
625941e12eb69b55b151cc64
def getRfactor(self, ref_da): <NEW_LINE> <INDENT> pi = self.patterns_iterator <NEW_LINE> ref_pi = ref_da.patterns_iterator <NEW_LINE> R_factor_list = [] <NEW_LINE> if len(self.pattern_indices) == 1: <NEW_LINE> <INDENT> pattern = next(pi) <NEW_LINE> R_factor_list.append( R_factor_paper(pattern, next(ref_pi), self.q_map,...
Get R factors from diffraction patterns :param ref_da: The DiffractionAnalysis class instance of the reference data :type DiffractionAnalysis class :return: [full period resolution, a list of r factors for each pair of diffraction patters] :rtype: [list, list]
625941e1cad5886f8bd27389
def did_rename(self, fid, ncomp, newdir=None): <NEW_LINE> <INDENT> if ncomp is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> opath = self.getpath(fid) <NEW_LINE> if newdir is None: <NEW_LINE> <INDENT> if opath is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> ocomps = opath.split(b'/') <NEW_LINE> ncomps = ...
Announce that we renamed using a fid - we'll try to update other fids based on this (we can't really do it perfectly). NOTE: caller must provide a final-component. The caller can supply the new path (and should do so if the rename is not based on the retained path for the supplied fid, i.e., for rename ops where fid c...
625941e1046cf37aa974d0f4
def get(self, region): <NEW_LINE> <INDENT> return super(RegionManager, self).get( region_id=base.getid(region))
Retrieve a region. :param region: the region to be retrieved from the server. :type region: str or :class:`keystoneclient.v3.regions.Region` :returns: the specified region returned from server. :rtype: :class:`keystoneclient.v3.regions.Region`
625941e14e696a04525c97fd
def draw_circle(self, x, y, r, ch): <NEW_LINE> <INDENT> _lib.caca_draw_circle.argtypes = [ _Canvas, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint32 ] <NEW_LINE> _lib.caca_draw_circle.restype = ctypes.c_int <NEW_LINE> if not isinstance(ch, str): <NEW_LINE> <INDENT> raise CanvasError("Specified character is in...
Draw a circle on the canvas using the given character. x -- center X coordinate y -- center Y coordinate r -- circle radius ch -- the UTF-32 character to be used to draw the circle outline
625941e123849d37ff7b343d
def part_two(input_data: List[str]): <NEW_LINE> <INDENT> for index, item in enumerate(input_data): <NEW_LINE> <INDENT> match = find_common_ids(item, input_data[index+1:]) <NEW_LINE> if match: <NEW_LINE> <INDENT> print(''.join([i for n, i in enumerate(list(item)) if list(match)[n] == i]))
Puzzle Answer == pazvmqbftrbeosiecxlghkwud
625941e196565a6dacc8fa7a
def test_photo_user_exists(self): <NEW_LINE> <INDENT> self.assertTrue(self.user is not None)
Test that Photo has user.
625941e13317a56b8693a000
def remove_data_post_large_delta_time(df): <NEW_LINE> <INDENT> list_to_remove = [] <NEW_LINE> idx_high = np.where(df.delta_time.values > 150)[0] <NEW_LINE> IDs = df.SNID.values <NEW_LINE> for idx in idx_high: <NEW_LINE> <INDENT> ID = IDs[idx] <NEW_LINE> same_lc = True <NEW_LINE> while same_lc: <NEW_LINE> <INDENT> list_...
Remove rows in the same light curve after a gap > 150 days Reason: If no signal has been saved in a time frame of 150 days, it is unlikely there is much left afterwards Args: df (pandas.DataFrame): dataframe holding lightcurve data Returns: (pandas.DataFrame) dataframe where large delta time rows have been re...
625941e18e05c05ec3eea727
def export_meta_graph(obj, filename, signatures=None, options=None): <NEW_LINE> <INDENT> options = options or save_options.SaveOptions() <NEW_LINE> export_dir = os.path.dirname(filename) <NEW_LINE> meta_graph_def, exported_graph, _, _ = _build_meta_graph( obj, signatures, options) <NEW_LINE> file_io.atomic_write_string...
Exports the MetaGraph proto of the `obj` to a file. This function goes through the same procedures saved_model.save goes to produce the given object's MetaGraph, then saves it to the given file. It skips saving checkpoint information, and is useful when all one wants is the graph defining the model. Args: obj: A tr...
625941e1d4950a0f3b08c6fa
def test_models_simpletext_html5_sanitize_tag(self): <NEW_LINE> <INDENT> content = """<iframe src="http://perdu.com/" border=0></iframe>""" <NEW_LINE> attempted = ( """&lt;iframe src="http://perdu.com/" """ """border="0"&gt;&lt;/iframe&gt;""" ) <NEW_LINE> instance = SimpleText(body=content) <NEW_LINE> instance.save() <...
HTML5lib Cleaner escape potential malicious tag like iframe. Behavior can be modified with settings: https://github.com/divio/djangocms-text-ckeditor#configurable-sanitizer
625941e160cbc95b062c68f3