code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def add_view(self, request, form_url='', extra_context=None): <NEW_LINE> <INDENT> extra_context = extra_context or {} <NEW_LINE> first, last, entries = Report.get_new_report_details() <NEW_LINE> extra_context['no_entries'] = not JournalEntry.entries_exists() <NEW_LINE> extra_context['entries'] = entries <NEW_LINE> extr...
Django view for overriding the view where you add reports.
625941d8ad47b63b2c50a206
def one_to_all(self, ptraj1, ptraj2, index1): <NEW_LINE> <INDENT> logger.info('GPU computing') <NEW_LINE> assert np.count_nonzero(ptraj1 - ptraj2) == 0 <NEW_LINE> results = np.empty(len(ptraj1), dtype=np.float32) <NEW_LINE> self._gpurmsd.set_rmsd_array(results) <NEW_LINE> self._gpurmsd.all_against_one_rmsd(int(index1))...
Compute the distance from the `index1th` frame to the rest of the frames Note, for GPURMSD, ptraj1 and ptraj2 must be the same, and must be the trajectories that were passed to __init__ to be loaded onto the GPU
625941d8566aa707497f47ed
def load_data(): <NEW_LINE> <INDENT> fname = '101_ObjectCategories' <NEW_LINE> origin = ('http://www.vision.caltech.edu/Image_Datasets/Caltech101/' '101_ObjectCategories.tar.gz') <NEW_LINE> path = get_file(fname, origin=origin, untar=True, md5_hash='b224c7392d521a49829488ab0f1120d9') <NEW_LINE> subdirs = [os.path.join(...
Loads Caltech 101 dataset. # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
625941d8956e5f7376d710f3
def main(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _main() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> exit(1)
Wrapper main function that handles broken pipes and keyboard interrupts.
625941d80a366e3fb873eaa3
def generate_xmas_tree(rows=10): <NEW_LINE> <INDENT> pass
Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation): * *** *****
625941d85510c4643540f666
@wq.command() <NEW_LINE> @click.argument("project_name", required=True) <NEW_LINE> @click.argument("destination", required=False) <NEW_LINE> def start(project_name, destination): <NEW_LINE> <INDENT> call_command( 'startproject', project_name, destination, template=template, extensions=["py", "yml", "conf", "html", "sh"...
Start a new project with wq.app and wq.db. A new Django project will be created from a wq-specific template. After running this command, you may want to do the following:  chmod +x deploy.sh db/manage.py sudo chown www-data media/ cd app; wq init See https://wq.io/docs/setup for more tips on getting st...
625941d8498bea3a759b9d36
def display_utxos_for_disable_choice_default(wallet_service, utxos_enabled, utxos_disabled): <NEW_LINE> <INDENT> def default_user_choice(umax): <NEW_LINE> <INDENT> jmprint("Choose an index 0 .. {} to freeze/unfreeze or " "-1 to just quit.".format(umax)) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT...
CLI implementation of the callback required as described in wallet_disableutxo
625941d8462c4b4f79d1d958
def install_dll(self, eci): <NEW_LINE> <INDENT> if sys.platform == 'win32': <NEW_LINE> <INDENT> self.get_pythonapi_handle = rffi.llexternal( 'pypy_get_pythonapi_handle', [], DLLHANDLE, compilation_info=eci)
NOT_RPYTHON Called when the dll has been compiled
625941d85fcc89381b1e1949
def generate_traffic_noise_params(seed1, seed2) -> Tuple[float, float]: <NEW_LINE> <INDENT> wavelength_cos = 60 + 20 * (dhash(seed1 + seed2) / 0xffffffff) - 10 <NEW_LINE> wavelength_sin = 60 + 20 * (dhash(seed1 * seed2) / 0xffffffff) - 10 <NEW_LINE> return wavelength_cos, wavelength_sin
generates some parameters for the traffic noise It should look random, and it is symmetrical (Can't think why it has to be symmetrical, but it would be easy enough to modify it not to be if need be)
625941d8851cf427c661a794
def reset_buffer(self): <NEW_LINE> <INDENT> self.buf = bytearray(self.blen)
Reset the buffer
625941d8bd1bec0571d908b7
def get_gelfilepath(self): <NEW_LINE> <INDENT> filename = self.Root.Gelfilepath.get() <NEW_LINE> if not filename: <NEW_LINE> <INDENT> config = self.parse_config_from_yaml_widget() <NEW_LINE> if 'gelfile' in config: <NEW_LINE> <INDENT> return config['gelfile'] <NEW_LINE> <DEDENT> <DEDENT> return filename
Returns content of gel-filepath entry widget.
625941d80383005118ecf869
def __init__(self, return_code): <NEW_LINE> <INDENT> self.return_code = return_code <NEW_LINE> super().__init__()
Return an instance of a Halt ControlSignal object.
625941d873bcbd0ca4b2c2fe
def email(title, gfyear=None, *, type=_EMAILTYPE_POSTFIX): <NEW_LINE> <INDENT> (root, period), gfyear = _validate(title, gfyear) <NEW_LINE> root = _normalize(root) <NEW_LINE> try: <NEW_LINE> <INDENT> root = next(email for r, p, email in _SPECIAL_CASES if (r, p) == (root, period)) <NEW_LINE> <DEDENT> except StopIteratio...
Givet en titel af (root, period), returner titlens emailnavn. :param tuple title: tupel af en str og int, hvor strengen er roden af titlen og int er perioden. :param int gfyear: året hvor nuværende BEST er blevet valgt. Det kan også sættes som en context. Se :doc:`gfyear`. :param...
625941d8bf627c535bc13457
def __init__(self, cache, session_id, ttl): <NEW_LINE> <INDENT> assert session_id is None or type(session_id) is str <NEW_LINE> assert type(ttl) is int <NEW_LINE> self._cache = cache <NEW_LINE> self._ttl = ttl <NEW_LINE> if session_id is None: <NEW_LINE> <INDENT> self._id = Session._generate_id() <NEW_LINE> <DEDENT> el...
Initialize user session. Will generate a new session id if session id is None.
625941d8046cf37aa974cfce
def set_filter(self, andesite_filter: Filter) -> None: <NEW_LINE> <INDENT> self[andesite_filter.__filter_name__] = andesite_filter
Set the value for a filter. Args: andesite_filter: Filter to set
625941d87d43ff24873a2f29
def __init__(self, frame2cam_map): <NEW_LINE> <INDENT> super(CameraMap, self).__init__() <NEW_LINE> cm_new = self.MAPTK_LIB.maptk_camera_map_new <NEW_LINE> cm_new.argtypes = [ctypes.c_size_t, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(Camera.C_TYPE_PTR)] <NEW_LINE> cm_new.restype = self.C_TYPE_PTR <NEW_LINE> fn_list...
:param frame2cam_map: Association of frame number to camera instance :type frame2cam_map: dict of (int, maptk.Camera)
625941d8c4546d3d9de72cbd
def preprocess_image(image): <NEW_LINE> <INDENT> tmp_img = cv2.GaussianBlur(image, (3, 3), 5) <NEW_LINE> img = cv2.addWeighted(image, 1.5, tmp_img, -0.5, 0) <NEW_LINE> img = cv2.equalizeHist(img) <NEW_LINE> return img
Sharpens the image, then applies histogram equalization
625941d897e22403b379d223
def FD_int(eta, order): <NEW_LINE> <INDENT> return integrate.quad(lambda x: x**order/(1 + np.exp(x - eta)), 0, 100)[0];
Numerically computes the Fermi integral.
625941d871ff763f4b549917
def remove_stopwords(tokens): <NEW_LINE> <INDENT> return [w for w in tokens if w not in ENG_STOPWORDS]
Remove stopwords from tokens.
625941d84d74a7450ccd444b
def getTOFbeta(ins,dsp): <NEW_LINE> <INDENT> return ins['beta-0']+ins['beta-1']/dsp**4+ins['beta-q']/dsp**2
get TOF peak profile beta :param dict ins: instrument parameters with at least 'beat-0', 'beta-1' & 'beta-q' as values only :param float dsp: d-spacing of peak :returns: float getTOFbeta: peak beat
625941d88a43f66fc4b542eb
def build_saver(self): <NEW_LINE> <INDENT> default_saver = tf.train.Saver(max_to_keep=3, allow_empty=True) <NEW_LINE> self.savers = {self.name: default_saver}
Build variable savers. By default, I build a saver to save all variables. In case you need to recover a part of variables, you can inherit this method and create multiple savers for different variables. All savers should arrange in a dict which maps saver and its saving name
625941d882261d6c526ab72a
def _AllotLibraries(module_tree, libraries_map): <NEW_LINE> <INDENT> allotment_map = collections.defaultdict(set) <NEW_LINE> for library, modules in libraries_map.items(): <NEW_LINE> <INDENT> ancestor = _ClosestCommonAncestor(module_tree, modules) <NEW_LINE> if not ancestor: <NEW_LINE> <INDENT> raise Exception('Cannot ...
Allot all libraries to a module. Parameters: module_tree: Dictionary mapping each module to its parent. Modules can map to None, which is considered the root of the tree. libraries_map: Dictionary mapping each library to a set of modules, which depend on the library. Returns: A dictionary mapping mappin...
625941d8236d856c2ad44a65
def _create_datasets(self): <NEW_LINE> <INDENT> X = self.df.drop(columns='Fake or Satire?') <NEW_LINE> y = self.df['Fake or Satire?'] <NEW_LINE> X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=self.test_size) <NEW_LINE> self.X_train = X_train.reset_index(drop=True) <NEW_LINE> self.X_test = X_test.re...
creates train and test datasets. :return: train and test datasets
625941d856ac1b37e6264454
def rows(query, row_func=dict): <NEW_LINE> <INDENT> def inner(model, *args, **kwargs): <NEW_LINE> <INDENT> return [row_func(r) for r in model.engine.execute(query, *args, **kwargs)] <NEW_LINE> <DEDENT> return inner
A helper function that takes a query and returns a function that will query the database and return a list of rows with the row_func applied to each.
625941d8287bf620b61d3cea
def _start_server(self) -> bool: <NEW_LINE> <INDENT> command = ('/bin/systemctl', 'start', self.unit) <NEW_LINE> try: <NEW_LINE> <INDENT> check_call(command) <NEW_LINE> <DEDENT> except CalledProcessError as cpe: <NEW_LINE> <INDENT> LOGGER.debug(cpe) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
Starts the server.
625941d8b5575c28eb68e28a
def author_articles(self, title: str) -> List[str]: <NEW_LINE> <INDENT> key = f'wiki.author-articles:{title}' <NEW_LINE> data = cache.get(key) <NEW_LINE> if not data: <NEW_LINE> <INDENT> data = [page.name for page in self.mw.Pages.get(title).backlinks()] <NEW_LINE> cache.set(key, data, config.CACHE_TIMEOUT) <NEW_LINE> ...
List of titles by the author
625941d84428ac0f6e5baa7c
def get_variables(self): <NEW_LINE> <INDENT> if not self.built: <NEW_LINE> <INDENT> self.build() <NEW_LINE> <DEDENT> if tfe.in_eager_mode(): <NEW_LINE> <INDENT> variables = [] <NEW_LINE> for layer in self.layers.values(): <NEW_LINE> <INDENT> variables += layer.variables <NEW_LINE> <DEDENT> return variables <NEW_LINE> <...
Get the list of all trainable variables in the graph.
625941d8004d5f362079a5ba
def normalize_salary_string(txt): <NEW_LINE> <INDENT> from_char = ["حقوق توافقی", "حقوق حقوق پایه (وزارت کار)"] <NEW_LINE> to_char = ["Negotiable", 2600000] <NEW_LINE> for old, replacement in zip(from_char, to_char): <NEW_LINE> <INDENT> if txt == old: <NEW_LINE> <INDENT> txt = replacement <NEW_LINE> return txt <NEW_LIN...
extract salary amount from given string if it exists and convert it to an integer number Input Parameter Example ---> حقوق از ۱۰,۰۰۰,۰۰۰ تومان Expected output Example ---> 10000000
625941d84a966d76dd551299
def test_cryptocompare_query_pricehistorical(cryptocompare): <NEW_LINE> <INDENT> price = cryptocompare.query_endpoint_pricehistorical( from_asset=A_SNGLS, to_asset=A_BTC, timestamp=1475413990, ) <NEW_LINE> assert price
Test that cryptocompare price historical query works fine
625941d8ac7a0e7691ed4350
def isValidSudoku(self, board): <NEW_LINE> <INDENT> usedRow = [[0 for i in range(9)] for j in range(9)] <NEW_LINE> usedClomn = [[0 for i in range(9)] for j in range(9)] <NEW_LINE> usedSuqare = [[0 for i in range(9)] for j in range(9)] <NEW_LINE> result = True <NEW_LINE> for i in range(9): <NEW_LINE> <INDENT> for j in r...
:type board: List[List[str]] :rtype: bool
625941d8e1aae11d1e749f42
def getStock(self, name): <NEW_LINE> <INDENT> return self._stock[name]
Returns the amount of stock available for a provided item name
625941d8187af65679ca53a7
def get_default_delivery_option(self): <NEW_LINE> <INDENT> delivery_options = self.get_delivery_options() <NEW_LINE> if len(delivery_options) > 0: <NEW_LINE> <INDENT> return delivery_options[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Return the default delivery option, which is the first delivery option in the system or None if no delivery option is available.
625941d8e64d504609d74ac8
def resample(data, s_freq, axis='time'): <NEW_LINE> <INDENT> output = data._copy() <NEW_LINE> for i in range(data.number_of('trial')): <NEW_LINE> <INDENT> out_samples = int(floor(data.number_of('time')[i] / data.s_freq * s_freq)) <NEW_LINE> orig_samples = int(out_samples / s_freq * data.s_freq) <NEW_LINE> interval = (d...
Downsample the data after applying a filter. Parameters ---------- data : instance of Data data to downsample s_freq : int or float desired sampling frequency axis : str axis you want to apply downsample on (most likely 'time') Returns ------- instance of Data downsampled data
625941d8b57a9660fec33b0f
def __init__(self, robot, interface=None, camera=None, first_person_view=False, speed=10, priority=None, verbose=False): <NEW_LINE> <INDENT> self.robot = robot <NEW_LINE> if speed == 0: <NEW_LINE> <INDENT> speed = 1 <NEW_LINE> <DEDENT> self.speed = speed if speed > 0 else -speed <NEW_LINE> if not isinstance(interface, ...
Initialize the Bridge between a Mouse-Keyboard interface and a wheeled robot instance. Args: robot (WheeledRobot): wheeled robot instance. interface (None, MouseKeyboardInterface): mouse keyboard interface. If None, it will create one. camera (WorldCamera): world camera instance. This will allow the user t...
625941d8adb09d7d5db6ca17
def __init__(self, connect_info: irc.ConnectInfo, **kwargs): <NEW_LINE> <INDENT> Chatbot.__init__(self, connect_info, **kwargs) <NEW_LINE> irc.ClientProtocol.__init__(self, connect_info) <NEW_LINE> self.connect_info = connect_info <NEW_LINE> self.__nick_rotation = iter(self.connect_info.nicks) <NEW_LINE> self.__nick = ...
Initializes the IRC chat bot. :param connect_info: the connection information to use
625941d8099cdd3c635f0ee2
def _auto_attach_shaders(self): <NEW_LINE> <INDENT> if self.AUTO_ATTACH is None: <NEW_LINE> <INDENT> return self._funcs.keys() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.AUTO_ATTACH
Return a list of shaders to automatically attach/detach
625941d8a05bb46b383ecaa9
def test_should_convert_kanji_to_number_4(self): <NEW_LINE> <INDENT> result = AddressParser( "1410064 神奈川県横浜市青葉区青葉台四丁目9-4-406 2階" ) <NEW_LINE> result = result.get_output_components() <NEW_LINE> self.assertTrue("4-" in result["street_address"])
It should convert kanji of 4 to numeric value
625941d896565a6dacc8f953
def setOfWords2Vec(vocabList, inputSet): <NEW_LINE> <INDENT> returnVec = [0] * len(vocabList) <NEW_LINE> for word in vocabList: <NEW_LINE> <INDENT> if word in vocabList: <NEW_LINE> <INDENT> returnVec[vocabList.index(word)] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('the word: %s is not in my Vocabulary!' %...
Function: 根据vocabList词汇表,将inputSet向量化,向量的每个元素为 1或 0 :param vocabList: createVocabList返回的列表 :param inputSet: 切分的词条列表 :return: returnVec - 文档向量,词集模型 Modify: 2018-08-14
625941d8d8ef3951e32437c6
def test_check_rt_controls(self): <NEW_LINE> <INDENT> resource_type = 'Patient' <NEW_LINE> rr = get_resourcerouter() <NEW_LINE> response = check_rt_controls(resource_type) <NEW_LINE> expect = SupportedResourceType.objects.get(resourceType=resource_type, fhir_source=rr) <NEW_LINE> self.assertEquals(response.id, expect.i...
Get SupportedResourceType from resource_type
625941d88e7ae83300e4b255
def fieldExists(in_fc: str, fieldname: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fieldList = arcpy.ListFields(os.path.join(arcpy.env.workspace, in_fc)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> fieldList = arcpy.ListFields(in_fc) <NEW_LINE> <DEDENT> for f in fieldList: <NEW_LINE> <INDENT> if f.na...
Check whether field exists in feature class.
625941d8be7bc26dc91cd884
def eat(self, char): <NEW_LINE> <INDENT> if self.peak() != char: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.pos += 1 <NEW_LINE> return True
Try to eat a character.
625941d8cad5886f8bd27261
def _l2t_interp(label): <NEW_LINE> <INDENT> if 'Interp' in label: <NEW_LINE> <INDENT> prefix = list(takewhile(lambda l: l != 'Interp', label)) <NEW_LINE> suffix = label[label.index('Interp')+1:] <NEW_LINE> if len(prefix) == 1: <NEW_LINE> <INDENT> return 'Supplement I to Part %s' % prefix[0] <NEW_LINE> <DEDENT> elif suf...
Helper function converting interpretation labels to text. Assumes _l2t_subterp failed
625941d8d58c6744b4257ee7
def spawn_large_box(space): <NEW_LINE> <INDENT> mass = 10 <NEW_LINE> h = random.randint(26, 40) <NEW_LINE> w = h <NEW_LINE> size = (h, w) <NEW_LINE> intertia = pymunk.moment_for_box(mass, size) <NEW_LINE> body = pymunk.Body(mass, intertia) <NEW_LINE> body.position = 300, 500 <NEW_LINE> box = pymunk.Poly(body, [(-w, -h)...
A funtion that controls how the boxes will spawn.
625941d8099cdd3c635f0ee3
def create(self, req, *args, **kwargs): <NEW_LINE> <INDENT> context = req.context <NEW_LINE> try: <NEW_LINE> <INDENT> values = json.loads(req.body) <NEW_LINE> url = req.url <NEW_LINE> if 'default_ttl' not in values.keys(): <NEW_LINE> <INDENT> values['default_ttl'] = "3600" <NEW_LINE> <DEDENT> if 'renewal' not in values...
create the dns zones
625941d8fb3f5b602dac391e
@analysis_results_blueprint.route('/analysis_results/<result_uuid>', methods=['GET']) <NEW_LINE> def get_single_result(result_uuid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> uuid = UUID(result_uuid) <NEW_LINE> analysis_result = AnalysisResultMeta.objects.get(uuid=uuid) <NEW_LINE> result = analysis_result_schema.dum...
Get single analysis result.
625941d815fb5d323cde0d9b
def test_jpeg_insert(self, client): <NEW_LINE> <INDENT> test_data = { "file_name": "c29bb130a677fc8e3a3fe66221eec68e.jpeg", "path": "images/raw/c29bb130a677fc8e3a3fe66221eec68e.jpeg", } <NEW_LINE> cwd = os.getcwd() <NEW_LINE> test_file = open(cwd + '/api/tests/c29bb130a677fc8e3a3fe66221eec68e.jpeg', 'rb') <NEW_LINE> da...
Start with a blank database.
625941d83c8af77a43ae3a2b
def read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, verbose=True, private_key=None, dialect='legacy', **kwargs): <NEW_LINE> <INDENT> pandas_gbq = _try_import() <NEW_LINE> return pandas_gbq.read_gbq( query, project_id=project_id, index_col=index_col, col_order=col_order, reauth=reauth, ver...
Load data from Google BigQuery. The main method a user calls to execute a Query in Google BigQuery and read results into a pandas DataFrame. This function requires the `pandas-gbq package <https://pandas-gbq.readthedocs.io>`__. Authentication to the Google BigQuery service is via OAuth 2.0. - If "private_key" is no...
625941d8d7e4931a7ee9e1a7
def test_net_on_dataset( args, dataset_name, proposal_file, output_dir, multi_gpu=False, gpu_id=0): <NEW_LINE> <INDENT> dataset = JsonDataset(dataset_name) <NEW_LINE> test_timer = Timer() <NEW_LINE> test_timer.tic() <NEW_LINE> if multi_gpu: <NEW_LINE> <INDENT> num_images = len(dataset.get_roidb()) <NEW_LINE> all_boxes,...
Run inference on a dataset.
625941d8009cb60464c63639
def activate(self, master_key): <NEW_LINE> <INDENT> if not self.public_key: <NEW_LINE> <INDENT> raise Exception("Cannot activate UserKey: Public key must be filled first.") <NEW_LINE> <DEDENT> self.master_key_cipher = encrypt_master_key(master_key, self.public_key) <NEW_LINE> self.save()
Activate the UserKey by saving encrypted copy of the master key.
625941d9d6c5a102081442d5
def maketrans(fromstr, tostr): <NEW_LINE> <INDENT> if len(fromstr) != len(tostr): <NEW_LINE> <INDENT> raise ValueError("maketrans arguments must have same length") <NEW_LINE> <DEDENT> global _idmapL <NEW_LINE> if not _idmapL: <NEW_LINE> <INDENT> _idmapL = list(_idmap) <NEW_LINE> <DEDENT> L = _idmapL[:] <NEW_LINE> froms...
maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length.
625941d8507cdc57c6306f68
@click.command("panel", short_help="Load a gene panel") <NEW_LINE> @click.argument("path", type=click.Path(exists=True), required=False) <NEW_LINE> @click.option("--panel-id", help="The panel identifier name") <NEW_LINE> @click.option("--institute", help="Specify the owner of the panel. Defaults to cust000.") <NEW_LINE...
Add a gene panel to the database.
625941d976d4e153a657edbb
def test_config_images_list(self): <NEW_LINE> <INDENT> result = {'retcode': 0, 'stdout': 'image1\nimage2\n'} <NEW_LINE> salt_mock = { 'cmd.run_all': MagicMock(return_value=result), } <NEW_LINE> with patch.dict(kubeadm.__salt__, salt_mock): <NEW_LINE> <INDENT> assert kubeadm.config_images_list() == ['image1', 'image2'] ...
Test kuebadm.config_images_list without parameters
625941d991af0d3eaac9bca4
def toxml(self, element): <NEW_LINE> <INDENT> element = SubElement(element, "FilterRule") <NEW_LINE> SubElement(element, "Name", self._name) <NEW_LINE> SubElement(element, "Value", self._value) <NEW_LINE> return element
Convert to XML.
625941d956ac1b37e6264455
def create_edges(self): <NEW_LINE> <INDENT> for node_id, children in nx.get_node_attributes(self.graph, "com_children").items(): <NEW_LINE> <INDENT> if children: <NEW_LINE> <INDENT> self.graph.add_edges_from(((child, node_id) for child in children))
Takes nx.DiGraph, adds edges to child_comments and returns nx.DiGraph.
625941d91f5feb6acb0c4dd5
def _set_boundaries(self): <NEW_LINE> <INDENT> cur_label = self.gt[0] <NEW_LINE> mask = np.zeros(self.gt.shape, dtype=bool) <NEW_LINE> for label_idx, label in enumerate(self.gt): <NEW_LINE> <INDENT> if label == cur_label: <NEW_LINE> <INDENT> mask[label_idx] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.boun...
Define boundaries for each segment from where sample.
625941d98c3a873295158645
def setup_task_session(self,device): <NEW_LINE> <INDENT> from auto_session import SSH <NEW_LINE> from auto_session import Telnet <NEW_LINE> from auto_session import Unknown <NEW_LINE> if 'ssh' in device.ctype: <NEW_LINE> <INDENT> session = SSH(device.ipaddress,device.username,device.password) <NEW_LINE> <DEDENT> elif '...
Establish a session to the relevant device. If SSH or Telnet is not defined a default Unknown session is used for error handling purposes. This will generate a notification in the task execution screen.
625941d9b545ff76a891409e
def train_single_fold(self, x_train, y_train): <NEW_LINE> <INDENT> print("Training {} classifier with {}".format(self.model_type, self.hyperparameters)) <NEW_LINE> modelobj = self._get_model_object(self.model_type, self.hyperparameters, self.n_cores) <NEW_LINE> trained_model = modelobj.fit(x_train, y_train) <NEW_LINE> ...
Trains a model and saves it as self.trained_model Args: x_train [ndarray]: features in training set (no id column, no target) y_train [ndarray]: target variable in training set (no id column)
625941d921bff66bcd684bda
def iteration(self, node_status=True): <NEW_LINE> <INDENT> self.clean_initial_status(self.available_statuses.values()) <NEW_LINE> actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} <NEW_LINE> self.progress_I = {node: 0 for node in actual_status if actual_status[node] == 1} <NEW_LIN...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
625941d93346ee7daa2b2ff6
def set_Server(self, value): <NEW_LINE> <INDENT> super(ListTagsInputSet, self)._set_input('Server', value)
Set the value of the Server input for this Choreo. ((required, string) Your Zendesk domain and subdomain (e.g., temboocare.zendesk.com).)
625941d9091ae356686671e4
def refresh(self, children=True): <NEW_LINE> <INDENT> super(GUI.ScrollableContainer, self).refresh() <NEW_LINE> self.min_offset = 0 <NEW_LINE> for comp in self.container.child_components: <NEW_LINE> <INDENT> if comp.computed_position[1] < self.min_offset: <NEW_LINE> <INDENT> self.min_offset = comp.computed_position[1] ...
Updates the scrollable container.
625941d95166f23b2e1a53e2
def frames_to_time(cut_frames, frame_rate, frame_offset=0): <NEW_LINE> <INDENT> cut_times = [] <NEW_LINE> for start, end in cut_frames: <NEW_LINE> <INDENT> if frame_offset != 0: <NEW_LINE> <INDENT> start = start + frame_offset <NEW_LINE> end = end + frame_offset <NEW_LINE> <DEDENT> cut_times.append((start / frame_rate,...
Convert a list of frames to a list of times using The frame-rate of the intended video file. a frame offset can be used to shift the time for more accurate times
625941d938b623060ff0b076
def print_user_infos(*args, **kwargs): <NEW_LINE> <INDENT> print(name) <NEW_LINE> print(args, type(args)) <NEW_LINE> print(kwargs, type(kwargs))
*arges :arg类型是一个元组,他接受不确定个数 的非keywords类型参数 **kwargs kwargs类型是一盒字典,他接受不确定个数 的非keywords类型参数 :param args: :param kwargs: :return:
625941d9d164cc6175782fd7
def output_json_file(title, filename): <NEW_LINE> <INDENT> json_title = json.dumps(title, indent=4) <NEW_LINE> with open(filename, 'w') as output: <NEW_LINE> <INDENT> output.write(json_title)
Creates a file with video titles in json format
625941d94e696a04525c96d5
def textScaleHandler(self, event=None): <NEW_LINE> <INDENT> if(not self.__callbackState.isLabelDragMode()): <NEW_LINE> <INDENT> self.__callbackState.toggleLabelDragMode() <NEW_LINE> self.__UI_Statechart.event('<KeyPress-r>', self) <NEW_LINE> self.__callbackState.toggleLabelDragMode() <NEW_LINE> <DEDENT> else: <NEW_LINE...
Activate the UI_Statechart to handle the reactive behaviour
625941d9925a0f43d254a102
def get_absolute_url(self): <NEW_LINE> <INDENT> return self.content_object.get_absolute_url()
The published item doesn't have it's own permalink. It just redirect to the permalink of the child model.
625941d9fb3f5b602dac391f
def get_subject(self, obj, subscriber): <NEW_LINE> <INDENT> return unicode(obj)
Returns the subject for the email that this object represents.
625941d963b5f9789fde736f
def create(self, name, media=None, flist=None, cpu=2, memory=512, nics=None, port=None, mount=None, tags=None, config=None): <NEW_LINE> <INDENT> if nics is None: <NEW_LINE> <INDENT> nics = [] <NEW_LINE> <DEDENT> args = { 'name': name, 'media': media, 'cpu': cpu, 'flist': flist, 'memory': memory, 'nics': nics, 'port': p...
:param name: Name of the kvm domain :param media: (optional) array of media objects to attach to the machine, where the first object is the boot device each media object is a dict of {url, type} where type can be one of 'disk', or 'cdrom', or empty (default to disk) example: [{'url': 'nbd+un...
625941d9bf627c535bc13458
def order_dict_alphabetically(d): <NEW_LINE> <INDENT> od = OrderedDict() <NEW_LINE> for key in sorted(list(d.keys())): <NEW_LINE> <INDENT> assert key not in od <NEW_LINE> od[key] = d[key] <NEW_LINE> <DEDENT> return od
Sort a given dictionary alphabetically :param dict d: :return:
625941d938b623060ff0b077
def __init__(self, kind, line_number, val, nxt=None): <NEW_LINE> <INDENT> ExpNode.__init__(self, kind, line_number, nxt) <NEW_LINE> self.val = val
Initializes an integer expression node. :val: Integer value that this node represents.
625941d9656771135c3ebafa
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TopicGraphCreateRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941d9046cf37aa974cfcf
def generate_meta_story(original_story, numbered_entities): <NEW_LINE> <INDENT> meta_story = [] <NEW_LINE> for sentence in original_story: <NEW_LINE> <INDENT> for numbered_entity in numbered_entities: <NEW_LINE> <INDENT> sentence = sentence.replace(numbered_entity['text'], numbered_entity['ner']) <NEW_LINE> <DEDENT> me...
Generate a "meta story" by replacing named entities in the original story with numbered entities. :param original_story: a list of sentences. :param numbered_entities: a list of dictionaries where each entry has an original piece of text and a numbered type. :return: a list of sentences.
625941d9de87d2750b86001e
def remove_port(self, port_no): <NEW_LINE> <INDENT> self._remove_vertex(port_no, VertexType.PORT)
Removes switch port from the topology. Also removes all associated links.
625941d93317a56b86939edd
def _skel_children(self, server_request): <NEW_LINE> <INDENT> inputs = [] <NEW_LINE> inputs.append(Fnorb.orb.CORBA.TC_boolean) <NEW_LINE> outputs = [] <NEW_LINE> outputs.append(Fnorb.orb.CORBA.typecode("IDL:att.com/AttNotification/IactSeq:1.0")) <NEW_LINE> exceptions = [] <NEW_LINE> server_request.initialise(inputs, ou...
Operation: IDL:att.com/AttNotification/Interactive/children:1.0
625941d921a7993f00bc7f7d
def get_genomic_distances(lengths, counts=None): <NEW_LINE> <INDENT> if sparse.issparse(counts): <NEW_LINE> <INDENT> if not sparse.isspmatrix_coo(counts): <NEW_LINE> <INDENT> counts = counts.tocoo() <NEW_LINE> <DEDENT> return _get_genomic_distances_sparse(lengths, counts) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f...
Get genomic distances
625941d9ad47b63b2c50a207
def _freePos(self): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for i, row in enumerate(self.mazeTable): <NEW_LINE> <INDENT> for j, p in enumerate(row): <NEW_LINE> <INDENT> if p is False: <NEW_LINE> <INDENT> res.append((i, j)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return res
produce a list of the free positions.
625941d95fdd1c0f98dc04bd
def readromercsv(self): <NEW_LINE> <INDENT> pass
do stuff
625941d90a366e3fb873eaa5
def p_function_call_arg_diff(p): <NEW_LINE> <INDENT> p[0] = FunctionCall(Id('diff'), List([FunctionCall(Id(p[1]), p[4]), p[4][0], Id(p[2])]))
expression : ID list_apostrophe LPAREN expression_list RPAREN
625941d9956e5f7376d710f6
def findWords(self, words): <NEW_LINE> <INDENT> list=[] <NEW_LINE> for row in [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]: <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> w=word.lower() <NEW_LINE> if set(w) <= row: <NEW_LINE> <INDENT> list.append(word) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return l...
:type words: List[str] :rtype: List[str]
625941d910dbd63aa1bd2e2c
def is_push_message(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> puth_title=u"消息推送" <NEW_LINE> locator_title=("id","menuitem-1142") <NEW_LINE> is_push_message = EC.text_to_be_present_in_element(locator_title,puth_title)(self.browser) <NEW_LINE> self.assertTrue(is_push_message) <NEW_LINE> logger_message.loginfo(u...
消息推送菜单
625941d9851cf427c661a797
def _api_is_accessible(self, **kwargs): <NEW_LINE> <INDENT> endpoint = '/datasets' <NEW_LINE> url = self._create_url(endpoint) <NEW_LINE> kwargs = self._update_headers(kwargs, {'api-key': self._api_key}) <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.head(url, **kwargs) <NEW_LINE> response.raise_for_status() <...
Checks that the API is accessible and it is possible to authenticate against it. :returns: Boolean
625941d973bcbd0ca4b2c300
def assetmutator_path(self, path, **kw): <NEW_LINE> <INDENT> request = self.request <NEW_LINE> mutant = Mutator(request, path, rendering_val=self.rendering_val, **kw) <NEW_LINE> if not request.registry.settings['assetmutator.each_request']: <NEW_LINE> <INDENT> if not mutant.mutated: <NEW_LINE> <INDENT> pass <NEW_LINE> ...
Returns a Pyramid :meth:`~pyramid.request.Request.static_path` of the mutated asset (and mutates the asset if needed). :param path: The Pyramid asset path to process. :type path: string - Required :type mutator: dict or string - Optional :param mutator: Allows you to override/specify a specific mutator to use ...
625941d98e05c05ec3eea600
def get_us_capitals(): <NEW_LINE> <INDENT> points = [] <NEW_LINE> dir_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> with open(f'{dir_path}/att48_xy.txt') as fp: <NEW_LINE> <INDENT> for cnt, line in enumerate(fp): <NEW_LINE> <INDENT> x, y = line.strip().split(" ")[0], line.strip().split(" ")[-1] <NEW_LIN...
https://people.sc.fsu.edu/~jburkardt/datasets/tsp/tsp.html ATT48 is a set of 48 cities (US state capitals) from TSPLIB. The minimal tour has length 33523.
625941d97cff6e4e81117c0f
def get_tag_tasks(self): <NEW_LINE> <INDENT> return TaggedItem.objects.get_by_model(Task, self.name)
gets the tasks of a specific tag
625941d950812a4eaa59c5a9
def import_data_loaders(batch_size): <NEW_LINE> <INDENT> train_database = SymbolDatasetIterable(CONSTELLATION, PRECURSOR_NUM, POSTCURSOR_NUM, train=True) <NEW_LINE> valid_database = SymbolDatasetIterable(CONSTELLATION, PRECURSOR_NUM, POSTCURSOR_NUM, train=False) <NEW_LINE> train_loader = DataLoader(train_database, batc...
This function imports the train and test database :param batch_size: size of each batch in the databases :param sequence_len: length of each sequence in the database :return: two datasets, training and validation
625941d9379a373c97cfadd0
@shared_task <NEW_LINE> def analyze_pointsource(area_of_interest): <NEW_LINE> <INDENT> return {'survey': point_source_pollution(area_of_interest)}
Given an area of interest, returns point sources of pollution within it.
625941d9236d856c2ad44a66
def _docker_build_exec_api(self, path_dockerfile, baseimg, path_repos, outimg="", rm_intermediate=True, entrypt_bin="", tmpwork_dir="/tmp", debug=False): <NEW_LINE> <INDENT> dockerfile = os.path.basename(path_dockerfile) <NEW_LINE> dck_api = APIClient() <NEW_LINE> fobj = BytesIO(dockerfile.encode('utf-8')) <NEW_LINE> _...
@brief Execute docker Python API via its lower-level API.
625941d9435de62698dfded7
def testGetTarget(self): <NEW_LINE> <INDENT> log.info('Starting unit test for command targeting') <NEW_LINE> newCmd = command.Command('attack') <NEW_LINE> newCbt = getTestCombat() <NEW_LINE> newCmd.getTarget(newCbt.units, 'rebels', auto=True)
Unit test for getting a target
625941d9c432627299f04ed1
@app.route("/explain", methods=["POST"]) <NEW_LINE> def return_score_and_explanations(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> input_text = request.json["text"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logging.warning( 'Wrong request, expected POST request with JSON payload and a "text" field.' )...
Get the score and prediction for a given input text.
625941d97b180e01f3dc4a83
def evaluate_accuracy(y_true, y_pred): <NEW_LINE> <INDENT> acc = accuracy_score(y_true, y_pred) <NEW_LINE> confmat = confusion_matrix(np.argmax(y_true, axis=1), np.argmax(y_pred, axis=1)) <NEW_LINE> return acc, confmat
Estimate accuracy of classification :param y_true: :param y_pred: :return: accuracy, confusion matrix
625941d966673b3332b9231c
def set_loglevel(self, level, parent=False): <NEW_LINE> <INDENT> level = level or logging.NOTSET <NEW_LINE> if not isinstance(level, int) and not isinstance(level, basestring): <NEW_LINE> <INDENT> raise ValueError('set_loglevel. Level must be of type int or string, got: "{0}/{1}"' .format(level, type(level))) <NEW_LINE...
wrapper for log.setLevel, accept int or string. Levels can be found in logging class. At the time this was written they are: CRITICAL:50 DEBUG:10 ERROR:40 FATAL:50 INFO:20 NOTSET:0 WARN:30 WARNING:30
625941d966673b3332b9231b
def add_order_entry(self, orderid): <NEW_LINE> <INDENT> open_orders = self.get_open_orders_pd() <NEW_LINE> if open_orders.id.isin([orderid]).any(): <NEW_LINE> <INDENT> order_pd_base = pd.read_pickle(self.pklAdd_orders) <NEW_LINE> a = open_orders[open_orders.id == orderid] <NEW_LINE> cn_tz = pytz.timezone('Asia/Shanghai...
Add a new log entry (somewhere, either CSV, cloud database, etc.) keeping track of all order detail Returns: Nothing
625941d91f037a2d8b946487
@func_locker.lock_function <NEW_LINE> def simple_locked_function(index=None): <NEW_LINE> <INDENT> global counter_file <NEW_LINE> time.sleep(0.05) <NEW_LINE> with open(_get_function_lock_path('simple_locked_function')) as rf: <NEW_LINE> <INDENT> content = rf.read() <NEW_LINE> <DEDENT> if index is not None: <NEW_LINE> <I...
Read the lock file and return it
625941d971ff763f4b549919
def __init__(self, rules): <NEW_LINE> <INDENT> self.setModel(rules)
Initialize Declensor with the given rules. Args: rules (iterable)
625941d97d847024c06be548
def GenerateLines(obj, verbose=False, recursive=False, summarize=True, format_name='text'): <NEW_LINE> <INDENT> if format_name == 'text': <NEW_LINE> <INDENT> d = DescriberText(verbose=verbose, recursive=recursive, summarize=summarize) <NEW_LINE> <DEDENT> elif format_name == 'csv': <NEW_LINE> <INDENT> d = DescriberCsv(v...
Returns an iterable of lines (without ) that describes |obj|.
625941d991f36d47f21ac77e
def __init__(self, model): <NEW_LINE> <INDENT> super(SimpleValidation, self).__init__(model=model) <NEW_LINE> self.logger = logging.getLogger("facerec.validation.SimpleValidation")
Args: model [Model] model to perform the validation on
625941d94428ac0f6e5baa7d
def getTypeBasedOnAttributes(self): <NEW_LINE> <INDENT> return self.__class__
Returns class by default, but overloaded in the TimeSnapshot class to differentiate time and epsilon snapshots.
625941d9f548e778e58cd809
def _select_heater_profile_setpoint(self, heaterProfileSetPoint): <NEW_LINE> <INDENT> self._write_register(self.BME680_CTRL_GAS_1, heaterProfileSetPoint)
Selects heater set-points of the sensor that will be used in forced mode. :param heaterProfileSetPoint: Heater profile set-point.
625941d95f7d997b87174d24
def get_repo_task(repo_name): <NEW_LINE> <INDENT> repo_key = safe_ndb_get_key_by_id('repo:'+repo_name) <NEW_LINE> if repo_key: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> logging.debug("Repo-get: Inserting task to retrieve repo {0}" " for organization {1}".format(settings.ORG_NAME, repo_name)) <NEW_LINE> safe_start_...
Create a task that will try to get the given repository from github for the given organization, and store it separately on the datastore.
625941d9cc0a2c11143dd11b
def naloga32(): <NEW_LINE> <INDENT> mnozica_resitev = set() <NEW_LINE> stevke = {1, 2, 3, 4, 5, 6, 7, 8, 9} <NEW_LINE> for a in range(10, 99): <NEW_LINE> <INDENT> for b in range(102, 987): <NEW_LINE> <INDENT> produkt = a * b <NEW_LINE> if produkt < 10000: <NEW_LINE> <INDENT> nase_stevke = {int(str(a)[0]), int(str(a)[1]...
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
625941d90a366e3fb873eaa6
def portal_sessions_sync(self, portalsessionsdata): <NEW_LINE> <INDENT> delayed_import() <NEW_LINE> global _ServerSession, _AccountDB, _ServerConfig, _ScriptDB <NEW_LINE> for sess in self.values(): <NEW_LINE> <INDENT> del sess <NEW_LINE> <DEDENT> for sessid, sessdict in portalsessionsdata.items(): <NEW_LINE> <INDENT> s...
Syncing all session ids of the portal with the ones of the server. This is instantiated by the portal when reconnecting. Args: portalsessionsdata (dict): A dictionary `{sessid: {property:value},...}` defining each session and the properties in it which should be synced.
625941d9dc8b845886cb57c0