code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def writeFile(fn,d): <NEW_LINE> <INDENT> log("writeFile: "+fn) <NEW_LINE> try: <NEW_LINE> <INDENT> p = os.path.dirname(fn) <NEW_LINE> os.makedirs(p,exist_ok=True) <NEW_LINE> f = open(fn,"b+w") <NEW_LINE> w = f.write(d) <NEW_LINE> f.close() <NEW_LINE> log("writeFile: "+str(w)+" of "+str(len(d))+" written") <NEW_LINE> <D... | Creates a file with data | 625941c5a8370b771705289b |
def terminate_connection(self, connection_name): <NEW_LINE> <INDENT> sa = OrderedDict(ike=connection_name) <NEW_LINE> try: <NEW_LINE> <INDENT> logs = self.session.terminate(sa) <NEW_LINE> for log in logs: <NEW_LINE> <INDENT> message = log['msg'].decode('ascii') <NEW_LINE> yield OrderedDict(message=message) <NEW_LINE> <... | :param connection_name:
:type connection_name: str | 625941c5f8510a7c17cf96f7 |
def evaluate_runtime(self, test_runtime): <NEW_LINE> <INDENT> mn,mx = self.attrs.get( 'runtime_range', [None,None] ) <NEW_LINE> if mn != None and test_runtime < mn: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if mx != None and test_runtime > mx: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | If a runtime range is specified in this object, the given runtime is
evaluated against that range. False is returned only if the given
runtime is outside the specified range. | 625941c53c8af77a43ae379a |
def retrieveArticles(self, url, pickleFile=None): <NEW_LINE> <INDENT> self.logger.debug('Retrieving info from ' + url) <NEW_LINE> response = requests.get(url) <NEW_LINE> jsonData = json.loads(json.dumps(response.json())) <NEW_LINE> if str(jsonData['status']).lower() == "ok": <NEW_LINE> <INDENT> return jsonData <NEW_LIN... | Retrieves news articles from the URL and dumps them if file is passed | 625941c54d74a7450ccd41bf |
def parse_suggest_form_data(form_data, card_key_prefix): <NEW_LINE> <INDENT> n_suggestions = int(form_data['dropdown-suggestions']) <NEW_LINE> unique_top_code_levels = int(form_data['dropdown-variability']) <NEW_LINE> cards = [] <NEW_LINE> for key in form_data.keys(): <NEW_LINE> <INDENT> if card_key_prefix in key: <NEW... | [summary]
Args:
form_data ([type]): [description]
card_key_prefix ([type]): [description]
Returns:
[type]: [description] | 625941c5099cdd3c635f0c57 |
def users(self): <NEW_LINE> <INDENT> return self._campfire.users(self.name) | Lists the users chatting in the room.
Returns a set of the users. | 625941c56e29344779a6260f |
def create_lead_matrix(data): <NEW_LINE> <INDENT> N, time_steps = data.shape <NEW_LINE> lead_matrix = zeros((N, N)) <NEW_LINE> upper_triangle = [(i, j) for i in range(N) for j in range(i + 1, N)] <NEW_LINE> for (i, j) in upper_triangle: <NEW_LINE> <INDENT> x, y = data[i], data[j] <NEW_LINE> d = x.dot(cyc_diff(y)) - y.d... | Create the lead matrix from the data. | 625941c5a8370b771705289c |
def histogramme_T2m(self): <NEW_LINE> <INDENT> self.type_de_carte = "histo_T2m" <NEW_LINE> self.construire_Noms() <NEW_LINE> compteur = 0 <NEW_LINE> tures = np.arange(103, dtype='f') <NEW_LINE> ctures = np.arange(103) <NEW_LINE> for t_fichier in (12,24,36,48,60,72,84,96,102): <NEW_LINE> <INDENT> nom_fichier = self.nom_... | Renvoie un diagramme de la température à deux mètres (°C) prévu par Arome 0.025°.
Crée une figure unique qui courvre toutes les échéances (les échéances d'Arome 0.025°
sont au pas de temps horaire), renvoie et sauvegarde le diagramme. | 625941c5cb5e8a47e48b7aa7 |
def ScalerMode(self, dwelltime=None, numframes=1): <NEW_LINE> <INDENT> print("Putting Area Detector to ScalerMode" , self.prefix) <NEW_LINE> try: <NEW_LINE> <INDENT> self.cam.put('TriggerMode', 'Internal') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.cam.put('ImageMode', 'Sin... | set to scaler mode: ready for step scanning
Arguments:
dwelltime (None or float): dwelltime per frame in seconds [1.0]
numframes (None or int): number of frames to collect [1]
Notes:
1. numframes should be 1, unless you know what you're doing.
2. Files will be saved by the file saver
| 625941c54e696a04525c9447 |
def authenticatedQuery(myUsername,myPsswd,queryString,outputFileName="out.vot", retrieve=False): <NEW_LINE> <INDENT> str_login = "curl -k -c cookies.txt -X POST -d username=%s -d password=%s -L \"%stap-server/login\" " % (myUsername,myPsswd,gacsurl) <NEW_LINE> str_query = "curl -k -b cookies.txt -i -X POST --data \"PHA... | Send a query to GACS using Authenticated access and check for progress
Parameters
----------
myUsername : string
user name
myPsswd : string
password
queryString : string
string to be sent to GACS
outputFileName : string, optional
file to write results to
retrieve : {True, False}
flag to trigger res... | 625941c5f9cc0f698b1405f8 |
def seed(self, seed=None): <NEW_LINE> <INDENT> self.par_env.seed(seed) | Seed the environment | 625941c5507cdc57c6306cd3 |
def test_054_range_proper_subset1(self): <NEW_LINE> <INDENT> q = IbendportconQuery(self.p, range_="s4:c1,c2", range_subset=True, range_proper=True) <NEW_LINE> ibendportcons = sorted(n.name for n in q.results()) <NEW_LINE> self.assertListEqual(["test54"], ibendportcons) | Ibendportcon query with context range proper subset match | 625941c5a79ad161976cc141 |
def ldap_tear_down(): <NEW_LINE> <INDENT> ldap = entities.AuthSourceLDAP().search() <NEW_LINE> for ldap_auth in range(len(ldap)): <NEW_LINE> <INDENT> users = entities.User(auth_source=ldap[ldap_auth]).search() <NEW_LINE> for user in range(len(users)): <NEW_LINE> <INDENT> users[user].delete() <NEW_LINE> <DEDENT> ldap[ld... | Teardown the all ldap settings user, usergroup and ldap delete | 625941c5fb3f5b602dac368d |
def make_time(year, month, day, time): <NEW_LINE> <INDENT> if time == '2400': <NEW_LINE> <INDENT> time = '0000' <NEW_LINE> <DEDENT> time = time.zfill(4) <NEW_LINE> return dateutil.parser.parse('{}-{}-{}-{}'.format(year, month, day, time)) | Given a year, month, day, and time (hhmm format), parse and return the
corresponding datetime object. | 625941c5187af65679ca511a |
def search_da(name: str, sentence: str) -> bool: <NEW_LINE> <INDENT> da_list = ['說', '調查', '辦理', '偵訊', '訊問', '諭令', '指揮', '提起', '指出', '表示', '搜索', '認定', '認為', '獲報', '接獲', '依據', '報告', '拿出', '負責'] <NEW_LINE> if re.search(f'(檢察官|員警|警察|律師|監委|廳長)(...、)?{name}(、...)?則?({"|".join(da_list)})', sentence): <NEW_LINE> <INDENT> retu... | 搜索pattern: "(職業)(人名)(指定動作)"
可允許兩人姓名中間有、,再多就不行了。 | 625941c58e7ae83300e4afc7 |
def wrapper(self, amp_list): <NEW_LINE> <INDENT> if isinstance(amp_list, list) and all(isinstance(elem, (int, float, complex)) for elem in amp_list): <NEW_LINE> <INDENT> if round(numpy.sum(numpy.square(numpy.absolute(amp_list))) - 1, 10) == 0: <NEW_LINE> <INDENT> return function(self, amp_list) <NEW_LINE> <D... | Method to set new coefficients for the possible states of the register. The input
parameter is a list of real or complex number and their squared sum must be equal to 1.
Number of elements in the least must be equal with the number of possible states.
Arguments:
amp_list {list} -- List of int, float or complex o... | 625941c5ff9c53063f47c1f0 |
def load_data(data_dir, subject_nb=1, session_nb=1, sfreq=256., ch_ind=[0, 1, 2, 3], stim_ind=5, replace_ch_names=None): <NEW_LINE> <INDENT> if subject_nb == 'all': <NEW_LINE> <INDENT> subject_nb = '*' <NEW_LINE> <DEDENT> if session_nb == 'all': <NEW_LINE> <INDENT> session_nb = '*' <NEW_LINE> <DEDENT> data_path = os.pa... | Load CSV files from the /data directory into a Raw object.
Args:
data_dir (str): directory inside /data that contains the
CSV files to load, e.g., 'auditory/P300'
Keyword Args:
subject_nb (int or str): subject number. If 'all', load all
subjects.
session_nb (int or str): session number. If... | 625941c5bd1bec0571d9062b |
def __getattr__(self, name): <NEW_LINE> <INDENT> return self.get_ideal(name) | EXAMPLES::
sage: sd = SymbolicData() # optional - database_symbolic_data
sage: sd.Cyclic5 # optional - database_symbolic_data
Traceback (most recent call last):
...
AttributeError: No ideal matching 'Cyclic5' found in database.
sage: sd.Cyclic_5 # optional - database_symbolic_data
Ideal (v + w + ... | 625941c5eab8aa0e5d26db53 |
def test_skip(): <NEW_LINE> <INDENT> print('Testing skip()') <NEW_LINE> result = funcs.skip('hello world',1) <NEW_LINE> introcs.assert_equals('hello world',result) <NEW_LINE> result = funcs.skip('hello world',2) <NEW_LINE> introcs.assert_equals('hlowrd',result) <NEW_LINE> result = funcs.skip('hello world',3) <NEW_LINE>... | Test procedure for function skip(). | 625941c5a17c0f6771cbe04d |
def setUp(self): <NEW_LINE> <INDENT> if not self.prepared: <NEW_LINE> <INDENT> Object.objects.all().delete() <NEW_LINE> try: <NEW_LINE> <INDENT> self.group = Group.objects.get(name='test') <NEW_LINE> <DEDENT> except Group.DoesNotExist: <NEW_LINE> <INDENT> Group.objects.all().delete() <NEW_LINE> self.group = Group(name=... | Initial Setup | 625941c563d6d428bbe444eb |
def test_kde_from_json(self, simple_storage_model): <NEW_LINE> <INDENT> model = simple_storage_model <NEW_LINE> kde = load_recorder( model, { "type": "GaussianKDEStorageRecorder", "node": "Storage", "target_volume_pc": 0.2, }, ) <NEW_LINE> model.run() <NEW_LINE> pdf = kde.to_dataframe() <NEW_LINE> p = kde.aggregated_va... | Test loading KDE recorder from JSON data. | 625941c538b623060ff0ade9 |
def Stop(self): <NEW_LINE> <INDENT> total_run_time = int((Now() - self._start_time).total_seconds()) <NEW_LINE> self.LogOnceOnStop(DEVAPPSERVER_CATEGORY, STOP_ACTION, value=total_run_time) <NEW_LINE> self.LogBatch(self._log_once_on_stop_events.itervalues()) | Ends a Google Analytics session for the current client. | 625941c5d58c6744b4257c5c |
def _decide_who_will_move_out(self): <NEW_LINE> <INDENT> spouse1, spouse2 = self.subjects <NEW_LINE> config = spouse1.sim.config <NEW_LINE> if spouse1.male: <NEW_LINE> <INDENT> if random.random() < config.chance_a_male_divorcee_is_one_who_moves_out: <NEW_LINE> <INDENT> spouse_who_will_move_out = spouse1 <NEW_LINE> <DED... | Decide which of the divorcees will move out. | 625941c55f7d997b87174a92 |
def in_both_tables(title: str, cur, conn) -> bool: <NEW_LINE> <INDENT> return in_myanimelist_table(title, cur, conn) and in_youtube_table(title, cur, conn) | Check if the title populates both tables in the database. | 625941c52eb69b55b151c8a9 |
@bot.event <NEW_LINE> @asyncio.coroutine <NEW_LINE> def on_member_unban(server: discord.Server, user: discord.User): <NEW_LINE> <INDENT> log.warning("{1.name} (ID:{1.id}) was unbanned from {0.name}".format(server, user)) <NEW_LINE> yield from send_log_message(bot, server, "**{0.name}#{0.discriminator}** was unbanned.".... | Chamado sempre que um membro é desbanido de um servidor. | 625941c58e7ae83300e4afc8 |
def process_rpm_ql_line(line_str, allowed_keys): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name, key_str = line_str.split(' ', 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> logger.error("Failed to split line '{0}".format(repr(line_str))) <NEW_LINE> return False <NEW_LINE> <DEDENT> if name in no_key_p... | Checks single line of rpm-ql for correct keys
:param line_str: line to process
:param allowed_keys: list of allowed keys
:return: bool | 625941c51d351010ab855b18 |
def __init__(self, data_vector, index): <NEW_LINE> <INDENT> self.data_vector = data_vector <NEW_LINE> self._index = index <NEW_LINE> self._visited = False <NEW_LINE> self._belongs_to_cluster = False <NEW_LINE> self._noise = False | data_vector is a numpy matrix
index should be the unique index in the original matrix
:param data_vector: | 625941c57b25080760e39456 |
def fix_for_issue29(data, key): <NEW_LINE> <INDENT> if data.ca.items[key][3] is not None: <NEW_LINE> <INDENT> data.ca.items[key][3] = None | Fix issue#29. | 625941c58a43f66fc4b54062 |
def merge_data(dict_data_alpha, dict_data_beta, primary_key): <NEW_LINE> <INDENT> dict_data_combo = dict_data_alpha.copy() <NEW_LINE> for alpha in dict_data_combo: <NEW_LINE> <INDENT> for beta in dict_data_beta: <NEW_LINE> <INDENT> if alpha[primary_key] == beta[primary_key]: <NEW_LINE> <INDENT> alpha.update(beta) <NEW_... | Method to merge the data in two python dictionaries together | 625941c515baa723493c3f70 |
def last_ship(ship, row): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> for i in range(len(row)): <NEW_LINE> <INDENT> if row[i] == ship: <NEW_LINE> <INDENT> index = i <NEW_LINE> <DEDENT> <DEDENT> return index | (str, list of str) -> int
Precondition: row.count(ship) > 0
Return the last index of ship in the list row.
>>> last_ship('d', [EMPTY, 'd', 'd', 'd'])
3
>>> last_ship('a', ['a', EMPTY, EMPTY, EMPTY, 'a', EMPTY])
4
# Note the impossible case: in fact, this helper function will be used to
# detect cases in which su... | 625941c50a366e3fb873e815 |
def unlock(self): <NEW_LINE> <INDENT> vi_ctype = _visatype.ViSession(self._vi) <NEW_LINE> error_code = self._library.niFgen_UnlockSession(vi_ctype, None) <NEW_LINE> errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=True) <NEW_LINE> return | unlock
Releases a lock that you acquired on an device session using
lock. Refer to lock for additional
information on session locks. | 625941c5a4f1c619b28b0038 |
def ShutdownDevices(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("ShutdownDevices", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.ShutdownDevicesResponse() <NE... | 关闭服务器
:param request: 调用ShutdownDevices所需参数的结构体。
:type request: :class:`tencentcloud.bm.v20180423.models.ShutdownDevicesRequest`
:rtype: :class:`tencentcloud.bm.v20180423.models.ShutdownDevicesResponse` | 625941c5e64d504609d7483c |
def start_pwm(self): <NEW_LINE> <INDENT> self._pwm = GPIO.PWM(self.pin_number,self.frequency) <NEW_LINE> self._pwm.start(self.duty_cycle) | Start pulse width modulation running (using self.frequency and
self.duty_cycle). | 625941c5004d5f362079a330 |
def CASE6( self, main ): <NEW_LINE> <INDENT> import json <NEW_LINE> import time <NEW_LINE> respFlowId = 1 <NEW_LINE> main.case( "Delete the Group and Flow added through Rest api " ) <NEW_LINE> main.step( "Deleting Group and Flows" ) <NEW_LINE> ctrl = main.Cluster.active( 0 ) <NEW_LINE> response = ctrl.REST.getFlows( de... | Deleting the Group and Flow | 625941c5be383301e01b5485 |
def __init__(self, key, txt=None, doc=None, url=None, lang=None, otherparams=None, extraheaders=None, server='https://api.meaningcloud.com/'): <NEW_LINE> <INDENT> if server[len(server)-1] != '/': <NEW_LINE> <INDENT> server += '/' <NEW_LINE> <DEDENT> self._params = {} <NEW_LINE> meaningcloud.Request.__init__(self, (serv... | ParserRequest constructor
:param key:
License key
:param txt:
Text to use in the API calls
:param doc:
File to use in the API calls
:param url:
Url to use in the API calls
:param lang:
Language used in the request
:param otherparams:
Array where other params can be added to be used in the API c... | 625941c592d797404e304186 |
def paint_footers(self): <NEW_LINE> <INDENT> with open(self.footer_include, 'r') as h: <NEW_LINE> <INDENT> footer_lines = h.readlines() <NEW_LINE> <DEDENT> for file in self.include_pages: <NEW_LINE> <INDENT> with open(file, 'r+') as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> try: <NEW_LINE> <INDENT> begin ... | Crawl directories for webpages. Possibly have a '_include.py' file to streamline this.
Look for `<!--FOOTER BEGINS HERE-->` and `<!--FOOTER ENDS HERE-->` using readlines.
Replace block with standard `footer_include.txt` file.
Save file. | 625941c5eab8aa0e5d26db54 |
def soft_update(self, local_model, target_model, tau): <NEW_LINE> <INDENT> for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): <NEW_LINE> <INDENT> target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data) | Soft update model parameters.
θ_target = τ*θ_local + (1 - τ)*θ_target
θ_target = θ_target + τ*(θ_local - θ_target)
θ_local = r + gamma * θ_local(s+1)
Params
======
local_model (PyTorch model): weights will be copied from
target_model (PyTorch model): weights will be copied to
tau (float): interpolation par... | 625941c555399d3f055886af |
def mult_mat_mat(*args): <NEW_LINE> <INDENT> if len(args) == 2: <NEW_LINE> <INDENT> a, b = args <NEW_LINE> return [[sum(ae*be for ae, be in zip(a_row, b_col)) for b_col in zip(*b)] for a_row in a] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return mult_mat_mat(args[0], mult_mat_mat(*args[1:])) | Multiply two matrices for any indexable types. | 625941c5fb3f5b602dac368e |
def update_graph(self): <NEW_LINE> <INDENT> self.patt_img.delete("flash") <NEW_LINE> self.patt_img.delete("xaxis") <NEW_LINE> min_fpi_ms = 0 <NEW_LINE> for i in range(1, len(self.temp_patt.flash_list)): <NEW_LINE> <INDENT> flshnum = self.temp_patt.flash_list[i] <NEW_LINE> if flshnum is not None: <NEW_LINE> <INDENT> thi... | Redraw the graph of the pattern. The x-axis is also redrawn in case
the flash pattern interval changes. | 625941c526068e7796caecd9 |
def getDisplayedImage(self): <NEW_LINE> <INDENT> if not self._savedExpression or self._savedExpression == "x": <NEW_LINE> <INDENT> self._savedExpression = "x" <NEW_LINE> image = self.image <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for f in vigra.ufunc.__all__: <NEW_LINE> <INDENT> exec('from vigra.ufunc import %s' %... | Returns the displayed image and the normalize flag
(BYTE or NBYTE) as tuple/pair.
Note that the returned image is the original image if no
expression is applied, i.e. you should not change the returned
object. If active, the expression is applied via
eval() on every call of getDisplayedImage(). | 625941c5be7bc26dc91cd5ff |
def __init__(self, src=u'', container=None): <NEW_LINE> <INDENT> RTAtom.__init__(self, src, container) | Marks the beginning of an optional Key area which does not
affect the roman numeral analysis. (For instance, it is
possible to analyze in Bb major, while remaining in g minor)
>>> possibleKey = romanText.rtObjects.RTOptionalKeyOpen('?(Bb:')
>>> possibleKey
<RTOptionalKeyOpen '?(Bb:'>
>>> possibleKey.getKey()
<music21... | 625941c5379a373c97cfab40 |
def remove_peaks(self, two_theta, intensities): <NEW_LINE> <INDENT> is_peak = np.zeros_like(two_theta, dtype=bool) <NEW_LINE> for peak in self.peak_ranges: <NEW_LINE> <INDENT> is_peak = np.logical_or( is_peak, np.logical_and(two_theta>=peak[0], two_theta<=peak[1]) ) <NEW_LINE> <DEDENT> red_two_theta = two_theta[~is_pea... | Remove peaks from the dataset, leaving only the background.
Returns
=======
two_theta
Two theta array with only non-peak values.
intensities
Intensity array with only non-peak values. | 625941c5cc40096d6159594d |
def mtm_cross_spectrum(tx, ty, weights, sides='twosided'): <NEW_LINE> <INDENT> N = tx.shape[-1] <NEW_LINE> if ty.shape != tx.shape: <NEW_LINE> <INDENT> raise ValueError('shape mismatch between tx, ty') <NEW_LINE> <DEDENT> if isinstance(weights, (list, tuple)): <NEW_LINE> <INDENT> autospectrum = False <NEW_LINE> weights... | The cross-spectrum between two tapered time-series, derived from a
multi-taper spectral estimation.
Parameters
----------
tx, ty : ndarray (K, ..., N)
The complex DFTs of the tapered sequence
weights : ndarray, or 2-tuple or list
Weights can be specified as a length-2 list of weights for spectra tx
and ty r... | 625941c5287bf620b61d3a61 |
def message_user(self, request, message, level=messages.INFO, extra_tags='', fail_silently=False): <NEW_LINE> <INDENT> if not isinstance(level, int): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> level = getattr(messages.constants, level.upper()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> levels = me... | Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a s... | 625941c56aa9bd52df036d9f |
def rest_configure_ntp(self, ntp_server): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = test.Test() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c = t.controller('master') <NEW_LINE> try: <NEW_LINE> <INDENT> url = '/rest/v1/model/ntp-server/' <NEW_LINE> c... | Configure NTP server
Inputs:
ntp_server: Name of NTP server
Returns: True if configuration is successful, false otherwise | 625941c5f7d966606f6a9fff |
def run_episode( envnmt: AssortmentEnvironment, actor: Agent, n_steps: int, ) -> Tuple[np.ndarray, dict]: <NEW_LINE> <INDENT> envnmt.reset() <NEW_LINE> actor.reset() <NEW_LINE> top_item = envnmt.top_item <NEW_LINE> rewards = np.zeros(n_steps) <NEW_LINE> for ix in tqdm(range(n_steps)): <NEW_LINE> <INDENT> assortment = a... | :param n_steps: simulation horizon
:return:
rewards = 1D numpy array of size (horizon,)
with entries = expected_reward from action taken given env parameters | 625941c5a219f33f34628968 |
def Dispose(self): <NEW_LINE> <INDENT> pass | Dispose(self: GZipStream, disposing: bool)
Releases the unmanaged resources used by the System.IO.Compression.GZipStream and optionally
releases the managed resources.
disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources. | 625941c5d6c5a10208144046 |
def cache_graph(self): <NEW_LINE> <INDENT> if self._cache_key == tuple(self.edges): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._edges_by_parent = defaultdict(list) <NEW_LINE> for (source, edge_name, target) in self.edges: <NEW_LINE> <INDENT> self._edges_by_parent[source].append((target, edge_name)) <NEW_LINE> ... | Precompute edges indexed by parent or child | 625941c58a349b6b435e8170 |
def make_thinner(interval): <NEW_LINE> <INDENT> last = None <NEW_LINE> def thinner(curr): <NEW_LINE> <INDENT> nonlocal last <NEW_LINE> if last is None or curr - last >= interval: <NEW_LINE> <INDENT> last = curr <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT... | Return a thinner function for the given interval.
The function should be called with sequential values;
if the value should be used, the function will return True,
if ignored, False.
:param interval: Interval; whatever makes sense for the values passed in.
:return: Thinner function. | 625941c582261d6c526ab499 |
def check_environment(): <NEW_LINE> <INDENT> options = type('Options', (object,), {})() <NEW_LINE> options.ci_flags = os.getenv('CI_FLAGS', '') <NEW_LINE> options.aws_region = os.getenv('DEFAULT_AWS_REGION', 'eu-central-1') <NEW_LINE> options.gateway = os.getenv('DCOS_ADVANCED_GATEWAY', None) <NEW_LINE> options.vpc = o... | Test uses environment variables to play nicely with TeamCity config templates
Grab all the environment variables here to avoid setting params all over
Returns:
object: generic object used for cleanly passing options through the test
Raises:
AssertionError: if any environment variables or resources are missing... | 625941c50fa83653e4656fb8 |
def get_assets(self): <NEW_LINE> <INDENT> return self | Get assets | 625941c53317a56b86939c58 |
def describe_pet(animal_type, pet_name): <NEW_LINE> <INDENT> print("\nI have a " + animal_type + ".") <NEW_LINE> print("My " + animal_type + "'s name is " + pet_name.title() + ".") | Выводит информацию о животном. | 625941c58c0ade5d55d3e9b6 |
def s_one_one(topics): <NEW_LINE> <INDENT> s_one_one_res = [] <NEW_LINE> for top_words in topics: <NEW_LINE> <INDENT> s_one_one_t = [] <NEW_LINE> for w_prime_index, w_prime in enumerate(top_words): <NEW_LINE> <INDENT> for w_star_index, w_star in enumerate(top_words): <NEW_LINE> <INDENT> if w_prime_index == w_star_index... | This function performs s_one_one segmentation on a list of topics.
s_one_one segmentation is defined as: s_one_one = {(W', W*) | W' = {w_i}; W* = {w_j}; w_i, w_j belongs to W; i != j}
Example:
>>> topics = [np.array([1, 2, 3]), np.array([4, 5, 6])]
>>> s_one_pre(topics)
[[(1, 2), (1, 3), (2, 1), (2, 3), (3... | 625941c556b00c62f0f14655 |
def addon_remove(module=""): <NEW_LINE> <INDENT> pass | Delete the add-on from the file system
:param module: Module, Module name of the add-on to remove
:type module: string, (optional, never None) | 625941c5442bda511e8be417 |
def __get_obs_e_from_obs(obs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> e = obs.select(channel='E')[0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> h = obs.select(channel='H')[0] <NEW_LINE> d = obs.select(channel='D')[0] <NEW_LINE> e = __get_trace('E', d.stats, ChannelConverter.get_obs_e_from_obs(h.data, d.data)... | Get trace containing observatory E component.
Returns E if found, otherwise computes E from H,D.
Parameters
----------
obs : obspy.core.Stream
observatory components (E) or (H, D).
Returns
-------
obspy.core.Trace
observatory component E. | 625941c54e696a04525c9448 |
def _pop_last_line(file_obj): <NEW_LINE> <INDENT> bytes_from_end = 1 <NEW_LINE> file_obj.seek(0, 2) <NEW_LINE> length = file_obj.tell() + 1 <NEW_LINE> while bytes_from_end < length: <NEW_LINE> <INDENT> file_obj.seek((-1) * bytes_from_end, 2) <NEW_LINE> data = file_obj.read() <NEW_LINE> if bytes_from_end == length - 1 a... | Utility function to get the last line from a file (shared between ADB and
SUT device managers). Function also removes it from the file. Intended to
strip off the return code from a shell command. | 625941c526238365f5f0ee69 |
def test_07(self): <NEW_LINE> <INDENT> sine = ns.Sine(100) <NEW_LINE> b = ns.Buffer(100) <NEW_LINE> b << sine.generate(1.0, 2.0) <NEW_LINE> data = ns.Buffer(b) <NEW_LINE> data(data > 0.5).set(0.5); <NEW_LINE> data(data < -0.5).set(-0.5); <NEW_LINE> gold_fn = fn("gold/Buffer_out1.wav") <NEW_LINE> gold = ns.Buffer(gold_f... | Buffer advanced operator | 625941c507f4c71912b1147e |
def is_safe_path(path: str, follow_symlinks: bool = True) -> bool: <NEW_LINE> <INDENT> base_dir = app.config['DATA_DIRECTORY'] <NEW_LINE> if follow_symlinks: <NEW_LINE> <INDENT> return os.path.realpath(path).startswith(base_dir) <NEW_LINE> <DEDENT> return os.path.abspath(path).startwith(base_dir) | Checks `completePath` to ensure that it lives inside the exposed /data
directory. | 625941c5711fe17d8254236b |
def path_chessboard_images(name_dir): <NEW_LINE> <INDENT> return _path_images(name_dir, dtype="chessboard") | According to the plant number return a dict[id_camera][angle] containing
filename of the raw image.
:return: dict[id_camera][angle] of filename | 625941c563f4b57ef000111a |
def REST_instantiate(self,param): <NEW_LINE> <INDENT> return param | instantiate a REST resource based on the id
this method MUST be overridden in your class. it will be passed
the id (from the url fragment) and should return a model object
corresponding to the resource.
if the object doesn't exist, it should return None rather than throwing
an error. if this method returns None and i... | 625941c529b78933be1e56ab |
def build(exp, tag, force, **params): <NEW_LINE> <INDENT> sim_root = SIM_PATH.joinpath(exp, tag) <NEW_LINE> script_root = SCRIPT_PATH.joinpath(exp, tag) <NEW_LINE> script_file = script_root.joinpath("script.json") <NEW_LINE> noise_file = script_root.joinpath("noise.npy") <NEW_LINE> force_file = script_root.joinpath("fo... | Create a simulation script. | 625941c563b5f9789fde70e2 |
def get_data_in_project(self, project_id, visibility_filter=None, filter_value=None): <NEW_LINE> <INDENT> resulted_data = [] <NEW_LINE> try: <NEW_LINE> <INDENT> query = self.session.query(model.DataType ).join((model.Operation, model.Operation.id == model.DataType.fk_from_operation) ).join(model.Algorithm).join(model.A... | Get all the DataTypes for a given project, including Linked Entities and DataType Groups.
:param visibility_filter: when not None, will filter by DataTye fields
:param filter_value: when not None, will filter with ilike multiple DataType string attributes | 625941c5ab23a570cc25017e |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 12 <NEW_LINE> (_x.header.seq, _x.header.stamp.secs, _x.header.st... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941c5ac7a0e7691ed40cc |
@pytest.fixture <NEW_LINE> def sample_dir(): <NEW_LINE> <INDENT> return pathlib.Path(__file__).resolve().parent / "samples" | Returns the pathlib.Path of the samples directory. | 625941c5236d856c2ad447d5 |
def test_create_user_success(self): <NEW_LINE> <INDENT> mw = [] <NEW_LINE> headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} <NEW_LINE> r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) <NEW_LINE> assert_equal(r1.status, 200) <NE... | ACCOUNT (REST): send a POST to create a new user | 625941c5b7558d58953c4f14 |
def _transform(self, identity_values): <NEW_LINE> <INDENT> def extract_groups(groups_by_domain): <NEW_LINE> <INDENT> for groups in groups_by_domain.values(): <NEW_LINE> <INDENT> for group in {g['name']: g for g in groups}.values(): <NEW_LINE> <INDENT> yield group <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def normalize_user... | Transform local mappings, to an easier to understand format.
Transform the incoming array to generate the return value for
the process function. Generating content for Keystone tokens will
be easier if some pre-processing is done at this level.
:param identity_values: local mapping from valid evaluations
:type identi... | 625941c5d18da76e235324d1 |
def POST(self, *args, **kwargs): <NEW_LINE> <INDENT> return BadRequest() | Return a 400, unless implemented (per spec). | 625941c532920d7e50b281cc |
def store_values(self): <NEW_LINE> <INDENT> for feature in self.features: <NEW_LINE> <INDENT> row = self.listbox_rows[feature] <NEW_LINE> is_active = row[COL_SWITCH].get_active() <NEW_LINE> self.settings.set("feature_" + feature, is_active) <NEW_LINE> if is_active: <NEW_LINE> <INDENT> logging.debug("Feature '%s' has be... | Get switches values and store them | 625941c50383005118ecf5e0 |
def episode_delta(self): <NEW_LINE> <INDENT> pass | Return max absolute change in values. Don't change values. | 625941c5a79ad161976cc142 |
@api.route('/deployments/inv/<string:subsite>/<string:node>', methods=['GET']) <NEW_LINE> def get_deployment_sensors(subsite, node): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sensors_list = _get_deployment_sensors(subsite, node) <NEW_LINE> return jsonify({'sensors': sensors_list}) <NEW_LINE> <DEDENT> except Exceptio... | Get list of deployment sensors in inventory for a mooring and node.
Sample
request: http://localhost:4000/uframe/deployments/inv/CE01ISSM/MFC31
response:
{
"sensors": [
{
"array": "Coastal Endurance",
"key": "00-CPMENG000",
"name": "Platfor... | 625941c516aa5153ce362475 |
def update_type_and_attribute_ids(self): <NEW_LINE> <INDENT> self.get_type_name_map() <NEW_LINE> if len(self.input_network.types)>0: <NEW_LINE> <INDENT> self.input_network.types = [self.network_template_type] <NEW_LINE> <DEDENT> for n_j in self.input_network.nodes: <NEW_LINE> <INDENT> self.name_maps['NODE'][n_j.name] =... | For each node, link and group in the network change its attribute ID to
the newly created positive ID, and do the same with their type ID. | 625941c57b180e01f3dc47fd |
def _set_condition( self, cr, uid, inv_id, commentid, key, partner_id=False ): <NEW_LINE> <INDENT> if not commentid: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if not partner_id: <NEW_LINE> <INDENT> raise osv.except_osv( _('No Customer Defined !'), _('Before choosing condition text select a customer.')) <NEW_LIN... | Set the text of the notes in invoices | 625941c5596a897236089abf |
def create_server(helper, name=None, imageRef=None, flavorRef=None, metadata=None, diskConfig=None, body_override=None, region="ORD", key_name=None, request_func=json_request): <NEW_LINE> <INDENT> body = body_override <NEW_LINE> if body is None: <NEW_LINE> <INDENT> data = { "name": name if name is not None else 'test_s... | Create a server with the given body and returns the response object and
body.
:param name: Name of the server - defaults to "test_server"
:param imageRef: Image of the server - defaults to "test-image"
:param flavorRef: Flavor size of the server - defaults to "test-flavor"
:param metadata: Metadata of the server - opt... | 625941c5460517430c394186 |
def xvals(self): <NEW_LINE> <INDENT> return self.Ls | Returns a list of the x-values | 625941c501c39578d7e74e38 |
def write(self, address, data): <NEW_LINE> <INDENT> if address > 127 or address < 0: <NEW_LINE> <INDENT> raise ValueError("Tried to transmit to an invalid I2C address!") <NEW_LINE> <DEDENT> data = bytes(data) <NEW_LINE> write_status = self.api.write(address, data) <NEW_LINE> return write_status | Sends data over the I2C bus.
Args:
address -- The 7-bit I2C address for the target device.
Should not contain read/write bits. Can be used to address
special addresses, for now; but this behavior may change.
data -- The data to be sent to the given device. | 625941c53539df3088e2e347 |
def op_table(gr): <NEW_LINE> <INDENT> return { 'inv': inv(gr), 'mul': mul(gr), 'add': add(gr), 'sub': sub(gr), 'exp': exp(gr), 'log': log(gr), } | TODO: Use this instead of anything else. | 625941c5cc0a2c11143dce8d |
def create_epic_mmen_dataset(caption_type, is_train=True, batch_size=EPIC_MMEN.batch_size, num_triplets=EPIC_MMEN.num_triplets, action_dataset=False, is_test=False): <NEW_LINE> <INDENT> is_train_str = 'train' if is_train else 'validation' <NEW_LINE> if is_test: <NEW_LINE> <INDENT> is_train_str = 'test' <NEW_LINE> <DEDE... | Creates a mmen dataset object for EPIC2020 using default locations of feature files and relational dicts files. | 625941c5bde94217f3682def |
def default_loader(data: str, img_size: tuple, crop=None, extension=None, rotate=None, cached=False, random_offset=False, random_scale=False, point_indices=None): <NEW_LINE> <INDENT> if not cached: <NEW_LINE> <INDENT> _data = SingleImage.from_files(data, extension=extension) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Helper Function to load single sample
Parameters
----------
data : str or :class:`SingleImage2D`
image file to load
img_size : tuple
image size for resizing
crop : None or float
if None: nor cropping will be applied
if float: specifies boundary proportion for cropping
extension : str or None:
speci... | 625941c53d592f4c4ed1d06e |
def new(num_buckets=256): <NEW_LINE> <INDENT> aMap = [] <NEW_LINE> for i in range(0, num_buckets): <NEW_LINE> <INDENT> aMap.append([]) <NEW_LINE> return aMap | Initializes a Map with the given number of buckets. | 625941c50fa83653e4656fb9 |
def _prepare_host_call_fn(self, processed_t_fetches, op_fetches, graph, graph_summary_tag): <NEW_LINE> <INDENT> if self._parameters.trace_dir is None: <NEW_LINE> <INDENT> raise ValueError('Provide a trace_dir for tensor tracer in summary mode. ' '--trace_dir=/model/dir') <NEW_LINE> <DEDENT> def _write_cache(step, event... | Creates a host call function that will write the cache as tb summary.
Args:
processed_t_fetches: List of tensor provided to session.run.
op_fetches: List of operations provided to session.run.
graph: TensorFlow graph.
graph_summary_tag: the summary_tag name for the given graph.
Raises:
ValueError if trace_di... | 625941c524f1403a92600b65 |
def create_consumer(self, topic, proxy, fanout=False): <NEW_LINE> <INDENT> raise NotImplementedError() | Create a consumer on this connection. | 625941c57b180e01f3dc47fe |
def test_update1(self): <NEW_LINE> <INDENT> pass | Test case for update1
Update CRF version for current Study based on auth token provided # noqa: E501 | 625941c5956e5f7376d70e6b |
def likelihood(self, x, mean, cov, pi): <NEW_LINE> <INDENT> l = 0 <NEW_LINE> for _k in range(self.k): <NEW_LINE> <INDENT> l += self.gaussian(x, mean[_k], cov[_k]) * pi[_k] <NEW_LINE> <DEDENT> l = np.sum(np.log(l)) <NEW_LINE> return l | Calculate likelihood. | 625941c5adb09d7d5db6c78d |
def __init__(self, site, search_time=10): <NEW_LINE> <INDENT> self.site = site <NEW_LINE> self.__search_time = int(search_time)+1 | site:支持nyaa或者sukebei, search_time:搜索页面范围 | 625941c5d7e4931a7ee9df1a |
def route_exist(self, route): <NEW_LINE> <INDENT> err, out = self.openshift_exec("get routes", output="json") <NEW_LINE> try: <NEW_LINE> <INDENT> routes_in_os = json.loads(out) <NEW_LINE> for route_os in routes_in_os["items"]: <NEW_LINE> <INDENT> if route_os["spec"]["to"]["name"] == self.app.deploy_name and route_os["s... | Verifies if the route exists in the current project
Args:
route: the route to verify
Returns:
True if exists, False otherwise | 625941c5ff9c53063f47c1f1 |
def draw_text(c, text, color, x_left, y_center, align=LEFT, max_w=None, shadow=None): <NEW_LINE> <INDENT> text = fit_text(c, text, max_w) <NEW_LINE> if not text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> x_bearing, y_bearing, text_width, text_height, x_advance, y_advance = c.text_extents(text) <NEW_LINE> if not ma... | :param c: cairo drawing context
:param text: the text to draw
:param color: list or tuple with RGB or RGBA colors, floats from 0.0 to 1.0
:param x_left: left end of text space
:param y_center: vertical center of text space
:param align: 'left', 'center', 'right'
:param max_w: maximum width the text might use, set this ... | 625941c5de87d2750b85fd8f |
def process_character_replace(self): <NEW_LINE> <INDENT> if not self.last_selected: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.last_selected == self.DIRECTORY: <NEW_LINE> <INDENT> progress_message = self.char_replace.process_directory(self.directory_path) <NEW_LINE> <DEDENT> elif self.last_selected == self.... | Call the char replace operation on directory or file selected. | 625941c521a7993f00bc7cea |
def print_bytes(byte_str): <NEW_LINE> <INDENT> if isinstance(byte_str, str): <NEW_LINE> <INDENT> print(byte_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(str(byte_str, encoding='utf8')) | Prints a string or converts bytes to a string and then prints. | 625941c5adb09d7d5db6c78e |
def shared_window(self): <NEW_LINE> <INDENT> return self.in_shared_window | is the editor running in a window which could be shared with
another editor instance (because it is a shell window,
and this instance could be suspended or closed)
Usually false for GUI editors.
Note: remote editors running in a remote display
which appears as a single window to be local operating system
(X servers ... | 625941c56fece00bbac2d73a |
def get_md5_hexdigest(email): <NEW_LINE> <INDENT> return hashlib.md5(email).hexdigest()[0:30] | Return an md5 hash for a given email.
The length is 30 so that it fits into Django's ``User.username`` field. | 625941c5cb5e8a47e48b7aa9 |
def is_special_token(self, token): <NEW_LINE> <INDENT> special_tokens = set([ "[CLS]", "[SEP]", "[PAD]", "[Q]", "[YES]", "[NO]", "[NoLongAnswer]", "[NoShortAnswer]", "[SA]", "[/SA]", "[UNK]", "[CLS]", "[SEP]", "[MASK]" ]) <NEW_LINE> if token in special_tokens: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if toke... | Is this a special token reserved for BERT or TyDi QA modeling? | 625941c5e8904600ed9f1f29 |
@account.route('/oauth') <NEW_LINE> def account_oauth(): <NEW_LINE> <INDENT> code = request.args.get('code') <NEW_LINE> if not code: <NEW_LINE> <INDENT> abort(500) <NEW_LINE> <DEDENT> config = current_app.config <NEW_LINE> url = config.get('GITHUB_TOKEN_ACCESS_URL') <NEW_LINE> params = { 'client_id': config.get('GITHUB... | oauth 注册
:return: | 625941c53617ad0b5ed67ef6 |
def _call_transaction(conn, *args, **kwargs): <NEW_LINE> <INDENT> failed = False <NEW_LINE> result = [] <NEW_LINE> can_validate = False <NEW_LINE> can_commit_confirmed = False <NEW_LINE> has_candidate_datastore = False <NEW_LINE> for i in conn.server_capabilities: <NEW_LINE> <INDENT> if "urn:ietf:params:netconf:capabil... | Function to edit device configuration in a reliable fashion using
capabilities advertised by NETCONF server.
:param target: (str) name of datastore to edit configuration for, if no
``target`` argument provided and device supports candidate datastore uses
``candidate`` datastore, uses ``running`` datastore othe... | 625941c5d99f1b3c44c6758e |
def relative_rate(self): <NEW_LINE> <INDENT> return _blocks_swig5.rms_cf_sptr_relative_rate(self) | relative_rate(rms_cf_sptr self) -> double | 625941c5dd821e528d63b1a8 |
def training(loss, learning_rate, grad_norm, common_var, ten_var) : <NEW_LINE> <INDENT> tvars_common = common_var <NEW_LINE> tvars_ten = ten_var <NEW_LINE> grads_common, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars_common), grad_norm) <NEW_LINE> grads_ten, _ = tf.clip_by_global_norm(tf.gradients(loss, tvar... | args:
loss
learning_rate: it should be a placeholder
grad_norm: max grad norm
return :
train_op | 625941c58e05c05ec3eea371 |
def iexclusive(self,*others): <NEW_LINE> <INDENT> self._data = segment_exclusive( self._data, *others ) <NEW_LINE> return self | Exclude other segments (in place).
Extracts parts of segments that do not overlap with any other
segment. Will remove overlaps as a side effect.
Parameters
----------
*others : segment arrays | 625941c521bff66bcd684952 |
def build_model( cfg ) : <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> model.add( Cropping2D(cropping=((70,25), (0,0)) , input_shape=INPUT_SHAPE ) ) <NEW_LINE> model.add( Lambda(lambda x : x / 255.0 - 0.5) ) <NEW_LINE> model.add( Convolution2D(24, (5,5), strides=(2,2), activation="relu") ) <NEW_LINE> model.add( C... | Heavily inspired by code in Behavioral Cloning,
section 15. Even More Powerful Network
Just added dropout | 625941c5a8ecb033257d30cb |
def valid_station(station: str): <NEW_LINE> <INDENT> station = station.strip() <NEW_LINE> if len(station) != 4: <NEW_LINE> <INDENT> raise BadStation('ICAO station idents must be four characters long') <NEW_LINE> <DEDENT> uses_na_format(station) | Checks the validity of a station ident
This function doesn't return anything. It merely raises a BadStation error if needed | 625941c5498bea3a759b9aad |
def load(self): <NEW_LINE> <INDENT> return self.application | Load configuration. | 625941c5a05bb46b383ec821 |
def _append_xml(self, asset, context, inst_mode, uber_xml ): <NEW_LINE> <INDENT> snapshot = Snapshot.get_latest_by_sobject(asset, context) <NEW_LINE> loader_context = ProdLoaderContext() <NEW_LINE> loader_context.set_context(context) <NEW_LINE> loader_context.set_option('instantiation', inst_mode) <NEW_LINE> loader = l... | append xml to the uber_xml | 625941c5d4950a0f3b08c34e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.