code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def is_leaf(self, p): <NEW_LINE> <INDENT> return self.num_children(p) == 0 | Return True if Position p does not have any children | 625941c6ac7a0e7691ed40f4 |
def __init__(self): <NEW_LINE> <INDENT> self.EnableScan = None <NEW_LINE> self.ScanPathAll = None <NEW_LINE> self.ScanPathType = None <NEW_LINE> self.ScanPath = None <NEW_LINE> self.RequestId = None | :param EnableScan: 是否开启实时监控
:type EnableScan: bool
:param ScanPathAll: 扫描全部路径
注意:此字段可能返回 null,表示取不到有效值。
:type ScanPathAll: bool
:param ScanPathType: 当ScanPathAll为true 生效 0扫描以下路径 1、扫描除以下路径
注意:此字段可能返回 null,表示取不到有效值。
:type ScanPathType: int
:param ScanPath: 自选排除或扫描的地... | 625941c6cad5886f8bd26fff |
def make_app(include_packages: Sequence[str] = ()) -> Flask: <NEW_LINE> <INDENT> for package_name in include_packages: <NEW_LINE> <INDENT> import_submodules(package_name) <NEW_LINE> <DEDENT> app = Flask(__name__) <NEW_LINE> @app.errorhandler(ServerError) <NEW_LINE> def handle_invalid_usage(error: ServerError) -> Respon... | Creates a Flask app that serves up a simple configuration wizard. | 625941c63c8af77a43ae37c4 |
def testIdReprEval(self): <NEW_LINE> <INDENT> a = Id('bar') <NEW_LINE> self.assert_(a == eval(repr(a))) | eval(repr(Id())) | 625941c6cb5e8a47e48b7ad1 |
def graph_2007(): <NEW_LINE> <INDENT> date = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] <NEW_LINE> y_label = [0, 5000000, 10000000, 15000000, 20000000] <NEW_LINE> line_chart = pygal.Line(legend_at_bottom=True) <NEW_LINE> line_chart.title = 'Total Ridership of BTS 2007 (หน่วย : ... | plot graph with pygal | 625941c64428ac0f6e5ba817 |
def __init__(self, energy, index, mur, muv=None, magn=None): <NEW_LINE> <INDENT> self.energy = energy <NEW_LINE> self.index = index <NEW_LINE> self.mur = mur <NEW_LINE> self.muv = muv <NEW_LINE> self.magn = magn <NEW_LINE> self.fij = 1. | Parameters
----------
energy: float
Energy realtive to the ground state
index: int
Excited state index
mur: list of three floats or complex numbers
Length form dipole matrix element
muv: list of three floats or complex numbers or None
Velocity form dipole matrix element, default None
magn: list of three floats ... | 625941c629b78933be1e56d3 |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> name = config.get(CONF_NAME) <NEW_LINE> lat = config.get(CONF_LATITUDE, hass.config.latitude) <NEW_LINE> lon = config.get(CONF_LONGITUDE, hass.config.longitude) <NEW_LINE> key = config.get(CONF_API_KEY) <NEW_LINE> if None in (lat, l... | Set up the WorldTidesInfo sensor. | 625941c64c3428357757c34e |
def get_eline(self, name, config=True): <NEW_LINE> <INDENT> resp = self.ctrl.http_get_request( self.ctrl.get_req_url(config) + "/lumina-flowmanager-eline:elines/eline/{}".format(name)) <NEW_LINE> r = {} <NEW_LINE> if resp is not None: <NEW_LINE> <INDENT> r['status_code'] = resp.status_code <NEW_LINE> r['content'] = res... | Get a Flow Manager eline given the eline name
:param name: eline name to get
:return: response keywords (see add_eline for description) | 625941c621bff66bcd68497a |
def _training_options(parser): <NEW_LINE> <INDENT> model_options = [name for name in models.__dict__ if callable(models.__dict__[name])] <NEW_LINE> parser_train = parser.add_argument_group('TRAIN', 'Training Options') <NEW_LINE> parser_train.add_argument('--model-name', type=str, choices=model_options, default='CNN_bas... | Training options | 625941c6d6c5a1020814406f |
def train(ctx, cids, msday, meday, acquired): <NEW_LINE> <INDENT> name = 'random-forest-training' <NEW_LINE> log = logger(ctx, name) <NEW_LINE> aux = timeseries.aux(ctx=ctx, cids=cids, acquired=acquired) .filter('trends[0] NOT IN (0, 9)') .repartition(ccdc.PRODUCT_PARTITIONS).p... | Trains a random forest model for a set of chip ids
Args:
ctx: spark context
cids (sequence): sequence of chip ids [(x,y), (x1, y1), ...]
msday (int): ordinal day, beginning of training period
meday (int); ordinal day, end of training period
acquired (str): ISO8601 date range
Retu... | 625941c63317a56b86939c81 |
def create_wf_df(self, df_filter): <NEW_LINE> <INDENT> df_wf = pd.DataFrame() <NEW_LINE> wf_length_count = {} <NEW_LINE> for i, v in enumerate(df_filter['data_address']): <NEW_LINE> <INDENT> wf = self.read_waveform(v) <NEW_LINE> wf_len = len(wf) <NEW_LINE> if wf_len not in wf_length_count: <NEW_LINE> <INDENT> wf_length... | Given a DataFrame (i.e. df_filter) this method:
1) looks at the data_address column
2) send the address to read_waveform which retuns a 1 by x array of the waveform data points
3) the array is added to a DataFrame
4) the waveform, xi and ix is sent to calculate_time which returns an array of time (x) values
5) a time c... | 625941c67047854f462a1431 |
def update(self, instance, validated_data): <NEW_LINE> <INDENT> customer_name = validated_data.get('customer_name', instance.customer_name) <NEW_LINE> customer_address = validated_data.get('customer_address', instance.customer_address) <NEW_LINE> pizza_id = validated_data.get('pizza_id', instance.pizza.id) <NEW_LINE> p... | PUT/PATCH Support for full form update or partial Updates | 625941c61f5feb6acb0c4b77 |
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, security_key=None ): <NEW_LINE> <INDENT> super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context... | :param str api_key: The API key (AK) required by Baidu Map to perform
geocoding requests. API keys are managed through the Baidu APIs
console (http://lbsyun.baidu.com/apiconsole/key).
:param str scheme:
See :attr:`geopy.geocoders.options.default_scheme`.
:param int timeout:
See :attr:`geopy.geocoders.... | 625941c6bde94217f3682e18 |
def append(self, raw_data, tenant_id): <NEW_LINE> <INDENT> while raw_data: <NEW_LINE> <INDENT> usage_start, data = self._filter_period(raw_data) <NEW_LINE> self._check_commit(usage_start, tenant_id) <NEW_LINE> self._dispatch(data, tenant_id) | Append rated data before committing them to the backend.
:param raw_data: The rated data frames.
:param tenant_id: Tenant the frame is belonging to. | 625941c6460517430c3941ae |
def only_grey(self): <NEW_LINE> <INDENT> rawval = (self.r + self.b + self.g) / 3 <NEW_LINE> n = min( range(len(_grey_vals)), key=[abs(x - rawval) for x in _grey_vals].__getitem__, ) <NEW_LINE> return n + 232 | Finds the greyscale color. | 625941c6a8ecb033257d30f3 |
def testLatinSymbols(self): <NEW_LINE> <INDENT> nodes = self.tokenizer.lookUp('kana', 4) <NEW_LINE> self.assertEqual(6, len(nodes)) <NEW_LINE> self.assertEqual(4 + 0, nodes[0].startPos) <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> self.assertEqual('kana', node.token.text) | Latin chars are grabbed as a whole | 625941c6167d2b6e31218bbc |
def handleScopePrefix(self, prefix): <NEW_LINE> <INDENT> scope = self.scope() <NEW_LINE> typeArgs = [] <NEW_LINE> hasPrefix = False <NEW_LINE> for component in prefix: <NEW_LINE> <INDENT> nameInfo = scope.lookup(component.name, component.location, fromExternal=hasPrefix) <NEW_LINE> if not nameInfo.isScope(): <NEW_LINE>... | Processes the components of a scope prefix (a list of ast.ScopePrefixComponent). This
looks up each component in the list and checks type arguments (using
handleClassTypeArgs). Returns a scope and a list of Types, which will be implicit
type arguments for whatever is after the prefix. | 625941c66fb2d068a760f0c1 |
def main(config): <NEW_LINE> <INDENT> full_replacements = ["removed", "replaced_clone", "replaced_pink", "timeshifted"] <NEW_LINE> ltd_replacements = ["adults", "original"] <NEW_LINE> analysis_dir = os.path.join('../openSMILE_analysis/random_forests', 'predict_SM/long_files/summary', config) <NEW_LINE> for replacement ... | Main function. Builds and saves a ranking_table and a weighted_table for
each replacement condition.
Paremeters
----------
config : string
openSMILE configuration file basename
Returns
-------
None
Outputs
-------
*ranking_table.csv : CSV file
a csv of ranking_table
*weighted_table.csv : CSV file
a ... | 625941c66fece00bbac2d763 |
def requires_tls_version(version): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(*args, **kw): <NEW_LINE> <INDENT> if not has_tls_version(version): <NEW_LINE> <INDENT> raise unittest.SkipTest(f"{version} is not available.") <NEW_LINE> <DEDENT> else: <NEW_LINE... | Decorator to skip tests when a required TLS version is not available
:param version: TLS version name or ssl.TLSVersion member
:return: | 625941c6435de62698dfdc72 |
def test_one_element(self): <NEW_LINE> <INDENT> i = [1] <NEW_LINE> self.assertEqual(partition(i, 0, len(i) - 1), 0) | Test one element array. | 625941c6090684286d50ed0a |
def encode64(num): <NEW_LINE> <INDENT> data = struct.pack('<Q', num).rstrip('\x00') <NEW_LINE> if len(data)==0: <NEW_LINE> <INDENT> data = '\x00' <NEW_LINE> <DEDENT> return base64.urlsafe_b64encode(data).rstrip('=') | Encoding given number into base64 | 625941c6dd821e528d63b1d0 |
def edit_iface(vm_name): <NEW_LINE> <INDENT> iface_type = params.get("iface_type") <NEW_LINE> iface_model = params.get("iface_model") <NEW_LINE> edit_error = "yes" == params.get("edit_error", "no") <NEW_LINE> if iface_type: <NEW_LINE> <INDENT> edit_cmd = (r":%s /<interface type=.*>/<interface type='{0}'>/" "".format(if... | Modify vm's interface information by virsh edit command. | 625941c6e5267d203edcdcc4 |
def replace(self, key, val, flags=0, expireTime=0): <NEW_LINE> <INDENT> return self._set(b"replace", key, val, flags, expireTime, b"") | Replace the given C{key}. It must already exist in the server.
@param key: the key to replace.
@type key: L{bytes}
@param val: the new value associated with the key.
@type val: L{bytes}
@param flags: the flags to store with the key.
@type flags: L{int}
@param expireTime: if different from 0, the relative time in se... | 625941c61d351010ab855b42 |
def pagify(text, delims=[], escape=True, shorten_by=8, page_length=2000): <NEW_LINE> <INDENT> in_text = text <NEW_LINE> while len(in_text) > page_length: <NEW_LINE> <INDENT> closest_delim = max([in_text.rfind(d, 0, page_length - shorten_by) for d in delims]) <NEW_LINE> closest_delim = closest_delim if closest_delim != ... | DOES NOT RESPECT MARKDOWN BOXES OR INLINE CODE | 625941c68a349b6b435e8199 |
def _parse_stream(self, resp): <NEW_LINE> <INDENT> verb = self.verbose <NEW_LINE> tweets_read = 0 <NEW_LINE> last_keep_alive = time.perf_counter() <NEW_LINE> while self.running and not resp.raw.closed: <NEW_LINE> <INDENT> for next_tweet in resp.iter_lines(): <NEW_LINE> <INDENT> if next_tweet and next_tweet != b'\n': <N... | Parse incoming tweets from the streaming response and put them in a thread queue.
Detects keep-alive newlines sent every ~30 seconds. If a keep-alive is detected,
no tweets have been received for a while so the thread sleeps for a brief time to yield
to the consumer.
Note that no processing is done to the tweets at ... | 625941c6a17c0f6771cbe078 |
def setup(h, w): <NEW_LINE> <INDENT> setpos(-w/2, (h/2 - 10)) <NEW_LINE> setheading(-90) <NEW_LINE> pencolor("bisque") <NEW_LINE> for x in range(19): <NEW_LINE> <INDENT> down() <NEW_LINE> dot(5, "grey") <NEW_LINE> up() <NEW_LINE> forward(h/19) <NEW_LINE> <DEDENT> for x in range(19): <NEW_LINE> <INDENT> up() <NEW_LINE> ... | Places the nail holes with the corresponding height and width
and then places string across to weave through -- 19 | 625941c692d797404e3041b0 |
def test_hex_to_rgb_black(self): <NEW_LINE> <INDENT> result = util.hex_to_rgb("#000000") <NEW_LINE> self.assertEqual(result, "0,0,0") | > Convert #000000 to RGB. | 625941c6be383301e01b54ae |
def get_auth_smstext(user="", realm=""): <NEW_LINE> <INDENT> ret = False <NEW_LINE> smstext = "<otp>" <NEW_LINE> pol = getPolicy({'scope': 'authentication', 'realm': realm, "action" : "smstext" }) <NEW_LINE> if len(pol) > 0: <NEW_LINE> <INDENT> smstext = getPolicyActionValue(pol, "smstext", String=True) <NEW_LINE> log.... | this function checks the policy scope=authentication, action=smstext
This is a string policy
The function returns the tuple (bool, string),
bool: If a policy is defined
string: the string to use | 625941c630c21e258bdfa4c2 |
def _run_kernel(self): <NEW_LINE> <INDENT> self.program.sum(self.queue, self.global_size, None, *self.buffers) <NEW_LINE> a_plus_b = numpy.empty(self.global_size, dtype = self.dtype) <NEW_LINE> cl.enqueue_copy(self.queue, a_plus_b, self.buffers[-1]) <NEW_LINE> return la.norm(a_plus_b - self.a_plus_b) | Run the kernel (self.program). Subclasses should overwrite this. | 625941c6cdde0d52a9e53058 |
def __init__(self, name): <NEW_LINE> <INDENT> super(GoTo, self).__init__(name) | Init method for the GoTo behavior. | 625941c68e71fb1e9831d7d0 |
def get_optima( self, sample_x: np.ndarray, sample_y: np.ndarray, run_callback: bool = True ) -> Tuple[np.array, float, float, float]: <NEW_LINE> <INDENT> pass | calculate the optima of the given acquisition function
:param sample_x: input of samples
:param sample_y: outputs of samples
:param run_callback: should callback be executed or not
:return: x-value of the optima, y-value of the optima and the acquisition function value of the optima | 625941c60fa83653e4656fe2 |
def queue_data(self, service_name, data): <NEW_LINE> <INDENT> with self._collector_lock: <NEW_LINE> <INDENT> self._queue.append({ 'service': service_name, 'data': data, 'timestamp': strftime("%Y-%m-%d %H:%M:%S", gmtime()) }) | Adds a message from a given service to the queue, so it can be sent
at a random time interval.
:param service_name: The name of the service calling the method.
:type service_name: str
:param data: The message (can be an object too). Must be JSON
serializable.
:type data: Any
:return: None
:rtype: None | 625941c6a934411ee37516ba |
def html2rst(html_string, force_headers=False, center_cells=False, center_headers=False): <NEW_LINE> <INDENT> if os.path.isfile(html_string): <NEW_LINE> <INDENT> file = open(html_string, 'r', encoding='utf-8') <NEW_LINE> lines = file.readlines() <NEW_LINE> file.close() <NEW_LINE> html_string = ''.join(lines) <NEW_LINE>... | Convert a string or html file to an rst table string.
Parameters
----------
html_string : str
Either the html string, or the filepath to the html
force_headers : bool
Make the first row become headers, whether or not they are
headers in the html file.
center_cells : bool
Whether or not to center the co... | 625941c6e64d504609d74866 |
def incoming_veh(self, veh, origin_cross, x = 0): <NEW_LINE> <INDENT> if type(veh) is not Vehicle: <NEW_LINE> <INDENT> raise notVehicleError <NEW_LINE> <DEDENT> if not isinstance(origin_cross, Cross): <NEW_LINE> <INDENT> raise notCrossError <NEW_LINE> <DEDENT> if origin_cross not in [self.cross1,self.cross2]: <NEW_LINE... | Incoming vehicle on the road from origin_cross
x is the position of the vehicle on the road when arriving
(useful when vehicles come from another road with a certain speed) | 625941c68da39b475bd64f98 |
def list_by_resource_group( self, resource_group_name, skip_token=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_ve... | Lists all the jobs available under the given resource group.
:param resource_group_name: The Resource Group Name.
:type resource_group_name: str
:param skip_token: $skipToken is supported on Get list of jobs, which provides the next page in
the list of jobs.
:type skip_token: str
:keyword callable cls: A custom type ... | 625941c6b5575c28eb68e026 |
def init_config(self, app): <NEW_LINE> <INDENT> for k in dir(config): <NEW_LINE> <INDENT> if k.startswith("SSO_SAML_"): <NEW_LINE> <INDENT> app.config.setdefault(k, getattr(config, k)) <NEW_LINE> <DEDENT> <DEDENT> app.config.setdefault( "SSO_SAML_PREPARE_FLASK_REQUEST_FUNCTION", prepare_flask_request ) | Initialize configuration. | 625941c68da39b475bd64f99 |
def randomFullAccount(): <NEW_LINE> <INDENT> id_ = steamIdFormula(random.randint(1, 999999999)) <NEW_LINE> account = BeautifulSoup(requests.get("https://steamcommunity.com/profiles/{}".format( id_)).text, "html.parser") <NEW_LINE> while not account.find(class_="actual_persona_name") or account.find(class_="profile_priv... | Generate a random account that exists and is not private.
Returns:
Valid Steam Community ID (int) | 625941c6f9cc0f698b140623 |
def delete(self, purge=False): <NEW_LINE> <INDENT> if not self.data: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if purge: <NEW_LINE> <INDENT> self.purge_cards() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.empty() <NEW_LINE> <DEDENT> DataColumn.delete_column(self.data) | Delete itself | 625941c6a4f1c619b28b0062 |
def words_length(self): <NEW_LINE> <INDENT> return len(self.__words) | :return: number of the words in this aspect | 625941c69f2886367277a8b4 |
def _get_exec_driver(): <NEW_LINE> <INDENT> contextkey = 'docker.exec_driver' <NEW_LINE> if contextkey in __context__: <NEW_LINE> <INDENT> return __context__[contextkey] <NEW_LINE> <DEDENT> from_config = __salt__['config.get'](contextkey, None) <NEW_LINE> if from_config is not None: <NEW_LINE> <INDENT> __context__[cont... | Get the method to be used in shell commands | 625941c63617ad0b5ed67f1e |
def _focusout_invalid(self, **kwargs): <NEW_LINE> <INDENT> pass | Handle invalid data on a focus event | 625941c63cc13d1c6d3c73a1 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(BarChartWidget, self).__init__(parent) | Init function.
Arguments:
* parent -- parent element of this widget -- default = None | 625941c63617ad0b5ed67f1f |
def sigwinch_handler(self, *dummy): <NEW_LINE> <INDENT> self.resize_event = True | Resize event callback | 625941c64d74a7450ccd41ea |
def generate_input(input_text): <NEW_LINE> <INDENT> if input_text: <NEW_LINE> <INDENT> if 'full_name' in input_text or 'fullname' in input_text: <NEW_LINE> <INDENT> return fake.first_name() + fake.last_name() <NEW_LINE> <DEDENT> elif 'username' in input_text: <NEW_LINE> <INDENT> return fake.user_name() <NEW_LINE> <DEDE... | Generate fake string based on input_text
:param `str` input_text: name of input form
:return: fake data
:rtype: `unicode` | 625941c65fdd1c0f98dc0259 |
def bitstream_pack(iterable): <NEW_LINE> <INDENT> l = bitstr_len(iterable) <NEW_LINE> bit_range = range(2**l) <NEW_LINE> stream_input_str = ",".join(['='.join(map(repr, [l,b])) for b in bit_range]) <NEW_LINE> packed_stream = pack(stream_input_str) <NEW_LINE> return packed_stream | (Deprecated) Return a BitStream representation of `iterable` by packing. | 625941c6956e5f7376d70e94 |
def GetLocalStop(self): <NEW_LINE> <INDENT> pass | Return local (scene) stop time.
return : Local stop time. | 625941c6442bda511e8be440 |
def get_random_id() -> str: <NEW_LINE> <INDENT> random_id = '_' + uuid.uuid4().hex <NEW_LINE> return random_id | Generate a random ID string. The random ID will start with the '_'
character. | 625941c6a8ecb033257d30f4 |
def check_class_no(self, indexstr, ustr): <NEW_LINE> <INDENT> ret = None <NEW_LINE> if ustr and len(ustr.strip()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> num = int(ustr) <NEW_LINE> if num > 45 or num < 1: <NEW_LINE> <INDENT> ret = u'不在[1,45]之间' <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDEN... | 类号 清洗验证 | 625941c64527f215b584c47f |
def mkstemp(*args, **kwargs): <NEW_LINE> <INDENT> if 'prefix' not in kwargs: <NEW_LINE> <INDENT> kwargs['prefix'] = '__salt.tmp.' <NEW_LINE> <DEDENT> close_fd = kwargs.pop('close_fd', True) <NEW_LINE> fd_, f_path = tempfile.mkstemp(*args, **kwargs) <NEW_LINE> if close_fd is False: <NEW_LINE> <INDENT> return fd_, f_path... | Helper function which does exactly what ``tempfile.mkstemp()`` does but
accepts another argument, ``close_fd``, which, by default, is true and closes
the fd before returning the file path. Something commonly done throughout
Salt's code. | 625941c60a50d4780f666eb8 |
def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> print(X[0].shape) <NEW_LINE> print(self.X_train.shape) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> dists[i] = np.sqr... | Compute the distance between each test point in X and each training point
in self.X_train using a single loop over the test data.
Input / Output: Same as compute_distances_two_loops | 625941c644b2445a339320bd |
def call_svd(x, k, draw): <NEW_LINE> <INDENT> global d, u, v <NEW_LINE> m = x.shape[0] <NEW_LINE> n = x.shape[1] <NEW_LINE> if n > m: <NEW_LINE> <INDENT> if draw == 1: <NEW_LINE> <INDENT> print('Do Transpose SVD') <NEW_LINE> v, d, u = linalg.svd(x.T, full_matrices=0) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDEN... | Reduce dimension with SVD. | 625941c615baa723493c3f9b |
def __call__(self): <NEW_LINE> <INDENT> if self._renderedValueSet(): <NEW_LINE> <INDENT> value = self._data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self.context.default <NEW_LINE> <DEDENT> if value == self.context.missing_value: <NEW_LINE> <INDENT> value = self._translate(_("SourceDisplayWidget-missing", ... | Render the current value
| 625941c6442bda511e8be441 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, FleetdispatchJobsupdateDispatchJobs): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941c6d58c6744b4257c87 |
def to_psf(self, file_path: Union[Path, str]): <NEW_LINE> <INDENT> raise UnsupportedExportError | Export this Interchange to a CHARMM-style .psf file. | 625941c650485f2cf553cdc0 |
def readFeatures(featuresFile): <NEW_LINE> <INDENT> print ("Reading features") <NEW_LINE> with open(featuresFile, 'r') as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> dims = [int(x) for x in line.split()] <NEW_LINE> features = np.empty(dims) <NEW_LINE> wordBidict = bidict() <NEW_LINE> wordCount = 0 <NEW_LINE> ... | Load all features from file and populate features array and bidict
bidict[word] maps to index of word feature in features array | 625941c6090684286d50ed0b |
def authenticated(func): <NEW_LINE> <INDENT> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> if g.user is None: <NEW_LINE> <INDENT> return redirect('{}?{}'.format( url_for('main'), urlencode({'next': request.url}), )) <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> wrapped.__name__ = func.__name_... | Decorator for pages accessible only when logged in. | 625941c68c3a8732951583e0 |
def normalize_faces(self, image_list): <NEW_LINE> <INDENT> avg = self.average_face <NEW_LINE> images = np.matrix(np.column_stack(image_list)) - np.column_stack([avg] * len(image_list)) <NEW_LINE> return images | Take a list of image vectors and return a matrix with normalized columns. | 625941c667a9b606de4a7ee1 |
@mysql_decorator <NEW_LINE> def delete_data_of_table(db, table_name): <NEW_LINE> <INDENT> db.cursor().execute("DELETE FROM %s;" % table_name) <NEW_LINE> print("Table %s has been cleared\n" % table_name) | Delete all data from table
:param str table_name: Name of the table to drop. | 625941c6be7bc26dc91cd629 |
def HostDatastoreConnectInfo(vim, *args, **kwargs): <NEW_LINE> <INDENT> obj = vim.client.factory.create('ns0:HostDatastoreConnectInfo') <NEW_LINE> if (len(args) + len(kwargs)) < 1: <NEW_LINE> <INDENT> raise IndexError('Expected at least 2 arguments got: %d' % len(args)) <NEW_LINE> <DEDENT> required = [ 'summary' ] <NEW... | The base data object type for information about datastores on the host. | 625941c69b70327d1c4e0dfb |
def find_sum(node, _sum, path, level): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> path[level] = node.get_root_val() <NEW_LINE> temp = 0 <NEW_LINE> for i in range(level, -1, -1): <NEW_LINE> <INDENT> temp += path[i] <NEW_LINE> if temp == _sum: <NEW_LINE> <INDENT> print_path(path, ... | Helper function to find all paths which sum up to the given value
Args:
node(BinaryTree): The node to start calculating
_sum(Integer): The given sum
path(List): The List instance to store the values
level(Integer): The level in which the node is located | 625941c6e76e3b2f99f3a835 |
def configure(self): <NEW_LINE> <INDENT> pass | grid configuration, e.g. configure neighborhoods | 625941c667a9b606de4a7ee2 |
def binary_tanh_op(x): <NEW_LINE> <INDENT> return 2 * round_through(_hard_sigmoid(x)) - 1 | Binary hard sigmoid for training binarized neural network.
The neurons' activations binarization function
It behaves like the sign function during forward propagation
And like:
hard_tanh(x) = 2 * _hard_sigmoid(x) - 1
clear gradient when |x| > 1 during back propagation
# Reference:
- [BinaryNet: Training Dee... | 625941c63539df3088e2e371 |
def _factor_Cd(self, scales, omega, dt, dj): <NEW_LINE> <INDENT> if dj <= 0: <NEW_LINE> <INDENT> raise ValueError('dj must be > 0') <NEW_LINE> <DEDENT> Ck = self._factor_Ck(scales, omega, dt) <NEW_LINE> Cd = (dj * np.sqrt(dt)) / (Ck * self.time(0)) <NEW_LINE> return Cd | The factor Cd is defined in eq. 13 in (Torrence 1998).
Parameters
----------
omega : float or 1d array_like object
angular frequency(es).
scale : float or 1d array_like object
wavelet scale(s).
dt : integer
number of data samples.
dj : float
scale resolution.
Returns
-------
Ck : 1d numpy array
re... | 625941c610dbd63aa1bd2bcb |
def PtDisableShadows(): <NEW_LINE> <INDENT> pass | Turns shadows off | 625941c6507cdc57c6306cff |
def close(self, sshc, terminate): <NEW_LINE> <INDENT> sshc.sendline("exit") <NEW_LINE> if terminate: <NEW_LINE> <INDENT> sshc.terminate() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sshc.expect( self.options["shell_prompts"] + self.options["extra_prompts"], self.options["cmd_timeout"], ) <NEW... | Closes a connection object.
Args::
sshc: the pexpect object to close
terminate: a boolean value to terminate all connections or not
Returns:
None: the sshc will be at the jumpbox, or the connection is closed | 625941c699cbb53fe6792c0e |
def test_ask(self): <NEW_LINE> <INDENT> dialog = DialogHelper() <NEW_LINE> dialog.set_input_stream(self.get_input_stream('\n8AM\n')) <NEW_LINE> self.assertEqual('2PM', dialog.ask(self.get_output_stream(), 'What time is it?', '2PM')) <NEW_LINE> output = self.get_output_stream() <NEW_LINE> self.assertEqual('8AM', dialog.... | DialogHelper.ask() behaves properly | 625941c6c4546d3d9de72a5a |
def test_integration_below(): <NEW_LINE> <INDENT> response = test_client.post( '/', data={ 'phone_number': '5558675309', 'asset': 'BTC', 'market': 'coinbase', 'cond_option': '0', 'price': '100' }) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> cb = price_tracker_fake("45") <NEW_LINE> twilio = twilio_fake() <N... | Make post request to the website, make sure texter sends the message. | 625941c6d8ef3951e3243564 |
def predict_proba(self, X): <NEW_LINE> <INDENT> probabilities = np.zeros((X.shape[0], self.y.shape[1]), dtype=np.float64) <NEW_LINE> distances = (pairwise_distances(X, self.centroids_, metric=self.metric)) <NEW_LINE> if(self.metric == 'cosine'): <NEW_LINE> <INDENT> distances = 1 - distances <NEW_LINE> <DEDENT> else: <N... | Returns a matrix for each of the samples to belong to each of the classes.
The matrix has shape = [n_samples, n_classes] where n_samples is the
size of the first dimension of the input matrix X and n_classes is the number of
classes as determined from the parameter 'y' obtained during training.
Parameters
----------
X... | 625941c6c432627299f04c6c |
def local_num_id_generator(context: Iterable = (), start: Optional[int] = None) -> IDGenerator: <NEW_LINE> <INDENT> if start is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start = max((elem.id for elem in context)) + 1 <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> start = 1 <NEW_LINE> <DEDENT... | Return a generator for IDs that are unique within a given `context`.
The next id is calculated simply by incrementing a number by 1.
The initial number can be set by explicitely giving a start value or by
giving a context (i.e. an iterable of objects that have a numerical id).
In the latter case the initial number is... | 625941c660cbc95b062c656a |
def check_typos(request): <NEW_LINE> <INDENT> soup = get_soup('http://www.google.com/search?q=' + request.lower()) <NEW_LINE> raw = soup.find_all("a", class_="spell") <NEW_LINE> if raw == []: <NEW_LINE> <INDENT> return request <NEW_LINE> <DEDENT> new_name = re.sub(u'[^А-Яа-я\s]*', u'', str(raw[0])).lstrip() <NEW_LINE> ... | Эта функция позволит проверить не опечатался ли пользователь.
:param request: string
:return: string | 625941c62eb69b55b151c8d5 |
def test_extra_extension_category(self): <NEW_LINE> <INDENT> self.assertEqual(self.base.x, "BaseExtra x", msg="x != 'BaseExtra x'") <NEW_LINE> return | Base class extended with a category subclass | 625941c65510c4643540f40e |
def mouseDoubleClickEvent (self, event): <NEW_LINE> <INDENT> self.diag = NameDialog( parent=self.parent, title="Rename %s %s"%( type(self), self.name ), default=self.name) <NEW_LINE> self.diag.accepted.connect(self.renameElement) <NEW_LINE> self.diag.show() | Edit visual name on `QtGui.mouseDoubleClickEvent`.
:param event: `QtGui.mouseDoubleClickEvent`. | 625941c67047854f462a1432 |
def name_validate_full_name_with_http_info(self, input, **kwargs): <NEW_LINE> <INDENT> all_params = ['input'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> para... | Parse and validate a full name # noqa: E501
Parses a full name string (e.g. "Mr. Jon van der Waal Jr.") into its component parts (and returns these component parts), and then validates whether it is a valid name string or not # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchrono... | 625941c6187af65679ca5145 |
def engine_kw(dsn): <NEW_LINE> <INDENT> if dsn.startswith('mysql://'): <NEW_LINE> <INDENT> return {'pool_recycle': 60} <NEW_LINE> <DEDENT> elif dsn.startswith('postgresql'): <NEW_LINE> <INDENT> app_name = config.get('application_identifier', 'clay') <NEW_LINE> celery_identifier = os.environ.get('CELERY_IDENTIFIER') <NE... | Get the appropriate engine keywords for a given DSN.
This is particularly important because there are specific ways to
do connection pooling for Postgres and MySQL to ensure that load
balancing works; the out-of-the-box settings in SQLAlchemy are not
appropriate for either database. | 625941c697e22403b379cfc0 |
def get_for_days(self, symbol, days): <NEW_LINE> <INDENT> params = { "symbol": symbol, "interval": "daily", "start": arrow.utcnow().shift(days=-days).format("YYYY-MM-DD"), "end": arrow.utcnow().format("YYYY-MM-DD"), } <NEW_LINE> try: <NEW_LINE> <INDENT> body = self.make_call("markets/history", params) <NEW_LINE> return... | Get returns for a symbol for a number of days
Params:
symbol: str: Symbol to query
days: int: number of days to query
Returns:
Parsed returns from Tradier's API
Raises:
TradierException: for errors talking to Tradier
BadRequest: for 400 codes from tradier
BadResponse: for 500 codes, unparseable... | 625941c699fddb7c1c9de3b9 |
def get_last3_messages(src): <NEW_LINE> <INDENT> today = date.today().strftime('%Y-%m-%d') <NEW_LINE> db = get_db() <NEW_LINE> msgs = db.execute( 'SELECT timeSent, message FROM communication' ' WHERE source=? AND timeSent LIKE ?' ' ORDER BY timeSent DESC LIMIT 3', (src, today + '%') ).fetchall() <NEW_LINE> return msgs | gets the last 3 saved messages by src from the communication table | 625941c666656f66f7cbc1d2 |
def asdict(self): <NEW_LINE> <INDENT> return attr.asdict(self) | Return class attributes in a dictionary. | 625941c6be8e80087fb20c6c |
def append(self, item): <NEW_LINE> <INDENT> new_node = Node(item) <NEW_LINE> if(self.head == None): <NEW_LINE> <INDENT> self.head = new_node <NEW_LINE> self.tail = self.head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tail.next = new_node <NEW_LINE> self.tail = self.tail.next <NEW_LINE> <DEDENT> self.ll_length +... | Insert the given item at the tail of this linked list.
Running time: O(1) only change the node (tail) | 625941c621bff66bcd68497b |
@manager.command <NEW_LINE> def db_empty(): <NEW_LINE> <INDENT> print("Dropping database...") <NEW_LINE> with app.app_context(): <NEW_LINE> <INDENT> populate_g() <NEW_LINE> web.models.db_empty(db) | Will drop the database. | 625941c676e4537e8c351699 |
def predict_labels(images, model_options, image_pyramid=None): <NEW_LINE> <INDENT> outputs_to_scales_to_logits = multi_scale_logits( images, model_options=model_options, image_pyramid=image_pyramid, is_training=False, fine_tune_batch_norm=False) <NEW_LINE> predictions = {} <NEW_LINE> for output in sorted(outputs_to_sca... | Predicts segmentation labels.
Args:
images: A tensor of size [batch, height, width, channels].
model_options: A ModelOptions instance to configure models.
image_pyramid: Input image scales for multi-scale feature extraction.
Returns:
A dictionary with keys specifying the output_type (e.g., semantic
predicti... | 625941c67cff6e4e811179ad |
def __call__(self): <NEW_LINE> <INDENT> wintegral = self.wintegral <NEW_LINE> work_array_windex_index_list = [] <NEW_LINE> for wrr in wintegral.wrr_list(): <NEW_LINE> <INDENT> assert wrr.rr().rrtype() == 'vrr', "Only VRR RRs allowed in this algorithm (contracted, VRR-only, with auxiliary)" <NEW_LINE> if ... | Setup indexing attributes for integral arrays attached to integral_wrapper
based on specific algorithm details (sets up integral_wrapper.work_array). | 625941c69b70327d1c4e0dfc |
def GetResources(self): <NEW_LINE> <INDENT> return {'Pixmap': 'Draft_Layer', 'MenuText': QT_TRANSLATE_NOOP("Draft_Layer", "Layer"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Layer", "Adds a layer to the document.\nObjects added to this layer can share the same visual properties such as line color, line width, and shape color... | Set icon, menu and tooltip. | 625941c630dc7b766590198f |
def fetchDataBetweenLines(self, start_pattern, end_pattern): <NEW_LINE> <INDENT> output = [] <NEW_LINE> output1 = self.searchLine(start_pattern) <NEW_LINE> output2 = self.searchLine(end_pattern) <NEW_LINE> if output1 and output2: <NEW_LINE> <INDENT> output.append(output1[0][0].strip()) <NEW_LINE> self.goToLine(output1[... | Returns all the lines between the lines where start line is the line
in which start_pattern is found and end line is the line in which
end_pattern is found.
:param start_pattern: Pattern to search for line to start from.
:param end_pattern: Pattern to search for line as end.
:return: List of string having all lines | 625941c60fa83653e4656fe3 |
def distance(self, point): <NEW_LINE> <INDENT> dlambda = self.lon - point.lon <NEW_LINE> num = ((np.cos(point.lat) * np.sin(dlambda)) ** 2 + (np.cos(self.lat) * np.sin(point.lat) - np.sin(self.lat) * np.cos(point.lat) * np.cos(dlambda)) ** 2) <NEW_LINE> den = (np.sin(self.lat) * np.sin(point.lat) + np.cos(self.lat) * n... | Get distance using Vincenty formula. | 625941c64428ac0f6e5ba819 |
def evaluate(self, script, state_variables=None): <NEW_LINE> <INDENT> if state_variables is not None: <NEW_LINE> <INDENT> for var in state_variables: <NEW_LINE> <INDENT> vars()[var] = state_variables[var] <NEW_LINE> <DEDENT> <DEDENT> elif SmartMonContext().state_variables is not None: <NEW_LINE> <INDENT> for var in Sma... | Evaluate script. | 625941c6462c4b4f79d1d6f8 |
def send_message_to_kafka(self, p): <NEW_LINE> <INDENT> mqtttopic = p[0] <NEW_LINE> message = p[1] <NEW_LINE> print("Kafka-MQTT Connector") <NEW_LINE> print("Mqtt Topic: " , mqtttopic) <NEW_LINE> kafka_topic = ''.join([change(c, "/", "_") for c in mqtttopic]) <NEW_LINE> kafka_message = message.decode("utf-8") <NEW_LINE... | Send message to kafka consumer | 625941c6d6c5a10208144071 |
def test_steps(self): <NEW_LINE> <INDENT> self.assertEqual(SpectralShape(360, 830, 1).steps, 1) | Tests
:attr:`colour.colorimetry.spectrum.SpectralShape.steps` attribute. | 625941c663d6d428bbe44517 |
def _error_if_not_exists(self, module): <NEW_LINE> <INDENT> if not self._check_if_module_exists(module): <NEW_LINE> <INDENT> raise LookupError('The module where this operation comes from is not registered!') | Helper method for throwing a concrete error if a module has not been registered, yet tries to write into the
database without having a reference.
:param module: A string naming your plugin.
:type module: str
:raise LookupError: If the module doesn't exist, it raises an error. | 625941c64e696a04525c9473 |
def show_fact_sheet_f(responses, derived): <NEW_LINE> <INDENT> return show_fact_sheet_f_you(responses, derived) or show_fact_sheet_f_spouse(responses, derived) | If one of the claimants earns over $150,000, Fact Sheet F is indicated. | 625941c696565a6dacc8f6f3 |
def testLiftover(self): <NEW_LINE> <INDENT> self.runCmd('vtools import vcf/CEU.vcf.gz --build hg18') <NEW_LINE> self.assertFail('vtools liftover') <NEW_LINE> self.assertSucc('vtools liftover -h') <NEW_LINE> self.assertFail('vtools liftover -v 0') <NEW_LINE> self.assertFail('vtools liftover non_existing_build') <NEW_LIN... | Test command vtools liftover | 625941c607f4c71912b114a9 |
def get_enum_dict(enum_cls) -> dict: <NEW_LINE> <INDENT> return enum_cls.__members__ | 输出枚举字典,{ 枚举名:枚举项, ... }
:param enum_cls: 枚举类
:return: 枚举字典 | 625941c601c39578d7e74e63 |
def init_context_current_setting(self, context): <NEW_LINE> <INDENT> conf = context.current_setting[0] <NEW_LINE> arch = context.current_setting[1] <NEW_LINE> setting = (conf, arch) <NEW_LINE> context.settings[setting] = { 'conf': conf, 'arch': arch, 'TARGET_NAME': [], 'target_type': '', 'OUTPUT_DIRECTORY': [], 'inc_di... | Define settings of converter.
:param context: converter context
:type context: Context | 625941c6dd821e528d63b1d1 |
def test_can_retry(self): <NEW_LINE> <INDENT> block = RetryingBlock() <NEW_LINE> self.configure_block(block, {}) <NEW_LINE> target_func = MagicMock(side_effect=[Exception, Exception, 5]) <NEW_LINE> self.assertEqual(block.execute_with_retry(target_func), 5) <NEW_LINE> self.assertEqual(target_func.call_count, 3) | Tests that the mixin can retry methods that fail | 625941c6bde94217f3682e1a |
def test__consume_entropy(): <NEW_LINE> <INDENT> value, entropy = _consume_entropy('', int(4 * 4 + 2), 'abcd', 2) <NEW_LINE> assert value == 'ca' <NEW_LINE> assert entropy == 1 | test__consume_entropy function | 625941c623e79379d52ee58d |
def set_config_path(self, new_config_path): <NEW_LINE> <INDENT> oldpath = self.get_config_path() <NEW_LINE> cdir, cfile = os.path.split(new_config_path) <NEW_LINE> if not cdir.startswith('/'): <NEW_LINE> <INDENT> cdit='/'+cdir <NEW_LINE> <DEDENT> if not cfile: <NEW_LINE> <INDENT> cfile = 'site.yaml' <NEW_LINE> <DEDENT>... | Will return the old config path if it was changed | 625941c6eab8aa0e5d26db7f |
def test_replace_mixin_collection_for_sanity(self): <NEW_LINE> <INDENT> headers = {CONTENT_TYPE: 'text/occi', LOCATION: self.compute.identifier} <NEW_LINE> handler = CollectionHandler(self.registry, headers, '', ()) <NEW_LINE> handler.post('/mystuff/') <NEW_LINE> headers = {CONTENT_TYPE: 'text/occi', LOCATION: self.net... | Add mixins to resources. | 625941c6090684286d50ed0c |
def _get_relevant_cards(spell_cost, cards): <NEW_LINE> <INDENT> cards = copy.deepcopy(cards) <NEW_LINE> try: <NEW_LINE> <INDENT> cards.pop('s') <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> relevant_mana_colors = set(''.join(spell_cost.keys())) <NEW_LINE> for land_type in cards.keys(... | Converts cards whose colored mana is irrelevant to colorless mana sources. | 625941c6dd821e528d63b1d2 |
def oh_no_dragon(state): <NEW_LINE> <INDENT> return np.where(state[PLAYER_DEPTH]==1) == np.where(state[DRAGON_DEPTH]==1) | Checks if the player was eaten by the dragon. | 625941c626068e7796caed05 |
def blasr(args): <NEW_LINE> <INDENT> from maize.apps.grid import MakeManager <NEW_LINE> from maize.utils.iter import grouper <NEW_LINE> reffasta, fofn = args.ref_fasta, args.fofn <NEW_LINE> flist = sorted([x.strip() for x in open(fofn)]) <NEW_LINE> h5list = [] <NEW_LINE> mm = MakeManager() <NEW_LINE> for i, fl in enume... | %prog blasr ref.fasta fofn
Run blasr on a set of PacBio reads. This is based on a divide-and-conquer
strategy described below. | 625941c64527f215b584c480 |
def is_playable(self, card): <NEW_LINE> <INDENT> target_pile = self.piles.get(card.color) <NEW_LINE> card_on_top = target_pile.top() <NEW_LINE> if card_on_top is None or card.number == card_on_top.number + 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Return whether a card can be played. | 625941c65e10d32532c5ef4f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.