query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test that the Mp3Controller properly sets the file path of the file it was given.
def test_mp3_controller(file_input, filepath, monkeypatch): user_input = StringIO(file_input) test = VideoSynth() controller = Mp3Controller(test) monkeypatch.setattr('sys.stdin', user_input) controller.create_file_path() assert test.file_path() == filepath
[ "def setUp(self):\n super().setUp()\n self.file_path = 'file.json'", "def test_filepath(self):\n self.assertEqual(self.spec.path, self.merlin_spec_filepath)", "def test_load_file(self):\n self.assertTrue(os.path.exists(MEDIA_ROOT+\"/pl_test1_\"+self.loader.version))\n self.ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2.
def ensure_iob2(tags): tags = list(tags) for i, tag in enumerate(tags): if tag == 'O': continue split = tag.split('-') if len(split) != 2 or split[0] not in ['I', 'B']: return False if split[0] == 'B': continue elif i == 0 or tags[i - 1...
[ "def iob2(tags):\r\n for i, tag in enumerate(tags):\r\n if tag == 'O':\r\n continue\r\n split = tag.split('-')\r\n if len(split) != 2 or split[0] not in ['I', 'B']:\r\n return False\r\n if split[0] == 'B':\r\n continue\r\n elif i == 0 or tags[i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the least changes to a set of comparisons so that they are consistent (transitive), it returns a topological ranking. comparisons A dictionary with tuple keys in the form of (i, j), values are scalars indicating the probability of i > j. It is assumed that comparisons are symmetric. Use 0 for i j (and any value in...
def find_ranking(comparisons, equal_width=0.2, max_rank=-1, verbose=False): # remove unnecessary variables comparisons = {(i, j) if i < j else (j, i): value if i < j else 1 - value for (i, j), value in comparisons.items()} nodes = np.unique( [i for ij in comparisons.keys() for i i...
[ "def knapsack_comparisons(pairs: List[Tuple[int, int]]):\n # Make a directed graph\n g = nx.DiGraph()\n # Add each of the pairwise comparisons as edges, increase/decrease weight by 1 if already present\n for pair in pairs:\n if pair in g.edges:\n g.edges[pair[0], pair[1]]['weight'] += ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
admin can generate a user csv which contains all user info
def user_list_csv(): us = user.User.query.all() filename = 'xxx.csv' csv_name = _rename_file(filename) url = app.config['CSV_FILES_DEST'] + '/' + csv_name with codecs.open(url, 'wb') as csvfile: #fieldnames = ['账号', '姓名', '描述', '角色', '邮箱', '电话', '工作电话', '公司', '部门', '职位'] fieldnames ...
[ "def export_users(_request):\n query = models.UserProfile.all().order('email')\n rows = []\n for user in query:\n is_superuser = 0\n if user.is_superuser:\n is_superuser = 1\n rows.append('%s,%s\\n' % (user.email, is_superuser))\n\n response = http.HttpResponse(''.join(rows), mimetype='text/csv')\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a `module_name` name and a `function_name` return the path where to install the correspondent script. The path is relative to "~/.gnome2/nautilusscripts".
def get_new_script_path(module_name, function_name): return os.path.join(util.get_last_part_of_dotted_name(module_name), function_name)
[ "def getmodulepath(modulename):\n return USERLIBDIR + '\\\\' + modulename + '.sikuli\\\\' + modulename + '.py'", "def python_script_exists(package=None, module=None):\n assert module is not None\n try:\n if package is None:\n path = imp.find_module(module)[1]\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a sequence of dicts, one for each console scripts installed by this package,
def get_console_scripts_info(): entry_points_map = pkg_resources.get_entry_map('rbco.nautilusscripts', 'console_scripts') return [ { 'name': ep.name, 'module': ep.module_name, 'function': ep.attrs[0], } for ep in entry_points_map.itervalues() i...
[ "def _iter_commands(self):\n return {entry_point.name: entry_point for entry_point in\n pkg_resources.iter_entry_points('chanjo.subcommands')}", "def _iter_commands(self):\n return {entry_point.name: entry_point for entry_point in\n pkg_resources.iter_entry_points('trailblazer....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the Nautilus' scripts for the current user.
def install(): src = None if len(sys.argv) == 2: src = sys.argv[1] elif len(sys.argv) > 2: print >> sys.stderr, 'USAGE: rbco_nautilusscripts_install [SOURCE_DIR]' sys.exit(1) paths = ( '~/.gnome2/nautilus-scripts', '~/.gnome2/nemo-scripts', '~/.config/caj...
[ "def install_init_script():\n run('sudo touch %s' % env.init_script)\n run('sudo chown %s %s' % (env.user, env.init_script))\n run('sudo update-rc.d %s defaults' % os.path.basename(env.init_script))\n update_init_script()", "def install(args):\n if not args.only_symlink:\n install_prerequisi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the .egginfo directory name as created/expected by setuptools
def setuptools_egg_info_dir(path): filename = basename(path) name, version = name_version_fn(filename) return "{0}-{1}.egg-info".format(name, version)
[ "def _get_egg_path(self):\n try:\n _dist = get_distribution('janitoo_nut')\n return _dist.__file__\n except AttributeError:\n return 'src-nut/config'", "def build_egg_info():\n\n os.mkdir('setuptools.egg-info')\n with io.open('setuptools.egg-info/entry_points.t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an iterator that will remove every installed file.
def remove_iterator(self): if not self.is_installed: logger.error("Error: Can't find meta data for: {0!r}". format(self.cname)) return if not self.noapp: remove_app(self.meta_dir, self.prefix) _run_script(self.meta_dir, 'pre_egguninst...
[ "def post_process(self, *args, **kwargs):\n to_delete = []\n files = super(CachedFilesPlusMixin, self).post_process(*args, **kwargs)\n for name, hashed_name, processed in files:\n if self.remove_unversioned and name != hashed_name:\n to_delete.append(name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the content of the EGGINFO/inst/files_to_install.txt file, create/remove the links listed therein.
def _create_links(self): for line in self.iter_files_to_install(): arcname, link = line.split() if link == 'False': continue self.files.append(create_link(arcname, link, self.prefix))
[ "def updateLinks():\n\n # Now get download links and save them to file\n result = SafeConfigParser()\n getDownloadLinks(result)\n file = open(get_config().get('extensions', 'downloadLinksFile'), 'wb')\n result.write(file)\n file.close()\n\n writeUpdateManifest(result)", "def convert_links(file):\n try:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an iterator that will iterate over each archive to be extracted.
def install_iterator(self, extra_info=None): self.pre_extract() with ZipFile(self.path) as zp: self.z = zp arcnames = self.z.namelist() is_custom_egg = eggmeta.is_custom_egg(self.path) use_legacy_egg_info_format = has_legacy_egg_info_format(arcnames, ...
[ "def robust_iterator(archive):\n unpacker = RobustUnpacker(lambda item: isinstance(item, dict) and b'path' in item)\n _state = 0\n def missing_chunk_detector(chunk_id):\n nonlocal _state\n if _state % 2 != int(not chunk_id in self.chunks):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator returns a sorted list of all installed packages. Each element is the filename of the egg which was used to install the package.
def get_installed(prefix=sys.prefix): egg_info_dir = join(prefix, 'EGG-INFO') if not isdir(egg_info_dir): return pat = re.compile(r'([a-z0-9_.]+)$') for fn in sorted(os.listdir(egg_info_dir)): if not pat.match(fn): continue d = read_meta(join(egg_info_dir, fn)) ...
[ "def iter_packages(self):\n for packages_set in self._name_to_packages.values():\n for package in packages_set:\n yield package", "def collect_installed_distributions():\n for distribution in pkg_resources.working_set:\n distribution_spec = str(distribution.as_requiremen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple wrapper to install an egg using default egginst progress bar.
def install_egg_cli(path, prefix, noapp=False, extra_info=None): installer = EggInst(path, prefix, False, None, noapp) progress = console_progress_manager_factory("installing egg", installer.fn, size=installer.installed_size) with progress: for curren...
[ "def install(self, egg, dir_path):", "def python_install_eggs():\n python_cluster_components = [c for c in REPO_LIST_CLUSTER if c != \"reana-ui\"]\n for component in python_cluster_components:\n for cmd in [\n \"python setup.py bdist_egg\",\n ]:\n run_command(cmd, compone...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple wrapper to remove an egg using default egginst progress bar.
def remove_egg_cli(path, prefix, noapp=False): installer = EggInst(path, prefix, False, None, noapp=noapp) remover = installer._egginst_remover if not remover.is_installed: logger.error("Error: can't find meta data for: %r", remover.cname) return progress = console_progress_manager_facto...
[ "def remove(self, egg):", "def reset_progressbars(gallery_conf, fname):\n\n # disable tqdm\n import AFQ.data.s3bids as afs\n import AFQ._fixes as fixes\n import AFQ.segmentation as seg\n import AFQ.viz.utils as utils\n\n afs.tqdm = _no_tqdm\n fixes.tqdm = _no_tqdm\n seg.tqdm = _no_tqdm\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a 3 column `DataFrame` with every combination of compound, concentration, and mechanismofaction. Includes compounds with unknown MoA.
def moa_df(self) -> pd.DataFrame: return ( self.image_df[["compound", "concentration", "moa"]] .drop_duplicates() .sort_values(["compound", "concentration"]) .reset_index(drop=True) )
[ "def get_compound_df(idx, compound_dict, standard_types):\n\n if standard_types is None or compound_dict['standard_type'] is None:\n is_valid_std_type = False\n else:\n compound_std_type = compound_dict['standard_type'].lower()\n is_valid_std_type =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get metadata for the given image at `rel_index`.
def metadata(self, rel_index) -> Metadata: row = self.image_df.iloc[rel_index] ( site, well, replicate, plate, compound, concentration, moa, image_idx, ) = row[ [ "site",...
[ "def get_ch_metadata(self, index):\n\n tag = self.get_ch_tag(index)\n\n return getattr(self, f\"{tag.lower()}_metadata\")", "def met(r):\n image_url = r.get(\"image\")\n if image_url is None:\n if r.get(\"source\") is not None:\n image_url = r.get(\"source\").get(\"href\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Index route handler. Requests sync of archives with YouTube and redirects to videos list view.
def web_index(): try: auth_check() except Exception as e: return flask.redirect(str(e)) db_update_archives() return flask.redirect('videos')
[ "def index():\n seen = set()\n seen_add = seen.add\n videos = []\n all_videos = mythVideo.searchVideos(insertedafter = '1900-01-01 00:00:00')\n\n for video in all_videos:\n path = video.filename.split('/')[0]\n if path not in seen and not seen_add(path):\n video.url = url_for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters video list. First loads all tracked videos or videos from selected channel. Then filters those by 'archived' and/or 'played'.
def web_videos_filter(channel, tracks, archived, played): videos = [] if channel == 'all': for tracked in tracks: videos.append(yt_get_channel_videos(tracked['id'])) videos = [ item for sublist in videos for item in sublist ] else: ...
[ "def filter_videos(\n files: list\n):\n#cSpell:words webm vchd rmvb gifv xvid vidx\n video_extensions = [\n \"WEBM\",\n \"MPG\",\"MP2\", \"MPEG\", \"MPE\", \"MPV\",\n \"OGV\",\"OGG\",\n \"MP4\", \"M4P\", \"M4V\",\n \"AVI\",\n \"WMV\",\n \"MOV\",\"QT\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play random unplayed video. Chooses random unplayed video from selected channel and redirects to its detail page view.
def web_videos_random_unplayed(channel): try: choice = random.choice([ video['snippet']['resourceId']['videoId'] for video in yt_get_channel_videos(channel) if video['played'] is None ]) except IndexError: return flask.redirect(flask.url_for('videos',...
[ "def web_videos_random_archived(channel):\n\n try:\n choice = random.choice([\n video['snippet']['resourceId']['videoId']\n for video in yt_get_channel_videos(channel)\n if video['archived'] is not None\n ])\n except IndexError:\n return flask.redirect(fla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play next unplayed video. Chooses next (chronologically) unplayed video from selected channel and redirects to its detail page view.
def web_videos_next_unplayed(channel): try: choice = sorted([ video for video in yt_get_channel_videos(channel) if video['played'] is None ], key = lambda video: video['snippet']['publishedAt'])[0] except IndexError: return flask.redirect(flask.url_fo...
[ "def get_next_video(self):\n if self.number_of_plays < 5:\n try:\n self.current_product_index += 1\n self.video_source = self.get_video_source()\n except IndexError:\n self.current_product_index = 0\n self.video_source = self.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Play random archived video. Chooses random archived video from selected channel and redirects to its detail page view.
def web_videos_random_archived(channel): try: choice = random.choice([ video['snippet']['resourceId']['videoId'] for video in yt_get_channel_videos(channel) if video['archived'] is not None ]) except IndexError: return flask.redirect(flask.url_for('vi...
[ "def web_videos_random_unplayed(channel):\n\n try:\n choice = random.choice([\n video['snippet']['resourceId']['videoId']\n for video in yt_get_channel_videos(channel)\n if video['played'] is None\n ])\n except IndexError:\n return flask.redirect(flask.url...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Channels track route handler. Renders tracking using connected YouTube account page.
def web_channels_track(user = None, subs = [], tracks = [], tracking = True, error = False): try: auth_check() except Exception as e: return flask.redirect(str(e)) return flask.render_template('channels.html', user = flask.session['user'], subs = yt_get_subscriptions(), tra...
[ "def linkTrackToChannel(*args, **kwargs):\n pass", "def web_channels_update():\n\n try:\n auth_check()\n except Exception as e:\n return flask.redirect(str(e))\n\n tracks = flask.request.args.get('tracks', None)\n query = flask.request.args.get('query', None)\n\n if tracks is not N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles channel tracking. Tracks or untracks YouTube channels using connected account or by user query. Then redirects to channels management page. Uses GET query parameters ``tracks`` and ``query``.
def web_channels_update(): try: auth_check() except Exception as e: return flask.redirect(str(e)) tracks = flask.request.args.get('tracks', None) query = flask.request.args.get('query', None) if tracks is not None: web_channels_update_tracks(tracks) if query is not No...
[ "def web_channels_track(user = None, subs = [], tracks = [], tracking = True, error = False):\n\n try:\n auth_check()\n except Exception as e:\n return flask.redirect(str(e))\n\n return flask.render_template('channels.html', user = flask.session['user'],\n subs = yt_get_subscriptions()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles channel subscriptions. Subscribes user to or unsubscribes user from given YouTube channel, then redirects to given page. Time delay is needed, because of YouTube Data API delays. Uses GET query parameter ``update`` (URL encoded JSON data). Its data contain ``id`` (YouTube subscription ID), ``subscribe`` (flag w...
def web_channels_subscriptions(): try: auth_check() except Exception as e: return flask.redirect(str(e)) update = flask.request.args.get('update', None) if update is not None: update_data = json.loads(urllib.parse.unquote(update)) if update_data['subscribe']: ...
[ "def web_channels_update():\n\n try:\n auth_check()\n except Exception as e:\n return flask.redirect(str(e))\n\n tracks = flask.request.args.get('tracks', None)\n query = flask.request.args.get('query', None)\n\n if tracks is not None:\n web_channels_update_tracks(tracks)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Archive route handler. Renders archive management view.
def web_archive(): try: auth_check() except Exception as e: return flask.redirect(str(e)) return flask.render_template('archive.html', user = flask.session['user'], archives = db_get_archives())
[ "def show_archive():\n return render_template('archive.html')", "def master_archive(f, e):\n template = e.get_template(TEMPLATES['archive'])\n write_file(\"archives.html\", template.render(entries=f))", "def archive(self, item):\n self._createAction(item, \"archive\")", "def view_box_archive(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles archive management. Inserts video to archive, imports entire playlist into archive or renames given archive. Uses GET query parameter ``name`` (new given archive name).
def web_archive_insert_rename(type = None, id = None): try: auth_check() except Exception as e: return flask.redirect(str(e)) if id is not None: if type == 'video': web_archive_insert_video(id) elif type == 'playlist': web_archive_import_playlist(id)...
[ "def update_archive(request):\n _logger.info('Starting to update archive event database')\n # if 'clear_all' in request.GET and request.user.is_staff:\n # _logger.info('Deleting all old entries')\n # clear_archive_and_cache()\n archive = requests.get(JSON_ARCHIVE_PATH).json()\n _logger.inf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts video to archive. Inserts video to the first available archive. Creates new archive if all are full.
def web_archive_insert_video(id): db = get_db() user_id = flask.session['user']['id'] video_id = id video = yt_get_video(video_id) channel_id = video['snippet']['channelId'] archive = None for playlist in db_get_archives(): if playlist['contentDetails']['itemCount'] < 5000: ...
[ "def do_insert(input_m3u, video, index):\n insert_video(input_m3u, video, index)", "def add_one_video_to_database(full_path,\n video_path,\n root,\n remote_url,\n filename,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports playlist to archive. Imports entire playlist to the first available archive. Creates new archive if all are full.
def web_archive_import_playlist(id): db = get_db() user_id = flask.session['user']['id'] for item in yt_get_playlist_items(id): video_id = item['snippet']['resourceId']['videoId'] video = yt_get_video(video_id) channel_id = video['snippet']['channelId'] archive = None ...
[ "def import_archive(self):\n if self.archive:\n archive = IrkruTildaArchive(self.archive, material=self)\n archive.process()", "def _load_playlist(self, playlist=None):\n _LOGGER.debug(\"Load playlist\")\n if not self._update_entity_ids():\n return\n \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renames archive. Renames given archive. Time delay is needed because of YouTube Data API delays.
def web_archive_rename(id, name): if name is not None: yt_rename_playlist(id, name) time.sleep(5)
[ "def my_hook(d):\n episode, anime_name = current_anime_eps(args.URL)\n\n if d['status'] == 'finished':\n print('Done downloading, now renaming & moving ...')\n filename, extension = os.path.splitext(d['filename'])\n dirname = os.path.dirname(os.path.abspath(__file__))\n os.rename(o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates youtubedl batch file. Generates batch file for youtubedl to download archived videos. Optionally uses uploaded youtubedl ``archive`` file to only include videos not yet downloaded.
def web_archive_batch(): try: auth_check() except Exception as e: return flask.redirect(str(e)) batch = set() if 'archiveFile' in flask.request.files: file = flask.request.files['archiveFile'] if file.filename != '': if file and allowed_file(file.filename):...
[ "def web_archive_config():\n\n try:\n auth_check()\n except Exception as e:\n return flask.redirect(str(e))\n\n socket_timeout = flask.request.args.get('ytdl-socket-timeout', '120')\n retries = flask.request.args.get('ytdl-retries', 'infinite')\n output = flask.request.args.get('ytdl-ou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads comments. Downloads archived videos' comments. Places them to subdirectories by YouTube channel ID and generates ZIP archive.
def web_archive_comments(): try: auth_check() except Exception as e: return flask.redirect(str(e)) archive_comments = io.BytesIO() with zipfile.ZipFile(archive_comments, 'w') as zf: for video_id in db_get_archived(): video = yt_get_video(video_id) comme...
[ "def get_yt_comments(client, video_id):\n API_LIMIT = 550\n # import codecs\n # f = codecs.open('comments.txt', 'w', 'utf8')\n count = 1\n ret_comments = []\n\n for comment in comments_generator(client, video_id):\n if not comment.content.text:\n continue\n # author_name =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates youtubedl configuration file. Generates configuration file for youtubedl. Gets values from GET query parameters.
def web_archive_config(): try: auth_check() except Exception as e: return flask.redirect(str(e)) socket_timeout = flask.request.args.get('ytdl-socket-timeout', '120') retries = flask.request.args.get('ytdl-retries', 'infinite') output = flask.request.args.get('ytdl-output', '%(uplo...
[ "def devpiserver_genconfig(tw, config, argv, writer):", "def generate_config():\n\n return {\n \"email_subject\": DEFAULT_EMAIL_SUBJECT,\n \"from_email\": DEFAULT_FROM_EMAIL,\n \"to_email\": DEFAULT_TO_EMAIL,\n \"url\": DEFAULT_URL,\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the stringified version of the generated xml
def xml_string(self): if self._xml_string is not None: return self._xml_string return etree.tostring(self._xml_node)
[ "def get_xml_string(self) -> str:\n return etree.tostring(self.xml, method='c14n', exclusive=True).decode('utf-8')", "def xml_string(self):\r\n if self._xml_string is not None:\r\n return self._xml_string\r\n\r\n return etree.tostring(self._xml_node)", "def to_string(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers a list of events in vim. name is a string with the name of the plugin. events is a list of tuples, containing the event name, files it should match, the function that should be called and default arguments.
def register_events( register, name, events ): group_name = '%(name)s_events' % locals() func_reg = ':py manager.funcs[ %(func_id)s ]' log.info( 'Register\'s events for %s.', name ) _vim.command( 'augroup %(group_name)s' % locals() ) _vim.command( 'au!' ) for e in events: event, ftype, func, args = e func_...
[ "def DRegister(*events):\n _debug = False\n\n def registered_plugin(f):\n for event in events:\n pluginManager.PluginManager.set_event(event, f)\n if _debug:\n sys.stderr.write('DRegister(%s) to %s\\n' % (f.__name__, event))\n return f\n return registered_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unregisters a list of events in vim. name is a string with the name of the plugin. events is a list of tuples, containing the event name, files it should match, the function that should be called and default arguments.
def unregister_events( register, name, events ): group_name = '%(name)s_events' % locals() log.info( 'Register\'s events for %s.', name ) _vim.command( 'augroup %(group_name)s' % locals() ) _vim.command( 'au!' ) _vim.command( 'augroup END' ) for e in events: event, ftype, func, args = e func_id = '%s.%s.%s...
[ "def register_events( register, name, events ):\n\tgroup_name = '%(name)s_events' % locals()\n\tfunc_reg = ':py manager.funcs[ %(func_id)s ]'\n\n\tlog.info( 'Register\\'s events for %s.', name )\n\t_vim.command( 'augroup %(group_name)s' % locals() )\n\t_vim.command( 'au!' )\n\n\tfor e in events:\n\t\tevent, ftype, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to merge two fields, based on their field positions and types.
def _merge_fields(a: Field, b: Field) -> Optional[Field]: # Merge the types: merged_type: Optional[FieldType] = None # Constant fields can be merged with any other type. To make type merging easier, swap a and b if b is # constant. if b.type is FieldType.CONST: a, b = b, a # Constant ...
[ "def _safe_combine_fields(\n fields_a: Mapping[str, BaseField], fields_b: Mapping[str, BaseField]\n ) -> MutableMapping[str, BaseField]:\n combined = OrderedDict(fields_a)\n for key, value_b in fields_b.items():\n if key not in combined:\n combined[key] = value_b\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Either return the value at a certain key, or set the return value of a function to that key, then return that value.
def retrieve_and_set(self, key: Hashable, func: Callable[[], T]) -> T: if key not in self: self[key] = func() return self[key]
[ "def result(obj, key, default=None):\n if not obj:\n return default\n\n ret = base_get(obj, key, default=default)\n\n if callable(ret):\n ret = ret()\n\n return ret", "def get_value(data, key):\n if key in data:\n return data[key]\n return None", "def get(func_or_val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the inputs to a numpy array.
def _convert_to_np_array(inputs: Union[float, Tuple[float], np.ndarray], dim): outputs = None if isinstance(inputs, (tuple, np.ndarray)): outputs = np.array(inputs) else: outputs = np.full(dim, inputs) if len(outputs) != dim: raise ValueError("The inputs array has a different dimension {}" ...
[ "def as_array(self):\n return self.generate_input()", "def convert_to_numpy(self):\n print(self.x_train_list)\n self.x_train_list = np.array(self.x_train_list)\n self.y_train = np.array(self.y_train)", "def _to_numpy_ndarray(cls, data):\n if isinstance(data, np.ndarray):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the MKL interface status if debug mode is on
def print_mkl_debug(): if not MKL.MKL_DEBUG: return if get_version_string() is None: print("mkl-service must be installed to get full debug messaging") else: print(get_version_string()) print("MKL linked: {fn}".format(fn=_libmkl._name)) print("MKL interface {np} | {c}".for...
[ "def debug():", "def vv_flag():\n log.setLevel(logging.DEBUG)", "def debug_mode():\n\n # store state and switch console to debug\n _log_state.debug_logs()", "def debug():\n\n return", "def debug(state: bool, /) -> None:", "def enableDebugLoadOutput(self):\n key = \"NatlinkmainDebugLoad\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the sparse matrix indicies are in the correct integer type
def _check_scipy_index_typing(sparse_matrix): int_max = np.iinfo(MKL.MKL_INT_NUMPY).max if (sparse_matrix.nnz > int_max) or (max(sparse_matrix.shape) > int_max): msg = "MKL interface is {t} and cannot hold matrix {m}\n".format(m=repr(sparse_matrix), t=MKL.MKL_INT_NUMPY) msg += "Try changing MKL...
[ "def is_integer(matrix):\n return numpy.issubdtype(matrix.dtype, numpy.integer)", "def test_dtype_int_graph(self):\n G = nx.complete_graph(3)\n A = nx.to_numpy_matrix(G, dtype=int)\n assert_equal(A.dtype, int)", "def is_sparse(A):\n if isinstance(A, torch.Tensor):\n return A.la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the array layout code for a dense array in C or F order. Raises a ValueError if the array is not contiguous.
def _get_numpy_layout(numpy_arr, second_arr=None): # Return the second array order if the first is ambiguous if numpy_arr.flags.c_contiguous and numpy_arr.flags.f_contiguous and second_arr is not None: if second_arr.flags.c_contiguous: return LAYOUT_CODE_C, numpy_arr.shape[1] elif s...
[ "def get_preferred_sparse_format():\n return \"coo\"", "def c_layout_from_shape(shape, dtype):\n dim = c_layout_from_shape(tail(shape), dtype)\n extent = head(shape)\n stride = dim.stride * dim.extent\n return Dimension(dim, extent, stride)", "def to_ctype(self, array, name_cvalue):\n if not i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create MKL internal representation for BSR matrix
def _create_mkl_sparse_bsr(matrix): double_precision = _is_double(matrix) handle_func = MKL._mkl_sparse_d_create_bsr if double_precision else MKL._mkl_sparse_s_create_bsr # Get the blocksize and check that the blocks are square _blocksize = matrix.blocksize[0] if _blocksize != matrix.blocksize[1]...
[ "def _export_mkl_sparse_bsr(bsr_mkl_handle, double_precision):\n\n # Allocate for output\n ordering, nrows, ncols, indptrb, indptren, indices, data = _allocate_for_export(double_precision)\n block_layout = _ctypes.c_int()\n block_size = MKL.MKL_INT()\n\n # Set output\n out_func = MKL._mkl_sparse_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export a MKL sparse handle of CSR or CSC type
def _export_mkl(csr_mkl_handle, double_precision, output_type="csr"): output_type = output_type.lower() if output_type == "csr": out_func = MKL._mkl_sparse_d_export_csr if double_precision else MKL._mkl_sparse_s_export_csr sp_matrix_constructor = _spsparse.csr_matrix elif output_type == "c...
[ "def _export_mkl_sparse_bsr(bsr_mkl_handle, double_precision):\n\n # Allocate for output\n ordering, nrows, ncols, indptrb, indptren, indices, data = _allocate_for_export(double_precision)\n block_layout = _ctypes.c_int()\n block_size = MKL.MKL_INT()\n\n # Set output\n out_func = MKL._mkl_sparse_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export a BSR matrix from MKL's internal representation to scipy
def _export_mkl_sparse_bsr(bsr_mkl_handle, double_precision): # Allocate for output ordering, nrows, ncols, indptrb, indptren, indices, data = _allocate_for_export(double_precision) block_layout = _ctypes.c_int() block_size = MKL.MKL_INT() # Set output out_func = MKL._mkl_sparse_d_export_bsr i...
[ "def _create_mkl_sparse_bsr(matrix):\n\n double_precision = _is_double(matrix)\n handle_func = MKL._mkl_sparse_d_create_bsr if double_precision else MKL._mkl_sparse_s_create_bsr\n\n # Get the blocksize and check that the blocks are square\n _blocksize = matrix.blocksize[0]\n\n if _blocksize != matrix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get pointers for output from MKL internal representation
def _allocate_for_export(double_precision): # Create the pointers for the output data indptrb = _ctypes.POINTER(MKL.MKL_INT)() indptren = _ctypes.POINTER(MKL.MKL_INT)() indices = _ctypes.POINTER(MKL.MKL_INT)() ordering = _ctypes.c_int() nrows = MKL.MKL_INT() ncols = MKL.MKL_INT() data ...
[ "def getptr(self, *indices):", "def ldmk_to_points(shape, dtype = 'int'):\n coords = np.zeros((68, 2), dtype = dtype)\n for i in range(68):\n coords[i] = (shape.part(i).x, shape.part(i).y)\n return coords", "def _export_mkl(csr_mkl_handle, double_precision, output_type=\"csr\"):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deallocate a MKL sparse handle
def _destroy_mkl_handle(ref_handle): ret_val = MKL._mkl_sparse_destroy(ref_handle) _check_return_value(ret_val, "mkl_sparse_destroy")
[ "def __del__( self ):\n mkl.DftiFreeDescriptor( ctypes.byref(self.descriptor) )", "def __del__(self):\n self.ds = None\n self.destroy_array()", "def __del__(self):\n #self.myCModule.free_array(self.arrayRef)\n pass", "def ggml_free(ctx: ffi.CData) -> None:\n ...", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorder indexes in a MKL sparse handle
def _order_mkl_handle(ref_handle): ret_val = MKL._mkl_sparse_order(ref_handle) _check_return_value(ret_val, "mkl_sparse_order")
[ "def _major_index_fancy(self, idx):\n _, N = self._swap(*self.shape)\n M = idx.size\n new_shape = self._swap(M, N)\n if self.nnz == 0 or M == 0:\n return self.__class__(new_shape, dtype=self.dtype)\n\n return self.__class__(\n _index._csr_row_index(self.data,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a MKL sparse handle to CSR format
def _convert_to_csr(ref_handle, destroy_original=False): csr_ref = sparse_matrix_t() ret_val = MKL._mkl_sparse_convert_csr(ref_handle, _ctypes.c_int(10), _ctypes.byref(csr_ref)) try: _check_return_value(ret_val, "mkl_sparse_convert_csr") except ValueError: try: _destroy_mkl...
[ "def coo_tocsr(*args):\n return _coo.coo_tocsr(*args)", "def to_csr(self):\n if self.sparse and type(self.data) != csr_matrix and hasattr(self.data, 'tocsr'):\n logging.debug(\"Converting data matrix to CSR Matrix\")\n self.data.tocsr()", "def to_csr(self):\n return spar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure that both matrices are single precision floats or both are double precision floats If not, convert to double precision floats if cast is True, or raise an error if cast is False
def _type_check(matrix_a, matrix_b=None, cast=False): if matrix_b is None and matrix_a.dtype in NUMPY_FLOAT_DTYPES: return matrix_a elif matrix_b is None and cast: return _cast_to_float64(matrix_a) elif matrix_b is None: err_msg = "Matrix data type must be float32 or float64; {a} pr...
[ "def test_float_conversion_dtype(self):\n\n x = np.array([-1, 1])\n # Test all combinations of dtypes conversions\n dtype_combin = np.array(np.meshgrid(\n OutputPreprocessing.float_dtype_list,\n OutputPreprocessing.float_dtype_list)).T.resha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if the array is doubles, false if singles, and raise an error if it's neither.
def _is_double(arr): # Figure out which dtype for data if arr.dtype == np.float32: return False elif arr.dtype == np.float64: return True else: raise ValueError("Only float32 or float64 dtypes are supported")
[ "def is_double(self, size=None):\n return False", "def is_double(self):\n answer = self._call('is_double')\n return answer.yes", "def isDouble(self):\n return _yarp.Value_isDouble(self)", "def test_doubles(self):\n self.assertEqual(doubles(self.TestData), 3)\n self.as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the matrix is dense or a sparse format we can turn into an MKL object. False otherwise.
def _is_allowed_sparse_format(matrix): if _spsparse.isspmatrix(matrix): return _spsparse.isspmatrix_csr(matrix) or _spsparse.isspmatrix_csc(matrix) or _spsparse.isspmatrix_bsr(matrix) else: return True
[ "def _is_dense(x):\n if not isinstance(x, (scipy.sparse.spmatrix, np.ndarray)):\n raise NotImplementedError(\n \"this function should only be called on \"\n \"sparse.scipy.sparse.spmatrix or \"\n \"numpy.ndarray, not,\",\n x,\n )\n return isinstance(x,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define dtypes empirically Basically just try with int64s and if that doesn't work try with int32s There's a way to do this with intel's mkl helper package but I don't want to add the dependency
def _empirical_set_dtype(): MKL._set_int_type(_ctypes.c_longlong, np.int64) try: _validate_dtype() except ValueError as err: MKL._set_int_type(_ctypes.c_int, np.int32) try: _validate_dtype() except ValueError: raise ImportError("Unable to set MKL nu...
[ "def _cast_unsupported_dtypes(tensor):\n\n if tensor.dtype.__eq__(dtypes.int64):\n # outside-compilation doesn't support int64 input yet.\n return math_ops.cast(tensor, dtypes.int32)\n if tensor.dtype.__eq__(dtypes.bfloat16) or tensor.dtype.__eq__(\n dtypes.float16):\n # Sinc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a geometry to the viewer.
def add_geometry(self, name, geometry, **kwargs): # convert geometry to constructor args args = rendering.convert_to_vertexlist(geometry, **kwargs) # create the indexed vertex list self.vertex_list[name] = self.batch.add_indexed(*args) # save the MD5 of the geometry self....
[ "def addGeometry(self, geom):\n\n return self.__fig.addGeometry(geom)", "def addGeometry(self, geometry):\n subDivBoxTree = SubDivBoxTree(geometry.mesh)\n subDivBoxTree.createTreeRoot(geometry.bbox)\n self.subDivBoxTrees[geometry.guid] = subDivBoxTree", "def addGeometry(self, geom):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle backface culling on or off. It is on by default but if you are dealing with non watertight meshes you probably want to be able to see the back sides.
def toggle_culling(self): self.view['cull'] = not self.view['cull'] self.update_flags()
[ "def toggle_surface(self):", "def oobeCull():\n\n base.oobeCull()\n return 'Toggled OOBE Cull'", "def toggle_wireframe(self):\n self.view['wireframe'] = not self.view['wireframe']\n self.update_flags()", "def turn_face_up(self):\n self.face_up = True", "def toggle_surface_mode(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle unfilled wireframe mode on or off, good for looking inside meshes. Off by default.
def toggle_wireframe(self): self.view['wireframe'] = not self.view['wireframe'] self.update_flags()
[ "def toggle_wireframe():\n model_editor = viewport.get_model_panel()\n if model_editor:\n viewport.toggle_wireframe(model_editor)", "def wireframe(self):\n return self.uniform_buffer.data[\"wireframe\"] > 0", "def toggle_surface(self):", "def setDisplayMode(self, mode):\n return \"W...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle between fullscreen and windowed mode.
def toggle_fullscreen(self): self.view['fullscreen'] = not self.view['fullscreen'] self.update_flags()
[ "def toggle_full_screen(self):\n if self.isFullScreen():\n self.showMaximized()\n else:\n self.showFullScreen()", "def switch(self):\n self.fullscreen = not (self.fullscreen)\n self.setScreenMode()", "def toggleFullScreen(self):\n if not self.isFullScreen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle a rendered XYZ/RGB axis marker on, world frame, or every frame. Off by default.
def toggle_axis(self): # cycle through three axis states states = [False, 'world', 'all'] # the state after toggling index = (states.index(self.view['axis']) + 1) % len(states) # update state to next index self.view['axis'] = states[index] # perform gl actions ...
[ "def toggle_surface(self):", "def toggle_annotation(self):\n self.__data['Show annotation'] = not self.__data['Show annotation']", "def toggle_draw_axes(self):\n if self.draw_axes:\n self.draw_axes = False\n else:\n self.draw_axes = True\n self.redraw()", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the view flags and call what is needed with gl to handle it correctly.
def update_flags(self): # view mode, filled vs wirefrom if self.view['wireframe']: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) else: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) # set fullscreen or windowed self.set_fullscreen(fullscreen=self...
[ "def gl_draw(self):\n pass", "def on_view_open(gui, view):\n pass", "def __handle_view_door(self, gamestate_component):", "def _update_view(self) -> None:\n self.view_matrix = lookAt.create_look_at(self._eye, self._target, self._up) \n self.current_shader.set_view(self.view_matrix) #U...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the current color buffer to a file object in PNG format.
def save_image(self, file_obj): manager = pyglet.image.get_buffer_manager() colorbuffer = manager.get_color_buffer() # if passed a string save by name if hasattr(file_obj, 'write'): colorbuffer.save(file=file_obj) else: colorbuffer.save(filename=file_obj)
[ "def _save_buffer(self):\n img_data = renderer.fbuffer.read(mode='color', alpha=False)\n img = Image.fromarray(img_data)\n img.save(self._save_fname)\n self._save_flag = False", "def save_to_buffer(self) -> io.BytesIO:\n image = get_screenshot_as_png(self._layout)\n buffe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a dictionary containing view parameters, calculate a transformation matrix.
def view_to_transform(view): transform = view['ball'].matrix() transform[0:3, 3] = view['center'] transform[0:3, 3] -= np.dot(transform[0:3, 0:3], view['center']) transform[0:3, 3] += view['translation'] * view['scale'] * 5.0 return transform
[ "def _prepare_transforms(self, view):\n raise NotImplementedError()\n # Todo: this method can be removed if we somehow enable the shader\n # to specify exactly which transform functions it needs by name. For\n # example:\n #\n # // mapping function is automatically defi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an MD5 for a geometry object
def geometry_hash(geometry): if hasattr(geometry, 'md5'): # for most of our trimesh objects md5 = geometry.md5() elif hasattr(geometry, 'tostring'): # for unwrapped ndarray objects md5 = str(hash(geometry.tostring())) if hasattr(geometry, 'visual'): # if visual prope...
[ "def MD5(self) -> _n_0_t_3[_n_0_t_9]:", "def getmd5(image: Image):\n return hashlib.md5(image.tobytes()).hexdigest()", "def md5(self):\n return self._md5", "def md5(obj):\n import hashlib\n # print \"self.conf\", str(self.conf)\n # if type(obj) is not str:\n # obj = str(obj)\n # p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts coordinates into pygame coordinates
def to_pygame_coords(self, coords): coords = Vector(coords) if Window.FollowPlayer: # offset coords by screen center coords = coords + (self.size * .5) # offset coords by centered_obj center_point = game.current_level.player.position + Vector(game.current_...
[ "def to_pygame(coords):\r\n return (coords[0], HEIGHT - coords[1])", "def to_pygame(coords):\n return (int(coords[1] * -pg_scale + height / 2 + 600),int(coords[0] * pg_scale + width / 2 - 550))", "def convert_to_pygame_coords(p):\n return int(p.x), int(-p.y+600)", "def to_pygame(p):\n return int(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overriding the grandparent's (WebsocketClient) listen method in order to calculate the order depth and copy the data to the shared namespace for the TUI to display
async def _listen(self,sub_params): async with websockets.connect(self.url) as websocket: await websocket.send(json.dumps(sub_params)) # self.keepalive.start() start_time = time.time() while not self.shutdown_event.is_set(): try: ...
[ "def wsSubData_nb(self):\n uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', ''))\n channel = self.r.pubsub()\n channel.subscribe(self.channel)\n channel.parse_response()\n websocket_fd = uwsgi.connection_fd()\n redis_fd = cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mounts a VP and opens a terminal window into the job's files. Returns a tuple (a, b) where 'a' is the exit code and 'b' a JSON string.
def worker(session, args): #print("Hello " + args.jobid + "!") session.login(args.vcnc) # # Lookup the grid job on the vcnc # Exit if you don't find it. response = grid.get(session, args.jobid) if (response['status_code'] != 200): return (1, response) # # Extract the ...
[ "def shell(cmd):\n return G.DEVICE.shell(cmd)", "def openTerminal():\n\n nodes = nuke.selectedNodes()\n if nodes:\n for node in nodes:\n if node.Class() in ['Read', 'Write']:\n if 'views' in node.knobs().keys():\n path = os.path.dirname(node['file'].eva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the generate function.
def __call__(self): return self.generate()
[ "def do_generate(self):\n pass", "def _do_generate(self):\n try:\n self.do_generate()\n self.ready()\n except Exception as ex: #pylint: disable=broad-except\n logger.exception(\"Error running do_generate\")\n self.fail(str(ex))", "def main():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears grid and samples for generating new samples.
def _clear_previous_samples(self): del self._grid del self._samples # -------------------------------- # Grid Parameters # -------------------------------- self._cell_length = self._radius / np.sqrt(self._dim) self._grid_shape = np.array([int(np.ceil( ...
[ "def resetSamples(self):\n\t\tself.samples = []", "def clearPlayground(self):\n\n for cell in self.cells:\n cell.delete()\n self.cells = []\n self.generation = 0", "def clear_grid(self):\n self.grid = [[self.EMPTY for x in range(self.width)] for y in range(self.height)]", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the grid coordinate of the point.
def _get_grid_coord(self, point): return tuple([int(point[i] / self._cell_length) for i in range(self._dim)])
[ "def get_grid_coordinate(self):\n return (int(self.position.x // (2 * Molecule.radius)),\n int(self.position.y // (2 * Molecule.radius)))", "def get_grid_position(self):\n tile_size_x = constants.WINDOW_WIDTH / constants.GRID_TILE_LENGTH\n tile_size_y = constants.WINDOW_HEIGHT ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to make a random point in proximity of active_point. Attempts to make a random point around the active_point k times. If the new point is too close to another point, it will discard and try. If it fails k times, the function returns None.
def _make_point(self, active_point): # -------------------------------- # Create Random Parameters # -------------------------------- for _ in range(self._k): # Defines radial distance from active_point. rho = np.random.uniform(self._radius, 2 * self._radius) ...
[ "def make_points(self, k, point):\n n = k\n\n while n:\n new_point = self.generate(point)\n if self.check(point, new_point):\n return new_point\n\n n -= 1\n\n return False", "def get_point(k, refpt,r,a,samples,nx,ny,cells,width,height):\n i =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates distance vectors for calculating all neighbors from a given point. A neighbor can be only so far away from the original point and is dependent on the number of dimensions. We calculate every possible coordinate on the grid that the neighbor can be part of relative to a point and store that information for later...
def _create_neighbor_distances(self): # -------------------------------- # Create Directions from Point # -------------------------------- diff = [[0 for _ in range(self._dim)]] curr = diff[0][:] for i in range(self._dim): # Each diff is a unit vector, only ha...
[ "def _get_neighbours(point):\n # Pull coords out of point.\n x = point[0]\n y = point[1]\n z = point[2]\n return ((x-1, y, z), (x+1, y, z), (x, y-1, z), (x, y+1, z), (x, y, z-1), (x, y, z+1))", "def _get_neighbors(size, point):\n i, j = point\n\n neighbors = [(i - 1, j), (i + 1, j), (i, j - 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that the parameter provided in the yaml file for configuration is correct. Some of the params requires list of two values. This is mostly checked as part of this function
def validate_yaml_values(yaml_values, multicar): # Verify if all the yaml keys required for launching models have same number of values same_len_values = [MODEL_S3_BUCKET_YAML_KEY, MODEL_S3_PREFIX_YAML_KEY, MODEL_METADATA_FILE_S3_YAML_KEY, CAR_COLOR_YAML_KEY] LOG.info(yaml_values) ...
[ "def validate_config_dict(self):\n config_options = [\"pipeline_name\",\n \"num_processors\",\n \"num_sessions_at_once\",\n \"available_memory\",\n \"cluster_system\",\n \"output_direc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if connection open.
def connection_open(self): return self.conn_status == self.CONN_OPEN
[ "def is_open(self):\n\t\treturn self.conn.open", "def is_open(self):\n\t\treturn (self.proxy is not None and self._sap_addr is not None)", "def is_connected(self):\n return \"_connection\" in self.__dict__", "def isOpen(self):\n return self.transport_sock is not None", "def is_open(self):\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if connection closed.
def connection_closed(self): return self.conn_status == self.CONN_CLOSED
[ "def connection_closed(self) -> bool:", "def close_connection(self) -> bool:\n return self.get_header('Connection') != 'keep-alive'", "def is_closed(self):\n return self.__com.has_quit()", "def closed(self):\n return self._stream is None", "def closed(self):\n return self.stream.clos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if connection failed.
def connection_failed(self): return self.conn_status == self.CONN_FAILED
[ "def connection_failed(self, connection, error):\n assert False", "def isError(self):\n return _yarp.ConnectionReader_isError(self)", "def check_error(failure):\n failure.trap(ConnectionRefusedError, ResponseNeverReceived)\n return False", "def _connect_failed(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute setpoints from node and domoticz data
def computeSetpoints(node: dict, domo: dict) -> dict: # url = u'http://{}:{}/templow={}&temphigh={}&minduty={}&maxduty={}&hyster={}&addressCtrl={}' data = {} if node is None: return {} sensors = node['sensors'] if len(sensors) == 0: return {} if len(sensors) == 1: address...
[ "def set(self,points,data):\n self.maxDepth = 0\n self.numNodes = 1\n self.root = Node(list(zip(points,data)))\n self.recursive_split(self.root,optimize=True)", "def get_node_points(node):\n for item in coordinate_list:\n if item[0] == node.value:\n return (item[1]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Estimate ARMA parameters using HannanRissanen procedure.
def hannan_rissanen(endog, ar_order=0, ma_order=0, demean=True, initial_ar_order=None, unbiased=None): spec = SARIMAXSpecification(endog, ar_order=ar_order, ma_order=ma_order) endog = spec.endog if demean: endog = endog - endog.mean() p = SARIMAXParams(spec=spec) nobs =...
[ "def estimation(self,ts_data):\n arma_order = self.arma_order[:]\n model_arma = ARIMA(ts_data, arma_order) \n results_arma = model_arma.fit(disp=-1) \n\n residule_arma = results_arma.resid\n\n # print(results_arma.summary())\n #res_arch.plot(annualize='D')\n p = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a residual block with repeating bottleneck blocks.
def _residual_block(input, id_block, conv_block, mid_f, output_f, repetitions, stage, is_first_layer=False): for i in range(repetitions): if i == 0 and is_first_layer is True: input = conv_block(mid_f, output_f, stage, i, input, stride=(1, 1)) elif i == 0 and is_first_layer is False: ...
[ "def build_residual_block(self, incoming_layer, ratio_n_filter=1.0, ratio_size=1.0, has_left_branch=False,\n upscale_factor=4, ix=''):\n simple_block_name_pattern = ['res%s_branch%i%s', 'bn%s_branch%i%s', 'res%s_branch%i%s_relu']\n \n net = {}\n \n # right bran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_evidence
def test_get_evidence(self): query_string = [('keywords', 'keywords_example'), ('pageNumber', 56), ('pageSize', 56)] response = self.client.open('/api/evidence/{statementId}'.format(statementId='statementId_example'), me...
[ "def test_evidence_retrieves_instead_of_overwrites(self):\n e = Evidence(key=\"NBK\", author='Rodney Dangerfield', title=\"Natural Born Killers\")\n r = DataObject(key='Dangerfields_dramatic_range')\n e.asserts(r)\n e.save()\n\n e1 = Evidence(author='Rodney Dangerfield')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load modules, set keybinding and create L{deskbar.core.ThreadPool.ThreadPool}
def run(self): # Ready to load modules self._module_loader.load_all_async() self._setup_keybinder() self._threadpool.start()
[ "def register_pooling(key, module):\n register(key, module, pooling_dict)", "def __init__(self, module, poolclass=QueuePool, **kw):\n\n self.module = module\n self.kw = kw\n self.poolclass = poolclass\n self.pools = {}\n self._create_pool_mutex = threading.Lock()", "def __i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get directory where modules are stored
def get_modules_dir(self): return self._modules_dir
[ "def get_current_modules_dir() -> str:\n return BASE_PATH", "def MODULE_DIR(cls) -> str:\n from ixian_docker.modules import webpack\n\n return os.path.dirname(os.path.realpath(webpack.__file__))", "def getConfDir():\n\t\n\tmodulePath=os.path.dirname(os.path.abspath(inspect.getfile(inspect.curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect to module's C{queryready} signal Load history if all modules have been initialized
def on_module_initialized(self, loader, module): self._inited_modules += 1 # Forward results module.connect ('query-ready', self.forward_query_ready) if (self._inited_modules == self._loaded_modules): self._history.load() self._emit_initialized()
[ "def ready(self):\n import libs.core.analytics.api.signals", "def _on_modules_load(self):", "def startup(self):\r\n for module in self.modules.values():\r\n module.startup(self.evetq)", "def ready(self):\n # export app settings\n self.export_settings()\n # import ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements `tensorflow_privacy.DPQuery.get_noised_result`. Updates tree state, and returns noised cumulative sum and updated state. Computes new cumulative sum, and returns its noised value. Grows tree state by one new leaf, and returns the new state.
def get_noised_result(self, sample_state, global_state): new_cumulative_sum = tf.nest.map_structure( tf.add, global_state.samples_cumulative_sum, sample_state) cumulative_sum_noise, new_tree_state = self._tree_aggregator.get_cumsum_and_update( global_state.tree_state) noised_cumulative_sum =...
[ "def get_noised_result(self, sample_state, global_state):\n # The [0] is needed because of how tf.RaggedTensor.from_two_splits works.\n # print(tf.RaggedTensor.from_row_splits(values=[3, 1, 4, 1, 5, 9, 2, 6],\n # row_splits=[0, 4, 4, 7, 8, 8]))\n # <tf.RaggedTensor ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a query instance with L2 norm clipping and Gaussian noise.
def build_l2_gaussian_query(cls, clip_norm, noise_multiplier, record_specs, noise_seed=None, use_efficient=True): if clip_norm <= 0: raise ValueError(f'`clip_no...
[ "def generate_similar_density_query(query):\n similar_start_date = generate_similar_timestamp(query.start_date)\n similar_end_date = generate_similar_timestamp(query.end_date, min_timestamp=similar_start_date)\n different_sample = random.uniform(0, 1)\n\n return Query(algorithm_name=query.algorithm_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns state after resetting the tree. This function will be used in `restart_query.RestartQuery` after calling `get_noised_result` when the restarting condition is met.
def reset_state(self, noised_results, global_state): del noised_results new_tree_state = self._tree_aggregator.reset_state(global_state.tree_state) return attr.evolve( global_state, previous_tree_noise=self._zero_initial_noise(), tree_state=new_tree_state)
[ "def state(self):\n result = self.getResult()\n return result.state", "def reset(self):\n # Initialize the timestep\n self.timestep = 0\n self.state = self.starting_state\n\n return self.starting_state", "def _do_query_state(self):\n return self._lutron.send(Lutron.O...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function constructs a complete tree given all the leaf nodes. The function takes a 1D array representing the leaf nodes of a tree and the tree's arity, and constructs a complete tree by recursively summing the adjacent children to get the parent until reaching the root node. Because we assume a complete tree, if the ...
def _build_tree_from_leaf(leaf_nodes: tf.Tensor, arity: int) -> tf.RaggedTensor: def pad_zero(leaf_nodes, size): paddings = [[0, size - len(leaf_nodes)]] return tf.pad(leaf_nodes, paddings) leaf_nodes_size = tf.constant(len(leaf_nodes), dtype=tf.float32) num_layers = tf.math.ceil( tf.math.log(leaf...
[ "def arity(t):\n # base case, reached a leaf\n if len(t.children) == 0:\n return 0\n else:\n # general case\n return max([arity(x) for x in t.children] + [len(t.children)])\n pass", "def build_root(self, iterable):\n # TODO: Implement this method\n # Try implementing thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements `tensorflow_privacy.DPQuery.preprocess_record`. This method builds the tree, flattens it and applies `inner_query.preprocess_record` to the flattened tree.
def preprocess_record(self, params, record): arity, inner_query_params = params preprocessed_record = _build_tree_from_leaf(record, arity).flat_values # The following codes reshape the output vector so the output shape of can # be statically inferred. This is useful when used with # `tff.aggregators...
[ "def _preprocess(self):\n # A 2D table storing all possible queries.\n self._table = {}\n\n # Build the table using bottom-up dynamic programming.\n for p in breadth_first_traversal(self._tree):\n self._table[p.index()] = [p]\n\n l = 0\n while (l < self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements `tensorflow_privacy.DPQuery.get_noised_result`. This function reconstructs the `tf.RaggedTensor` from the flattened tree output by `preprocess_records.`
def get_noised_result(self, sample_state, global_state): # The [0] is needed because of how tf.RaggedTensor.from_two_splits works. # print(tf.RaggedTensor.from_row_splits(values=[3, 1, 4, 1, 5, 9, 2, 6], # row_splits=[0, 4, 4, 7, 8, 8])) # <tf.RaggedTensor [[3, 1, 4...
[ "def preprocess_record(self, params, record):\n arity, inner_query_params = params\n preprocessed_record = _build_tree_from_leaf(record, arity).flat_values\n # The following codes reshape the output vector so the output shape of can\n # be statically inferred. This is useful when used with\n # `tff.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to decide which `add_noise` to use according to tf version.
def _get_add_noise(stddev, seed: int = None): if distutils.version.LooseVersion( tf.__version__) < distutils.version.LooseVersion('2.0.0'): # The seed should be only used for testing purpose. if seed is not None: tf.random.set_seed(seed) def add_noise(v): return v + tf.random.normal( ...
[ "def _sample_new_noise(self, *, tf_sess=None):\n if self.framework == \"tf\":\n tf_sess.run(self.tf_sample_new_noise_op)\n elif self.framework == \"tf2\":\n self._tf_sample_new_noise_op()\n else:\n for i in range(len(self.noise)):\n self.noise[i] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that adds a line at the top of a dataframe
def appforth(df, line): df.loc[-1]=line df.index = df.index + 1 # shifting index df = df.sort_index() # sorting by index return df
[ "def add_row_at_top(df):\n df.loc[-1] = np.zeros(df.shape[1]) # adding a row\n df.index = df.index + 1 # shifting index\n df = df.sort_index() # sorting by index\n return df", "def insertLines(data):\n data = pd.DataFrame(data)\n for _,row in data.iterrows():\n insertLine(row)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scopes a CAR object name, via dm[object][action], or dm[object]
def car_object_scoper(object_name): return "match(tag, \"dm-{}-.*\")".format(object_name)
[ "def set_find_object(intent, session):\n\n session_attributes = {}\n card_title = intent['name']\n should_end_session = False\n\n # gets the name of the object to find from the CocoLabels \n if 'CocoLabel' in intent['slots']:\n find_object = intent['slots']['CocoLabel']['value']\n\n # u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scopes a basic data model object name, via a tag for that object
def default_object_scoper(object_name): return "tag=\"{}\"".format(object_name)
[ "def scope(self, name):\r\n raise NotImplementedError", "def enterScope(self, name):", "def tag_detail(request, tag, page=None, **kwargs):\n if not kwargs.get('template_name'):\n kwargs['template_name'] = template_name_for_gbobject_queryset_filtered(\n 'tag', slugify(tag))\n\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return starting and ending positions of next url in 'page'
def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None,0 url_start = page.find('"',start_link) url_end = page.find('"',url_start+1) url= page[url_start+1:url_end] return url, url_end
[ "def index_range(page: int, page_size: int) -> tuple:\n start = (page - 1) * page_size\n end = start + page_size\n return start, end", "def extract_next_page(parser):\n tbl_list = parser.table.findAll('table')\n a_list = tbl_list[1].findAll('a')\n next_url = a_list[-1]['href']\n return next_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the content of 'page' as a string
def get_page(page): import urllib2 source = urllib2.urlopen(page) return source.read()
[ "def get_page_text(self):\n pass", "def get_page_by_id(self, pageid):\n return str(self.cursor.execute(\"SELECT content FROM content WHERE pageid=?\", pageid).fetchone()).lower()", "def process_page(page):\n content = utils.any2unicode(page, 'utf8').strip()\n content = re.sub(r\"[^a-zA-Z]\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add keyword and correspoding url to index
def add_to_index(index,keyword,url): if keyword in index: if url not in index[keyword]: index[keyword].append(url) else: index[keyword] = [url]
[ "def add_page_to_index(index,url,content):\n\tkeywords = split_string(content,\".,-!<>/=\\\"\")\n\tfor keyword in keywords:\n\t\tadd_to_index(index,keyword,url)", "def add_search_keyword(self, keyword):\n pass", "def add_page_to_index(index, url, content):\n words = content.split()\n for word in wo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add given content as correspoding to given url into index
def add_page_to_index(index,url,content): keywords = split_string(content,".,-!<>/=\"") for keyword in keywords: add_to_index(index,keyword,url)
[ "def add_page_to_index(index, url, content):\n words = content.split()\n for word in words:\n add_to_index(index, word, url)\n return index", "def add_to_index(index,keyword,url):\n\tif keyword in index:\n\t\tif url not in index[keyword]:\n\t\t\tindex[keyword].append(url)\n\telse:\n\t\tindex[keywo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all crawled links starting with seed page never exceeding max_depth number of links
def web_crawler(seed, max_depth): to_crawl = [seed] crawled = [] next_depth = [] current_depth = 0 while to_crawl and current_depth <= max_depth: link = to_crawl.pop(0) if link not in crawled: content = get_page(link) add_page_to_index(index, link, content) outlinks = get_all_links(content) grap...
[ "def get_urls(self, depth_of_tree):\n self.links_per_depth_counter = self.next_level_children\n self.next_level_children = 0\n self.depth += 1\n while self.depth <= depth_of_tree and self.total_links_traversed < self.max_webpages:\n while self.links_per_depth_counter > 0 and s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a challenge list in which the participant team has participated.
def get_participant_team_challenge_list(request, participant_team_pk): try: participant_team = ParticipantTeam.objects.get(pk=participant_team_pk) except ParticipantTeam.DoesNotExist: response_data = {"error": "Participant Team does not exist"} return Response(response_data, status=statu...
[ "def challenges(self):\n return [gc.challenge for gc in GrandChallenge.objects.filter(round=self.round_number).order_by('challenge__status')]", "def get_teams_and_corresponding_challenges_for_a_participant(\n request, challenge_pk\n):\n # first get list of all the participants and teams related to th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a participant from a Participant Team
def delete_participant_from_team(request, participant_team_pk, participant_pk): try: participant_team = ParticipantTeam.objects.get(pk=participant_team_pk) except ParticipantTeam.DoesNotExist: response_data = {"error": "ParticipantTeam does not exist"} return Response(response_data, stat...
[ "def delete_participant(namespace, workspace, participant_id):\n body = [{\"entityType\": \"participant\", \"entityName\": participant_id}]\n res = firecloud_api.delete_entities(namespace, workspace, body)\n return res", "def test_teams_delete_team_v1(self):\n pass", "def remove_participant_team...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of teams and corresponding challenges for a participant
def get_teams_and_corresponding_challenges_for_a_participant( request, challenge_pk ): # first get list of all the participants and teams related to the user participant_objs = Participant.objects.filter( user=request.user ).prefetch_related("team") is_challenge_host = is_user_a_host_of_cha...
[ "def get_participant_team_challenge_list(request, participant_team_pk):\n try:\n participant_team = ParticipantTeam.objects.get(pk=participant_team_pk)\n except ParticipantTeam.DoesNotExist:\n response_data = {\"error\": \"Participant Team does not exist\"}\n return Response(response_data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
API to remove the participant team from a challenge
def remove_participant_team_from_challenge( request, challenge_pk, participant_team_pk ): challenge = get_challenge_model(challenge_pk) participant_team = get_participant_model(participant_team_pk) if participant_team.created_by == request.user: if participant_team.challenge_set.filter(id=chal...
[ "def test_teams_remove_user_from_team_v1(self):\n pass", "def test_teams_delete_team_v1(self):\n pass", "def delete_workteam(WorkteamName=None):\n pass", "def test_teams_remove_user_from_team_v2(self):\n pass", "def delete_participant_from_team(request, participant_team_pk, participa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare a batch import of stock from the WMS
def import_warehouse_stock_qty_batch(session, model_name, backend_id, filters=None): if filters is None: filters = {'skus': 'ALL'} env = get_environment(session, model_name, backend_id) importer = env.get_connector_unit(WarehouseImport) importer.run(filters['skus'])
[ "def batcher(self, stock_list=None, batch_size=3): \n \n if stock_list is None:\n stock_list = self.target_df[\"stock_id\"].unique().tolist()\n \n for b in range(int(np.ceil(len(stock_list)/batch_size))):\n \n # load data for current batch of s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }