code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def action(self, request, action, msg='', *args, level=LogLevel.INFO, **kwargs): <NEW_LINE> <INDENT> self.log(level, action, request.path, "<{0}> {1}", LogAction.label(action), msg.format(*args, **kwargs)) | Specifically logs a LogEntry with a log message containing the specified action. Unlike the others this forces
a specific action to be chosen and the LogLevel defaults to INFO.
:param request: Request object with path property (request.path)
:param action: LogAction to associate wit hthis log entry, the associated Log... | 625941d2a8370b7717052a46 |
def get_article(article_id): <NEW_LINE> <INDENT> if not isinstance(article_id, int): <NEW_LINE> <INDENT> raise TypeError('article_id must be an int value.') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> article = Article.objects.get(id=article_id) <NEW_LINE> <DEDENT> except Article.DoesNotExist: <NEW_LINE> <INDENT> retu... | Get specified article data
:param article_id:
:return: | 625941d207d97122c4178a35 |
def evaluateForce(force, positions, boxVectors=None): <NEW_LINE> <INDENT> system = openmm.System() <NEW_LINE> for i in range(len(positions)): <NEW_LINE> <INDENT> system.addParticle(0) <NEW_LINE> <DEDENT> if boxVectors is not None: <NEW_LINE> <INDENT> system.setDefaultPeriodicBoxVectors(*boxVectors) <NEW_LINE> <DEDENT> ... | Computes the value of a Force_ object for a given set of particle coordinates and box
vectors. Whether periodic boundary conditions will be used or not depends on the
corresponding attribute of the Force_ object specified as the collective variable.
Parameters
----------
positions : list(openmm.Vec3)
A lis... | 625941d21f037a2d8b9463a5 |
def argparse_compile_argdoc(epi, doc): <NEW_LINE> <INDENT> prog = doc.strip().splitlines()[0].split()[1] <NEW_LINE> headlines = list(_ for _ in doc.strip().splitlines() if _ and not _.startswith(" ")) <NEW_LINE> description = headlines[1] <NEW_LINE> epilog_at = doc.index(epi) <NEW_LINE> epilog = doc[epilog_at:] <NEW_LI... | Construct the 'argparse.ArgumentParser' with Epilog but without Arguments | 625941d299fddb7c1c9de538 |
def updateStatus(self, id, status): <NEW_LINE> <INDENT> kparams = KalturaParams() <NEW_LINE> kparams.addStringIfDefined("id", id) <NEW_LINE> kparams.addIntIfDefined("status", status); <NEW_LINE> self.client.queueServiceActionCall("cuepoint_cuepoint", "updateStatus", "None", kparams) <NEW_LINE> if self.client.isMultiReq... | Update cuePoint status by id | 625941d24a966d76dd5511b8 |
def replace_elem(lst, index, elem): <NEW_LINE> <INDENT> assert index >= 0 and index < len(lst), 'Index is out of bounds' <NEW_LINE> return [elem if x == index else lst[x] for x in range(len(lst))] | Create and return a new list whose elements are the same as those in
LST except at index INDEX, which should contain element ELEM instead.
>>> old = [1, 2, 3, 4, 5, 6, 7]
>>> new = replace_elem(old, 2, 8)
>>> new
[1, 2, 8, 4, 5, 6, 7]
>>> new is old # check that replace_elem outputs a new list
False | 625941d263d6d428bbe44697 |
def getFilterFun(self): <NEW_LINE> <INDENT> logger.debug("Filterfun with self.IgnoreDirs: %s", self.IgnoreDirs) <NEW_LINE> return lambda path: os.path.isdir(path) and os.path.basename(path) not in self.IgnoreDirs | Default filterfun for get... | 625941d291f36d47f21ac69b |
@app.route("/iface", methods=['GET', 'POST']) <NEW_LINE> def browser_iface(): <NEW_LINE> <INDENT> return "No implementado" | Permite la comunicacion con el agente via un navegador
via un formulario | 625941d2baa26c4b54cb12c6 |
def infer_freq(index, warn=True): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> if isinstance(index, com.ABCSeries): <NEW_LINE> <INDENT> values = index.values <NEW_LINE> if not (com.is_datetime64_dtype(index.values) or com.is_timedelta64_dtype(index.values) or values.dtype == object): <NEW_LINE> <INDENT> raise Typ... | Infer the most likely frequency given the input index. If the frequency is
uncertain, a warning will be printed
Parameters
----------
index : DatetimeIndex
if passed a Series will use the values of the series (NOT THE INDEX)
warn : boolean, default True
Returns
-------
freq : string or None
None if no dis... | 625941d256b00c62f0f14802 |
def __init__(self): <NEW_LINE> <INDENT> filename = os.path.basename(inspect.getfile(self.__class__)) <NEW_LINE> self.prefix = filename.split('.')[0] <NEW_LINE> self.name = self.__class__.__name__ <NEW_LINE> self._data_store = defaultdict(dict) <NEW_LINE> self._debug_store = defaultdict(dict) <NEW_LINE> self._meta_store... | Instantiate all of the feature extractor's properties. | 625941d230dc7b7665901b0e |
def model_export(model, filepath): <NEW_LINE> <INDENT> model_string = model.circuit <NEW_LINE> model_name = model.name <NEW_LINE> initial_guess = model.initial_guess <NEW_LINE> if model._is_fit(): <NEW_LINE> <INDENT> parameters_ = list(model.parameters_) <NEW_LINE> model_conf_ = list(model.conf_) <NEW_LINE> data_dict =... | Exports a model to JSON
Parameters
---------
model: CustomCircuit
Circuit model object
filepath: Path String
Destination for exporting model object | 625941d23c8af77a43ae3949 |
def set_from_other(self, other, strategy='projection', close_limit=0.1): <NEW_LINE> <INDENT> flag_same_mesh = self.has_same_mesh(other) <NEW_LINE> if flag_same_mesh == 'same': <NEW_LINE> <INDENT> self.set_data(other()) <NEW_LINE> return <NEW_LINE> <DEDENT> if strategy == 'interpolation': <NEW_LINE> <INDENT> coors = sel... | Set the variable using another variable. Undefined values (e.g. outside
the other mesh) are set to numpy.nan, or extrapolated.
Parameters
----------
strategy : 'projection' or 'interpolation'
The strategy to set the values: the L^2 orthogonal projection (not
implemented!), or a direct interpolation to the node... | 625941d2d53ae8145f87a417 |
def main(): <NEW_LINE> <INDENT> h0 = ConcreteHandler0() <NEW_LINE> h1 = ConcreteHandler1() <NEW_LINE> h2 = ConcreteHandler2() <NEW_LINE> h0.successor = h1 <NEW_LINE> h1.successor = h2 <NEW_LINE> h2.successor = FallbackHandler() <NEW_LINE> requests = [4, 2, 14, 24, 35, 24, 18, 7] <NEW_LINE> for request in requests: <NEW... | >>> What is this pattern about?
The Chain of responsibility is an object oriented version of the
`if ... elif ... elif ... else ...` idiom, with the
benefit that the condition–action blocks can be dynamically rearranged
and reconfigured at runtime.
This pattern aims to decouple the senders of a request from its
receiv... | 625941d21b99ca400220ac59 |
def __init__(self): <NEW_LINE> <INDENT> pass | 1,2,3,4,5,6,7,8
for 1 to 8:
1+..6>=s
2直接从6开始加 不用再遍历2...6 | 625941d285dfad0860c3b003 |
def on_x265_max_cu_combobox_changed(self, x265_max_cu_combobox): <NEW_LINE> <INDENT> if self.x265_handlers.is_widgets_setting_up: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> max_cu_index = x265_max_cu_combobox.get_active() <NEW_LINE> for row in self.inputs_page_handlers.get_selected_rows(): <NEW_LINE> <INDENT> ffmpe... | Applies the Max CU option and updates the preview page.
:param x265_max_cu_combobox: Combobox that emitted the signal. | 625941d27cff6e4e81117b2e |
def write(self): <NEW_LINE> <INDENT> if self.outfile: <NEW_LINE> <INDENT> if isinstance(self.outfile, StringType): <NEW_LINE> <INDENT> outfile = open(self.outfile, 'wb') <NEW_LINE> outfile.write(self.getvalue()) <NEW_LINE> outfile.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.outfile.write(self.getvalue())... | Writes to disc | 625941d26e29344779a627b9 |
def get_more(self): <NEW_LINE> <INDENT> sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;' <NEW_LINE> cursor = self.conn.cursor() <NEW_LINE> cursor.execute(sql, ('百家', )) <NEW_LINE> rest = [dict(zip([k[0] for k in cursor.description], row)) for row in cursor.fetchall()] <NEW_LINE> cursor.close(... | 获取多条数据 | 625941d296565a6dacc8f873 |
def rob(self, nums): <NEW_LINE> <INDENT> def rob(nums): <NEW_LINE> <INDENT> now = prev = 0 <NEW_LINE> for n in nums: <NEW_LINE> <INDENT> now, prev = max(now, prev + n), now <NEW_LINE> <DEDENT> return now <NEW_LINE> <DEDENT> return max(rob(nums[len(nums) != 1:]), rob(nums[:-1])) | :type nums: List[int]
:rtype: int
https://leetcode.com/problems/house-robber-ii/discuss/59934/
the idea is similar like House Robber (LC 198)
the tricky part is pick first one or not will influence last one
so it will get max from with first one (rob(nums[:-1])) or without first one (rob(nums[len(nums) != 1:]))
beats... | 625941d2a17c0f6771cbe1f8 |
def _nonStandardEparOptionFor(self, paramTypeStr): <NEW_LINE> <INDENT> if paramTypeStr == "pset": <NEW_LINE> <INDENT> import pseteparoption <NEW_LINE> return pseteparoption.PsetEparOption <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Override to allow use of PsetEparOption.
Return None or a class which derives from EparOption. | 625941d2be7bc26dc91cd7a6 |
def clean_leader(self): <NEW_LINE> <INDENT> new_leader = self.cleaned_data['leader'] <NEW_LINE> if hasattr(new_leader, 'student_group') and ( new_leader.student_group != self.instance): <NEW_LINE> <INDENT> raise ValidationError(u"Студент не входить до даної групи!", code='invalid') <NEW_LINE> <DEDENT> return new_leader | Check if leader is in the same group | 625941d250485f2cf553cf42 |
def hiddenAdjust(self, next_layer, use_momentum=False, learning_rate=0.01): <NEW_LINE> <INDENT> output = self.last_output <NEW_LINE> derivative = output * (1 - output) <NEW_LINE> previous_layer_sum = 0 <NEW_LINE> for neuron in next_layer: <NEW_LINE> <INDENT> previous_layer_sum += (neuron.delta * neuron.input_weights[se... | Modifies the output layer values based on momentum, weight, and learning rate.
:param next_layer: next layer to pass the new values to.
:param use_momentum: Boolean. momentum yes or no.
:param learning_rate: float. learning rate multiplier. | 625941d27d847024c06be465 |
def encode_multipart(fields, files, boundary=None): <NEW_LINE> <INDENT> import mimetypes <NEW_LINE> import random <NEW_LINE> import string <NEW_LINE> _BOUNDARY_CHARS = string.digits + string.ascii_letters <NEW_LINE> def escape_quote(s): <NEW_LINE> <INDENT> return s.replace('"', '\\"') <NEW_LINE> <DEDENT> if boundary is... | Encodes a file in order to send it as an answer to a form | 625941d2566aa707497f470f |
def parse(self, data): <NEW_LINE> <INDENT> self.unknown_short, data = read_uint16(data) <NEW_LINE> self.filename, data = data.split('\x00', 1) <NEW_LINE> self.src_path, data = data.split('\x00', 1) <NEW_LINE> self.unknown_long_1, data = read_uint32(data) <NEW_LINE> self.unknown_long_2, data = read_uint32(data) <NEW_LIN... | Parse binary data containing an OLENativeStream structure,
to extract the OLE object it contains.
(see MS-OLEDS 2.3.6 OLENativeStream)
:param data: bytes, OLENativeStream structure containing an OLE object
:return: | 625941d27b180e01f3dc49a4 |
def get_return_data(offset,keyword="街拍"): <NEW_LINE> <INDENT> url = "https://www.toutiao.com/search_content/" <NEW_LINE> params = { "offset":offset, "format":"json", "keyword":keyword, "autoload":"true", "count":20, "cur_tab":1, "from":"search_tab", } <NEW_LINE> r = requests.get(url,params=params) <NEW_LINE> return r.j... | :param offset: 偏移量
:param keyword: 搜索关键字
:return: 搜索结果页面【data】数据 | 625941d20a50d4780f66703b |
def dictionaries(): <NEW_LINE> <INDENT> f = {'fruit': 'apple', 'quantity': 4, 'color': 'green'} <NEW_LINE> print(f) <NEW_LINE> a = f['fruit'] <NEW_LINE> print(a) <NEW_LINE> f['quantity'] = f['quantity'] + 1 <NEW_LINE> print(f) <NEW_LINE> amazing_grace = {'name': {'first_name': 'Grace', 'last_name': 'Hopper'}, 'jobs': [... | This is to review basic operations with dictionaries. | 625941d26fece00bbac2d8e7 |
def predict(self, x): <NEW_LINE> <INDENT> preds = [] <NEW_LINE> for point in x: <NEW_LINE> <INDENT> neighbors = self.rangeQuery(point) <NEW_LINE> label = self.df[neighbors[0], 2] <NEW_LINE> preds.append(label) <NEW_LINE> <DEDENT> return preds | Return the predicted labels | 625941d2be7bc26dc91cd7a7 |
def find_duplicates( self, value: int or float or str, column_name: int or float or str ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for row_index in self.column_values(column_name)[value]: <NEW_LINE> <INDENT> yield row_index <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return | Yields duplicates in this row file
:param value: int, float, or str
:param column_name: int, float or str
:return: Generator[str, int] | 625941d2956e5f7376d71015 |
def extract_upper1(phrase): <NEW_LINE> <INDENT> return list(filter(str.isupper, phrase)) | :param phrase:
:return: list
>>> extract_upper("This Is Upper")
['T', 'I', 'U'] | 625941d230bbd722463cbf6f |
def test_ever_4_hours(self): <NEW_LINE> <INDENT> vrecurr = utils.build_rrule_from_text("INTERVAL=4;FREQ=HOURLY") <NEW_LINE> assert vrecurr["FREQ"] == ["HOURLY"] <NEW_LINE> assert vrecurr["INTERVAL"] == [4] <NEW_LINE> vRecur(vrecurr).to_ical().decode() == "FREQ=HOURLY;INTERVAL=4" <NEW_LINE> assert len(vrecurr.keys()) ==... | Repeat every 4 hours. | 625941d2a8ecb033257d3275 |
@color_conversion_function(XYZColor, BaseRGBColor) <NEW_LINE> def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs): <NEW_LINE> <INDENT> temp_X = cobj.xyz_x <NEW_LINE> temp_Y = cobj.xyz_y <NEW_LINE> temp_Z = cobj.xyz_z <NEW_LINE> logger.debug(" \- Target RGB space: %s", target_rgb) <NEW_LINE> target_illum = target_rgb.nat... | XYZ to RGB conversion. | 625941d24428ac0f6e5ba99b |
def add_json_data(request): <NEW_LINE> <INDENT> name_cat = u'生產/工廠職位' <NEW_LINE> data = json.load(open('/Users/mac/Desktop/projects/selenium/生產.txt')) <NEW_LINE> for x in data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> labor_gov.objects.create( number=x['number'], company=x['company'], location=x['location'], treatm... | 用來將資料放入資料庫中,現在沒有用 | 625941d25e10d32532c5f0cf |
def load_defined_vggish_slim_checkpoint(session, checkpoint_path): <NEW_LINE> <INDENT> with tf.Graph().as_default(): <NEW_LINE> <INDENT> define_vggish_slim(training=False) <NEW_LINE> vggish_var_names = [v.name for v in tf.global_variables()] <NEW_LINE> <DEDENT> with session.graph.as_default(): <NEW_LINE> <INDENT> globa... | Loads a pre-trained VGGish-compatible checkpoint.
This function can be used as an initialization function (referred to as
init_fn in TensorFlow documentation) which is called in a Session after
initializating all variables. When used as an init_fn, this will load
a pre-trained checkpoint that is compatible with the VG... | 625941d20fa83653e4657163 |
def _get_set_name_from_id(self, id_to_convert: str) -> str: <NEW_LINE> <INDENT> ml.log_event('get set name from id {}'.format(id_to_convert)) <NEW_LINE> try: <NEW_LINE> <INDENT> for set_id in self.data['data'].keys(): <NEW_LINE> <INDENT> if id_to_convert == set_id: <NEW_LINE> <INDENT> set_name = self.data['data'][set_i... | :param id_to_convert: a set id, great parameter for starting a search in the present json format
:return: | 625941d221bff66bcd684afa |
def transpose(self): <NEW_LINE> <INDENT> self.__array = transpose(self.__array) <NEW_LINE> self.__width, self.__array = uniform(self.__array) | Rotate the data table by 90 degrees
Reference :func:`transpose` | 625941d2f9cc0f698b1407a3 |
def get_expired_resources(): <NEW_LINE> <INDENT> date = tools.get_date() <NEW_LINE> res = ( db.query(Resource.id) .filter(Resource.state == "Alive") .filter(Resource.expiry_date > 0) .filter(Resource.desktop_computing == "YES") .filter(Resource.expiry_date < date) .all() ) <NEW_LINE> return [r[0] for r in res] | Get the list of resources whose expiry_date is in the past and which are not dead yet.
0000-00-00 00:00:00 is always considered as in the future. Used for desktop computing schema. | 625941d2d164cc6175782ef6 |
def train_classify_tensorflow_nn(X_df, y_df, kfolds=5): <NEW_LINE> <INDENT> df_list = [] <NEW_LINE> for idx, X_train, X_test, y_train_valence, y_train_arousal, y_test_valence, y_test_arousal in k_folds(X_df, y_df, kfolds): <NEW_LINE> <INDENT> print('noop') <NEW_LINE> <DEDENT> res = pd.concat(df_list) <NEW_LINE> return ... | Train and classify using kfolds iteration and libsvm SVR
:param X_df: pandas dataframe audio features with columns (ID, ft_1, ...ft_n) where ID column is the dataframe's index col
:param y_df: pandas dataframe audio targets (valence and arousal) with columns (ID, VALENCE, AROUSAL) where ID column is the dataframe's ind... | 625941d2be383301e01b562c |
def import_to_datastore(directory, provider_code, year, batch_size): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert batch_size > 0 <NEW_LINE> files_from_cbs = get_files(directory) <NEW_LINE> if len(files_from_cbs) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> logging.info("Importing '{}'".format(directory... | goes through all the files in a given directory, parses and commits them | 625941d2596a897236089c68 |
def forward(self, *, n_sample=1, **kwargs): <NEW_LINE> <INDENT> x = kwargs.pop("observe_x") <NEW_LINE> y = kwargs.pop("observe_y") <NEW_LINE> if n_sample is None: <NEW_LINE> <INDENT> n_sample = self.n_sample <NEW_LINE> <DEDENT> z_mean, z_std = self.original_variational(x) <NEW_LINE> assert z_mean.size() == z_std.size()... | In training phase, z = \sigma * z_std + z_mean, and sample \sigma from N(0, 1)
In testing phase, sample z from Q(z|x)
:param n_sample: positive integer
:param kwargs:
observe_x: in shape (batch_size, x_dims)
observe_y: in shape (batch_size, y_dims)
:return: P(x|z), Q(z|x), z_samples | 625941d2498bea3a759b9c57 |
def p_expression_int(token): <NEW_LINE> <INDENT> token[0] = token[1] | expression : INTEGER | 625941d27047854f462a15b1 |
def delete_business(yelp_id, conn): <NEW_LINE> <INDENT> return conn.execute(Business.delete().where(Business.c.yelp_id == yelp_id)) | Delete the business with the given yelp id. | 625941d271ff763f4b549835 |
def __init__(self, name, scope): <NEW_LINE> <INDENT> self.scope = list(scope) <NEW_LINE> self.name = name <NEW_LINE> self.sat_tuples = dict() <NEW_LINE> self.sat_function = None <NEW_LINE> self.sup_function = None <NEW_LINE> self.sup_tuples = dict() | create a constraint object, specify the constraint name (a
string) and its scope (an ORDERED list of variable objects).
The order of the variables in the scope is critical to the
functioning of the constraint.
Consraints are implemented as storing a set of satisfying
tuples (i.e., each tuple specifies a value for each... | 625941d28c3a873295158564 |
def run_gradient_descent_iteration(X, Y, theta, alpha, lambda_factor, temp_parameter): <NEW_LINE> <INDENT> grad = np.empty(theta.shape) <NEW_LINE> p = compute_probabilities(X, theta, temp_parameter) <NEW_LINE> J = np.arange(0, theta.shape[0], 1).reshape(theta.shape[0], 1) <NEW_LINE> J = (J == Y).astype(float) <NEW_LINE... | Runs one step of batch gradient descent
Args:
X - (n, d) NumPy array (n datapoints each with d features)
Y - (n, ) NumPy array containing the labels (a number from 0-9) for each
data point
theta - (k, d) NumPy array, where row j represents the parameters of our
model for label j
alp... | 625941d2a934411ee375183c |
def get_health_monitor_data(self): <NEW_LINE> <INDENT> site = self._connect_site() <NEW_LINE> sp_list = site.List(self.report_list) <NEW_LINE> return sp_list.GetListItems('All Reports') | return: example:
[{'Failing Servers': 'server1
',
'Failing Services': 'SPTimerService (SPTimerV4)',
'Modified': datetime.date(2018, 3, 11),
'Severity': '2 - Warning',
'Title': 'The paging file size should exceed the amount of physical RAM in '
... | 625941d2ab23a570cc25032c |
def addArtist(p_filename, p_artist): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> MetadataManagerL1.addArtist(p_filename, p_artist) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("MetadataManager2.addArtist() error: ", e) <NEW_LINE> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> Metadat... | appends new artist to the artist metadata
:param p_filename: name/path of the file
:type p_filename: string
:param p_artist: artist we are adding into the artist metadata
:type p_artist: string
:return: True if operation was successful
:rtype: bool | 625941d2f7d966606f6aa1ae |
def teardown(): <NEW_LINE> <INDENT> os.environ['FLASK_CONFIGURATION'] = pre_config | reset environment
| 625941d23539df3088e2e4f4 |
def _get_consumption_records_data(consumption_df): <NEW_LINE> <INDENT> raw_consumption_records_data = _get_raw_consumption_records_data( consumption_df) <NEW_LINE> consumption_records_data = _process_raw_consumption_records_data( raw_consumption_records_data) <NEW_LINE> return consumption_records_data | Get consumption records from single project_id/fuel_type group. | 625941d2507cdc57c6306e85 |
def get_pay_album(self, xm_fm_id, page_num): <NEW_LINE> <INDENT> response = self.s.get(self.album_tracks_api.format(xm_fm_id, page_num), headers=self.header) <NEW_LINE> return response | 获取付费的音频的播放源信息
:param xm_fm_id:
:param max_page:
:return: response | 625941d2bd1bec0571d907d8 |
def __init__(self, handles, rate): <NEW_LINE> <INDENT> self.rate = rate <NEW_LINE> self.handles = handles | function to instance the streamer
:param rate: scanner rate
:param handles: connection to labjack devices
:return: | 625941d26aa9bd52df036f4d |
def test_too_few_diagnostics_records(self): <NEW_LINE> <INDENT> log.debug('===== START TEST NOT ENOUGH DIAGNOSTICS RECORDS =====') <NEW_LINE> with open(os.path.join(RESOURCE_PATH, 'too_few_VELPT_SN_11402_2014-07-02.aqd'), 'rb') as file_handle: <NEW_LINE> <INDENT> num_particles_to_request = num_expected_particles = 71 <... | The file used in this test has only 19 diagnostics records in the second set.
Twenty are expected. The records are all still processed.
The error is simply noted. | 625941d2cdde0d52a9e531dd |
def get_all_container(path): <NEW_LINE> <INDENT> image_list = [] <NEW_LINE> for root, _, files in os.walk(path): <NEW_LINE> <INDENT> for filename in files: <NEW_LINE> <INDENT> full_path = os.path.join(root, filename) <NEW_LINE> if os.path.splitext(full_path)[1] == '.img': <NEW_LINE> <INDENT> image_list.append(full_path... | This function is looking for img-files in a given path and returns their
absolute path as a list | 625941d23346ee7daa2b2f15 |
def create_firewall(self, context, firewall, host): <NEW_LINE> <INDENT> LOG.debug("create_firewall: firewall %s", firewall) <NEW_LINE> event_data = {'event': CSR_FW_EVENT_CREATE, 'context': context, 'firewall': firewall, 'host': host} <NEW_LINE> self.event_q.enqueue(CSR_FW_EVENT_Q_NAME, event_data) | Handle Rpc from plugin to create a firewall. | 625941d28c0ade5d55d3eb64 |
def generate_particle_state_vector(self, particle_speed, initial_string): <NEW_LINE> <INDENT> v = [] <NEW_LINE> index = 0 <NEW_LINE> for value in initial_string: <NEW_LINE> <INDENT> if value == 'L': <NEW_LINE> <INDENT> v.append(ParticleState(position=index, speed=particle_speed, direction='L')) <NEW_LINE> <DEDENT> elif... | Turn the given string format into a list of immutable particle states
| 625941d23eb6a72ae02ec689 |
def test_change_no_context_with_full_path_multiple_files(self): <NEW_LINE> <INDENT> changes = ['set /files/etc/hosts/service-name test', 'set /files/etc/services/service-name test'] <NEW_LINE> filename = '/etc/hosts/service-name' <NEW_LINE> filename_ = '/etc/services/service-name' <NEW_LINE> comt = 'Error: Changes shou... | Test handling of different paths with no context supplied | 625941d22ae34c7f2600d2da |
def is_local(self): <NEW_LINE> <INDENT> return bool(self.byte_ints[0] & 0b00000010) | Check whether the "locally administered" bit in a MAC address is set to 1. | 625941d263b5f9789fde728f |
def gcd(x, y): <NEW_LINE> <INDENT> if y == 0: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gcd(y, x%y) | Euclidean algorithm:
explanation: https://stackoverflow.com/questions/6005582/how-does-the-euclidean-algorithm-work/6005795#6005795 | 625941d2046cf37aa974cef0 |
def __call__(context, default): <NEW_LINE> <INDENT> pass | returns value to be indexed.
| 625941d226238365f5f0f018 |
def heatmap(self, X, win=None, env=None, opts=None): <NEW_LINE> <INDENT> assert X.ndim == 2, 'data should be two-dimensional' <NEW_LINE> opts = {} if opts is None else opts <NEW_LINE> opts['xmin'] = opts.get('xmin', np.asscalar(X.min())) <NEW_LINE> opts['xmax'] = opts.get('xmax', np.asscalar(X.max())) <NEW_LINE> opts['... | This function draws a heatmap. It takes as input an `NxM` tensor `X`
that specifies the value at each location in the heatmap.
The following `opts` are supported:
- `opts.colormap`: colormap (`string`; default = `'Viridis'`)
- `opts.xmin` : clip minimum value (`number`; default = `X:min()`)
- `opts.xmax` : clip... | 625941d2a17c0f6771cbe1f9 |
def testDrawSetRGBAImage(self): <NEW_LINE> <INDENT> symbol_index = self.map.symbolset.appendSymbol(self.x_symbol) <NEW_LINE> inline_layer = self.map.getLayerByName('INLINE') <NEW_LINE> s = inline_layer.getClass(0).getStyle(0) <NEW_LINE> s.symbol = symbol_index <NEW_LINE> s.size = -1 <NEW_LINE> inline_layer.transparency... | draw a map using the set image symbol | 625941d23346ee7daa2b2f16 |
def create_secret_link(request, message=None, expires_at=None): <NEW_LINE> <INDENT> record = get_record(request.recid) <NEW_LINE> if not record: <NEW_LINE> <INDENT> raise RecordNotFound(request.recid) <NEW_LINE> <DEDENT> description = render_template( "accessrequests/link_description.tpl", request=request, record=recor... | Receiver for request-accepted signal. | 625941d29b70327d1c4e0f7f |
def is_winning_row(row: str, color: str, amount_to_win=4) -> bool: <NEW_LINE> <INDENT> if color * amount_to_win in row: <NEW_LINE> <INDENT> return True | Given a row, return True if there are enough adjacent pieces of the same player | 625941d215baa723493c411f |
def lock(self, source_node): <NEW_LINE> <INDENT> if self.status != self.S_INIT: <NEW_LINE> <INDENT> raise ValueError("Trying to lock a task with status %s" % self.status) <NEW_LINE> <DEDENT> self._status = self.S_LOCKED <NEW_LINE> self.history.info("Locked by node %s", source_node) | Lock the task, source is the |Node| that applies the lock. | 625941d24c3428357757c4d1 |
def test_notes_is_not_not_es(self): <NEW_LINE> <INDENT> sp = self.SearchParser() <NEW_LINE> results = sp.parse_string('species where notes.id!=0') <NEW_LINE> self.assertEqual(str(results.statement), "SELECT * FROM species WHERE (notes.id != 0.0)") | acknowledges word boundaries | 625941d2097d151d1a223002 |
@retry_on_except(10) <NEW_LINE> def test_manual_overhead_hard(): <NEW_LINE> <INDENT> total = int(1e5) <NEW_LINE> with tqdm(total=total * 10, leave=True, miniters=1, mininterval=0, maxinterval=0) as t: <NEW_LINE> <INDENT> a = 0 <NEW_LINE> with relative_timer() as time_tqdm: <NEW_LINE> <INDENT> for i in _range(total): <N... | Test overhead of manual tqdm (hard) | 625941d238b623060ff0af97 |
def __init__(self, name, config_options): <NEW_LINE> <INDENT> Monitor.__init__(self, name, config_options) <NEW_LINE> ping_ttl = Monitor.get_config_option( config_options, 'ping_ttl', required_type='int', minimum=0, default=5 ) <NEW_LINE> ping_ms = str(ping_ttl * 1000) <NEW_LINE> ping_ttl = str(ping_ttl) <NEW_LINE> pla... | Note: We use -w/-t on Windows/POSIX to limit the amount of time we wait to 5 seconds.
This is to stop ping holding things up too much. A machine that can't ping back in <5s is
a machine in trouble anyway, so should probably count as a failure. | 625941d2091ae35668667106 |
def glUniform1fv(*argv): <NEW_LINE> <INDENT> pass | no string
| 625941d2cad5886f8bd27183 |
def test_mfs_ds3_lock_readonly(self): <NEW_LINE> <INDENT> ds3_lock_readonly(self, "MFS") | MFS DOSv3 lock file readonly | 625941d25fc7496912cc3b27 |
def yx_min_yx_max_to_xy_min_xy_max(bbox: tf.Tensor) -> tf.Tensor: <NEW_LINE> <INDENT> return tf.concat([ bbox[:,1:2], bbox[:,0:1], bbox[:,3:4], bbox[:,2:3] ], axis=-1) | Convert bbox from shape [ymin, xmin, ymax, xmax] to [xmin, ymin, xmax, ymax]
Args:
bbox A (tf.Tensor) list a bbox (n, 4) with n the number of bbox to convert
Returns:
The converted bbox | 625941d267a9b606de4a8062 |
@register.filter() <NEW_LINE> def qget(qstring, modifier): <NEW_LINE> <INDENT> if isinstance(qstring, QueryDict): <NEW_LINE> <INDENT> return qstring.getlist(modifier) | :type qstring: QueryDict | 625941d2d18da76e23532680 |
def is_valid_url(url, blacklist=[]): <NEW_LINE> <INDENT> url_parsed = urlparse(url) <NEW_LINE> if not url_parsed.scheme in ('http', 'https',): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for pattern in blacklist: <NEW_LINE> <INDENT> if fnmatch(url, pattern): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT>... | Checks if `url` is valid. For example:
>>> is_valid_url('http://www.google.com/')
True
>>> is_valid_url('ftp://192.168.1.1')
False
The blacklist parameter specifies urls which are always invalid. The
rules can be written with fnmatch expressions (see
http://docs.python.org/library/fnmatch.html).
>>> is_valid_url('h... | 625941d2435de62698dfddf7 |
def add_fast_rcnn_losses(model): <NEW_LINE> <INDENT> if cfg.TRAIN.SOFT_SAMPLING_ON: <NEW_LINE> <INDENT> cls_prob, loss_cls = model.net.SoftmaxWithLoss( ['cls_score', 'labels_int32', 'label_weights'], ['cls_prob', 'loss_cls'], scale=model.GetLossScale() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cls_prob, loss_cls ... | Add losses for RoI classification and bounding box regression. | 625941d27c178a314d6ef60a |
def __init__( self, name: str, ): <NEW_LINE> <INDENT> DSLExecutable.__init__(self) <NEW_LINE> self.name = name <NEW_LINE> self._type = None <NEW_LINE> log.debug(f"Creating {self!r}") | Initialize the DSLFragment.
:param name: the name of the fragment
:type name: str | 625941d2cc40096d61595afa |
def attr_list_min_eager_fallback(a, name=None, ctx=None): <NEW_LINE> <INDENT> _ctx = ctx if ctx else _context.context() <NEW_LINE> if not isinstance(a, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'a' argument to " "'attr_list_min' Op, not %r." % a) <NEW_LINE> <DEDENT> a = [_execute.make_int(... | This is the slowpath function for Eager mode.
This is for function attr_list_min | 625941d24e696a04525c95f5 |
def create_feature_vectors(self): <NEW_LINE> <INDENT> length_of_bond_features = Molecule.num_bond_features() <NEW_LINE> length_of_atom_features = Molecule.num_atom_features() <NEW_LINE> self.local_input_vector = np.zeros( (self.no_of_atoms, self.no_of_atoms, Molecule.num_of_features())) <NEW_LINE> for idx in xrange(sel... | :return: | 625941d2956e5f7376d71016 |
def create_workflow(self): <NEW_LINE> <INDENT> get_model = self.client.get_model <NEW_LINE> workflow = get_model('Workflow')(data=get_model('WorkflowData')()) <NEW_LINE> workflow.data.engine_name = self.engine_name <NEW_LINE> workflow.data.on_failure_email = self.on_failure_email <NEW_LINE> workflow.data.on_started_ema... | Create a workflow object and set the on_failure_email, on_started_email,
on_success_email, and tags fields to the defaults.
:return: the workflow object | 625941d23cc13d1c6d3c7523 |
def mongod_program( logger, executable=None, process_kwargs=None, **kwargs): <NEW_LINE> <INDENT> executable = utils.default_if_none(executable, config.DEFAULT_MONGOD_EXECUTABLE) <NEW_LINE> args = [executable] <NEW_LINE> suite_set_parameters = kwargs.pop("set_parameters", {}) <NEW_LINE> if config.MONGOD_SET_PARAMETERS i... | Return a Process instance that starts mongod arguments constructed from 'kwargs'. | 625941d2090684286d50ee90 |
def t_ERROR_two(self, t): <NEW_LINE> <INDENT> if t.value in reserved: <NEW_LINE> <INDENT> t.type = reserved[t.value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t.type = "ERROR" <NEW_LINE> <DEDENT> return t | ((([+*/%\-][ \t\n]*[+\-/%*][ \t\n]*)+)([+*/\-%][ \t\n]*)*|([0-9][0-9]*[A-Za-z_]+)|([A-Z][A-Za-z0-9_]+)|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*) | 625941d2d99f1b3c44c67736 |
def get_instrument_config(telescope, instrument): <NEW_LINE> <INDENT> config_file = os.path.join(default_refdata_directory, telescope, instrument, 'config.json') <NEW_LINE> config = read_json(config_file, raise_except=True) <NEW_LINE> strip_meta(config) <NEW_LINE> return config | Get the instrument configuration.
Must have the pandeia_refdata env variable set and pointing to the reference data
Parameters
----------
telescope: string
Telescope identifier string. Currently supports jwst, wfirst, and hst.
instrument: string
Instrument identifier string.
Returns
-------
config: dict
I... | 625941d245492302aab5e46e |
def predict_classes(self, x, batch_size=32, verbose=1): <NEW_LINE> <INDENT> proba = self.predict(x, batch_size=batch_size, verbose=verbose) <NEW_LINE> if proba.shape[-1] > 1: <NEW_LINE> <INDENT> return proba.argmax(axis=-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (proba > 0.5).astype('int32') | Generate class predictions for the input samples.
The input samples are processed batch by batch.
Arguments:
x: input data, as a Numpy array or list of Numpy arrays
(if the model has multiple inputs).
batch_size: integer.
verbose: verbosity mode, 0 or 1.
Returns:
A numpy array of class predic... | 625941d2d10714528d5ffe8e |
def get_modified_time(storage, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> modified_time = storage.get_modified_time(name) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if modified_time and tim... | Get modified time from storage, ensuring the result is a timezone-aware
datetime. | 625941d24d74a7450ccd436d |
def usedCombos(self, partyCombos): <NEW_LINE> <INDENT> return [x for x in partyCombos if x.isVisibleTo(self)] | return all used player combos for this offense | 625941d291f36d47f21ac69d |
def setup(self): <NEW_LINE> <INDENT> super(TransformationNewtonLineSearchUMF,self).setup() <NEW_LINE> self.sysOfEqnSetup() <NEW_LINE> self.analysisSetup('static_analysis') | Defines the solution procedure in the finite element
problem object. | 625941d2925a0f43d254a022 |
def getPriority(self, mapping): <NEW_LINE> <INDENT> priority = sorted([ (k,v['priority']) for k,v in mapping.items() ], key=itemgetter(1), reverse=True ) <NEW_LINE> priority = [ k for k,v in priority ] <NEW_LINE> return priority | '
Make a sorted list of renderers by priority, highest to lowest
Args
mapping Field/Custom renderer map. | 625941d263d6d428bbe44699 |
def arccosh(x, *args, **kwargs): <NEW_LINE> <INDENT> pass | arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Inverse hyperbolic cosine, element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored.... | 625941d2d6c5a102081441f6 |
def subparser_hook(subparsers): <NEW_LINE> <INDENT> subparser = subparsers.add_parser('visualize', description=__doc__, help=main.__doc__) <NEW_LINE> subparser.set_defaults(func=main) <NEW_LINE> add_name(subparser) <NEW_LINE> subparser.add_argument('-f', '--format', help='File extension for graph file. Defaults to PNG'... | Hook to add subparser for this command. | 625941d2a79ad161976cc2ef |
@preprocessor <NEW_LINE> def _divide_columns(ctx, numerators, denominators): <NEW_LINE> <INDENT> xs = ctx.matrix.select_columns(numerators) <NEW_LINE> ys = ctx.matrix.select_columns(denominators) <NEW_LINE> xs.coerce(float) <NEW_LINE> ys.coerce(float) <NEW_LINE> for col_x, col_y in itertools.product(xs.columns, ys.colu... | Divides pairs of numerical columns, as long as the divisor column
does not contain any 0 values. | 625941d2d99f1b3c44c67737 |
def toPythonIndex(self, index, s=None): <NEW_LINE> <INDENT> w = self <NEW_LINE> te = self.widget <NEW_LINE> if index is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif g.isInt(index): <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> elif index == '1.0': <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> e... | This is much faster than versions using g.toPythonIndex. | 625941d23d592f4c4ed1d215 |
def __init__(self, windowSize, lexicon, filters=None): <NEW_LINE> <INDENT> startPadding = "PADDING" <NEW_LINE> self.__window = Window(lexicon, windowSize, startPadding) <NEW_LINE> self.__lexicon = lexicon <NEW_LINE> self.__filters = filters <NEW_LINE> for i in ["all_lower", "first_uppercased", "all_uppercased", "contai... | :type windowSize: int
:param windowSize: the size of window
:type lexicon: data.Lexicon.Lexicon
:param lexicon:
:type filters: list[DataOperation.Filters.Filter]
:param filters: | 625941d2dd821e528d63b352 |
def _create_object_from_params(self, lookup, params): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = {k: v() if callable(v) else v for k, v in params.items()} <NEW_LINE> obj = self.create(**params) <NEW_LINE> return obj, True <NEW_LINE> <DEDENT> except IntegrityError as e: <NEW_LINE> <INDENT> try: <NEW_LINE> <IN... | Try to create an object using passed params. Used by get_or_create()
and update_or_create(). | 625941d22ae34c7f2600d2db |
def parseOSISString( self, referenceString ): <NEW_LINE> <INDENT> if BibleOrgSysGlobals.debugFlag and debuggingThisModule: <NEW_LINE> <INDENT> print( t("parseReferenceString( {!r} )").format( referenceString ) ) <NEW_LINE> <DEDENT> match = re.search( OSIS_VERSE_RE, referenceString ) <NEW_LINE> if match: <NEW_LINE> <IND... | Parses a string, expecting something like "SA2_19:5b"
Returns True or False on success | 625941d2be8e80087fb20deb |
def findfile(start,name): <NEW_LINE> <INDENT> for relpath,dirs,files in os.walk(start, topdown=True): <NEW_LINE> <INDENT> if name in files: <NEW_LINE> <INDENT> return os.path.join(start,relpath,name) <NEW_LINE> <DEDENT> <DEDENT> raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), start+name) | :param start:
:param name:
:return: | 625941d260cbc95b062c66ed |
def request(method, url, fields=None, headers=None): <NEW_LINE> <INDENT> return _DEFAULT_POOL.request(method, url, fields=fields, headers=headers) | A convenience, top-level request method. It uses a module-global ``PoolManager`` instance.
Therefore, its side effects could be shared across dependencies relying on it.
To avoid side effects create a new ``PoolManager`` instance and use it instead.
The method does not accept low-level ``**urlopen_kw`` keyword argument... | 625941d210dbd63aa1bd2d4e |
def _validate_database(self, discipline_name, group_name, attempts): <NEW_LINE> <INDENT> query = "SELECT attempts FROM achievements WHERE discipline_name = '{}' AND group_name = '{}'".format(discipline_name, group_name) <NEW_LINE> stored_attempts = self.DB_Handler.get_results(query) <NEW_LINE> stored_attempts = [ x[0] ... | Validates the stored Elements in the database
This is done by comparing the attemps paramters to the string stored in the database
...
Paramters
---------
discipline_name: str
Name of the Discipline
group_name: str
Name of the Group
attempts: str
String of all attempts from all Athletes of this group | 625941d250812a4eaa59c4cb |
def __init__(self, info_dict=None, hyper_params=None, reuse=False, is_saving=True, init_graph=True, mode='train', name='BASIC_DNN'): <NEW_LINE> <INDENT> super(BasicDNNModel, self).__init__() <NEW_LINE> self.is_saving = is_saving <NEW_LINE> self.init_graph = init_graph <NEW_LINE> try: <NEW_LINE> <INDENT> assert mode == ... | build basic dnn model
@param info_dict: None,
@param hyper_params: hyper parameters,
@param reuse: reuse the variables or not
@param is_saving: option for saving weights
@param init_graph: initialize graph
@param mode: enable a mode for run the model, 'train' or 'test'
@param name: model name | 625941d2099cdd3c635f0e05 |
def small(self): <NEW_LINE> <INDENT> self.set_dayu_size(dayu_theme.small) <NEW_LINE> return self | Set MDateTimeEdit to small size | 625941d2e5267d203edcde46 |
def set_AutoCorrect(self, value): <NEW_LINE> <INDENT> super(GetPastEventsInputSet, self)._set_input('AutoCorrect', value) | Set the value of the AutoCorrect input for this Choreo. ((optional, boolean) Transform misspelled artist names into correct artist names. The corrected artist name will be returned in the response. Defaults to 0.) | 625941d296565a6dacc8f875 |
def get_connectentry_is_time(self): <NEW_LINE> <INDENT> return self._connectentry_is_time | Get connectentry_is_time. | 625941d257b8e32f52483645 |
def test_dummy_clf(self): <NEW_LINE> <INDENT> X, Y, Z = self.create_bin_data() <NEW_LINE> self.check_task("RC s=most_frequent", X, Y, Z, transform=False, standardize=False) | Smoke test for classification. | 625941d24f88993c3716c210 |
def predictions(dataframe, features_list=['Hour', 'weekday', 'rain']): <NEW_LINE> <INDENT> features = dataframe.reset_index(drop=True)[features_list] <NEW_LINE> dummy_units = pd.get_dummies(dataframe.reset_index(drop=True)['UNIT'], prefix='unit') <NEW_LINE> features = features.join(dummy_units) <NEW_LINE> values = data... | The NYC turnstile data is stored in a pandas dataframe called
weather_turnstile.
Using the information stored in the dataframe, let's predict the
ridership of
the NYC subway using linear regression with gradient descent.
You can download the complete turnstile weather dataframe here:
https://www.dropbox.com/s/meyki2wl... | 625941d2a17c0f6771cbe1fa |
def __repr__(self): <NEW_LINE> <INDENT> return '<Leam {} {}>'.format(self.league_id, self.team_name) | Meaningless | 625941d28a349b6b435e831e |
def scan_student(all_students): <NEW_LINE> <INDENT> scanned_num = input('[Scan/Enter] Student ID: ') <NEW_LINE> try: <NEW_LINE> <INDENT> scanned_num = int(scanned_num) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('[WARNING] Invalid ID number!') <NEW_LINE> return None <NEW_LINE> <DEDENT> if scanned_n... | Asks for the input from a single student and looks up the associated name.
The input can be typed in manually or scanned with a USB scanner
:param all_students: a dictionary of form {name: id} for all the students
:returns: date-time of scan, last name, first name, grede, and ID number of student scanned | 625941d28a43f66fc4b5420e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.