code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_kwargs(self): <NEW_LINE> <INDENT> d = self.m0.to_dict() <NEW_LINE> m1 = Place(**d) <NEW_LINE> self.assertEqual(self.m0.id, m1.id) <NEW_LINE> self.assertEqual(self.m0.created_at, m1.created_at) <NEW_LINE> self.assertEqual(self.m0.updated_at, m1.updated_at) <NEW_LINE> self.assertNotEqual(self.m0, m1) | Test instantation with kwargs from json dictionary. | 625941dd656771135c3ebb97 |
def check_admin(): <NEW_LINE> <INDENT> if not current_user.is_admin: <NEW_LINE> <INDENT> abort(403) | Prevent non-admins from accesing the page | 625941dd92d797404e3044b0 |
def set_as_key_frame(self, ti): <NEW_LINE> <INDENT> self.insert_key_frame(ti, self.get_a_at(ti)) <NEW_LINE> self.remove_frame(ti + 1) <NEW_LINE> self.mark_redraw() | set the frame at time ti as key frame | 625941dda17c0f6771cbe375 |
def size_of_structure(structure_def: StructureDef) -> int: <NEW_LINE> <INDENT> num_of_bytes = 0 <NEW_LINE> for item in structure_def: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> var, plc_datatype, size = item <NEW_LINE> str_len = None <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> var, plc_datatype, size, ... | Calculate the size of a structure in number of BYTEs.
:param tuple structure_def: special tuple defining the structure and
types contained within it according o PLCTYPE constants
:return: data size required to read/write a structure of multiple types
:rtype: int
Expected input example for structure_def:
.. code:... | 625941dd5166f23b2e1a547e |
def format(self, width, output_format='txt', **fmt_dict): <NEW_LINE> <INDENT> fmt = self._get_fmt(output_format, **fmt_dict) <NEW_LINE> data = self.data <NEW_LINE> datatype = self.datatype <NEW_LINE> data_fmts = fmt.get('data_fmts') <NEW_LINE> if data_fmts is None: <NEW_LINE> <INDENT> data_fmt = fmt.get('data_fmt') <NE... | Return string.
This is the default formatter for cells.
Override this to get different formating.
A cell formatter must accept as arguments
a cell (self) and an output format,
one of ('html', 'txt', 'csv', 'latex').
It will generally respond to the datatype,
one of (int, 'header', 'stub'). | 625941ddb830903b967e9c2e |
def get_python_new_autogenerated_module(self): <NEW_LINE> <INDENT> return self.wrap_directory.file("madz_future.py") | Returns the path to the madz autogenerated module. | 625941dd046cf37aa974d06b |
def load_sources(self): <NEW_LINE> <INDENT> log.info("Loading the sources ...") <NEW_LINE> for shape in self.regions: <NEW_LINE> <INDENT> source = Detection.from_shape(self.frame, shape, self.config.source_outer_factor) <NEW_LINE> self.sources.append(source) | This function ...
:return: | 625941dd94891a1f4081bdd0 |
def test_delete_state(self): <NEW_LINE> <INDENT> exploration = exp_domain.Exploration.create_default_exploration( 'eid', 'A title', 'A category') <NEW_LINE> exploration.add_states(['first state']) <NEW_LINE> with self.assertRaisesRegexp( ValueError, 'Cannot delete initial state'): <NEW_LINE> <INDENT> exploration.delete... | Test deletion of states. | 625941ddbe383301e01b57a6 |
def show_scatter(self, xkey, ykey, colorkey="age", ax=None, **kwargs): <NEW_LINE> <INDENT> import matplotlib.pyplot as mpl <NEW_LINE> if ax is None: <NEW_LINE> <INDENT> fig = mpl.figure(figsize=[6, 4]) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fig = ax.figure <NEW_LINE> <DEDENT>... | Show the scatter plot of the sample parameters
Parameters
----------
xkey, ykey, colorkey: [string]
self.sample entries used as x, y and color values
ax: [matplotlib Axes] -optional-
ax where the figure will be displayed
**kwargs goes to ax.scatter()
Returns
-------
matplotlib Figure | 625941dd45492302aab5e5ec |
def mousePressEvent(self, event): <NEW_LINE> <INDENT> if event.button() != Qt.LeftButton: <NEW_LINE> <INDENT> event.accept() <NEW_LINE> return <NEW_LINE> <DEDENT> self._parent.select_item() <NEW_LINE> scene = self.scene() <NEW_LINE> if scene.link_drawer is None: <NEW_LINE> <INDENT> scene.select_link_drawer(LinkType.JUM... | Connector button mouse press event. Either starts or closes a link.
Args:
event (QGraphicsSceneMouseEvent): Event | 625941dd656771135c3ebb98 |
def parsetime(t): <NEW_LINE> <INDENT> return int(t[0:2]) * 3600 + int(t[2:4]) * 60 | Converts a string containing a start or stop time in VDR's
standard format ('hhmm') to the number of seconds since
midnight. | 625941dd4f88993c3716c38a |
def arrhenius_scaling(T, TA, Ts): <NEW_LINE> <INDENT> return np.exp(TA/Ts - TA/T) | Arrhenius temperature scaling relationship | 625941dd8a349b6b435e8499 |
def libsvm_convert_sparse_tensor(array_ids, array_values): <NEW_LINE> <INDENT> indice_flatten_v = [] <NEW_LINE> values_flatten_v = [] <NEW_LINE> index = 0 <NEW_LINE> for i in range(0, array_ids.shape[0]): <NEW_LINE> <INDENT> for j in range(0, len(array_ids[i])): <NEW_LINE> <INDENT> indice_flatten_v.append([index, array... | Transform the contents into TF understandable formats, which is similar to
sparse_tensor_to_train_batch().
Args:
array_ids: Sparse indices.
array_values: Sparse values.
Returns:
List of the transformed (ids, values). | 625941dd627d3e7fe0d69177 |
def __init__(self): <NEW_LINE> <INDENT> super(AwxConfig, self).__init__() | Constructor. | 625941ddaad79263cf390d6b |
def test_secrets(self): <NEW_LINE> <INDENT> files = { get_test_config_dir('secret.yaml'): ( BASE_CONFIG + 'http:\n' ' api_password: !secret http_pw'), 'secrets.yaml': ('logger: debug\n' 'http_pw: abc123'), } <NEW_LINE> self.maxDiff = None <NEW_LINE> with patch_yaml_files(files): <NEW_LINE> <INDENT> config_path = get_t... | Test secrets config checking method. | 625941dd4d74a7450ccd44e9 |
def get_data(self, name): <NEW_LINE> <INDENT> eval_string = self.__config.get(self.__data_section_name, name) <NEW_LINE> data = ast.literal_eval(eval_string) <NEW_LINE> return ConfigManager.ConfigDataBlockList(data) | Get orderbook data by name
:return: Name of the data | 625941dd090684286d50f00f |
def _get_pass_args(self): <NEW_LINE> <INDENT> pass_args = 'pass=' <NEW_LINE> pass_args += str(self.encode_pass) <NEW_LINE> pass_args += ':' <NEW_LINE> pass_args += 'stats=' <NEW_LINE> pass_args += self.stats <NEW_LINE> return pass_args | Returns args string for encode pass. | 625941ddb7558d58953c5235 |
def dia_fecha(fechaNac): <NEW_LINE> <INDENT> dia = (6, 7, 1, 2, 3, 4, 5) <NEW_LINE> arrayfNac=fechaNac.split('-') <NEW_LINE> dfNac=datetime.date(int(arrayfNac[2]),int(arrayfNac[1]),int(arrayfNac[0])) <NEW_LINE> val1=dfNac.month <NEW_LINE> val2=dfNac.year <NEW_LINE> if(dfNac.month == 1): <NEW_LINE> <INDENT> val1=13 <NEW... | Obtiene el dia de la fecha pasada como string en formato dd-mm-aaaa
El codigo original pertenece a Víctor R. Varela Medina (@VitocoSan) y
fue obtenido de:
http://vitocosan.wordpress.com/2009/01/15/ocioque-dia-de-la-semana-naciste-python/ | 625941dda934411ee37519ba |
def UpdateShare(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Updates a share.
MUST return CODE_NOT_FOUND if the share reference does not exist. | 625941dd377c676e912724cd |
def check_status_of_services(self) -> Dict[str, List[str]]: <NEW_LINE> <INDENT> status_dict = dict() <NEW_LINE> for service in self.services: <NEW_LINE> <INDENT> status_dict.update( { service.tag: [ service.running, service.config["description"], service.name, ] } ) <NEW_LINE> <DEDENT> return status_dict | check_status_of_services
Returns:
Dict[str, List[str]]: Dict of service tags and
corresponding status, description and name of the service as a list | 625941dd956e5f7376d71192 |
def _get_data_raw_type(self): <NEW_LINE> <INDENT> value = api.GenGetDataRawType(self._handle) <NEW_LINE> library.check_last_status_raise_on_error() <NEW_LINE> return value | Raw data type. | 625941ddf548e778e58cd8a5 |
def objective_repair( delta_angle, ind_ply_1, ind_ply_2, n_plies, status_bal=0, coeff_bal_status=0.5, coeff_delta_angle=0.5, coeff_position=0.5): <NEW_LINE> <INDENT> return - coeff_bal_status * status_bal+ coeff_delta_angle * delta_angle / 180+ coeff_position * calc_distanciation(ind_ply_1, n_plies, ind_ply_2) | calculates the objective function values to chose the plies to change to
improve the balance level of a laminate or its satisfaction to the 10% rule
(to minimise)
delta_angle / 180: normalised value for the difference in fibre orientation
2 * diff_position / n_plies: normalised value expressing the ply proximity
... | 625941dd167d2b6e31218ebb |
def next(self, val=1): <NEW_LINE> <INDENT> self.progress += val * self.step <NEW_LINE> newWrite = int(round(self.progress)) <NEW_LINE> if newWrite != self.lastWrite: <NEW_LINE> <INDENT> self.lastWrite = newWrite <NEW_LINE> message("\r%3i%%" % newWrite) | Increase percentage and refresh display if needed.
-- val: int
Number of actual updates to be performed. | 625941dd4e696a04525c9772 |
def __setattr__(self, attr, value): <NEW_LINE> <INDENT> self[attr] = value | This method allows the setting of internal keys like attributes | 625941dd57b8e32f524837c3 |
def get_abstract(metadata_dictionary: dict) -> str: <NEW_LINE> <INDENT> if "http://dbpedia.org/ontology/abstract" in metadata_dictionary: <NEW_LINE> <INDENT> for key, value in metadata_dictionary.items(): <NEW_LINE> <INDENT> if key == "http://dbpedia.org/ontology/abstract": <NEW_LINE> <INDENT> list_of_abstracts = value... | Iterate through metadata dictionary,
return abstract of chosen title in English | 625941dd56ac1b37e62644f1 |
def im(): <NEW_LINE> <INDENT> im = Imputer(missing_values='NaN', strategy='mean', axis=0) <NEW_LINE> data = im.fit_transform([[1, 2], [np.nan, 3], [7, 6]]) <NEW_LINE> print(data) <NEW_LINE> return None | 缺失值处理
:return:NOne | 625941ddbf627c535bc134f6 |
def move_with_selection(self, delta_x, delta_y): <NEW_LINE> <INDENT> self.move_shape([0, 0], [delta_x, delta_y]) | Translate the shape together with other selected items
delta_x, delta_y: translation in plot coordinates | 625941dd4428ac0f6e5bab1a |
def update(event, context): <NEW_LINE> <INDENT> project = event['ResourceProperties']['CodeBuildProject'] <NEW_LINE> build_id = create_docker_images(project) <NEW_LINE> physical_resource_id = build_id <NEW_LINE> response_data = {} <NEW_LINE> return physical_resource_id, response_data | Place your code to handle Update events here
To return a failure to CloudFormation simply raise an exception,
the exception message will be sent to CloudFormation Events. | 625941dd377c676e912724ce |
def testcode_file_id(filename, stem): <NEW_LINE> <INDENT> filename = os.path.basename(filename) <NEW_LINE> file_id = filename.replace('%s.' % (stem), '') <NEW_LINE> file_id = re.sub(r'\.inp=.*', '', file_id) <NEW_LINE> file_id = re.sub(r'\.args=.*', '', file_id) <NEW_LINE> return file_id | Extract the file_id from a filename in the testcode format. | 625941dd55399d3f055889dc |
@commandWrap <NEW_LINE> def mirrorJoint(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.mirrorJoint(*args, **kwargs) | :rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941dd009cb60464c636d6 |
def parse_gmt_file(path: Optional[str] = None) -> List[Tuple[str, str, Set[str]]]: <NEW_LINE> <INDENT> with open(path or GMT_HGNC_PATH) as file: <NEW_LINE> <INDENT> return [ _process_line(line) for line in file ] | Return file as list of pathway - gene sets
:param path: url from gmt file
:return: line-based processed file | 625941dde5267d203edcdfbf |
def to_message(self): <NEW_LINE> <INDENT> return CommentResponseMessage(id=self.key.id(), comment=self.content, added=self.timestamp) | Turns the Comment entity into a ProtoRPC object.
| 625941dd8c0ade5d55d3ece4 |
def create_query_dict(inner_params, country_list, sort_by, pages, andor): <NEW_LINE> <INDENT> params = { "q": create_inner_string(inner_params), "t":"ns", "cl": ",".join(country_list), "st":"adv", "ob": sort_by, "p": str(pages), "sa": andor } <NEW_LINE> return params | simpler way of creating api parameter dictionary
Arguments:
inner_params {dictionary} -- [description]
country_list {list} -- [description]
sort_by {string} -- [description]
pages {int} -- [description]
andor {string} -- [description]
Returns:
[type] -- [description] | 625941dd8e7ae83300e4b2f4 |
def deserialize(self, s): <NEW_LINE> <INDENT> if not s: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> left_list = [l_item for l_item in s.split("[")] <NEW_LINE> right_list = [r_item for r_item in left_list.pop().split("]")] <NEW_LINE> num_list = [int(item) for item in right_list[0].split(",") if item] <NEW_LINE> de... | :type s: str
:rtype: NestedInteger | 625941ddfbf16365ca6f64ef |
def etn_price_trend_of_item(self): <NEW_LINE> <INDENT> data = { "bld": "dbms/MDC/STAT/standard/MDCSTAT06601", "tboxisuCd_finder_secuprodisu2_5": f"{self.data_tp}/{self.data_nm}", "isuCd": self.data_cd, "codeNmisuCd_finder_secuprodisu2_5": self.data_nm, "strtDd": self.start, "endDd": self.end, } <NEW_LINE> return self.u... | 개별종목 시세추이 [13203] | 625941dd26068e7796caf009 |
def process(self, batch_x, training=False): <NEW_LINE> <INDENT> if batch_x.ndim == 3: <NEW_LINE> <INDENT> batch_x = np.expand_dims(batch_x, 0) <NEW_LINE> <DEDENT> return self._model(batch_x, training) | Develop RAW input and return RGB image. | 625941dd23849d37ff7b33b4 |
def ms_link_get_status(calldic=None): <NEW_LINE> <INDENT> calldic = calldic or idic() <NEW_LINE> respdic = odic(calldic) <NEW_LINE> respdic.result.utilization = netusage(False) <NEW_LINE> return json.dumps(respdic) | The request:
{
"args": {},
"request": "ms_link_get_status",
"trans_id": 1464244693,
"ts": "20160526143813"
}
response:
{
"err_code": 0,
"msg": "Demo response",
"response": "ms_link_get_status",
"result": {
"utilization": [
{
"port_uid": "1000_0",
... | 625941dd73bcbd0ca4b2c39d |
def read_data(image_dir, image_shape, label_path="labels.txt"): <NEW_LINE> <INDENT> label_dict = {} <NEW_LINE> if os.path.exists(label_path): <NEW_LINE> <INDENT> with open(label_path, encoding="utf-8") as file: <NEW_LINE> <INDENT> for line in file: <NEW_LINE> <INDENT> class_name, id = line.strip().split() <NEW_LINE> la... | 读取图片
:param image_dir:
:param image_shape:
:param label_path:
:return: | 625941dd6aa9bd52df0370cc |
def _yaml_load_object(name, config, default, *args): <NEW_LINE> <INDENT> options = config.get(name, dict()) <NEW_LINE> obj_type = options.pop('type', default) <NEW_LINE> try: <NEW_LINE> <INDENT> return eval(obj_type)(*args, **options) <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> msg = "ERROR: The %s block ... | Helper for loading MooseDocs objects: Reader, Renderer, Translator | 625941dd004d5f362079a658 |
@jit(nopython=True, cache=True) <NEW_LINE> def hist1d(data, bins): <NEW_LINE> <INDENT> d_indices = np.digitize(data, bins) <NEW_LINE> hist = np.zeros(bins.shape[0] - 1) <NEW_LINE> for i in range(data.shape[0]): <NEW_LINE> <INDENT> hist[d_indices[i] - 1] += 1 <NEW_LINE> <DEDENT> binwidths = np.diff(bins) <NEW_LINE> binc... | Creates a 1D histogram of the provided data (accelerated with numba)
Args:
data (ndarray): 1D array containing the data to be histogrammed
bins (ndarray): 1D array containing the binedges of the histogram
Returns:
Hist1d: A histogram object (namedtuple) containing the histogramed
data and othe... | 625941dd91af0d3eaac9bd42 |
def extend(self, items): <NEW_LINE> <INDENT> for item in items: self.append(item) | Append all elements from items to the queue | 625941dd0a366e3fb873eb43 |
def showdialog(self): <NEW_LINE> <INDENT> retval = QMessageBox.question(self.iface.mainWindow(), "Question", "Agregar Direccion?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) <NEW_LINE> val = None <NEW_LINE> if retval == QMessageBox.Yes: <NEW_LINE> <INDENT> val = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> va... | msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText("Insertar CL_NODO?")
msg.setWindowTitle("Insertar CL_NODOS")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_() | 625941dd82261d6c526ab7ca |
def header(): <NEW_LINE> <INDENT> return "# Some kind of legal stuff" + LF + LF | return some kind of header - legal stuff for example
@return: string | 625941dd31939e2706e4d18c |
def _try_aggregate_string_function(self, arg, *args, **kwargs): <NEW_LINE> <INDENT> assert isinstance(arg, str) <NEW_LINE> f = getattr(self, arg, None) <NEW_LINE> if f is not None: <NEW_LINE> <INDENT> if callable(f): <NEW_LINE> <INDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> assert len(args) == 0 <NEW_LINE> asse... | if arg is a string, then try to operate on it:
- try to find a function (or attribute) on ourselves
- try to find a numpy function
- raise | 625941dd1d351010ab855e42 |
def test_get_service_with_no_json(self): <NEW_LINE> <INDENT> hass = MagicMock() <NEW_LINE> m = mock_open() <NEW_LINE> with patch( 'homeassistant.components.notify.html5.open', m, create=True ): <NEW_LINE> <INDENT> service = html5.get_service(hass, {}) <NEW_LINE> <DEDENT> assert service is not None | Test empty json file. | 625941dd462c4b4f79d1d9f7 |
def test_register_view_authenticated(mock_request): <NEW_LINE> <INDENT> from .views.default import register_view <NEW_LINE> mock_request.authenticated_userid = 'test@user.com' <NEW_LINE> response = register_view(mock_request) <NEW_LINE> assert isinstance(response, HTTPFound) <NEW_LINE> assert response.location == '/hom... | register_view should redirect to home when user is authenticated. | 625941dd9b70327d1c4e10fd |
def directory_empty(path): <NEW_LINE> <INDENT> return len(os.listdir(path))==0 | Returns true if the directory is empty. False otherwise | 625941dde1aae11d1e749fe1 |
def _get_single_space(s): <NEW_LINE> <INDENT> return ' '.join(s.split()) | Returns a string with extra spaces removed. e.g. CS 111 -> CS 111 | 625941dd24f1403a92600e8a |
def _get_instance_nw_info(self, context, instance): <NEW_LINE> <INDENT> instance_type = flavors.extract_flavor(instance) <NEW_LINE> args = {'instance_id': instance['uuid'], 'rxtx_factor': instance_type['rxtx_factor'], 'host': instance['host'], 'project_id': instance['project_id']} <NEW_LINE> nw_info = self.network_rpca... | Returns all network info related to an instance. | 625941dd21bff66bcd684c76 |
def testAccountSettings(self): <NEW_LINE> <INDENT> self._tester.UpdateUser(self._cookie, settings_dict={'email_alerts': 'on_share_new', 'sms_alerts': 'on_share_new', 'storage_options': ['use_cloud']}) <NEW_LINE> response_dict = self._tester.QueryUsers(self._cookie, [self._user.user_id]) <NEW_LINE> self.assertTrue('acco... | Query for a user with non-empty account settings. | 625941dd30bbd722463cc0f0 |
def mySqrt(self, x): <NEW_LINE> <INDENT> i = 1 <NEW_LINE> j = x <NEW_LINE> res = 0 <NEW_LINE> while i <= j: <NEW_LINE> <INDENT> mid = i + (j-i) // 2 <NEW_LINE> if mid * mid == x: <NEW_LINE> <INDENT> return mid <NEW_LINE> <DEDENT> elif mid * mid > x: <NEW_LINE> <INDENT> j = mid - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | :type x: int
:rtype: int | 625941ddd10714528d60000d |
def get_data(col_names): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info("[AI-MAP]- read data and do some transformation") <NEW_LINE> data = pd.read_csv(train_sample_path, header=None, names=col_names, sep='\t', dtype='str') <NEW_LINE> print(data.shape) <NEW_LINE> print(data.head(5)) <NEW_LINE> print('--------... | Get data from local_file,if hdfs_path is not None, get data from HDFS file.
:param col_names:
:return: | 625941ddcc40096d61595c76 |
def _really_load(self, f, filename, ignore_discard, ignore_expires): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> magic = f.readline() <NEW_LINE> if not re.search(self.magic_re, magic): <NEW_LINE> <INDENT> f.close() <NEW_LINE> raise LoadError( "%r does not look like a Netscape format cookies file" % filename) <NEW_... | Parse cookies from string. Copied from MozillaCookieJar. | 625941dda934411ee37519bb |
def _maybe_project(var, proj): <NEW_LINE> <INDENT> if proj is not None: <NEW_LINE> <INDENT> return tf.nn.bias_add(tf.matmul(var, proj[0]), proj[1]) <NEW_LINE> <DEDENT> return var | Perform a projection of proj is not none. | 625941dd10dbd63aa1bd2ec9 |
def instance(data): <NEW_LINE> <INDENT> return FieldPACDurationsStd(data) | make an instance of FieldPACDurationsStd and return it | 625941ddd7e4931a7ee9e245 |
def _get_theme_from_code_owner(code_owner): <NEW_LINE> <INDENT> mappings = get_code_owner_theme_squad_mappings() <NEW_LINE> if mappings is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if code_owner in mappings: <NEW_LINE> <INDENT> return mappings[code_owner]['theme'] <NEW_LINE> <DEDENT> return None | Returns theme for a code_owner (e.g. 'theme-my-squad' => 'theme') | 625941dd099cdd3c635f0f81 |
def set_pref_service_host(host): <NEW_LINE> <INDENT> global PREF_API_HOST <NEW_LINE> PREF_API_HOST = host <NEW_LINE> return True | Helper to set the prefs service host
This can be handy for debugging or for easy ghosting of devices | 625941dd6e29344779a62937 |
def test_etcd_v2_version(self, etcdctl): <NEW_LINE> <INDENT> etcdctl_2_version = b"etcdctl version 2.3.8\n" <NEW_LINE> with patch("etcdctl.check_output") as comock: <NEW_LINE> <INDENT> comock.return_value = etcdctl_2_version <NEW_LINE> ver = etcdctl.version() <NEW_LINE> assert ver == "2.3.8" | Validate that etcdctl can parse versions for both etcd v2 and
etcd v3 | 625941dd44b2445a339323bb |
def list_clients(self, filters: Dict[str, Union[str, Pattern]]=None, order_by: str=None) -> list: <NEW_LINE> <INDENT> r = self._session.get("{}/api/s/{}/stat/sta".format(self._baseurl, self._site, verify=self._verify_ssl), data="json={}") <NEW_LINE> self._current_status_code = r.status_code <NEW_LINE> self._check_statu... | List all available clients from the api.
:param filters: dict of k/v pairs; string is compiled to regex
:param order_by: order by a key; defaults to '_id'
:return: A list of clients on the format of a dict | 625941ddd4950a0f3b08c672 |
def surface_to_probs(x1s, x2s, surface, grid_size, adjust_centers=True): <NEW_LINE> <INDENT> n_states = grid_size[0]*grid_size[1] <NEW_LINE> states = np.arange(n_states).reshape((grid_size[1],grid_size[0])) <NEW_LINE> res = len(x1s[0])//grid_size[0] <NEW_LINE> if adjust_centers: <NEW_LINE> <INDENT> res_adjust = res//2 ... | given a potential energy landscape (in the form of values for x1,
x2, and f(x1,x2) and a connectivity grid size) returns the transition
probability matrix that corresponds to that surface. Looks for the
highest energy between adjacent states and uses the arrhenius equation
to generate a rate. Potential energy surface i... | 625941dd30c21e258bdfa7c6 |
def next_player_turn(self) -> object: <NEW_LINE> <INDENT> if self.__turn == black: <NEW_LINE> <INDENT> return white <NEW_LINE> <DEDENT> elif self.__turn == white: <NEW_LINE> <INDENT> return black | Return the switched turn | 625941dd851cf427c661a833 |
def check_args(module, warnings): <NEW_LINE> <INDENT> pass | check args.
| 625941dd283ffb24f3c55c25 |
def ParseArguments(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="Perform Part 3 NHS Digital Technical Tests") <NEW_LINE> parser.add_argument("--input", help="Input postcode data", default="import_data.csv") <NEW_LINE> parser.add_argument("--matched", help="Output matched/validated data", default=... | Parse the command line arguments. | 625941dd60cbc95b062c686a |
def write(bytestream, smb_share, target_file, user, password, client_machine_name, server_name, server_ip): <NEW_LINE> <INDENT> logger = logging.getLogger("bytestream2smb.py") <NEW_LINE> logger.debug("-> bytestream2smb.write()") <NEW_LINE> logger.debug(" smb_share : %s" % smb_share) <NEW_LINE> logger.debug("... | Writes bytestream to server_name/smb_share/target_file | 625941dd046cf37aa974d06c |
def _decode_pixel(self, data): <NEW_LINE> <INDENT> return color565(*struct.unpack(self._DECODE_PIXEL, data)) | Decode bytes into a pixel color. | 625941dd0a50d4780f6671bc |
def prune(icp_config, machine_types, keep, aws_profile): <NEW_LINE> <INDENT> stack_type = icp_config['StackType'] <NEW_LINE> conn = boto.connect_ec2(profile_name=aws_profile) <NEW_LINE> for machine_type in machine_types: <NEW_LINE> <INDENT> images = conn.get_all_images(owners='self', filters={ 'tag:Service': MACHINE_TY... | Filter owned AMIs by machine type, environment, and count
Args:
icp_config (dict): Dict of configuration settings
machine_types (list): list of machine types to prune
keep (int): number of images of this machine type to keep
aws_profile (str): aws profile name to use for authentication | 625941dd7c178a314d6ef78b |
def get_scores(self): <NEW_LINE> <INDENT> hist = self.confusion_matrix <NEW_LINE> acc = np.diag(hist).sum() / hist.sum() <NEW_LINE> acc_cls = np.diag(hist) / hist.sum(axis=1) <NEW_LINE> acc_cls = np.nanmean(acc_cls) <NEW_LINE> iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist)) <NEW_LINE> mean_iu... | Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc | 625941dda79ad161976cc46c |
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): <NEW_LINE> <INDENT> last_sum = last_mean * last_sample_count <NEW_LINE> new_sum = _safe_accumulator_op(np.nansum, X, axis=0) <NEW_LINE> new_sample_count = np.sum(~np.isnan(X), axis=0) <NEW_LINE> updated_sample_count = last_sample_count + new... | Calculate mean update and a Youngs and Cramer variance update.
last_mean and last_variance are statistics computed at the last step by the
function. Both must be initialized to 0.0. In case no scaling is required
last_variance can be None. The mean is always required and returned because
necessary for the calculation ... | 625941dd97e22403b379d2c2 |
def f_oneway(*args): <NEW_LINE> <INDENT> n_classes = len(args) <NEW_LINE> n_samples_per_class = np.array([len(a) for a in args]) <NEW_LINE> n_samples = np.sum(n_samples_per_class) <NEW_LINE> ss_alldata = reduce(lambda x, y: x + y, [np.sum(a ** 2, axis=0) for a in args]) <NEW_LINE> sums_args = [np.sum(a, axis=0) for a i... | Performs a 1-way ANOVA.
The one-way ANOVA tests the null hypothesis that 2 or more groups have
the same population mean. The test is applied to samples from two or
more groups, possibly with differing sizes.
Parameters
----------
sample1, sample2, ... : array_like
The sample measurements should be given as argum... | 625941dd66656f66f7cbc4d3 |
def test_upload_image_to_recipe(self): <NEW_LINE> <INDENT> url = image_upload_url(self.recipe.id) <NEW_LINE> with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: <NEW_LINE> <INDENT> img = Image.new('RGB', (10, 10)) <NEW_LINE> img.save(ntf, format='JPEG') <NEW_LINE> ntf.seek(0) <NEW_LINE> res = self.client.post(url, ... | Test uploading an image to recipe | 625941dd3d592f4c4ed1d38d |
@app.route('/checksession') <NEW_LINE> def checksession(): <NEW_LINE> <INDENT> if 'user' in session: <NEW_LINE> <INDENT> return session['user'] <NEW_LINE> <DEDENT> return 'No a valied Session' | This method will establish a (/checksession) end point and when ever
'/checksession'
is called it will perform what ever defined in the below method.
This method for developer use to check the session status.
:return: | 625941dd67a9b606de4a81de |
def create_gpwd(self, lenght: int) -> str: <NEW_LINE> <INDENT> tmp = [] <NEW_LINE> lenght_r = random.randint(12, lenght) <NEW_LINE> for _ in range(lenght_r): <NEW_LINE> <INDENT> tmp.append(TABLE[random.randint(0, len(TABLE)-1)]) <NEW_LINE> <DEDENT> return tmp | Innitialisation aléatoire de l'individu | 625941dd4527f215b584c77b |
def forward(self, input, mixup_lambda=None): <NEW_LINE> <INDENT> x = input[:, None, :] <NEW_LINE> if self.training and mixup_lambda is not None: <NEW_LINE> <INDENT> x = do_mixup(x, mixup_lambda) <NEW_LINE> <DEDENT> x = self.conv_block1(x) <NEW_LINE> x = F.dropout(x, p=0.1, training=self.training) <NEW_LINE> x = self.co... | Input: (batch_size, data_length) | 625941ddb545ff76a891413d |
def p_intrinsic_procedure_name(p): <NEW_LINE> <INDENT> p[0] = p[1] | intrinsic_procedure_name : name | 625941dd50485f2cf553d0c2 |
def maxCoins(self, nums): <NEW_LINE> <INDENT> nums.append(1) <NEW_LINE> nums.insert(len(sums)-1, 1) <NEW_LINE> ans = 0 <NEW_LINE> def dfs(List, Sum): <NEW_LINE> <INDENT> if len(List) == 2: <NEW_LINE> <INDENT> ans = max(ans, Sum) <NEW_LINE> <DEDENT> for i in range(1, len(List)-1): <NEW_LINE> <INDENT> tmp = [] <NEW_LINE>... | :type nums: List[int]
:rtype: int | 625941dd31939e2706e4d18d |
def current_date_string(): <NEW_LINE> <INDENT> return datetime.utcnow().strftime("%Y-%m-%dt%H:%M:%S") | Get the current date as a string. Used for
making a new build which this plugin runs | 625941dde8904600ed9f2258 |
def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() | Return a nice string representation of this TimeArray | 625941ddeab8aa0e5d26de80 |
def execute(self): <NEW_LINE> <INDENT> z1 = self.z1 <NEW_LINE> z2 = self.z2 <NEW_LINE> y1 = abs(self.y1) <NEW_LINE> self.y2 = y1**(.5) + z1 + z2 | Evaluates the equation
y2 = y1**(.5) + z1 + z2. | 625941dd50812a4eaa59c646 |
def doppelanschnitt_Coordinates3d(aziele1,aziele2,pos1,pos2,plot_info=False): <NEW_LINE> <INDENT> ae1 = copy.deepcopy(aziele1) <NEW_LINE> ae2 = copy.deepcopy(aziele2) <NEW_LINE> logger.debug("copied aziele1:\n{}".format(ae1)) <NEW_LINE> logger.debug("copied aziele2:\n{}".format(ae2)) <NEW_LINE> ae1.fill(azimuth=ae1.azi... | calculate 3d position based on Coordinates3d
args:
aziele1,aziele2 (Coordinates3d): coordinates (azimuth/elevation) of
devices 1 and 2. These have to be northed
pos1, pos2 (Coordinates3d): length 1 coordinates (x,y,z) of devices
1 and 2
returns:
positions (Coordinates3d): (x,y,z) position... | 625941dd7c178a314d6ef78c |
def controlTravel(self, caster, targets=None): <NEW_LINE> <INDENT> if self.auto_entity: <NEW_LINE> <INDENT> caster = self.getEntity(caster) <NEW_LINE> <DEDENT> if not isinstance(targets, list): <NEW_LINE> <INDENT> targets = [targets] <NEW_LINE> <DEDENT> if len(targets) > 1 and not caster.immutable: <NEW_LINE> <INDENT> ... | Move one object to a new location.
.. code-block:: xml
<i>caster [$caster] MOVE target</i> | 625941dd656771135c3ebb99 |
def __init__(self, server, port, credentials, tid, fid, share): <NEW_LINE> <INDENT> cmd.Cmd.__init__(self, False) <NEW_LINE> self.prompt = '\x08' <NEW_LINE> self.server = server <NEW_LINE> self.transferClient = None <NEW_LINE> self.tid = tid <NEW_LINE> self.fid = fid <NEW_LINE> self.credentials = credentials <NEW_LINE>... | . | 625941dd5f7d997b87174dc2 |
def plot(decisionTree): <NEW_LINE> <INDENT> def toString(decisionTree, indent=''): <NEW_LINE> <INDENT> if decisionTree.results != None: <NEW_LINE> <INDENT> lsX = [(x, y) for x, y in decisionTree.results.items()] <NEW_LINE> lsX.sort() <NEW_LINE> szY = ', '.join(['%s: %s' % (x, y) for x, y in lsX]) <NEW_LINE> return szY ... | Plots the obtained decision tree. | 625941dd92d797404e3044b2 |
@app.route('/predict',methods=['POST']) <NEW_LINE> def predict(): <NEW_LINE> <INDENT> int_features = [int(x) for x in request.form.values()] <NEW_LINE> final_features = [np.array(int_features)] <NEW_LINE> feature_name = ['CreditScore','Age','Tenure','Balance','NumOfProducts','HasCrCard', 'IsActiveMember','EstimatedSala... | For rendering results on HTML GUI | 625941dd7d43ff24873a2fc9 |
def open_gripper(self, pos=0.08, eff=30.0, wait=False): <NEW_LINE> <INDENT> self._send_gripper_command(pos, eff, wait) <NEW_LINE> self.gripper_state = GripperState.OPEN | Opens gripper | 625941dd29b78933be1e59cf |
def add_term(self, coeff, power): <NEW_LINE> <INDENT> if len(self) > power: <NEW_LINE> <INDENT> if self[power] != None: <NEW_LINE> <INDENT> self[power] += coeff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self[power] = coeff <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> while len(self) < power: <NEW_LINE> <I... | Adds a new term to the polynomial.
If a term with the same power exists it will simply add the coeff to
the existing one. Else, if necessary the list will be filled with
None items to achieve the new rank. All None items are ignored in
every operation defined by the polynomial class.
Returns self.
coeff -- coefficie... | 625941dd0c0af96317bb850f |
@app.cli.command() <NEW_LINE> def test(): <NEW_LINE> <INDENT> test_dir = os.path.join('application', 'tests') <NEW_LINE> tests = unittest.TestLoader().discover(test_dir) <NEW_LINE> unittest.TextTestRunner(verbosity=2).run(tests) | Run the unit tests. | 625941dd21bff66bcd684c77 |
def length_hlamp(self, hlamp_min=6): <NEW_LINE> <INDENT> cn = self.segment_copy_number <NEW_LINE> hlamp = (cn.sum(axis=1) >= hlamp_min) * 1 <NEW_LINE> return (hlamp * self.l).sum() | Length of the genome with high level amplification.
| 625941ddb830903b967e9c30 |
def get_greens_filename(greens_name, station_name): <NEW_LINE> <INDENT> data = parse_greens_name(greens_name) <NEW_LINE> return "{name}_{terms}.{comp}".format(name=station_name, terms=data['terms'], comp=data['comp']) | Return green's function's filename
| 625941dd851cf427c661a834 |
def get_comment_karma(self): <NEW_LINE> <INDENT> return Comment.find({'user_id': self.id}).count() | fetch the number of votes this user has had on his/her comments | 625941dd26238365f5f0f19a |
def new_tile(self): <NEW_LINE> <INDENT> empty_square_lists = [] <NEW_LINE> for row in range(self._grid_height): <NEW_LINE> <INDENT> for col in range(self._grid_width): <NEW_LINE> <INDENT> if(self.get_tile(row, col) == 0): <NEW_LINE> <INDENT> empty_square_lists.append((row, col)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if... | Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time. | 625941dd4f6381625f114d63 |
def get_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('ernwin_dir', type = str, help='A directory containing the step*.coord files.') <NEW_LINE> parser.add_argument('--fair-ensemble', action='store', help='A folder containing the ' 'build*.coord files representing a fai... | Here all commandline & help-messages arguments are defined.
:returns: an instance of argparse.ArgumentParser | 625941dd94891a1f4081bdd2 |
def recover_path(self): <NEW_LINE> <INDENT> curr_point = self.finish_point <NEW_LINE> path = [curr_point] <NEW_LINE> while curr_point != self.start_point: <NEW_LINE> <INDENT> suitable_neighbour = [ neighbour for neighbour in self.find_neighbours(curr_point) if curr_point.d - neighbour.d == 1 ][0] <NEW_LINE> path.append... | Восстанавливает найденный путь. | 625941dd07d97122c4178bb9 |
def __calculate_goodness(self, cluster1, cluster2): <NEW_LINE> <INDENT> number_links = self.__calculate_links(cluster1, cluster2); <NEW_LINE> devider = (len(cluster1) + len(cluster2)) ** self.__degree_normalization - len(cluster1) ** self.__degree_normalization - len(cluster2) ** self.__degree_normalization; <NEW_LINE>... | !
@brief Calculates coefficient 'goodness measurement' between two clusters. The coefficient defines level of suitability of clusters for merging.
@param[in] cluster1 (list): The first cluster.
@param[in] cluster2 (list): The second cluster.
@return Goodness measure between two clusters. | 625941dd38b623060ff0b115 |
def loadRecentFileSlot(self): <NEW_LINE> <INDENT> self.runHook(self.hooks['loadRecentFileSlot_Start']) <NEW_LINE> fname = str(self.sender().text()) <NEW_LINE> self.loadImageStack(fname) <NEW_LINE> self.initialiseAxes() | load a file from recently opened list | 625941dd566aa707497f488c |
def test_convertToMapPoint(): <NEW_LINE> <INDENT> a = cu.convertToMapPoint( [1, 3] ) <NEW_LINE> assert bool(a) <NEW_LINE> assert bool(cu.convertToMapPoint( a )) <NEW_LINE> try: <NEW_LINE> <INDENT> cu.convertToMapPoint( "no location!" ) <NEW_LINE> assert False <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> a... | parameters: loc | 625941dd6fb2d068a760f3c9 |
def clear_left(ax=None): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <DEDENT> ax.spines['left'].set_color('none') <NEW_LINE> ax.yaxis.set_ticks_position('right') | Remove the left edge of the axis bounding box.
Parameters
----------
ax : axis object (default=pyplot.gca())
References
----------
http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html | 625941ddaad79263cf390d6d |
def scheduleInactivityCheck(self): <NEW_LINE> <INDENT> self.timer = Timer(self.options['inactivity'], self.checkInactivity) <NEW_LINE> self.timer.start() <NEW_LINE> pass | Start a timer to check if session's inactivity.
Timer will timeout in a duration which is set in options. | 625941dd2eb69b55b151cbda |
def get_orders(self): <NEW_LINE> <INDENT> orders = pd.read_csv(self.raw_data_dir + 'orders.csv') <NEW_LINE> orders = orders.fillna(0.0) <NEW_LINE> orders['days'] = orders.groupby(['user_id'])['days_since_prior_order'].cumsum() <NEW_LINE> orders['days_last'] = orders.groupby(['user_id'])['days'].transform(max) <NEW_LINE... | get order context information | 625941ddd10714528d60000e |
def mouseclick(pos): <NEW_LINE> <INDENT> memory.expose(pos) | Event handler to deal clic on a card.
:param pos: (int >= 0, int >= 0) | 625941dd090684286d50f011 |
def t_anom(E, e): <NEW_LINE> <INDENT> theta = 2*np.arctan(np.tan(E/2)*np.sqrt((1-e)/(1+e))) <NEW_LINE> return theta | Calculates the true anomaly of a body
angular parameter that defines the position of a body moving along a Keplerian orbit.
It is the angle between the direction of periapsis (closest approach to cent. body)
and the current position of the body, as seen from the main focus of the ellipse
(the point around which the... | 625941dd4d74a7450ccd44ec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.