content
stringlengths
22
815k
id
int64
0
4.91M
def general_string_parser(content_string, location): """ Parse the given string of endpoint/method/header/body content * search for all parameters in this string ** all params are replaced with a starting and ending symbol of non priority tag * evaluate what type of parameter it is: ** en...
5,327,200
def get_compare_collection(name, csv_line): """get compare collection data""" session = tables.get_session() if session is None: return {'isExist': False} response = {} try: collection_table = CollectionTable() cid = collection_table.get_field_by_key(CollectionTable.collectio...
5,327,201
def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ...
5,327,202
def scheming_multiple_choice_output(value): """ return stored json as a proper list """ if isinstance(value, list): return value try: return json.loads(value) except ValueError: return [value]
5,327,203
def logmap(x, x0): """ This functions maps a point lying on the manifold into the tangent space of a second point of the manifold. Parameters ---------- :param x: point on the manifold :param x0: basis point of the tangent space where x will be mapped Returns ------- :return: vecto...
5,327,204
def test_mg_k009_mg_k009_v(mode, save_output, output_format): """ TEST :model groups (ALL) : sequence: with 5 elements, all elements appeared and are in defined order """ assert_bindings( schema="msData/modelGroups/mgK009.xsd", instance="msData/modelGroups/mgK009.xml", class_...
5,327,205
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
5,327,206
def test_template_raw(device_raw, template, op): """Configurable test with template file. The rollback[+-no] operation specifies an index in a list of all commits that have been performed in this function. This means that rollback-1 will undo the last commit, rollback+0 will undo all commits, etc. ...
5,327,207
def evaluate_models_exploratory(X_normal:np.ndarray, X_te:np.ndarray, X_adv_deepfool:np.ndarray, X_adv_fgsm:np.ndarray, X_adv_pgd:np.ndarray, X_adv_dt:np.n...
5,327,208
def REMA_mosaic_r1_1_tile(dir_REMA,tile_name,dem_out,filter_params=None,format_out='GTiff',tgt_EPSG=3031,tgt_res=None,nodata_out=-9999,interp_method=None,geoid=False,tag_lonlat_tile=False,path_tile_index=None,tag_merge=False,tag_clip=False): """ :param dir_REMA: path to parent directory "8m" containing subdire...
5,327,209
def clear_data_home(data_home=None): """Delete all the content of the data home cache.""" data_home = get_data_home(data_home) shutil.rmtree(data_home)
5,327,210
def get_files_endpoint(entity_name): """ Given an entity name, generate a flask_restful `Resource` class. In `create_api_endpoints()`, these generated classes are registered with the API e.g. `api.add_resource(get_files_endpoint("Dataset"), "/datasets/<string:pid>/files")` :param entity_name: Name ...
5,327,211
def get_name(path): """get the name from a repo path""" return re.sub(r"\.git$", "", os.path.basename(path))
5,327,212
def abs_path(*paths): """Get the absolute path of the given file path. Args: *paths: path parts. Returns: An abs path string. """ return os.path.abspath(os.path.join(script_dir, '..', *paths))
5,327,213
def is_valid_shipping_method( checkout: Checkout, lines: Iterable["CheckoutLineInfo"], discounts: Iterable[DiscountInfo], subtotal: Optional["TaxedMoney"] = None, ): """Check if shipping method is valid and remove (if not).""" if not checkout.shipping_method: return False if not chec...
5,327,214
async def load_gdq_index(): """ Returns the GDQ index (main) page, includes donation totals :return: json object """ return (await load_gdq_json(f"?type=event&id={config['event_id']}"))[0]['fields']
5,327,215
def deleteRestaurantForm(r_id): """Create form to delete existing restaurant Args: r_id: id extracted from URL """ session = createDBSession() restaurant = session.query(Restaurant).get(r_id) if restaurant is None: output = ("<p>The restaurant you're looking for doesn't exist.<...
5,327,216
def password_account(data): """Modify account password. etcd_key: <ETCD_PREFIX>/account/<name> data: {'name': , 'pass': , 'pass2': } """ t_ret = (False, '') s_rsc = '{}/account/{}'.format(etcdc.prefix, data['name']) try: r = etcdc.read(s_rsc) except etcd.EtcdKeyNotFound as e: ...
5,327,217
def split_pkg(pkg): """nice little code snippet from isuru and CJ""" if not pkg.endswith(".tar.bz2"): raise RuntimeError("Can only process packages that end in .tar.bz2") pkg = pkg[:-8] plat, pkg_name = pkg.split("/") name_ver, build = pkg_name.rsplit("-", 1) name, ver = name_ver.rsplit(...
5,327,218
def depart(visitor: DocxTranslator, node: None): """Finish processing note node""" assert isinstance(visitor, DocxTranslator) assert isinstance(node, Node) visitor.p_style.pop() visitor.p_level -= 1
5,327,219
def gaussian(k, x): """ gaussian function k - coefficient array, x - values """ return k[2] * np.exp( -(x - k[0]) * (x - k[0]) / (2 * k[1] * k[1])) + k[3]
5,327,220
def get_physical_locator(context, record_dict): """Get physical locator that matches the supplied uuid.""" try: query = context.session.query(models.PhysicalLocators) physical_locator = query.filter_by( uuid=record_dict['uuid'], ovsdb_identifier=record_dict['ovsdb_identif...
5,327,221
def coins(n, arr): """ Counting all ways e.g.: (5,1) and (1,5) """ # Stop case if n < 0: return 0 if n == 0: return 1 ways = 0 for i in range(0, len(arr)): ways += coins(n - arr[i], arr) return ways
5,327,222
def function_tracing_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[Lambda.2] Lambda functions should use active tracing with AWS X-Ray""" iterator = paginator.paginate() for page in iterator: iso8601Time = datetime.datetime.now(datetime.timezone.utc).isoformat...
5,327,223
def compute_diff(old, new): """ Compute a diff that, when applied to object `old`, will give object `new`. Do not modify `old` or `new`. """ if not isinstance(old, dict) or not isinstance(new, dict): return new diff = {} for key, val in new.items(): if key not in old: ...
5,327,224
def test_init_params(): """ armedcheckswitch.py: Test __init__() with different parameters """ s1 = ArmedCheckSwitch(switched=True, armed=False) assert s1.is_switched() == True assert s1.is_armed() == False s2 = ArmedCheckSwitch(switched=False, armed=False) assert s2.is_switched() == Fa...
5,327,225
def append_and_output_per_file(args, dataset_name, eval_results, results_list): """ append results to a list, and output them; these results are associated to a single file :param args: the command line arguments, containing several options :param dataset_name: name of the dataset (or file) to which the...
5,327,226
def get_file_to_dict(fliepath,splitsign,name): """ 读取对应路径的文件,如果没有则创建 返回dict,splitsign为分隔符 """ if os.path.exists(fliepath+name+'.txt'): dict = {} with open(fliepath+name+'.txt',mode='r',encoding='utf-8') as ff: try: list = ff.read().splitlines() ...
5,327,227
def main(): """Start the server then tick in loop. """ address = "/run/com_handler.sock" try: os.unlink(address) except: if os.path.exists(address): raise socket.setdefaulttimeout(0.01) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(address...
5,327,228
def assign_nuts1_to_lad(c, lu=_LAD_NUTS1_LOOKUP): """Assigns nuts1 to LAD""" if c in lu.keys(): return lu[c] elif c[0] == "S": return "Scotland" elif c[0] == "W": return "Wales" elif c[0] == "N": return "Northern Ireland" else: return np.nan
5,327,229
async def get_all_persons(): """List of all people.""" with Session(DB.engine) as session: persons = session.query(Person).all() return [p.to_dict() for p in persons]
5,327,230
def main(): """ Main method of the sample Tango client. """ #This is for client object creation. Here, "sys/tg_test/1" is the fqdn of the device. print("Creating client of TangoTest device.") client_sample = TangoClient("sys/tg_test/1") #This invokes command on the device server in synchro...
5,327,231
def pivot_pull(pull: List[Dict[str, str]]): """Pivot so columns are measures and rows are dates.""" parsed_pull = parse_dates(pull) dates = sorted(list(set(row["sample_date"] for row in parsed_pull))) pivot = list() for date in dates: row = {"sample_date": date} observations = [row f...
5,327,232
def test_init_variations(): """Check that 3 ways of specifying a time + small offset are equivalent""" dt_tiny_sec = dt_tiny.jd2 * 86400. t1 = Time(1e11, format='cxcsec') + dt_tiny t2 = Time(1e11, dt_tiny_sec, format='cxcsec') t3 = Time(dt_tiny_sec, 1e11, format='cxcsec') assert t1.jd1 == t2.jd1...
5,327,233
def evaluate(data, model_path: str, dest_path: str, neighborhood_size: int, batch_size: int, endmembers_path: str, use_ensemble: bool = False, ensemble_copies: int = 1, noise_params: str = None, voting: ...
5,327,234
def _location_sensitive_score(W_query, W_fil, W_keys): """Impelements Bahdanau-style (cumulative) scoring function. This attention is described in: J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben- gio, “Attention-based models for speech recognition,” in Ad- vances in Neural Information Processing...
5,327,235
def dh_noConv( value, pattern, limit ): """decoding helper for a single integer value, no conversion, no rounding""" return dh( value, pattern, encNoConv, decSinglVal, limit )
5,327,236
def chooseFile(): """ Parameters ---------- None No parameters are specified. Returns ------- filenames: tuple A tuple that contains the list of files to be loaded. """ ## change the wd to dir containing the script curpath = os.path.dirname(os.path...
5,327,237
def downgrade(): """Unapply Add scheduling_decision to DagRun and DAG""" with op.batch_alter_table('dag_run', schema=None) as batch_op: batch_op.drop_index('idx_last_scheduling_decision') batch_op.drop_column('last_scheduling_decision') batch_op.drop_column('dag_hash') with op.batch...
5,327,238
def reward_strategy(orig_reward, actualperf, judgeperf, weight={'TP':1, 'TN': 1, 'FP': -1, 'FN':-1}): """ """ assert list(weight.keys()) == ['TP', 'TN', 'FP', 'FN'], "Please assign weights to TP, TN, FP and FN." # assert sum(weight.values()) == 0, "Summation of weight values needs to be 0." if actua...
5,327,239
def test_enqueue(dog_q): """test enqueue""" dog_q.enqueue('cat') assert dog_q.newest.val == 'cat' assert dog_q._len == 6
5,327,240
def get_user_ids_from_primary_location_ids(domain, location_ids): """ Returns {user_id: primary_location_id, ...} """ result = ( UserES() .domain(domain) .primary_location(location_ids) .non_null('location_id') .fields(['location_id', '_id']) .run().hits ...
5,327,241
def test_environment_repeated(): """Check the last value of repeated environment variables is used...""" with build_pypgf(srcdir / "repeated", "basic.py") as res: assert res.returncode == 0, "Environment variables not set correctly."
5,327,242
def log_prov_es(job, prov_es_info, prov_es_file): """Log PROV-ES document. Create temp PROV-ES document to populate attributes that only the worker has access to (e.g. PID).""" # create PROV-ES doc to generate attributes that only verdi know ps_id = "hysds:%s" % get_uuid(job['job_id']) bundle_i...
5,327,243
def get_next_states(state: State): """Create new states, but prioritize the following: asdjkgnmweormelfkmw Prioritize nothing... """ out = [] # First we check hallways. for i in HALLWAY_IND: # Check if the room has any crabs hall = state.rooms[i] if hall.is_empty(...
5,327,244
def _build_trainstep(fcn, projector, optimizer, strategy, temp=1, tau_plus=0, beta=0, weight_decay=0): """ Build a distributed training step for SimCLR or HCL. Set tau_plus and beta to 0 for SimCLR parameters. :model: Keras projection model :optimizer: Keras optimizer :strategy: tf.dis...
5,327,245
def main(): """ Main entry point of the app """ # logger.info("Logging for {__name__}.main()") # If module will never be run as script from terminal (command line), then you can # delete this block of code. # Check to see if read_args() function exists (defined above). If so, read the command-l...
5,327,246
def GatherToDataframe( session, analysis, version , save = True, **kwargs ): """ Load external data (pickle files mostly) into a session dataframe or series of session dataframes columns. You can specify the analysis type and version of that analysis you want to get loaded and saved inside a sessiondatafra...
5,327,247
def predict( gpu, gpu_allow_growth, ckpt_path, mode, batch_size, log_dir, sample_label, config_path, ): """ Function to predict some metrics from the saved model and logging results. :param gpu: str, which env gpu to use. :param gpu_allow_growth: bool, whether to allow gp...
5,327,248
def get_environment(): """ Light-weight routine for reading the <Environment> block: does most of the work through side effects on PETRglobals """ ValidExclude = None ValidInclude = None ValidOnly = True ValidPause = 0 #PETRglobals.CodeWithPetrarch1 = True #PETRglobals.CodeWithPetrarch2...
5,327,249
def test_filtering_pipeline_ml( mocker, dummy_context, pipeline_with_tag, pipeline_ml_with_tag, tags, from_nodes, to_nodes, node_names, from_inputs, ): """When the pipeline is filtered by the context (e.g calling only_nodes_with_tags, from_inputs...), it must return a Pipeli...
5,327,250
def create_variables_from_samples(sample_z_logits, sample_z_logp, sample_b, batch_index, sequence_index): """ Create the variables for RELAX control variate. Assumes sampled tokens come from decoder. :param sample_z_logits: [B,T,V] tensor containing sampled processed logits created by stacking logits during...
5,327,251
def register_sensor(name): """ Registers a new sensor. :param name The name of the sensor """ message = "REGISTER:" + name + '\n' sock.sendall(message) return
5,327,252
def test_post_ar(client): """Assert that business for regular (not xpro) business is correct to spec.""" headers = {'content-type': 'application/json'} fake_filing = ANNUAL_REPORT fake_filing['filing']['business']['identifier'] = 'CP0001965' fake_filing['filing']['annualReport']['annualGeneralMeetin...
5,327,253
def get2DHisto_(detector,plotNumber,geometry): """ This function opens the appropiate ROOT file, extracts the TProfile2D and turns it into a Histogram, if it is a compound detector, this function takes care of the subdetectors' addition. Note that it takes plotNumber as opposed to plot ...
5,327,254
def binlog2sql(request): """ 通过解析binlog获取SQL :param request: :return: """ instance_name = request.POST.get('instance_name') save_sql = True if request.POST.get('save_sql') == 'true' else False instance = Instance.objects.get(instance_name=instance_name) no_pk = True if request.POST.g...
5,327,255
def test_retrieve_sentry_logs_nostacktrace(): """Test retrieve sentry logs.""" responses.add(responses.GET, 'https://sentry.devshift.net/api/0/projects/' 'sentry/fabric8-analytics-production/issues/' '?statsPeriod=24h', json=sen...
5,327,256
def save_fig(fig, name, path, tight_layout=True): """ Saves a `matplotlib.pyplot.figure` as pdf file. :param matplotlib.pyplot.figure fig: instance of a `matplotlib.pyplot.figure` to save :param str name: filename without extension :param str path: path where the figure is saved, if None the figure...
5,327,257
def smtp_config_generator_str(results, key, inp): """ Set server/username config. :param kwargs: Values. Refer to `:func:smtp_config_writer`. :type kwargs: dict :param key: Key for results dict. :type key: str :param inp: Input question. :type inp: str """ if results[key] is N...
5,327,258
def delete_object_by_name(name, ignore_errors=False): """ Attempts to find an object by the name given and deletes it from the scene. :param name: the name of this object :param ignore_errors: if True, no exception is raised when the object is deleted. Otherwise, you will get a ...
5,327,259
def default_rollout_step(policy, obs, step_num): """ The default rollout step function is the policy's compute_action function. A rollout step function allows a developer to specify the behavior that will occur at every step of the rollout--given a policy and the last observation from the env--to d...
5,327,260
def perfilsersic(r_e, I_e, n, r): """Evaluate a Sersic Profile. funcion que evalua a un dado radio r el valor de brillo correspondiente a un perfil de sersic r_e : Radio de escala I_e : Intensidad de escala n : Indice de Sersic r : Radio medido desde el centr...
5,327,261
def background_profile(img, smo1=30, badval=None): """ helper routine to determine for the rotated image (spectrum in rows) the background using sigma clipping. """ import numpy as np from scipy import interpolate bgimg = img.copy() nx = bgimg.shape[1] # number of points in dire...
5,327,262
def get_object(bucket,key,fname): """Given a bucket and a key, upload a file""" return aws_s3api(['get-object','--bucket',bucket,'--key',key,fname])
5,327,263
def test_fetchyaml_with_destination_encoding_config(): """Get encoding from config.""" context = Context({ 'keyhere': {'sub': ['outkey', 2, 3], 'arbk': 'arbfile'}, 'fetchYaml': { 'path': '/arb/{keyhere[arbk]}', 'key': '{keyhere[sub][0]}'}}) with patch('pypyr.steps.fe...
5,327,264
def find_file(filename): """ This helper function checks whether the file exists or not """ file_list = list(glob.glob("*.txt")) if filename in file_list: return True else: return False
5,327,265
def read(fname): """Read a file and return its content.""" with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read()
5,327,266
def run(room, spawn): # type: (RoomMind, StructureSpawn) -> None """ Activates the spawner, spawning what's needed, as determined by the RoomMind. Manages deciding what parts belong on what creep base as well. :type room: rooms.room_mind.RoomMind :type spawn: StructureSpawn :type """ ...
5,327,267
def tweetnacl_crypto_secretbox(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_secretbox_xsalsa20po...
5,327,268
def parameterized_dropout(probs: Tensor, mask: Tensor, values: Tensor, random_rate: float = 0.5, epsilon: float = 0.1) -> Tensor: """ This function returns (values * mask) if random_rate == 1.0 and (value...
5,327,269
def get_auto_scale_v_core(resource_group_name: Optional[str] = None, vcore_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutoScaleVCoreResult: """ Represents an instance of an auto scale v-core resource. Latest API...
5,327,270
def fix_python_dylib_for_pkg(self): """change dylib ref to point to loader in package build format""" self.cmd.chdir(self.prefix) self.cmd.chmod(self.product.dylib) self.install_name_tool_id( f"@loader_path/../../../../support/{self.product.name_ver}/{self.product.dylib}", self.product.d...
5,327,271
def test_youtube_settings(mocker, settings): """ Test that Youtube object creation uses YT_* settings for credentials """ settings.YT_ACCESS_TOKEN = "yt_access_token" settings.YT_CLIENT_ID = "yt_client_id" settings.YT_CLIENT_SECRET = "yt_secret" settings.YT_REFRESH_TOKEN = "yt_refresh" m...
5,327,272
def text_output(xml,count): """Returns JSON-formatted text from the XML retured from E-Fetch""" xmldoc = minidom.parseString(xml.encode('utf-8').strip()) jsonout = [] for i in range(count): title = '' title = xmldoc.getElementsByTagName('ArticleTitle') title = parse_xml(title, i, '') pmid = '' pmid = xm...
5,327,273
def test_instantiations(): """@TODO: Docs. Contribution is welcome.""" r = Registry() r.add(foo) res = r.get_instance("foo", 1, 2)() assert res == {"a": 1, "b": 2} res = r.get_instance("foo", 1, b=2)() assert res == {"a": 1, "b": 2} res = r.get_instance("foo", a=1, b=2)() assert ...
5,327,274
def define_not_worked_days(list_of_days): """ Define specific days off Keyword arguments: list_of_days -- list of integer (0: Monday ... 6: Sunday) - default [5, 6] """ global NOT_WORKED_DAYS NOT_WORKED_DAYS = list_of_days return
5,327,275
def main(basic_files: list, start,increment,test): """ Renumber BASIC v2 Programs Support GOTO/GOSUB renumbering via a simple two-pass algorithm Known limitations: also renumber strings containing GOTO <number> because it is unable to skip quoted strings. Author: Giovanni G...
5,327,276
def datetime2str(target, fmt='%Y-%m-%d %H:%M:%S'): """ 将datetime对象转换成字符串 :param target: datetime :param fmt: string :return: string """ return datetime.datetime.strftime(target, fmt)
5,327,277
def periodic_targets_form(request, program): """ Returns a form for the periodic targets sub-section, used by the Indicator Form For historical reasons, the input is a POST of the whole indicator form sent via ajax from which a subset of fields are used to generate the returned template """ ...
5,327,278
def get_db(): """Returns an sqlite3.Connection object stored in g. Or creates it if doesn't exist yet.""" db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db
5,327,279
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" return isinstance(obj, basestring)
5,327,280
def _export_gene_set_pan_genome(meth, pan_genome_id): """Export orthologs from Pangenome as external FeatureSet objects. [26] :param pan_genome_id: ID of pangenome object [26.1] :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome :ui_name pan_genome_id: Pangenome ID :return: Generated Compare...
5,327,281
def launch_dashboard(): """Launch a dashboard displaying protocol summary and resource status.""" # Load the protocol & define a resource monitor instance (on local machine) protocol = MLEProtocol("mle_protocol.db") resource = MLEResource(resource_name="local", monitor_config={}) # You can also moni...
5,327,282
def collect_includes(formula): """ one of the most basic things to know about a module is which include files it comes with: e.g. for boost you're supposed to #include "boost/regex/foo.h", not #include "regex/foo.h" or #include "foo.h". For most modules this list of #includes c...
5,327,283
def get_log_by_date(log_file, log_capture_date, log_capture_date_option, log_capture_maxlen, log_min_level): """ capture log files based on capture_date before or after fields :param log_file: :param log_capture_date epoch formatted field in milliseconds :param log_capture_date_option: 'before', 'on...
5,327,284
def makeId(timestamp=0, machine=0, flow=0): """ using unix style timestamp, not python timestamp """ timestamp -= _base return (timestamp << 13) | (machine << 8) | flow
5,327,285
def write_dihed_to_file(structs, outname, verbose=True): """ Write the dihedral angles of a list of structures into a tab-separated file where each line represents a single structure and the columns alternate phi, psi angles for each residue :param structs: list of Structure objects :param outn...
5,327,286
def _get_token(cls, token_type): """ when token expire flush,return token value """ assert token_type in ['tenant_access_token', 'app_access_token'], token_type if not hasattr(cls.request, token_type) or hasattr(cls.request, token_type) or\ time.time() >= getattr(cls.request, token_t...
5,327,287
def crop_yield_plot(data_dict, savepath, quantiles=SOYBEAN_QUANTILES): """ For the most part, reformatting of https://github.com/JiaxuanYou/crop_yield_prediction/blob/master/6%20result_analysis/yield_map.py """ # load the svg file svg = Path('data/counties.svg').open('r').read() # Load into ...
5,327,288
def chunk(it: Iterator, size: int) -> Iterator: """ Nice chunking method from: https://stackoverflow.com/a/22045226 """ it = iter(it) return iter(lambda: tuple(islice(it, size)), ())
5,327,289
def sort_by_directory(path): """returns 0 if path is a directory, otherwise 1 (for sorting)""" return 1 - path.is_directory
5,327,290
def read_config(config): """ Read config file containing information of type and default values of fields :param config: path to config file :return: dictionary containing type and or default value for each field in the file """ dic_types = json.load(open(config, 'r')) ...
5,327,291
def is_right_hand_coordinate_system3(pose): """Checks whether the given pose follows the right-hand rule.""" n, o, a = pose[:3, 0], pose[:3, 1], pose[:3, 2] return n.dot(n).simplify() == 1 and o.dot(o).simplify() == 1 and a.dot(a).simplify() == 1 and sp.simplify(n.cross(o)) == a
5,327,292
def model_airmassfit(hjd, am, rawflux, limbB1, limB2, inc, period, a_Rs, Rp_Rs, show=False): """ Return the bestfit model for the lightcurve using 4 models of airmass correction: 1. model with no airmass correction 2. model with exponential airmass correction 3. model with linear airmass correction ...
5,327,293
def common_params_for_list(args, fields, field_labels): """Generate 'params' dict that is common for every 'list' command. :param args: arguments from command line. :param fields: possible fields for sorting. :param field_labels: possible field labels for sorting. :returns: a dict with params to pa...
5,327,294
def create_role(role, permissions=None): """Creates a Search Guard role. Returns when successfully created When no permissions are specified, we use some default cluster permissions. :param str role: Name of the role to create in Search Guard :param dict permissions: Search Guard role permissions (defa...
5,327,295
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) ...
5,327,296
def differences(sequence): """ Differences of the given sequence """ a, b = next(sequence), next(sequence) while True: yield b-a a,b = b,next(sequence)
5,327,297
def assign_bonus(client, bonus_list_path): """ Assign bonuses to group of workers. A csv file with following columns need to be provided: workerId, assignmentId, bonusAmount, reason :param client: boto3 client object for communicating to MTurk :param bonus_list_path: path to the csv file with f...
5,327,298
def decompress(obj): """Decompress LZSS-compressed bytes or a file-like object. Shells out to decompress_file() or decompress_bytes() depending on whether or not the passed-in object has a 'read' attribute or not. Returns a bytearray.""" if hasattr(obj, 'read'): return decompress_file(obj)...
5,327,299