content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# From https://github.com/RLBot/RLBot/blob/master/src/main/python/rlbot/version.py # Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module # https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package __version__ = '0.5.0' release_notes = { '0.5.0': """ - Removed string based configurations in rlgym.make(), everything is passed by kwargs now - Soren - Added StableBaselines3 compatibility - Rolv - Refactored and expanded reward functions - Rolv - Added replay converter - Rolv - Fixed TouchBallReward bug - Kevin NOTE: Some of these new tools (wrappers, replay converter, etc) will be moved to a different package in the next release """, '0.4.1': """ - Updated euler angles to match rlbot [pitch, yaw, roll] and added accessor functions - Bugfix: player.is_alive renamed to is_demoed - Added common rewards - Rolv - Added a reward combiner - Chainso - Added missing kickoff spawn - Fixed 2v2 and 3v3 action delivery - Fixed issue in 2v2 and 3v3 were blue bots would disappear over time - Added multi injector """, '0.4.0': """ - Major API refactor - Added boostpad boolean array to GameState - RLGym is now baselines compatible - Added improved Default configuration """, '0.3.0': """ - Pass initial state to env components on gym.reset() - Pass prev action to reward fn - info returned from gym.step() is now a Dict - Fixed obs size bug in RhobotObs """, '0.2.0': """ - Switched from custom_args dict to keyword args in rlgym.make() """, '0.1.4': """ - Gym now inherits openai.gym.Env - Chainso - Fixed bug where rlgym crashed trying to parse the state string in some scenarios """, '0.1.3': """ - Renamed PhysicsObject.orientation to euler_angles - euler_angles is now a function so they aren't calculated if not needed - Added rotation_mtx, forward, right and up vectors to PhysicsObject (only usable for the car) - Removed conversion to np array for rewards and observations - Fixed bug in RhobotObs """, '0.1.2': """ - Obs are now numpy arrays - Added types to core classes to make customization easier - Fixed bakkesmod bug """, '0.1.1': """ Added missing scipy dependency """, '0.1.0': """ Initial Release """ }
[ 2, 3574, 3740, 1378, 12567, 13, 785, 14, 7836, 20630, 14, 7836, 20630, 14, 2436, 672, 14, 9866, 14, 10677, 14, 12417, 14, 29412, 14, 45895, 13645, 14, 9641, 13, 9078, 198, 2, 9363, 262, 2196, 994, 523, 25, 198, 2, 352, 8, 356, 8...
2.865757
879
import unittest import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal from structured import common, gibbs, objects, varapprox from structured.common import mult_diag
[ 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 28177, 62, 40496, 11, 6818, 62, 18747, 62, 28177, 62, 40496, 198, 198, 6738, 20793, 1330, 2219, 11, 46795, 1443, 11, 5563...
3.603448
58
import Arena from MCTS import MCTS from hex.HexGame import HexGame, display from hex.HexPlayers import * from hex.pytorch.NNet import NNetWrapper as NNet import numpy as np from utils import * """ use this script to play any two agents against each other, or play manually with any agent. """ g = HexGame(6) # all players rp = RandomPlayer(g).play hp = HumanHexPlayer(g).play abp = AlphaBetaPlayer(g, maxDepth=3) abpp = abp.play # nnet players n1 = NNet(g) n1.load_checkpoint('./pretrained_models/hex/pytorch/','6x100x25_Best_iter99.pth.tar') args1 = dotdict({'numMCTSSims': 50, 'cpuct':1.0}) mcts1 = MCTS(g, n1, args1) n1p = lambda x, player: np.argmax(mcts1.getActionProb(x, player, temp=0)) # n2 = NNet(g) # n2.load_checkpoint('./pretrained_models/hex/pytorch/','old.pth.tar') # args2 = dotdict({'numMCTSSims': 50, 'cpuct':1.0}) # mcts2 = MCTS(g, n2, args2) # n2p = lambda x, player: np.argmax(mcts2.getActionProb(x, player, temp=0)) arena = Arena.Arena(n1p, abpp, g, display=display, mcts=mcts1, ab=abp) num = 20 print(arena.playGames(num, verbose=True)) total_turn = arena.total_turn print('sim count MCTS all', mcts1.sim_count, 'avg game', mcts1.sim_count/num, 'avg turn', mcts1.sim_count/total_turn) print('sim count alpha beta', abp.sim_count, 'avg game', abp.sim_count/num, 'avg turn', abp.sim_count/total_turn)
[ 11748, 10937, 198, 6738, 337, 4177, 50, 1330, 337, 4177, 50, 198, 6738, 17910, 13, 39, 1069, 8777, 1330, 22212, 8777, 11, 3359, 198, 6738, 17910, 13, 39, 1069, 24860, 1330, 1635, 198, 6738, 17910, 13, 9078, 13165, 354, 13, 6144, 316, ...
2.365419
561
"""Class definition for filtering duplicate files.""" from kaishi.core.misc import find_duplicate_inds from kaishi.core.misc import trim_list_by_inds from kaishi.core.misc import CollapseChildren from kaishi.core.pipeline_component import PipelineComponent class FilterDuplicateFiles(PipelineComponent): """Filter duplicate files, detected via hashing."""
[ 37811, 9487, 6770, 329, 25431, 23418, 3696, 526, 15931, 198, 6738, 38387, 21644, 13, 7295, 13, 44374, 1330, 1064, 62, 646, 489, 5344, 62, 521, 82, 198, 6738, 38387, 21644, 13, 7295, 13, 44374, 1330, 15797, 62, 4868, 62, 1525, 62, 521,...
3.656566
99
import re import itertools from bacteria_regex import BacteriaMatcher
[ 11748, 302, 198, 11748, 340, 861, 10141, 198, 198, 6738, 11492, 62, 260, 25636, 1330, 347, 10634, 19044, 2044, 628, 628, 198 ]
3.409091
22
from rodan.jobs.base import RodanTask from gamera.core import init_gamera, Image, load_image from gamera import gamera_xml from ProjectionSplitting import ProjectionSplitter from DirtyLayerRepair import DirtyLayerRepairman init_gamera()
[ 6738, 15299, 272, 13, 43863, 13, 8692, 1330, 6882, 272, 25714, 198, 198, 6738, 308, 18144, 13, 7295, 1330, 2315, 62, 70, 18144, 11, 7412, 11, 3440, 62, 9060, 198, 6738, 308, 18144, 1330, 308, 18144, 62, 19875, 198, 198, 6738, 4935, ...
3.408451
71
# Copyright (c) 2017, Matt Layman import os from handroll import logger from handroll.composers import Composer from handroll.composers.mixins import FrontmatterComposerMixin from handroll.i18n import _ class GenericHTMLComposer(FrontmatterComposerMixin, Composer): """A template class that performs basic handling on a source file The title will be extracted from the first line and the remaining source lines will be passed to a template method for further processing. """ output_extension = '.html' def compose(self, catalog, source_file, out_dir): """Compose an HTML document by generating HTML from the source file, merging it with a template, and write the result to output directory.""" data, source = self.get_data(source_file) template = self.select_template(catalog, data) # Determine the output filename. root, ext = os.path.splitext(os.path.basename(source_file)) filename = root + self.output_extension output_file = os.path.join(out_dir, filename) if self._needs_update(template, source_file, output_file): logger.info(_('Generating HTML for {source_file} ...').format( source_file=source_file)) data['content'] = self._generate_content(source) self._render_to_output(template, data, output_file) else: logger.debug(_('Skipping {filename} ... It is up to date.').format( filename=filename)) @property def select_template(self, catalog, data): """Select a template from the catalog based on the source file's data. """ if 'template' in data: return catalog.get_template(data['template']) else: return catalog.default def _generate_content(self, source): """Generate the content from the provided source data.""" raise NotImplementedError def _needs_update(self, template, source_file, output_file): """Check if the output file needs to be updated by looking at the modified times of the template, source file, and output file.""" if self._config.force: return True out_modified_time = None if os.path.exists(output_file): out_modified_time = os.path.getmtime(output_file) else: # The file doesn't exist so it definitely needs to be "updated." return True if os.path.getmtime(source_file) > out_modified_time: return True if template.last_modified > out_modified_time: return True return False def _render_to_output(self, template, data, output_file): """Render the template and data to the output file.""" with open(output_file, 'wb') as out: out.write(template.render(data).encode('utf-8')) out.write(b'<!-- handrolled for excellence -->\n')
[ 2, 15069, 357, 66, 8, 2177, 11, 4705, 18881, 805, 198, 198, 11748, 28686, 198, 198, 6738, 1021, 2487, 1330, 49706, 198, 6738, 1021, 2487, 13, 785, 1930, 364, 1330, 29936, 263, 198, 6738, 1021, 2487, 13, 785, 1930, 364, 13, 19816, 10...
2.596646
1,133
import os from oneandone.client import OneAndOneService token = os.getenv('ONEANDONE_TOKEN') client = OneAndOneService(token) # List all users users = client.list_users() # Retrieve a user user = client.get_user(user_id='') # Retrieve a user's API privileges api_info = client.api_info(user_id='') # Retrieve a user's API key api_key = client.show_api_key(user_id='') # Retrieve users current permissions user_permissions = client.show_user_permissions() # List IPs from which API access is allowed for a user ips_allowed = client.ips_api_access_allowed(user_id='') # Create user new_user = client.create_user(name='Test User', password='testing123', email='test@example.com', description='Test Description' ) # Add new IPs to the user ip1 = '12.54.127.11' ip2 = '14.97.4.171' ips = [ip1, ip2] response = client.add_user_ip(user_id='', user_ips=ips) # Modify user information response = client.modify_user(user_id='', description='', email='', password='', state='ACTIVE') # Modify a user's API privileges response = client.modify_user_api(user_id='', active=True) # Change a user's API key response = client.change_api_key(user_id='') # Delete a user response = client.delete_user(user_id='') # Remove an IP response = client.remove_user_ip(user_id='', ip='14.97.4.171')
[ 11748, 28686, 198, 6738, 530, 392, 505, 13, 16366, 1330, 1881, 1870, 3198, 16177, 198, 198, 30001, 796, 28686, 13, 1136, 24330, 10786, 11651, 6981, 11651, 62, 10468, 43959, 11537, 198, 198, 16366, 796, 1881, 1870, 3198, 16177, 7, 30001, ...
2.462478
573
""" An implementation of http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch (without any entropy coder or codebook size limit) """ ## message = 'TOBEORNOTTOBEORTOBEORNOT' ## encoded = list(encode(message)) ## output = ''.join(decode(encoded)) ## message == output #. True ## list(show_lzw(message)) #. ['T', 'O', 'B', 'E', 'O', 'R', 'N', 'O', 'T', 256, 258, 260, 265, 259, 261, 263] ## list(chunked_decode(iter(encoded))) #. ['T', 'O', 'B', 'E', 'O', 'R', 'N', 'O', 'T', 'TO', 'BE', 'OR', 'TOB', 'EO', 'RN', 'OT'] default_codebook = map(chr, range(256)) def encode(s, codebook=default_codebook): "Generate the LZW codes for string or iterable s." # Pre: each character in s has an entry in codebook. codes = dict((chunk, i) for i, chunk in enumerate(codebook)) chunk = '' for c in s: chunk += c if chunk not in codes: yield codes[chunk[:-1]] codes[chunk] = len(codes) chunk = chunk[-1] if chunk: yield codes[chunk] def decode(codes, codebook=default_codebook): """Given an LZW code sequence as an iterable, generate the plaintext character sequence it came from.""" # Pre: codebook is the same as the encoder's. for chunk in chunked_decode(iter(codes), codebook): for c in chunk: yield c ## m = 'XXXXXXXXXXXX' ## list(show_lzw(m)) #. ['X', 256, 257, 258, 256] ## x = list(encode(m)) ## list(chunked_decode(iter(x))) #. ['X', 'XX', 'XXX', 'XXXX', 'XX'] ## m == ''.join(chunked_decode(iter(x))) #. True ## test_reversible('xxxxxxxxxyyyyyyyyyyyyyyxxxxxxxxx') ## test_reversible('when in the course of human events to be or not to be') ## rle_test() ## exhaustive_binary_test() ## mil = list(encode('a' * 1000)) ## len(mil), max(mil) #. (45, 298)
[ 37811, 198, 2025, 7822, 286, 198, 4023, 1378, 268, 13, 31266, 13, 2398, 14, 15466, 14, 43, 368, 30242, 4, 36, 17, 4, 1795, 4, 6052, 57, 452, 4, 36, 17, 4, 1795, 4, 6052, 54, 417, 354, 198, 7, 19419, 597, 40709, 269, 12342, 393...
2.366534
753
import os import re import shutil if "{{ cookiecutter.has_models }}" == "no": shutil.rmtree("models") if "{{ cookiecutter.has_wizards }}" == "yes": os.mkdir("wizards") if "{{ cookiecutter.has_reports }}" == "yes": os.mkdir("reports") if "{{ cookiecutter.has_controller}}" == "yes": os.mkdir("controllers")
[ 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 628, 198, 361, 366, 27007, 19751, 8968, 353, 13, 10134, 62, 27530, 34949, 1, 6624, 366, 3919, 1298, 198, 220, 220, 220, 4423, 346, 13, 81, 16762, 631, 7203, 27530, 4943, 198, 198, ...
2.496183
131
from __future__ import print_function, absolute_import from builtins import str import sys, os, re, json, logging, errno from datetime import datetime from glob import glob from os.path import join, isfile, dirname, abspath, basename from makepy import argparse from makepy.config import read_setup_args, package_dir, read_config, read_basic_cfg, module_name from makepy.shell import run, cp, call_unsafe, sed, mkdir, rm, block, open from makepy.python import pyv, python, pip # load files and templates from makepy._templates import templates try: from makepy._datafiles import dirs as datadirs, files as datafiles except: datafiles = {}; datadirs = set() try: from makepy._makefiles import dirs as makedirs, files as makefiles except: makefiles = {}; makedirs = set() log = logging.getLogger('makepy') here = dirname(__file__) r_version = r'(__version__[^0-9]+)([0-9\.]+)([^0-9]+)'
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 4112, 62, 11748, 198, 198, 6738, 3170, 1040, 1330, 965, 198, 11748, 25064, 11, 28686, 11, 302, 11, 33918, 11, 18931, 11, 11454, 3919, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 673...
3.064846
293
print("Hello I am Sagar")
[ 4798, 7203, 15496, 314, 716, 25605, 283, 4943, 198 ]
2.888889
9
# coding:utf-8 """The file is just for test.""" import nltk from nltk.corpus import wordnet as wn from nltk.corpus import sentiwordnet as swn from nltk.stem import PorterStemmer from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() ps = PorterStemmer() def penn_to_wn(tag): """ Convert between the PennTreebank tags to simple Wordnet tags """ if tag.startswith('J'): return wn.ADJ elif tag.startswith('N'): return wn.NOUN elif tag.startswith('R'): return wn.ADV elif tag.startswith('V'): return wn.VERB return None def get_sentiment(word,tag): """ returns list of pos neg and objective score. But returns empty list if not present in senti wordnet. """ wn_tag = penn_to_wn(tag) if wn_tag not in (wn.NOUN, wn.ADJ, wn.ADV): return [] lemma = lemmatizer.lemmatize(word, pos=wn_tag) if not lemma: return [] synsets = wn.synsets(word, pos=wn_tag) if not synsets: return [] # Take the first sense, the most common synset = synsets[0] swn_synset = swn.senti_synset(synset.name()) return [swn_synset.pos_score(),swn_synset.neg_score(),swn_synset.obj_score()] if __name__ == '__main__': test_sentence = 'This is just a test whether is good or not ?'.split(' ') test_sentence_stem = [ps.stem(x) for x in test_sentence] print(test_sentence) print(test_sentence_stem) pos_val = nltk.pos_tag(test_sentence) senti_val = [get_sentiment(x, y) for (x, y) in pos_val] for word, value in zip(test_sentence, senti_val): print(word, value)
[ 2, 19617, 25, 40477, 12, 23, 198, 37811, 464, 2393, 318, 655, 329, 1332, 526, 15931, 198, 198, 11748, 299, 2528, 74, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 1573, 3262, 355, 266, 77, 198, 6738, 299, 2528, 74, 13, 10215...
2.329446
686
import io from os import path from setuptools import setup, find_packages MYDIR = path.abspath(path.dirname(__file__)) cmdclass = {} ext_modules = [] setup( name='airflow-notify-sns', version='0.0.2', author="Marcelo Santino", author_email="marcelo@santino.dev", description="Publish Airflow notification errors to SNS Topic", url='https://github.com/msantino/airflow-notify-sns', long_description=io.open('README.md', 'r', encoding='utf-8').read(), long_description_content_type="text/markdown", packages=find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, setup_requires=[], cmdclass=cmdclass, ext_modules=ext_modules, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
[ 11748, 33245, 198, 6738, 28686, 1330, 3108, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 26708, 34720, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 198, 28758, 4871...
2.610119
336
num = 10 num2 =20 num3 =300 num4 =40
[ 22510, 796, 838, 198, 22510, 17, 796, 1238, 198, 22510, 18, 796, 6200, 198, 22510, 19, 796, 1821, 198 ]
1.947368
19
from .base import BaseComponent
[ 6738, 764, 8692, 1330, 7308, 21950, 628 ]
4.714286
7
""" This program demonstrates an infinite loop. This program will need to be force closed as it will never end. """ keep_going = "y" #Variable to control the loop. #Warning! Infinite loop! This program will never end. while keep_going == "y": sales = float(input("Enter the amount of sales: ")) #Get a salesperson's sales and commission rate. comm_rate = float(input("Enter the commission rate: ")) commission = sales * comm_rate #Calculate the commission. print("The commission is $", format(commission, ",.2f"), sep="") #Display the commission. """ Since keep_going never changes in the body of the loop, the loop's condition will always be true. """
[ 37811, 198, 1212, 1430, 15687, 281, 15541, 9052, 13, 198, 1212, 1430, 481, 761, 284, 307, 2700, 4838, 355, 340, 481, 1239, 886, 13, 198, 37811, 198, 198, 14894, 62, 5146, 796, 366, 88, 1, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.607973
301
from django.urls import path, include from . import views from django.contrib.auth import views as auth_views from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name='game' urlpatterns = [ #Home path('', views.home, name="home"), #Lobby path('lobbies/', views.lobbies, name="lobbies"), path('createlobby/', views.lobbyForm, name="createlobby"), path('lobbies/<str:lobby_name>/', views.inLobby, name='lobby'), path('add_user_lobby/<lobby_name>/', views.addUser, name='add_user'), path('delete_lobby/<lobby_name>/', views.cancelLobby, name='cancel-lobby'), #Game path('game/<lobby_name>/', views.inGame, name="game"), #These are the urls for the registering and logging in for normal user path('register/', views.register, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.userLogout, name="logout"), #GameMaster Login path('login_gamemaster/', views.loginGamemaster, name="login_gamemaster"), #Password Reset path('password_reset/', auth_views.PasswordResetView.as_view(template_name="users/password_reset.html"), name="password_reset"), path('password_reset_sent/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_sent.html"), name="password_reset_sent"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_form.html"), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_done.html"), name="password_reset_complete"), ] #For the Images urlpatterns += staticfiles_urlpatterns()
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 201, 198, 6738, 764, 1330, 5009, 201, 198, 201, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 5009, 355, 6284, 62, 33571, 201, 198, 6738, 42625, 14208, 13, 3642, 822, ...
2.816054
598
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) """ This is the simplest Python GTK+3 snippet. See: http://python-gtk-3-tutorial.readthedocs.org/en/latest/layout.html """ from gi.repository import Gtk as gtk if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 357, 66, 8, 1853, 449, 2634, 29350, 44871, 27196, 11290, 357, 4023, 1378, 2503, 13, 73, 67, 24831,...
2.376923
130
import json from pathlib import Path __all__ = ["__version__", "__js__"] __js__ = json.load( (Path(__file__).parent.resolve() / "labextension/package.json").read_bytes() ) __version__ = __js__["version"]
[ 11748, 33918, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 834, 439, 834, 796, 14631, 834, 9641, 834, 1600, 366, 834, 8457, 834, 8973, 198, 834, 8457, 834, 796, 33918, 13, 2220, 7, 198, 220, 220, 220, 357, 15235, 7, 834, 7753, 834,...
2.714286
77
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Const Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.sheet class DataPilotFieldGroupBy(object): """ Const Class These constants select different types for grouping members of a DataPilot field by date or time. See Also: `API DataPilotFieldGroupBy <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1sheet_1_1DataPilotFieldGroupBy.html>`_ """ __ooo_ns__: str = 'com.sun.star.sheet' __ooo_full_ns__: str = 'com.sun.star.sheet.DataPilotFieldGroupBy' __ooo_type_name__: str = 'const' SECONDS = 1 """ Groups all members of a DataPilot field containing a date/time value by their current value for seconds. Example: The group :02 will contain all members that contain a time with a seconds value of 2, regardless of the date, hours and minutes of the member, e.g. 2002-Jan-03 00:00:02 or 1999-May-02 12:45:02. """ MINUTES = 2 """ Groups all members of a DataPilot field containing a date/time value by their current value for minutes. Example: The group :02 will contain all members that contain a time with a minutes value of 2, regardless of the date, hours and seconds of the member, e.g. 2002-Jan-03 00:02:00 or 1999-May-02 12:02:45. """ HOURS = 4 """ Groups all members of a DataPilot field containing a date/time value by their current value for hours. Example: The group 02 will contain all members that contain a time with a hour value of 2, regardless of the date, minutes and seconds of the member, e.g. 2002-Jan-03 02:00:00 or 1999-May-02 02:12:45. """ DAYS = 8 """ Groups all members of a DataPilot field containing a date/time value by their calendar day, or by ranges of days. Examples: See descriptions for XDataPilotFieldGrouping.createDateGroup() for more details about day grouping. """ MONTHS = 16 """ Groups all members of a DataPilot field containing a date/time value by their month. Example: The group Jan will contain all members with a date in the month January, regardless of the year, day, or time of the member, e.g. 2002-Jan-03 00:00:00 or 1999-Jan-02 02:12:45. """ QUARTERS = 32 """ Groups all members of a DataPilot field containing a date/time value by their quarter. Example: The group Q1 will contain all members with a date in the first quarter of a year (i.e. the months January, February, and march), regardless of the year, day, or time of the member, e.g. 2002-Jan-03 00:00:00 or 1999-Mar-02 02:12:45. """ YEARS = 64 """ Groups all members of a DataPilot field containing a date/time value by their year. Example: The group 1999 will contain all members with a date in the year 1999, regardless of the month, day, or time of the member, e.g. 1999-Jan-03 00:00:00 or 1999-May-02 02:12:45. """ __all__ = ['DataPilotFieldGroupBy']
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 15069, 33160, 1058, 33, 6532, 12, 22405, 12, 12041, 25, 19935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 4943, 198, 2, 345, 743,...
3.049278
1,177
# -*- coding: utf-8 -*- import pandas as pd
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 19798, 292, 355, 279, 67, 628 ]
2.142857
21
# flake8: noqa # import all models into this package # if you have many models here with many references from one model to another this may # raise a RecursionError # to avoid this, import only the models that you directly need like: # from from fds.sdk.MarketIntelligence.model.pet import Pet # or import this package, but before doing it, use: # import sys # sys.setrecursionlimit(n) from fds.sdk.MarketIntelligence.model.fetch_report_poll_id import FetchReportPollID from fds.sdk.MarketIntelligence.model.get_report_info import GetReportInfo from fds.sdk.MarketIntelligence.model.miapi_post_request import MIAPIPostRequest from fds.sdk.MarketIntelligence.model.post_request_example import PostRequestExample from fds.sdk.MarketIntelligence.model.post_response_info import PostResponseInfo from fds.sdk.MarketIntelligence.model.report_content import ReportContent from fds.sdk.MarketIntelligence.model.report_data_header import ReportDataHeader
[ 2, 781, 539, 23, 25, 645, 20402, 198, 198, 2, 1330, 477, 4981, 656, 428, 5301, 198, 2, 611, 345, 423, 867, 4981, 994, 351, 867, 10288, 422, 530, 2746, 284, 1194, 428, 743, 198, 2, 5298, 257, 3311, 24197, 12331, 198, 2, 284, 3368...
3.47619
273
""" #Ref: Sreenivas Sarwar Anik What are features? s """ ############################################## #Gabor filter, multiple filters in one. Generate fiter bank. """ For image processing and computer vision, Gabor filters are generally used in texture analysis, edge detection, feature extraction, etc. Gabor filters are special classes of bandpass filters, i.e., they allow a certain ‘band’ of frequencies and reject the others. ksize Size of the filter returned. sigma Standard deviation of the gaussian envelope. theta Orientation of the normal to the parallel stripes of a Gabor function. lambda Wavelength of the sinusoidal factor. gamma Spatial aspect ratio. psi Phase offset. ktype Type of filter coefficients. It can be CV_32F or CV_64F. indicates the type and range of values that each pixel in the Gabor kernel can hold. Basically float32 or float64 """ import numpy as np import cv2 import matplotlib.pyplot as plt ksize = 5 #Use size that makes sense to the image and fetaure size. Large may not be good. #On the synthetic image it is clear how ksize affects imgae (try 5 and 50) sigma = 3 #Large sigma on small features will fully miss the features. theta = 1*np.pi/4 #/4 shows horizontal 3/4 shows other horizontal. Try other contributions lamda = 1*np.pi /4 #1/4 works best for angled. gamma=0.4 #Value of 1 defines spherical. Calue close to 0 has high aspect ratio #Value of 1, spherical may not be ideal as it picks up features from other regions. phi = 0 #Phase offset. I leave it to 0. kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, lamda, gamma, phi, ktype=cv2.CV_32F) plt.imshow(kernel) img = cv2.imread('synthetic.jpg') #img = cv2.imread('BSE_Image.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) fimg = cv2.filter2D(img, cv2.CV_8UC3, kernel) kernel_resized = cv2.resize(kernel, (400, 400)) # Resize image cv2.imshow('Kernel', kernel_resized) cv2.imshow('Original Img.', img) cv2.imshow('Filtered', fimg) cv2.waitKey(5000) cv2.destroyAllWindows()
[ 198, 37811, 198, 2, 8134, 25, 311, 1361, 38630, 6866, 5767, 1052, 1134, 198, 198, 2061, 389, 3033, 30, 220, 198, 82, 198, 37811, 198, 198, 29113, 7804, 4242, 2235, 198, 2, 38, 4820, 8106, 11, 3294, 16628, 287, 530, 13, 2980, 378, ...
3.008863
677
"""Assorted utilities for tests""" import unittest from typing import Tuple, List import cv2 import numpy as np import numpy.testing as npt from active_shape_model import ActiveShapeModel from image_shape import ImageShape from imgutils import load_images, apply_median_blur, apply_sobel from incisors import Incisors from shape import Shape from data_preprocessing import Preprocessor TEST_IMAGES = { "center_diagonal_line": np.array( [ [255, 255, 255, 255, 0], [255, 255, 255, 0, 255], [255, 255, 0, 255, 255], [255, 0, 255, 255, 255], [0, 255, 255, 255, 255], ], np.uint8, ), "center_horizontal_line": np.array( [ [255, 255, 255, 255, 255], [255, 255, 255, 255, 255], [0, 0, 0, 0, 0], [255, 255, 255, 255, 255], [255, 255, 255, 255, 255], ], np.uint8, ), "center_diagonal_line_long": create_diagonal_test_image(50), "center_circle_long": create_circle_at_origin(50, 15), } def load_incisor( incisor=Incisors.UPPER_OUTER_LEFT, extra_text="", blur=False, sobel=False ) -> Tuple[ActiveShapeModel, List[ImageShape]]: """Loads asm and imgshapes for sample incisor""" images = load_images(range(1, 15)) pipeline = [(Preprocessor.bilateral, {"times": 2})] blurred_images = Preprocessor.apply(pipeline, images) if blur: images = blurred_images sobel_images = apply_sobel(images) if sobel: images = sobel_images asms, imgshapes = Incisors.active_shape_models(images, [incisor]) asm: ActiveShapeModel = asms[incisor] imgshape: List[ImageShape] = imgshapes[incisor] return asm, imgshape
[ 37811, 8021, 9741, 20081, 329, 5254, 37811, 198, 11748, 555, 715, 395, 198, 6738, 19720, 1330, 309, 29291, 11, 7343, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 1...
2.272135
768
import numpy as np import time import re import os import operator import pickle as pickle import dateutil from urllib.request import urlopen from collections import namedtuple from pybasicbayes.util.text import progprint, progprint_xrange from pgmult.utils import mkdir from ctm import get_sparse_repr, split_test_train from pgmult.lda import StickbreakingDynamicTopicsLDA ############# # loading # ############# ############# # fitting # ############# Results = namedtuple( 'Results', ['loglikes', 'predictive_lls', 'samples', 'timestamps']) ############# # running # ############# if __name__ == '__main__': ## sotu # K, V = 25, 2500 # TODO put back K, V = 5, 100 alpha_theta = 1. train_frac, test_frac = 0.95, 0.5 timestamps, (data, words) = load_sotu_data(V) ## print setup print('K=%d, V=%d' % (K, V)) print('alpha_theta = %0.3f' % alpha_theta) print('train_frac = %0.3f, test_frac = %0.3f' % (train_frac, test_frac)) print() ## split train test train_data, test_data = split_test_train(data, train_frac=train_frac, test_frac=test_frac) ## fit sb_results = fit_sbdtm_gibbs(train_data, test_data, timestamps, K, 100, alpha_theta) all_results = { 'sb': sb_results, } with open('dtm_results.pkl','w') as outfile: pickle.dump(all_results, outfile, protocol=-1)
[ 198, 11748, 299, 32152, 355, 45941, 198, 11748, 640, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 10088, 198, 11748, 2298, 293, 355, 2298, 293, 198, 11748, 3128, 22602, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 198, 67...
2.49009
555
import logging from vortex.errors import VortexException
[ 11748, 18931, 198, 6738, 42726, 13, 48277, 1330, 49790, 16922, 628, 628 ]
5
12
# Generated by Django 3.1.3 on 2020-12-01 19:08 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 18, 319, 12131, 12, 1065, 12, 486, 678, 25, 2919, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#!/usr/bin/env python import os import sys # See "Using the Django test runner to test reusable applications": # https://docs.djangoproject.com/en/3.1/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=2) failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) # #!/usr/bin/env python # import os # import sys # import django # from django.conf import settings # from django.test.utils import get_runner # def run_tests(*test_args): # # Since out app has no Models, we need to involve another 'tests' app # # with at least a Model to make sure that migrations are run for test sqlite database # if not test_args: # test_args = ['tests', 'ajax_datatable', ] # os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # django.setup() # TestRunner = get_runner(settings) # test_runner = TestRunner() # failures = test_runner.run_tests(test_args) # sys.exit(bool(failures)) # if __name__ == '__main__': # run_tests(*sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 2, 4091, 366, 12814, 262, 37770, 1332, 17490, 284, 1332, 42339, 5479, 1298, 198, 2, 3740, 1378, 31628, 13, 28241, 648, 404, 305, 752, 13, 785...
2.6714
493
from collections import defaultdict import time import numpy as np import os from math import ceil class MinHeap: """ Implementation of Min Heap data structure """ def create_min_heap(self, arr): """ Converts a given array into a min heap :param arr: input array of numbers """ n = len(arr) # last n/2 elements will be leaf nodes (CBT property) hence already min heaps # loop from n/2 to 0 index and convert each index node into min heap for i in range(int(n / 2), -1, -1): self.min_heapify(i, arr, n) def min_heapify(self, indx, arr, size): """ Assuming sub trees are already min heaps, converts tree rooted at current indx into a min heap. :param indx: Index to check for min heap """ # Get index of left and right child of indx node left_child = indx * 2 + 1 right_child = indx * 2 + 2 smallest = indx # check what is the smallest value node in indx, left child and right child if left_child < size: if arr[left_child].get_cost() < arr[smallest].get_cost(): smallest = left_child if right_child < size: if arr[right_child].get_cost() < arr[smallest].get_cost(): smallest = right_child # if indx node is not the smallest value, swap with the smallest child # and recursively call min_heapify on the respective child swapped with if smallest != indx: arr[indx], arr[smallest] = arr[smallest], arr[indx] self.min_heapify(smallest, arr, size) def insert(self, value): """ Inserts an element in the min heap :param value: value to be inserted in the heap """ self.heap.append(value) self.heap_size += 1 indx = self.heap_size - 1 # Get parent index of the current node parent = int(ceil(indx / 2 - 1)) # Check if the parent value is smaller than the newly inserted value # if so, then replace the value with the parent value and check with the new parent while parent >= 0 and self.heap[indx].get_cost() < self.heap[parent].get_cost(): self.heap[indx], self.heap[parent] = self.heap[parent], self.heap[indx] indx = parent parent = int(ceil(indx / 2 - 1)) def delete(self, indx): """ Deletes the value on the specified index node :param indx: index whose node is to be removed :return: Value of the node deleted from the heap """ if self.heap_size == 0: print("Heap Underflow!!") return self.heap[-1], self.heap[indx] = self.heap[indx], self.heap[-1] self.heap_size -= 1 self.min_heapify(indx, self.heap, self.heap_size) return self.heap.pop() def extract_min(self): """ Extracts the minimum value from the heap :return: extracted min value """ return self.delete(0) class Board: """ Class to represent the n x n Board / Matrix Stores the parent node of a board i.e. the board from which the new board was derived Stores the row, col of the blank space (0) on the board Stores the boards children if they exist else None Stores the manhattan heuristic of the board and moves made so far """ def get_manhattan(self): """ Calculates the manhattan heuristic of the given board :return: the value of manhattan heuristic """ n = len(self.arr) global coordinates_sol coordinates_board = defaultdict(list) for i in range(0, n): for j in range(0, n): coordinates_board[self.arr[i][j]] = [i, j] dist = 0 for i in range(n**2 - 1): dist += (abs(coordinates_sol[i][0] - coordinates_board[i][0]) + abs(coordinates_sol[i][1] - coordinates_board[i][1])) return dist def get_cost(self): """ calculates the moves coved so far + manhattan heuristic :return: returns the expected cost """ return self.manhattan + self.moves def move_up(self): """ Function to move one tile up in the board :return: True if shifting is possible else False """ if self.space_row + 1 >= len(self.arr): return False self.arr[self.space_row][self.space_col] = self.arr[self.space_row + 1][self.space_col] self.arr[self.space_row + 1][self.space_col] = 0 self.space_row += 1 self.manhattan = self.get_manhattan() self.moves += 1 return True def move_down(self): """ Function to move one tile down in the board :return: True if shifting is possible else False """ if self.space_row - 1 < 0: return False self.arr[self.space_row][self.space_col] = self.arr[self.space_row - 1][self.space_col] self.arr[self.space_row - 1][self.space_col] = 0 self.space_row -= 1 self.manhattan = self.get_manhattan() self.moves += 1 return True def move_left(self): """ Function to move one tile left in the board :return: True if shifting is possible else False """ if self.space_col + 1 >= len(self.arr): return False self.arr[self.space_row][self.space_col] = self.arr[self.space_row][self.space_col + 1] self.arr[self.space_row][self.space_col + 1] = 0 self.space_col += 1 self.manhattan = self.get_manhattan() self.moves += 1 return True def move_right(self): """ Function to move one tile right in the board :return: True if shifting is possible else False """ if self.space_col - 1 < 0: return False self.arr[self.space_row][self.space_col] = self.arr[self.space_row][self.space_col - 1] self.arr[self.space_row][self.space_col - 1] = 0 self.space_col -= 1 self.manhattan = self.get_manhattan() self.moves += 1 return True def get_final_board(n): """ :param n: size of the board (n x n) :return: 2-D array of Final required board representation """ solution = [] k = 1 for i in range(n): solution.append([]) for j in range(n): solution[-1].append(k) k += 1 solution[n-1][n-1] = 0 return solution def solvable(board, n): """ :param board: board representation to check for solvability :param n: size of the board (n x n) :return: True if board is solvable puzzle else False """ arr = [] for i in range(n): for j in range(n): if board.arr[i][j] == 0: continue arr.append(board.arr[i][j]) m = n**2 - 1 inv_count = 0 for i in range(m): for j in range(i + 1, m): if arr[i] > arr[j]: inv_count += 1 if n % 2 != 0: if inv_count % 2 == 0: return True return False else: if (inv_count + board.space_row) % 2 != 0: return True return False def astar(board): """ Performs A* over the board :param board: initial board representation :param n: size of the board (n x n) :return: Final board object, [number of iterations of while loop, max size of queue, unique boards seen] """ iterations = 0 max_size = 0 global solution q = MinHeap() seen_boards = set() seen_boards.add(tuple(np.array(board.arr).flatten())) q.insert(board) # Run until priority queue is not empty while q.size() != 0: iterations += 1 max_size = max(max_size, q.size()) board = q.extract_min() # If board is same as the final require solution, we are done, return if board.arr == solution: return board, [iterations, max_size, len(seen_boards)] # Move tile up board up_board = Board(board.arr, board, board.space_row, board.space_col) if up_board.move_up(): if tuple(np.array(up_board.arr).flatten()) not in seen_boards: q.insert(up_board) seen_boards.add(tuple(np.array(up_board.arr).flatten())) board.up = up_board # Move tile down board down_board = Board(board.arr, board, board.space_row, board.space_col) if down_board.move_down(): if tuple(np.array(down_board.arr).flatten()) not in seen_boards: q.insert(down_board) seen_boards.add(tuple(np.array(down_board.arr).flatten())) board.down = down_board # Move tile left board left_board = Board(board.arr, board, board.space_row, board.space_col) if left_board.move_left(): if tuple(np.array(left_board.arr).flatten()) not in seen_boards: q.insert(left_board) seen_boards.add(tuple(np.array(left_board.arr).flatten())) board.left = left_board # Move tile right board right_board = Board(board.arr, board, board.space_row, board.space_col) if right_board.move_right(): if tuple(np.array(right_board.arr).flatten()) not in seen_boards: q.insert(right_board) seen_boards.add(tuple(np.array(right_board.arr).flatten())) board.right = right_board def print_board(board, n, file): """ Print the board values in the report :param board: initial board representation :param n: size of the board (n x n) :param file: File object where data will be written """ for i in range(n): for j in range(n): file.write("{} ".format(board.arr[i][j])) file.write("\n") def print_steps(board, n, file): """ Print the Steps required to solve the puzzle with boards :param board: initial board representation :param n: size of the board (n x n) :param file: File object where data will be written """ arr = [] while board is not None: arr.append(board) board = board.parent for i in range(len(arr)-1, 0, -1): if arr[i].up == arr[i - 1]: file.write("Up\n") elif arr[i].down == arr[i - 1]: file.write("Down\n") elif arr[i].left == arr[i - 1]: file.write("Left\n") else: file.write("Right\n") print_board(arr[i - 1], n, file) file.write("\n") # Starter code: n = int(input("Enter value of n for n x n problem: ")) print("Enter Initial Configuration as follows:") print("Example 4 x 4 box: ") print("5 6 7 8 \n1 2 3 4 \n9 0 11 12 \n13 14 15 10\n") # Take initial board representation print("Enter your {} x {} configuration: ".format(n, n)) initial_board = [] for i in range(n): initial_board.append(list(map(int, input().split(" ")))) if len(initial_board[-1]) != n: print("Wrong input!!") exit(0) # Input validation s_r = -1 s_c = -1 for i in range(n): for j in range(n): if not (1 <= initial_board[i][j] <= n**2 - 1): if initial_board[i][j] == 0: s_r = i s_c = j else: print("Wrong input!!") exit(0) solution = get_final_board(n) coordinates_sol = defaultdict(list) for i in range(0, n): for j in range(0, n): coordinates_sol[solution[i][j]] = [i, j] start_board = Board(initial_board, s_r=s_r, s_c=s_c) if not solvable(start_board, n): print("The given board is not solvable") exit(0) print("Solving...") start_time = time.perf_counter() final_board, stats = astar(start_board) end_time = time.perf_counter() with open(os.path.join(os.curdir, 'astar_report.txt'), 'w') as f: print("Time taken:", end_time - start_time) f.write("Time taken: {}\n".format(end_time - start_time)) print("Number of A* iterations:", stats[0]) f.write("Number of A* iterations: {}\n".format(stats[0])) print("Max size of A* Queue:", stats[1]) f.write("Max size of A* Queue: {}\n".format(stats[1])) print("Unique boards seen:", stats[2]) f.write("Unique boards seen: {}\n".format(stats[2])) f.write("\nSteps:\n") print_board(start_board, n, f) f.write("\n") print_steps(final_board, n, f)
[ 6738, 17268, 1330, 4277, 11600, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 10688, 1330, 2906, 346, 628, 198, 4871, 1855, 1544, 499, 25, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 46333, 286, ...
2.235389
5,595
"""test fibonacci alogrithms""" from src.math import class_memoization_fibonacci from src.math import explicit_fibonacci from src.math import function_memoization_fibonacci from src.math import iterative_fibonacci from src.math import recursive_fibonacci def test_fibonacci(): """test fibonacci algorithms""" test_cases = ( (0, 0), (1, 1), (7, 13), (10, 55), ) for args, expected in test_cases: assert class_memoization_fibonacci(args) == expected assert explicit_fibonacci(args) == expected assert function_memoization_fibonacci(args) == expected assert iterative_fibonacci(args) == expected assert recursive_fibonacci(args) == expected
[ 37811, 9288, 12900, 261, 44456, 435, 519, 81, 342, 907, 37811, 198, 6738, 12351, 13, 11018, 1330, 1398, 62, 11883, 78, 1634, 62, 69, 571, 261, 44456, 198, 6738, 12351, 13, 11018, 1330, 7952, 62, 69, 571, 261, 44456, 198, 6738, 12351, ...
2.513793
290
from keras.models import Sequential, Model from keras.layers import Input, Dense, Reshape, Flatten, Dropout,multiply from keras.layers.advanced_activations import LeakyReLU from keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D import numpy as np
[ 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 11, 9104, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 23412, 11, 360, 1072, 11, 1874, 71, 1758, 11, 1610, 41769, 11, 14258, 448, 11, 16680, 541, 306, 198, 6738, 41927, 292, 13, 75, 6962...
3.186047
86
#!/usr/bin/env python3 # NanoSciTracker - 2020 # Author: Luis G. Leon Vega <luis@luisleon.me> # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # # This project was sponsored by CNR-IOM # Master in High-Performance Computing - SISSA import argparse import cv2 as cv import sys import time sys.path.append("../src") sys.path.append("../src/GlobalTracker") sys.path.append("../src/LocalTracker") sys.path.append("../src/Matcher") sys.path.append("../src/Utils") import GlobalTracker.world as World import GlobalTracker.utils as Utils import mcherry as Dataset import Utils.json_settings as Settings from Utils.json_tracer import Tracer if __name__ == "__main__": # Handle the arguments parser = argparse.ArgumentParser(description="Performs the local tracking") parser.add_argument( "--dataset", type=str, help="Choose the dataset", default="../data/mcherry/mcherry_single.json", ) parser.add_argument( "--overlapping", type=int, help="Overlapping of the scene in pixels", default=10 ) parser.add_argument("--frames", type=int, help="Number of frames", default=450) parser.add_argument( "--delay_player", type=float, help="Timer delay in seconds", default=0.01 ) parser.add_argument( "--sampling_rate_detection", type=float, help="Decimation of the detection", default=3, ) parser.add_argument( "--record", help="Enable video recording", dest="record", action="store_true" ) parser.add_argument( "--framerate", type=float, help="In case of recording, the framerate", default=25, ) parser.add_argument( "--no-display", help="Display analysis", dest="display", action="store_false" ) parser.set_defaults(display=True) parser.set_defaults(record=False) args = parser.parse_args() main(args)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 33504, 50, 979, 35694, 532, 12131, 198, 2, 6434, 25, 20894, 402, 13, 10592, 30310, 1279, 2290, 271, 31, 2290, 20919, 261, 13, 1326, 29, 198, 2, 198, 2, 49962, 284, 262, 2484...
2.905391
909
#!/usr/bin/env python3 import utils utils.check_version((3,7)) utils.clear() print('Hello, my name is Ethan Yee, I am a sophomore Digital & Interactive Media major from Chicago, IL.') print('My favorite video game is Super Smash Bros Ultimate for the Nintendo switch. The task of the game seems so simple, knock your friends off the platform before they knock you off. Seems fiarly simple, yet there is so much depth to it that allows a really skilled player to showcase their talents.') print('Prior to this class, I have absolutely no coding or game design experience. My biggest concern is that the learning curve may be too steep for me to keep up with all of the game design majors') print('I have been extremely excited to finish furnishing my damn apartment that I share with 4 roomates. It has already been 3 weeks and we still eat on the floor.') print('11985119 is my Stockoverflow User Number') print('https://github.com/Ethan-source is the URL to my GitHub profile')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 3384, 4487, 198, 198, 26791, 13, 9122, 62, 9641, 19510, 18, 11, 22, 4008, 198, 26791, 13, 20063, 3419, 198, 198, 4798, 10786, 15496, 11, 616, 1438, 318, 28926, 575, 1...
4.012195
246
import pathlib from typing import List, Optional from clang import cindex # helper {{{ DEFAULT_CLANG_DLL = pathlib.Path("C:/Program Files/LLVM/bin/libclang.dll") SET_DLL = False def get_tu(path: pathlib.Path, include_path_list: List[pathlib.Path] = None, use_macro: bool = False, dll: Optional[pathlib.Path] = None) -> cindex.TranslationUnit: ''' parse cpp source ''' global SET_DLL if not path.exists(): raise FileNotFoundError(str(path)) if not dll and DEFAULT_CLANG_DLL.exists(): dll = DEFAULT_CLANG_DLL if not SET_DLL and dll: cindex.Config.set_library_file(str(dll)) SET_DLL = True index = cindex.Index.create() kw = {} if use_macro: kw['options'] = cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD cpp_args = ['-x', 'c++', '-DUNICODE=1', '-DNOMINMAX=1'] if include_path_list is not None: for i in include_path_list: value = f'-I{str(i)}' if value not in cpp_args: cpp_args.append(value) return index.parse(str(path), cpp_args, **kw) # def get_token(cursor: cindex.Cursor) -> int: # if cursor.kind != cindex.CursorKind.INTEGER_LITERAL: # raise Exception('not int') # tokens = [x.spelling for x in cursor.get_tokens()] # if len(tokens) != 1: # raise Exception('not 1') # return int(tokens[0]) # }}}
[ 11748, 3108, 8019, 201, 198, 6738, 19720, 1330, 7343, 11, 32233, 201, 198, 6738, 537, 648, 1330, 269, 9630, 201, 198, 201, 198, 2, 31904, 22935, 90, 201, 198, 7206, 38865, 62, 5097, 15567, 62, 35, 3069, 796, 3108, 8019, 13, 15235, 7...
2.042818
724
import pytest from aioinject import providers from aioinject.containers import Container from aioinject.context import InjectionContext @pytest.fixture @pytest.fixture
[ 11748, 12972, 9288, 198, 198, 6738, 257, 952, 259, 752, 1330, 9549, 198, 6738, 257, 952, 259, 752, 13, 3642, 50221, 1330, 43101, 198, 6738, 257, 952, 259, 752, 13, 22866, 1330, 554, 29192, 21947, 628, 628, 198, 198, 31, 9078, 9288, ...
3.172414
58
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://epayments-api.developer-ingenico.com/s2sapi/v1/ # from ingenico.connect.sdk.domain.definitions.abstract_payment_method_specific_input import AbstractPaymentMethodSpecificInput from ingenico.connect.sdk.domain.hostedcheckout.definitions.mobile_payment_product302_specific_input_hosted_checkout import MobilePaymentProduct302SpecificInputHostedCheckout from ingenico.connect.sdk.domain.hostedcheckout.definitions.mobile_payment_product320_specific_input_hosted_checkout import MobilePaymentProduct320SpecificInputHostedCheckout
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 1398, 373, 8295, 12, 27568, 422, 262, 7824, 10288, 1043, 379, 198, 2, 3740, 1378, 538, 323, 902, 12, 15042, 13, 16244, 263, 12, 36795, 3713, 13, 785,...
3.376344
186
nome = input("Informe o seu nome:") print(quantosAs(nome))
[ 198, 198, 77, 462, 796, 5128, 7203, 818, 687, 68, 267, 384, 84, 299, 462, 25, 4943, 198, 4798, 7, 40972, 418, 1722, 7, 77, 462, 4008 ]
2.222222
27
import gym from rlberry.seeding import Seeder class Discrete(gym.spaces.Discrete): """ Class that represents discrete spaces. Inherited from gym.spaces.Discrete for compatibility with gym. rlberry wraps gym.spaces to make sure the seeding mechanism is unified in the library (rlberry.seeding) Attributes ---------- rng : numpy.random._generator.Generator random number generator provided by rlberry.seeding Methods ------- reseed() get new random number generator """ def __init__(self, n): """ Parameters ---------- n : int number of elements in the space """ assert n >= 0, "The number of elements in Discrete must be >= 0" gym.spaces.Discrete.__init__(self, n) self.seeder = Seeder() @property def reseed(self, seed_seq=None): """ Get new random number generator. Parameters ---------- seed_seq : np.random.SeedSequence, rlberry.seeding.Seeder or int, default : None Seed sequence from which to spawn the random number generator. If None, generate random seed. If int, use as entropy for SeedSequence. If seeder, use seeder.seed_seq """ self.seeder.reseed(seed_seq)
[ 11748, 11550, 198, 6738, 374, 75, 8396, 13, 325, 8228, 1330, 1001, 5702, 628, 198, 4871, 8444, 8374, 7, 1360, 76, 13, 2777, 2114, 13, 15642, 8374, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 5016, 326, 6870, 28810, 9029, 13...
2.455882
544
# 手动纯算法调用 import binascii from unicorn import * from unicorn.arm_const import * from UnicornTraceDebugger import udbg a1 = b'123' mu = Uc(UC_ARCH_ARM, UC_MODE_THUMB) #image image_base = 0x0 image_size = 0x10000 * 8 mu.mem_map(image_base, image_size) binary = open('jnilibs/libnative-lib.so','rb').read() mu.mem_write(image_base, binary) ### 非常简陋的加载方法 # stack stack_base = 0xa0000 stack_size = 0x10000 * 3 stack_top = stack_base - stack_size mu.mem_map(stack_base, stack_size) mu.reg_write(UC_ARM_REG_SP, stack_top) # data segment data_base = 0xf0000 data_size = 0x10000 * 3 mu.mem_map(data_base, data_size) mu.mem_write(data_base, a1) mu.reg_write(UC_ARM_REG_R0, data_base) #fix got mu.mem_write(0x1EDB0, b'\xD9\x98\x00\x00') #set hook #mu.hook_add(UC_HOOK_CODE, hook_code, 0) #mu.hook_add(UC_HOOK_MEM_UNMAPPED, hook_code, 0) target = image_base + 0x9B68 target_end = image_base + 0x9C2C #start try: dbg = udbg.UnicornDebugger(mu) mu.emu_start(target + 1, target_end) r2 = mu.reg_read(UC_ARM_REG_R2) result = mu.mem_read(r2, 16) print(binascii.b2a_hex(result)) except UcError as e: list_tracks = dbg.get_tracks() for addr in list_tracks: print(hex(addr)) print(e)
[ 2, 10545, 231, 233, 27950, 101, 163, 118, 107, 163, 106, 245, 37345, 243, 164, 108, 225, 18796, 101, 198, 11748, 9874, 292, 979, 72, 198, 198, 6738, 44986, 1330, 1635, 198, 6738, 44986, 13, 1670, 62, 9979, 1330, 1635, 198, 198, 6738...
2.061121
589
from django.core import serializers
[ 6738, 42625, 14208, 13, 7295, 1330, 11389, 11341, 628, 628, 628 ]
3.727273
11
""" tests for celery tasks """ from unittest.mock import patch, Mock import requests import tests.mocks as mocks from tasks import scheduler @patch('tasks.requests.post') @patch('service.resources.applications.requests.get') def test_scheduler(mock_query_get, mock_bluebeam_post, mock_env_access_key): # pylint: disable=unused-argument """ Test the scheduler chron process """ print("begin test_scheduler") mock_query_get.return_value.json.return_value = [mocks.SINGLE_ROW, mocks.SINGLE_ROW] scheduler.s().apply() assert mock_bluebeam_post.call_count == 2 @patch('tasks.requests.post') @patch('service.resources.applications.requests.get') def test_scheduler_bluebeam_error(mock_query_get, mock_bluebeam_post, mock_env_access_key): # pylint: disable=unused-argument """ Test the scheduler chron process """ print("begin test_scheduler_bluebeam_error") mock_query_get.return_value.json.return_value = [mocks.SINGLE_ROW, mocks.SINGLE_ROW] mock_bluebeam_post.return_value.status_code = 500 mock_response = Mock(status_code=500, text='Danger, Will Robinson!') mock_bluebeam_post.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError( response=mock_response ) scheduler.s().apply() assert mock_bluebeam_post.call_count == 2 assert mock_query_get.call_count == 1 @patch('tasks.requests.post') @patch('service.resources.applications.requests.get') def test_scheduler_query_error(mock_query_get, mock_bluebeam_post, mock_env_access_key): # pylint: disable=unused-argument """ Test the scheduler chron process """ print("begin test_scheduler_query_error") mock_query_get.side_effect = Exception("Oops!") scheduler.s().apply() assert mock_bluebeam_post.call_count == 0 assert mock_query_get.call_count == 1
[ 37811, 5254, 329, 18725, 1924, 8861, 37227, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 11, 44123, 198, 11748, 7007, 198, 11748, 5254, 13, 76, 3320, 355, 285, 3320, 198, 6738, 8861, 1330, 6038, 18173, 198, 198, 31, 17147, 10786...
2.727273
671
from django.conf import settings from api.staticdata.control_list_entries.models import ControlListEntry
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 40391, 13, 12708, 7890, 13, 13716, 62, 4868, 62, 298, 1678, 13, 27530, 1330, 6779, 8053, 30150, 628 ]
3.925926
27
from ...utils import db from .response.response_schema import (build_variant_response, build_biosample_or_individual_response) from . import BiosamplesParameters, GVariantsParameters, IndividualsParameters, generic_handler biosamples_proxy = BiosamplesParameters() gvariants_proxy = GVariantsParameters() individuals_proxy = IndividualsParameters() individuals_by_biosample = generic_handler('individuals', individuals_proxy, db.fetch_individuals_by_biosample, build_biosample_or_individual_response) biosamples_by_biosample = generic_handler('biosamples' , biosamples_proxy , db.fetch_biosamples_by_biosample , build_biosample_or_individual_response) gvariants_by_biosample = generic_handler('gvariants' , gvariants_proxy , db.fetch_variants_by_biosample , build_variant_response) individuals_by_variant = generic_handler('individuals', individuals_proxy, db.fetch_individuals_by_variant, build_biosample_or_individual_response) biosamples_by_variant = generic_handler('biosamples' , biosamples_proxy , db.fetch_biosamples_by_variant , build_biosample_or_individual_response) gvariants_by_variant = generic_handler('gvariants' , gvariants_proxy , db.fetch_variants_by_variant , build_variant_response) individuals_by_individual = generic_handler('individuals', individuals_proxy, db.fetch_individuals_by_individual, build_biosample_or_individual_response) biosamples_by_individual = generic_handler('biosamples' , biosamples_proxy , db.fetch_biosamples_by_individual , build_biosample_or_individual_response) gvariants_by_individual = generic_handler('gvariants' , gvariants_proxy , db.fetch_variants_by_individual , build_variant_response)
[ 6738, 2644, 26791, 1330, 20613, 198, 6738, 764, 26209, 13, 26209, 62, 15952, 2611, 1330, 357, 11249, 62, 25641, 415, 62, 26209, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
3.008865
564
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for mobilenet_edgetpu model.""" import os import tensorflow as tf from official.legacy.image_classification import preprocessing from official.projects.edgetpu.vision.modeling import common_modules from official.projects.edgetpu.vision.modeling import mobilenet_edgetpu_v1_model from official.projects.edgetpu.vision.modeling import mobilenet_edgetpu_v1_model_blocks # TODO(b/151324383): Enable once training is supported for mobilenet-edgetpu EXAMPLE_IMAGE = ('third_party/tensorflow_models/official/vision/' 'image_classification/testdata/panda.jpg') CKPTS = 'gs://**/efficientnets' def _copy_recursively(src: str, dst: str) -> None: """Recursively copy directory.""" for src_dir, _, src_files in tf.io.gfile.walk(src): dst_dir = os.path.join(dst, os.path.relpath(src_dir, src)) if not tf.io.gfile.exists(dst_dir): tf.io.gfile.makedirs(dst_dir) for src_file in src_files: tf.io.gfile.copy( os.path.join(src_dir, src_file), os.path.join(dst_dir, src_file), overwrite=True) if __name__ == '__main__': tf.test.main()
[ 2, 15069, 33448, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846,...
2.827586
609
from flask import Flask, request import json from flask_cors import CORS from app import utils, job from . import app, redis_store import threading CORS(app) # Activate the siege weapon... # No turning back now. @app.route('/api/enable', methods=['POST']) # Two factor @app.route('/api/getCode') @app.route('/api/verifyCode', methods=['POST']) # Get a token to use. You get one by sending the priming code as a post # request @app.route('/api/getToken', methods=['POST']) @app.route('/api/')
[ 6738, 42903, 1330, 46947, 11, 2581, 198, 11748, 33918, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 198, 198, 6738, 598, 1330, 3384, 4487, 11, 1693, 198, 6738, 764, 1330, 598, 11, 2266, 271, 62, 8095, 198, 198, 11748, 4704, 278, ...
2.874286
175
"""Functions for learning the structure of a bayesian network from an input dataset""" import numpy as np from collections import namedtuple from itertools import combinations from sklearn.metrics import mutual_info_score from ...factors import Factor from ...factors import CPT def greedy_network_learning(df, degree_network=2): """Learns the network using a greedy approach based on the mutual information between variables Args: df (pandas.Dataframe): dataset that contains columns with names corresponding to the variables in this BN's scope. degree_network (int): maximum number of parents each node can have. """ # init network network = [] nodes = set(df.columns) nodes_selected = set() # define structure of NodeParentPair candidates NodeParentPair = namedtuple('NodeParentPair', ['node', 'parents']) # select random node as starting point root = np.random.choice(tuple(nodes)) network.append(NodeParentPair(node=root, parents=None)) nodes_selected.add(root) # select each remaining node iteratively that have the highest # mutual information with nodes that are already in the network for i in range(len(nodes_selected), len(nodes)): nodes_remaining = nodes - nodes_selected n_parents = min(degree_network, len(nodes_selected)) node_parent_pairs = [ NodeParentPair(n, tuple(p)) for n in nodes_remaining for p in combinations(nodes_selected, n_parents) ] # compute the mutual information for each note_parent pair candidate scores = _compute_scores(df, node_parent_pairs) # add best scoring candidate to the network sampled_pair = node_parent_pairs[np.argmax(scores)] nodes_selected.add(sampled_pair.node) network.append(sampled_pair) return network def compute_cpts_network(df, network): """Computes the conditional probability distribution of each node in the Bayesian network Args: df (pandas.Dataframe): dataset that contains columns with names corresponding to the variables in this BN's scope. network (list): list of ordered NodeParentPairs """ P = dict() for idx, pair in enumerate(network): if pair.parents is None: cpt = CPT.from_factor(Factor.from_data(df, cols=[pair.node])).normalize() # cpt = CPT(marginal_distribution, conditioned=[pair.node]).normalize() else: # todo: there should be a from_data at CPT cpt = CPT.from_factor(Factor.from_data(df, cols=[*pair.parents, pair.node])).normalize() # cpt = CPT(joint_distribution, conditioned=[pair.node]).normalize() # add conditional distribution to collection P[pair.node] = cpt return P def _compute_scores(df, node_parent_pairs): """Computes mutual information for all NodeParentPair candidates""" scores = np.empty(len(node_parent_pairs)) for idx, pair in enumerate(node_parent_pairs): scores[idx] = _compute_mutual_information(df, pair) return scores
[ 37811, 24629, 2733, 329, 4673, 262, 4645, 286, 257, 15489, 35610, 3127, 422, 281, 5128, 27039, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 340, 861, 10141, 1330, 17790, 198, 6738, ...
2.748466
1,141
from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from django.db import DataError from django.http import JsonResponse, HttpResponse from django.utils.datastructures import MultiValueDictKeyError from django.views.decorators.csrf import csrf_exempt from clinicmodels.models import Patient from patient.forms import PatientForm from django.contrib.auth.models import User from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import permission_classes, api_view """ Handles all operations regarding the retrieval, update of patient models. """ @api_view(['GET']) @api_view(['GET']) # @permission_classes((IsAuthenticated,)) def get_patient_by_name(request): """ GET patient by name :param request: GET request with a name parameter :return: JSON Response with an array of users matching name """ try: # user = User.objects.get(username=request.user) # print(user.email) if 'name' not in request.GET: return JsonResponse({"message": "GET: parameter 'name' not found"}, status=400) patient_name = request.GET['name'] patient = Patient.objects.filter(name__contains=patient_name) if patient.count() == 0: return JsonResponse({"message": "Patient matching query does not exist"}, status=404) response = serializers.serialize("json", patient) return HttpResponse(response, content_type='application/json') except ObjectDoesNotExist as e: return JsonResponse({"message": str(e)}, status=404) except ValueError as e: return JsonResponse({"message": str(e)}, status=400) @api_view(['GET']) def get_patient_by_id(request): ''' GET patient identified by id :param request: GET request with an id parameter :return: JSON Response with an array of users mathing id ''' try: if 'id' not in request.GET: return JsonResponse({"message": "GET: parameter 'id' not found"}, status=400) patient_id = request.GET['id'] patient = Patient.objects.filter(id=patient_id) response = serializers.serialize("json", patient) return HttpResponse(response, content_type='application/json') except ObjectDoesNotExist as e: return JsonResponse({"message": str(e)}, status=404) except ValueError as e: return JsonResponse({"message": str(e)}, status=400) @api_view(['GET']) def get_patient_image_by_id(request): ''' GET image of patient by id :param request: GET with parameter id of patient you want the image of :return: FileResponse if image is found, 404 if not ''' try: if 'id' not in request.GET: return JsonResponse({"message": "GET: parameter 'id' not found"}, status=400) patient_id = request.GET['id'] patient = Patient.objects.get(pk=patient_id) image = patient.picture if "jpeg" in image.name.lower() or "jpg" in image.name.lower(): return HttpResponse(image.file.read(), content_type="image/jpeg") elif "png" in image.name.lower(): return HttpResponse(image.file.read(), content_type="image/png") else: return JsonResponse({"message": "Patient image is in the wrong format"}, status=400) except ObjectDoesNotExist as e: return JsonResponse({"message": str(e)}, status=404) except ValueError as e: return JsonResponse({"message": str(e)}, status=400) @api_view(['POST']) @csrf_exempt def create_new_patient(request): ''' POST request with multipart form to create a new patient :param request: POST request with the required parameters. Date parameters are accepted in the format 1995-03-30. :return: Http Response with corresponding status code ''' try: form = PatientForm(request.POST, request.FILES) if form.is_valid(): patient = form.save(commit=False) patient.save() response = serializers.serialize("json", [patient, ]) return HttpResponse(response, content_type="application/json") else: return JsonResponse(form.errors, status=400) except DataError as e: return JsonResponse({"message": str(e)}, status=400) @api_view(['POST']) @csrf_exempt def update_patient(request): ''' Update patient data based on the parameters :param request: POST with data :return: JSON Response with new data, or error ''' if 'id' not in request.POST: return JsonResponse({"message": "POST: parameter 'id' not found"}, status=400) patient_id = request.POST['id'] try: patient = Patient.objects.get(pk=patient_id) if 'village_prefix' in request.POST: patient.village_prefix = request.POST['village_prefix'] if 'name' in request.POST: patient.name = request.POST['name'] if 'contact_no' in request.POST: patient.contact_no = request.POST['contact_no'] if 'gender' in request.POST: patient.gender = request.POST['gender'] if 'travelling_time_to_village' in request.POST: patient.travelling_time_to_village = request.POST['travelling_time_to_village'] if 'date_of_birth' in request.POST['date_of_birth']: patient.date_of_birth = request.POST['date_of_birth'] if 'drug_allergy' in request.POST: patient.drug_allergy = request.POST['drug_allergy'] if 'parent' in request.POST: patient.parent = request.POST['parent'] if 'face_encodings' in request.POST: patient.face_encodings = request.POST['face_encodings'] if 'picture' in request.FILES: patient.picture = request.FILES['picture'] patient.save() response = serializers.serialize("json", [patient, ]) return HttpResponse(response, content_type="application/json") except ObjectDoesNotExist as e: return JsonResponse({"message": str(e)}, status=404) except DataError as e: return JsonResponse({"message": str(e)}, status=400)
[ 6738, 42625, 14208, 13, 7295, 1330, 11389, 11341, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 9945, 1330, 6060, 12331, 198, 6738, 42625, 14208, 13, 4023, 1330, 449, ...
2.615713
2,342
# -*- coding: utf-8 -*- # pylint: disable-msg= E1002, E1101 """ Created on Wed Nov 21 09:04:17 2012 This file contains the definition of a set of very simple abstraction patterns in order to perform rhythm interpretation on an ECG signal. @author: T. Teijeiro """ import kardioml.segmentation.teijeiro.knowledge.observables as o from kardioml.segmentation.teijeiro.knowledge.constants import ( PW_DURATION, ST_INTERVAL, N_PR_INTERVAL, N_QT_INTERVAL, ASYSTOLE_RR, PQ_INTERVAL, QRS_DUR, ) from kardioml.segmentation.teijeiro.model import Interval as Iv from kardioml.segmentation.teijeiro.model.automata import ( PatternAutomata, ABSTRACTED, ENVIRONMENT, BASIC_TCONST, ) from kardioml.segmentation.teijeiro.utils.units_helper import msec2samples as ms2sp import copy def _rstart_tconst(pattern, qrs): """ Temporal constraints for the Rhythm Start abstraction pattern. """ BASIC_TCONST(pattern, qrs) pattern.last_tnet.set_equal(qrs.time, pattern.hypothesis.time) def _p_qrs_tconst(pattern, pwave): """ Temporal constraints of the P Wave wrt the corresponding QRS complex """ BASIC_TCONST(pattern, pwave) obseq = pattern.obs_seq idx = pattern.get_step(pwave) if idx == 0 or not isinstance(obseq[idx - 1], o.QRS): return qrs = obseq[idx - 1] tnet = pattern.last_tnet tnet.add_constraint(pwave.start, pwave.end, PW_DURATION) # PR interval tnet.add_constraint(pwave.start, qrs.start, N_PR_INTERVAL) tnet.set_before(pwave.end, qrs.start) def _t_qrs_tconst(pattern, twave): """ Temporal constraints of the T waves with the corresponding QRS complex """ BASIC_TCONST(pattern, twave) obseq = pattern.obs_seq idx = pattern.get_step(twave) # We find the qrs observation precedent to this T wave. try: qrs = next(obseq[i] for i in range(idx - 1, -1, -1) if isinstance(obseq[i], o.QRS)) tnet = pattern.last_tnet if idx > 0 and isinstance(obseq[idx - 1], o.PWave): pwave = obseq[idx - 1] tnet.add_constraint(pwave.end, twave.start, Iv(ST_INTERVAL.start, PQ_INTERVAL.end + QRS_DUR.end)) # ST interval tnet.add_constraint(qrs.end, twave.start, ST_INTERVAL) # QT duration tnet.add_constraint(qrs.start, twave.end, N_QT_INTERVAL) except StopIteration: pass def _prev_rhythm_tconst(pattern, rhythm): """Temporal constraints of a cardiac rhythm with the precedent one.""" BASIC_TCONST(pattern, rhythm) pattern.last_tnet.set_equal(pattern.hypothesis.start, rhythm.end) def _asyst_prev_rhythm_tconst(pattern, rhythm): """Temporal constraints of an asystole with the precedent rhythm.""" BASIC_TCONST(pattern, rhythm) tnet = pattern.last_tnet tnet.set_equal(pattern.hypothesis.start, rhythm.end) tnet.add_constraint(pattern.hypothesis.start, pattern.hypothesis.end, ASYSTOLE_RR) def _qrs1_tconst(pattern, qrs): """Temporal constraints of the first QRS in the asystole.""" BASIC_TCONST(pattern, qrs) pattern.last_tnet.set_equal(pattern.hypothesis.start, qrs.time) pattern.last_tnet.set_before(qrs.end, pattern.hypothesis.end) def _qrs2_tconst(pattern, qrs): """Temporal constraints of the delayed QRS in the asystole.""" BASIC_TCONST(pattern, qrs) pattern.last_tnet.set_equal(qrs.time, pattern.hypothesis.end) if len(pattern.evidence[o.QRS]) > 1: prev = pattern.evidence[o.QRS][0] pattern.last_tnet.add_constraint(prev.time, qrs.time, ASYSTOLE_RR) def _rhythmstart_gconst(pattern, _): """General constraints of the rhythm start pattern.""" # We assume an starting mean rhythm of 75ppm, but the range allows from 65 # to 85bpm pattern.hypothesis.meas = o.CycleMeasurements((ms2sp(800), ms2sp(200)), (0, 0), (0, 0)) def _asystole_gconst(pattern, _): """General constraints of the asystole pattern.""" # The rhythm information is copied from the precedent rhythm. if pattern.evidence[o.Cardiac_Rhythm]: rhythm = pattern.evidence[o.Cardiac_Rhythm][0] pattern.hypothesis.meas = copy.copy(rhythm.meas) RHYTHMSTART_PATTERN = PatternAutomata() RHYTHMSTART_PATTERN.name = "Rhythm Start" RHYTHMSTART_PATTERN.Hypothesis = o.RhythmStart RHYTHMSTART_PATTERN.add_transition(0, 1, o.QRS, ABSTRACTED, _rstart_tconst, _rhythmstart_gconst) RHYTHMSTART_PATTERN.add_transition(1, 2, o.PWave, ABSTRACTED, _p_qrs_tconst) RHYTHMSTART_PATTERN.add_transition(2, 3, o.TWave, ABSTRACTED, _t_qrs_tconst) RHYTHMSTART_PATTERN.add_transition(1, 3, o.TWave, ABSTRACTED, _t_qrs_tconst) RHYTHMSTART_PATTERN.add_transition(1, 3) RHYTHMSTART_PATTERN.final_states.add(3) RHYTHMSTART_PATTERN.abstractions[o.QRS] = (RHYTHMSTART_PATTERN.transitions[0],) RHYTHMSTART_PATTERN.freeze() ASYSTOLE_PATTERN = PatternAutomata() ASYSTOLE_PATTERN.name = "Asystole" ASYSTOLE_PATTERN.Hypothesis = o.Asystole ASYSTOLE_PATTERN.add_transition(0, 1, o.Cardiac_Rhythm, ENVIRONMENT, _asyst_prev_rhythm_tconst) ASYSTOLE_PATTERN.add_transition(1, 2, o.QRS, ENVIRONMENT, _qrs1_tconst) ASYSTOLE_PATTERN.add_transition(2, 3, o.QRS, ABSTRACTED, _qrs2_tconst, _asystole_gconst) ASYSTOLE_PATTERN.add_transition(3, 4, o.PWave, ABSTRACTED, _p_qrs_tconst) ASYSTOLE_PATTERN.add_transition(4, 5, o.TWave, ABSTRACTED, _t_qrs_tconst) ASYSTOLE_PATTERN.add_transition(3, 5, o.TWave, ABSTRACTED, _t_qrs_tconst) ASYSTOLE_PATTERN.add_transition(3, 5) ASYSTOLE_PATTERN.final_states.add(5) ASYSTOLE_PATTERN.abstractions[o.QRS] = (ASYSTOLE_PATTERN.transitions[2],) ASYSTOLE_PATTERN.freeze() if __name__ == "__main__": pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 279, 2645, 600, 25, 15560, 12, 19662, 28, 412, 3064, 17, 11, 412, 1157, 486, 198, 37811, 198, 41972, 319, 3300, 5267, 2310, 7769, 25, 3023, 25, 1558, 2321, 198, 1...
2.304758
2,438
import unittest import os from ...BaseTestCase import BaseTestCase from centipede.Task import Task from centipede.Crawler.Fs import FsPath from centipede.Task.Fs.Checksum import ChecksumMatchError from centipede.Task.Image import UpdateImageMetadata class UpdateImageMetadataTest(BaseTestCase): """Test UpdateImageMetadata task.""" __sourcePath = os.path.join(BaseTestCase.dataDirectory(), "test.exr") __targetPath = os.path.join(BaseTestCase.dataDirectory(), "testToDelete.exr") def testUpdateImageMetadata(self): """ Test that the UpdateImageMetadata task works properly. """ crawler = FsPath.createFromPath(self.__sourcePath) updateTask = Task.create('updateImageMetadata') updateTask.add(crawler, self.__targetPath) result = updateTask.output() self.assertEqual(len(result), 1) crawler = result[0] import OpenImageIO as oiio inputSpec = oiio.ImageInput.open(self.__targetPath).spec() self.assertEqual(inputSpec.get_string_attribute("centipede:sourceFile"), self.__sourcePath) self.assertEqual(inputSpec.get_string_attribute("centipede:centipedeUser"), os.environ['USERNAME']) checkTask = Task.create('checksum') checkTask.add(crawler, self.__sourcePath) self.assertRaises(ChecksumMatchError, checkTask.output) customMetadata = {"testInt": 0, "testStr": "True"} UpdateImageMetadata.updateDefaultMetadata(inputSpec, crawler, customMetadata) self.assertEqual(inputSpec.get_int_attribute("centipede:testInt"), 0) self.assertEqual(inputSpec.get_string_attribute("centipede:testStr"), "True") @classmethod def tearDownClass(cls): """ Remove the file that was created. """ os.remove(cls.__targetPath) if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 6738, 2644, 14881, 14402, 20448, 1330, 7308, 14402, 20448, 198, 6738, 1247, 541, 18654, 13, 25714, 1330, 15941, 198, 6738, 1247, 541, 18654, 13, 34, 39464, 13, 42388, 1330, 376, 82, 15235, 1...
2.599444
719
from . import html5 from .examples import examples from lark import Lark from lark.tree import Tree
[ 6738, 764, 1330, 27711, 20, 198, 6738, 764, 1069, 12629, 1330, 6096, 198, 198, 6738, 300, 668, 1330, 406, 668, 198, 6738, 300, 668, 13, 21048, 1330, 12200, 628 ]
3.517241
29
#Turtle Race Game import turtle import random dice = [1,2,3,4,5,6] turtle.title("Turtle Race") turtle.setup(width=800, height=600) #Setup turtles playerone = turtle.Turtle() playerone.color('blue') playerone.shape('turtle') playerone.penup() playerone.goto(-200,100) #setup second turtle playertwo = playerone.clone() playertwo.color('red') playertwo.penup() playertwo.goto(-200,-100) #turtles homes #turtle one playerone.goto(300,60) playerone.down() playerone.circle(40) playerone.up() playerone.goto(-200,100) #turtle two playertwo.goto(300,-140) playertwo.down() playertwo.circle(40) playertwo.up() playertwo.goto(-200,-100) input('Pause - Get ready to RACE! - press Enter to start') #Start of the game for i in range (20): if playerone.pos() > (300,100): print ('Player One Wins') break elif playertwo.pos() >=(300,100): print ('Player two wins') break else: input('Player One press ENTER to roll the dice') outcome = random.choice(dice) playerone.fd(20*outcome) input('Player two press ENTER to roll the dice') outcome = random.choice(dice) playertwo.fd(20*outcome) print ('Game Over')
[ 2, 51, 17964, 12588, 3776, 201, 198, 201, 198, 11748, 28699, 201, 198, 11748, 4738, 201, 198, 201, 198, 67, 501, 796, 685, 16, 11, 17, 11, 18, 11, 19, 11, 20, 11, 21, 60, 201, 198, 201, 198, 83, 17964, 13, 7839, 7203, 51, 1796...
2.255357
560
from tqdm import tqdm import tensorflow as tf import numpy as np import cv2 import glob import gc import rasterio import pathlib import pandas as pd from rasterio.windows import Window from tensorflow.keras.layers import * from tensorflow.keras.applications import * from tensorflow.keras.callbacks import * from tensorflow.keras.metrics import * from tensorflow.keras.optimizers import Adam from patho.model.model_keras import build_model,dice_coeff,bce_dice_loss,tversky_loss,focal_tversky_loss from patho.utils.tfrecord import get_dataset, read_dataset from patho.utils.utils import rle_encode_less_memory, make_grid from patho.cfg.config import path_cfg,img_proc_cfg if __name__ == '__main__': tileProcCfg = img_proc_cfg() path_cfg = path_cfg() subm = inference(path_cfg.RESULTS_DIR + '/hubmap-model-1.h5', path_cfg.DATA_DIR) submission = pd.DataFrame.from_dict(subm, orient='index') submission.to_csv(path_cfg.RESULTS_DIR + '/submission.csv', index=False) print(submission.head())
[ 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 15095, 198, 11748, 308, 66, 198, 11748, 374, 1603, 952, 198, 11748, 3108, ...
2.752717
368
import pygame from units.Unit import Unit
[ 11748, 12972, 6057, 198, 198, 6738, 4991, 13, 26453, 1330, 11801, 628 ]
3.666667
12
from overrides import overrides from allennlp.common.util import JsonDict from allennlp.data import DatasetReader, Instance, Token from allennlp.models import Model from allennlp.predictors.predictor import Predictor from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter @Predictor.register('cvt-tagger') class CvtTaggerPredictor(Predictor): """ Predictor for the :class:`nlp_uncertainty_ssl.models.cvt_tagger.CvtTagger` model. This predictor is very much based on the :class:`from allennlp.predictors.sentence.SentenceTaggerPredictor` The main difference: 1. The option to use either the tokenizer that is in the constructor of the class or to provide the tokens within the JSON that is to be processed thus allowing the flexiability of using your own custom tokenizer. """ @overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance: """ Expects JSON that looks like either: 1. ``{"sentence": "..."}`` 2. ``{"sentence": "...", "tokens": ["..."]}`` 3. ``{"tokens": ["..."]}`` The first case will tokenize the text using the tokenizer in the constructor. The later two will just use the tokens given. Runs the underlying model, and adds the ``"words"`` to the output. """ if 'tokens' in json_dict: tokens = [Token(token) for token in json_dict['tokens']] else: sentence = json_dict["sentence"] tokens = self._tokenizer.split_words(sentence) return self._dataset_reader.text_to_instance(tokens)
[ 6738, 23170, 1460, 1330, 23170, 1460, 198, 198, 6738, 477, 1697, 34431, 13, 11321, 13, 22602, 1330, 449, 1559, 35, 713, 198, 6738, 477, 1697, 34431, 13, 7890, 1330, 16092, 292, 316, 33634, 11, 2262, 590, 11, 29130, 198, 6738, 477, 169...
2.595541
628
from django.shortcuts import render def about(request): """ A View to return the about.html """ return render(request, 'about/about.html') def privacy(request): """ A View to return the privacy.html """ return render(request, 'about/privacy.html')
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 628, 198, 4299, 546, 7, 25927, 2599, 198, 220, 220, 220, 37227, 317, 3582, 284, 1441, 262, 546, 13, 6494, 37227, 198, 220, 220, 220, 1441, 8543, 7, 25927, 11, 705, 10755, 14, 10755, ...
3.190476
84
""" The Scanner is responsible for iterating over the model.txt and transforming it into a more usable representation. It doesn't implement any transformations (expect for type casting). """ INPUT_SCAN_KEYS = { "max_feature_idx": ScannedValue(int), "num_class": ScannedValue(int), "num_tree_per_iteration": ScannedValue(int), "version": ScannedValue(str), "feature_infos": ScannedValue(str, True), "objective": ScannedValue(str, True), } TREE_SCAN_KEYS = { "Tree": ScannedValue(int), "num_leaves": ScannedValue(int), "num_cat": ScannedValue(int), "split_feature": ScannedValue(int, True), "threshold": ScannedValue(float, True), "decision_type": ScannedValue(int, True), "left_child": ScannedValue(int, True), "right_child": ScannedValue(int, True), "leaf_value": ScannedValue(float, True), "cat_threshold": ScannedValue(int, True, True), "cat_boundaries": ScannedValue(int, True, True), } def _scan_block(lines: list, items_to_scan: dict): """ Scans a block (= list of lines) into a key: value map. :param lines: list of lines in the block :param items_to_scan: dict with 'key': 'type of value' of keys to scan for :return: dict with a key-value pair for each key in items_to_scan. Raises RuntimeError if a non-nullable value from items_to_scan wasn't found in the block. """ result_map = {} for line in lines: # initial line in file if line == "tree": continue scanned_key, scanned_value = line.split("=") target_type = items_to_scan.get(scanned_key) if target_type is None: continue if target_type.is_list: if scanned_value: parsed_value = [target_type.type(x) for x in scanned_value.split(" ")] else: parsed_value = [] else: parsed_value = target_type.type(scanned_value) result_map[scanned_key] = parsed_value expected_keys = {k for k, v in items_to_scan.items() if not v.null_ok} missing_keys = expected_keys - result_map.keys() if missing_keys: raise RuntimeError(f"Missing non-nullable keys {missing_keys}") return result_map
[ 37811, 198, 464, 20937, 1008, 318, 4497, 329, 11629, 803, 625, 262, 2746, 13, 14116, 290, 25449, 340, 656, 257, 517, 198, 31979, 10552, 13, 198, 1026, 1595, 470, 3494, 597, 38226, 357, 1069, 806, 329, 2099, 13092, 737, 198, 37811, 628...
2.491071
896
import math import numpy if __name__ == "__main__": # test the iterative histogram iterative_histogram = IterativeHistogram(start=0, stop=10, n_bins=10) iterative_histogram.update(0) # 1 iterative_histogram.update(-1) # None iterative_histogram.update(10) # 10 iterative_histogram.update(9.99999) # 10 iterative_histogram.update(10.0001) # None iterative_histogram.update(0.5) # 1 iterative_histogram.update(1.5) # 2 iterative_histogram.update(1.0) # 2 iterative_histogram.update(1.99999) # 2 # ^ expect [2,3,0,0,0,0,0,0,0,2] print(iterative_histogram.get_histogram()) iterative_histogram = IterativeHistogram(start=0, stop=1.0, n_bins=10) iterative_histogram.update(0) # 1 iterative_histogram.update(-0.1) # None iterative_histogram.update(1.0) # 10 iterative_histogram.update(0.999999) # 10 iterative_histogram.update(1.00001) # None iterative_histogram.update(0.05) # 1 iterative_histogram.update(0.15) # 2 iterative_histogram.update(0.10) # 2 iterative_histogram.update(0.199999) # 2 # ^ expect [2,3,0,0,0,0,0,0,0,2] print(iterative_histogram.get_histogram()) iterative_histogram = IterativeHistogram(start=1, stop=2.0, n_bins=10) iterative_histogram.update(1 + 0) # 1 iterative_histogram.update(1 + -0.1) # None iterative_histogram.update(1 + 1.0) # 10 iterative_histogram.update(1 + 0.999999) # 10 iterative_histogram.update(1 + 1.00001) # None iterative_histogram.update(1 + 0.05) # 1 iterative_histogram.update(1 + 0.15) # 2 iterative_histogram.update(1 + 0.10) # 2 iterative_histogram.update(1 + 0.199999) # 2 # ^ expect [2,3,0,0,0,0,0,0,0,2] print(iterative_histogram.get_histogram()) iterative_histogram = IterativeHistogram(start=-0.5, stop=0.5, n_bins=10) iterative_histogram.update(-0.5 + 0) # 1 iterative_histogram.update(-0.5 + -0.1) # None iterative_histogram.update(-0.5 + 1.0) # 10 right edge iterative_histogram.update(-0.5 + 0.999999) # 10 iterative_histogram.update(-0.5 + 1.00001) # None iterative_histogram.update(-0.5 + 0.05) # 1 iterative_histogram.update(-0.5 + 0.15) # 2 iterative_histogram.update(-0.5 + 0.10) # 2 ... in near-edge cases float division may shift left a bin iterative_histogram.update(-0.5 + 0.199999) # 2 # DON'T USE THIS CLASS FOR BINS WITH SIZE that NEARS FLOAT PRECISION # ^ expect [2,3,0,0,0,0,0,0,0,2] print(iterative_histogram.get_histogram()) print(iterative_histogram.get_normalized_histogram()) print(sum(iterative_histogram.get_normalized_histogram())) iterative_histogram = IterativeHistogram(start=0, stop=1.0, n_bins=10, unbounded_lower_bin=True, unbounded_upper_bin=True) iterative_histogram.update(0) # 1 iterative_histogram.update(-0.1) # 1 iterative_histogram.update(1.0) # 10 iterative_histogram.update(0.999999) # 10 iterative_histogram.update(1.00001) # 10 iterative_histogram.update(0.05) # 1 iterative_histogram.update(0.15) # 2 iterative_histogram.update(0.10) # 2 iterative_histogram.update(0.199999) # 2 # ^ expect [3,3,0,0,0,0,0,0,0,3] print(iterative_histogram.get_histogram()) print(iterative_histogram.get_normalized_histogram()) print(sum(iterative_histogram.get_normalized_histogram()))
[ 11748, 10688, 201, 198, 11748, 299, 32152, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 1303, 1332, 262, 11629, 876, 1554, 21857, 201, 198, 220, 220, 220, ...
2.105171
1,721
import os from basePhantom import _BasePhantom class _PhantomAssets(_BasePhantom): """ Wrapper around the Phantom REST calls for Assets """
[ 11748, 28686, 198, 6738, 2779, 2725, 11456, 1330, 4808, 14881, 2725, 11456, 628, 198, 4871, 4808, 2725, 11456, 8021, 1039, 28264, 14881, 2725, 11456, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 27323, 2848, 1088, 262, 14407, 3061...
3.142857
49
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SolidBlue III - Open source data manager. # # __author__ = "Fabrizio Giudici" # __copyright__ = "Copyright © 2020 by Fabrizio Giudici" # __credits__ = ["Fabrizio Giudici"] # __license__ = "Apache v2" # __version__ = "1.0-ALPHA-4-SNAPSHOT" # __maintainer__ = "Fabrizio Giudici" # __email__ = "fabrizio.giudici@tidalwave.it" # __status__ = "Prototype" # -*- coding: utf-8 -*- import unittest import utilities from fingerprinting import FingerprintingControl if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 220, 15831, 14573, 6711, 532, 4946, 2723, 1366, 4706, 13, 198, 2, 198, 2, 220, 11593, 9800, 834, 796, 3...
2.437768
233
import collections import logging import os import os.path import re import sys log = logging.getLogger(__name__) def render_api_and_obj_classes(module_name, api_classes, template): '''Render a template.''' return str(template.render({"module": {"name": module_name}, "classes": api_classes, "dso_extension": dso_extension()})) def get_template_name(template_path): '''Get the template name from the binding name.''' template_name = os.path.basename(template_path) return re.sub(".tmpl$", "", template_name) def get_template_output(class_name, template_name): '''Determine the output filename from the template name.''' split_name = template_name.split('.') suffix_name = '.'.join(split_name[:-1]) extension = split_name[-1] return "{}{}.{}".format(class_name, suffix_name, extension) def generate_single_output_file( module_name, binding, api_classes, env, output_file_name): '''Generate a single named output file. Used by the default generator.''' with open(output_file_name, 'w') as output_file: template = env.get_template(binding) output_string = render_api_and_obj_classes( module_name, api_classes, template) output_file.write(output_string) def default_generator(module_name, binding, api_classes, env, output_dir): ''' Default generator. Used when there are no custom generators registered for a binding. This generator is appropriate for simple bindings that produce a single output file. Input: - module_name: The name of the module to generate. - binding: The name of the binding to generate. - api_classes: The classes to generate bindings for. - env: The jinja2 environment. - output_dir: The base directory for generator output. ''' template = env.get_template(binding) output_string = render_api_and_obj_classes( module_name, api_classes, template) output_file_name = os.path.join( output_dir, get_template_output( module_name, get_template_name(binding))) generate_single_output_file( module_name, binding, api_classes, env, output_file_name) return [output_file_name] class GeneratorContext(object): '''Holds a mapping of bindings to custom generators.''' GeneratorRecord = collections.namedtuple( 'GeneratorRecord', ['function', 'description']) def __init__(self): '''Initialise with no custom generators''' self._generator_map = {} def register(self, generator_function, bindings): ''' Register a generation function. Input: - generator_function: f(module_name, binding, api_classes, env, output_dir). - bindings: List of tuples describing bindings that this function generates. The format is [(binding_name, description), ...] ''' for binding in bindings: binding_name = binding[0] description = binding[1] record = GeneratorContext.GeneratorRecord(generator_function, description) self._generator_map[binding_name] = record def list_generators(self): ''' Return a list of registered binding generators. Output: - List of (binding_name, description) tuples ''' return [(binding, record.description) for binding, record in self._generator_map.items()] def generate(self, module_name, binding, api_classes, env, output_dir): ''' Generate a set of bindings. Input: - module_name: The name of the module to generate. - binding: The type of binding to generate. - api_classes: Classes to generate bindings for. - env: The template environment. - output_dir: Directory to write generated bindings to. ''' log.info('Finding generator for {}'.format(binding)) if binding in self._generator_map: log.info(' found in map') generator_func = self._generator_map[binding].function return generator_func(module_name, binding, api_classes, env, output_dir) else: log.info(' using default') return default_generator( module_name, binding, api_classes, env, output_dir) # This is the default generator context. generator_context = GeneratorContext() def generate(module_name, binding, api_classes, env, output_dir): '''Forward the request to the default generator context.''' return generator_context.generate( module_name, binding, api_classes, env, output_dir) def _activate_plugin(module_name): '''Internal function used to activate a plugin that has been found.''' log.info('Importing {}'.format(module_name)) module = __import__( 'ffig.generators.{0}'.format(module_name), fromlist=['setup_plugin']) module.setup_plugin(generator_context) def _scan_plugins(): ''' Internal function used to search the generators directory for plugins. Plugins may be written as a module (a single python file in the generators directory) or as a package (a subdirectory of generators, containing an __init__.py). In either case, plugins must define a function to register one or more generator functions against a list of one or more binding names: def setup_plugin(context): context.register(generator_func, [(binding, description), ...]) where generator_func is a function of the form f(module_name, binding, api_classes, env, output_dir) ''' basedir = os.path.realpath(os.path.dirname(__file__)) log.info('Scanning for plugins in {}'.format(basedir)) excluded_files = ['__init__.py', '__pycache__'] for entry in os.listdir(basedir): log.info('Checking {}'.format(entry)) if entry in excluded_files: log.info('Skipping excluded file {}'.format(entry)) continue filepath = os.path.join(basedir, entry) if os.path.isdir(filepath): log.info('Found plugin package {}'.format(entry)) # This is a generator package. Import it. _activate_plugin(os.path.basename(entry)) elif os.path.isfile(filepath) and entry.endswith('.py'): log.info('Found plugin module {}'.format(entry)) _activate_plugin(os.path.basename(entry)[:-3]) # Scan the generators directory for plugins and register them on # initialisation. _scan_plugins()
[ 11748, 17268, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 302, 198, 11748, 25064, 198, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 198, 198, 4299, 8543, 62, 15042, 62, 39...
2.603274
2,566
from selenium.webdriver.common.by import By
[ 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 1525, 1330, 2750, 628 ]
3.214286
14
import struct FILE_FORMAT_VERSION = 5
[ 11748, 2878, 198, 198, 25664, 62, 21389, 1404, 62, 43717, 796, 642, 198 ]
3
13
numbers = list(map(int, (input()).split(" "))) command = input() while command != 'end': tokens = command.split(" ") if tokens[0] == 'exchange': idx = int(tokens[1]) exchange(idx) elif tokens[0] == 'max': max_even_odd(tokens[1]) elif tokens[0] == 'min': min_even_odd(tokens[1]) elif tokens[0] == 'first': count = int(tokens[1]) first_even_odd(count, tokens[2]) elif tokens[0] == 'last': count = int(tokens[1]) last_even_odd(count, tokens[2]) command = input() print(numbers)
[ 77, 17024, 796, 1351, 7, 8899, 7, 600, 11, 357, 15414, 3419, 737, 35312, 7203, 366, 22305, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 21812, 796, 5128, 3419, 201, 198, 4514, 3141, 14512, 705, 4...
1.942122
311
import cv2 import numpy as np from sklearn.cluster import DBSCAN as skDBSCAN
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 565, 5819, 1330, 360, 4462, 44565, 355, 1341, 35, 4462, 44565, 628, 220, 220, 220, 220, 198, 220, 220, 220, 220 ]
2.416667
36
import uuid from pathlib import Path import factory import pytest from django.conf import settings from django.core.exceptions import MultipleObjectsReturned from django.core.files import File from tests.cases_tests.factories import ( ImageFactory, ImageFactoryWithImageFile, ImageFactoryWithImageFile4D, ImageFileFactoryWithMHDFile, ImageFileFactoryWithRAWFile, ) from tests.cases_tests.utils import get_sitk_image from tests.factories import ImageFileFactory @pytest.mark.django_db @pytest.mark.django_db @pytest.mark.django_db
[ 11748, 334, 27112, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 8860, 198, 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 20401, 10267, 82, 13615, 276,...
3.1
180
from .core import * from .terminal import cli __version__ = '0.2.5'
[ 6738, 764, 7295, 1330, 1635, 220, 198, 6738, 764, 23705, 282, 1330, 537, 72, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 17, 13, 20, 6, 628 ]
2.535714
28
"""------------------------------------------------------------*- fingerPrint module for Raspberry Pi Tested on: Raspberry Pi 3 B+ (c) Minh-An Dao 2019 (C) Bastian Raschke 2015 version 1.00 - 09/10/2019 -------------------------------------------------------------- * * --------------------------------------------------------------""" from pyfingerprint.pyfingerprint import PyFingerprint import RPi.GPIO as GPIO # default as BCM mode! import time from datetime import datetime import button # for the cancel button # ---------------------------- Private Parameters: # -----Starting parameter: FINGER_PORT = '/dev/ttyUSB0' FINGER_BAUDRATE = 57600 FINGER_ADDRESS = 0xFFFFFFFF FINGER_PASSWORD = 0x00000000 TOUCH_PIN = 4 # BCM Mode WAIT_TIME = 5 # waiting time between first and second scan of enroll func DEBOUNCE = 10 START_CHECKING = False Finger = None # button.init() # already been done in main.py positionNumber = int() # ------------------------------ Basic functions ------------------------------
[ 37811, 47232, 10541, 9, 12, 198, 220, 7660, 18557, 8265, 329, 24244, 13993, 198, 220, 6208, 276, 319, 25, 24244, 13993, 513, 347, 10, 198, 220, 357, 66, 8, 1855, 71, 12, 2025, 360, 5488, 13130, 198, 220, 357, 34, 8, 17520, 666, 28...
3.773723
274
import random import string from typing import Optional from application.data.game_state import GameState from application.data.word_manager import WordManager class GameManager: """ Manages all the games. """ def create_game(self) -> GameState: """ Creates a new game. Returns: the game state """ game_name = self._create_game_name() while game_name in self.games: game_name = self._create_game_name() return self.create_game_for_name(game_name) def create_game_for_name(self, game_name: str) -> GameState: """ Creates a new game with the given game name. Returns: the game state """ game_state = GameState(game_name, self.word_manager) self.games[game_name] = game_state return game_state def get_game_state(self, game_name: str) -> Optional[GameState]: """ Returns the game state for the given game name if one exists. Args: game_name: the game name Returns: the game state if one exists """ game_name = game_name.upper() return self.games.get(game_name, None) @staticmethod
[ 11748, 4738, 198, 11748, 4731, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 3586, 13, 7890, 13, 6057, 62, 5219, 1330, 3776, 9012, 198, 6738, 3586, 13, 7890, 13, 4775, 62, 37153, 1330, 9678, 13511, 628, 198, 4871, 3776, 13511, 25, 19...
2.350943
530
import random @DiceDecorator input_game = input("What Game are you playing?\n") if input_game.lower() == "monopoly": function(input_game,"2d6") while True: user_input = input("Roll Again? (Yes or No)\n") if user_input.lower() == "no": break function(input_game, "2d6") elif input_game.lower() == "dnd": input_dice_roll = input("What type of dice are you rolling?\n"+"(d4,d6,d8,d10,d12,d20)\n") input_how_many_dice = input("How many of the type of dice are you rolling?\n") function(input_game, str(input_how_many_dice+input_dice_roll)) else: raise("Unknown Game")
[ 11748, 4738, 198, 198, 31, 35, 501, 10707, 273, 1352, 198, 198, 15414, 62, 6057, 796, 5128, 7203, 2061, 3776, 389, 345, 2712, 30, 59, 77, 4943, 198, 361, 5128, 62, 6057, 13, 21037, 3419, 6624, 366, 2144, 35894, 1298, 198, 220, 220, ...
2.35206
267
class Concept: '''Defines a concept and its parents concepts.''' def __init__(self, index, parents=None): ''' Attributes: - self.index: identifies a concept; - self.parents: this concept's parents. ''' self.index = index self.parents = parents def from_line(elem): '''Obtains a concept from a line.''' data = elem.split(',') index = data[0] parents = None if len(data) == 2: parents = data[1].split('/') return Concept(index, parents)
[ 4871, 26097, 25, 198, 220, 220, 220, 705, 7061, 7469, 1127, 257, 3721, 290, 663, 3397, 10838, 2637, 7061, 628, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 6376, 11, 3397, 28, 14202, 2599, 198, 220, 220, 220, 220, 220, 220, ...
2.392857
224
# Copyright (c) 2021, 2022, Oracle and/or its affiliates. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2.0, # as published by the Free Software Foundation. # # This program is also distributed with certain software (including # but not limited to OpenSSL) that is licensed under separate terms, as # designated in a particular file or component or in included license # documentation. The authors of MySQL hereby grant you an additional # permission to link the program and your derivative works with the # separately licensed software that they have included with MySQL. # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License, version 2.0, for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import pytest from ... schemas import * @pytest.mark.usefixtures("init_mrs") @pytest.mark.usefixtures("init_mrs") @pytest.mark.usefixtures("init_mrs") @pytest.mark.usefixtures("init_mrs")
[ 2, 15069, 357, 66, 8, 33448, 11, 33160, 11, 18650, 290, 14, 273, 663, 29116, 13, 198, 2, 198, 2, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 2, 340, 739, 262, 2846, 286, 262, 22961, 3611...
3.809798
347
from corehq.apps.domain.models import Domain from corehq.apps.locations.models import SQLLocation from corehq.apps.sms.api import send_sms_to_verified_number from corehq.util.translation import localize from memoized import memoized
[ 6738, 4755, 71, 80, 13, 18211, 13, 27830, 13, 27530, 1330, 20021, 198, 6738, 4755, 71, 80, 13, 18211, 13, 17946, 602, 13, 27530, 1330, 49747, 3069, 5040, 198, 6738, 4755, 71, 80, 13, 18211, 13, 82, 907, 13, 15042, 1330, 3758, 62, ...
3.295775
71
import asyncio import os from rf_api_client import RfApiClient from rf_api_client.models.maps_api_models import MapLayout, NewMapDto from rf_api_client.rf_api_client import UserAuth USERNAME = os.getenv('USERNAME') PASSWORD = os.getenv('PASSWORD') MAP_ID = os.getenv('MAP_ID') if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(load_map()) loop.run_until_complete(create_map()) loop.run_until_complete(asyncio.sleep(0)) loop.close()
[ 11748, 30351, 952, 198, 11748, 28686, 198, 198, 6738, 374, 69, 62, 15042, 62, 16366, 1330, 371, 69, 32, 14415, 11792, 198, 6738, 374, 69, 62, 15042, 62, 16366, 13, 27530, 13, 31803, 62, 15042, 62, 27530, 1330, 9347, 32517, 11, 968, ...
2.554404
193
import importlib import logging import yaml import os from .eventbus import EventBus from .template import TemplateDict from performance.driver.core.utils import parseTimeExpr # TODO: Make @ expand to `performance.driver.core.classes` # TODO: Make MetricConfig use ComponentConfig def mergeConfig(source, destination): """ Merges `source` object into `destination`. """ for key, value in source.items(): if not key in destination: destination[key] = value elif type(value) is dict: # get node or create one node = destination.setdefault(key, {}) mergeConfig(value, node) elif type(value) in (list, tuple): destination[key] += value else: destination[key] = value return destination def loadConfigFile(filename): """ Load just a single YAML configuration file """ with open(filename, 'r') as f: config = yaml.load(f) # Validate if not config: raise ValueError( 'This configuration file contains no meaningful information') # Process includes includes = [] if 'include' in config: includes = config['include'] del config['include'] # Load includes for path in includes: if path[0] != '/': path = '{}/{}'.format(os.path.dirname(filename), path) path = os.path.abspath(path) # Merge every include in the root path subConfig = loadConfig(path) config = mergeConfig(subConfig, config) # Return config return config def loadConfig(filename): """ Load one or more configuration files at once """ if type(filename) in (list, tuple): config = {} for file in filename: config = mergeConfig(config, loadConfigFile(file)) return config else: return loadConfigFile(filename) class DefinitionsDict(TemplateDict): """ Definitions dictionary includes the `fork` function that allows the dict to be cloned, appending some additional properties """ def fork(self, *dicts): """ Create a copy of this dict and extend it with one or more parameters given """ copyDict = dict(self) for d in dicts: copyDict.update(d) return DefinitionsDict(copyDict) class ComponentConfig(dict): """ A component config handles configuration sections in the following form: - class: path.to.class ... props """ def instance(self, *args, **kwargs): """ Return a class instance """ # De-compose class path to module and class name if self['class'][0] == "@": classPath = 'performance.driver.core.classes.{}'.format( self['class'][1:]) else: classPath = 'performance.driver.classes.{}'.format(self['class']) self.logger.debug('Instantiating {}'.format(classPath)) pathComponents = classPath.split('.') className = pathComponents.pop() modulePath = '.'.join(pathComponents) # Get a reference to the class type self.logger.debug( 'Looking for \'{}\' in module \'{}\''.format(className, modulePath)) module = importlib.import_module(modulePath) classType = getattr(module, className) # Instantiate with the config class as first argument return classType(self, *args, **kwargs) class Configurable: """ Base class that provides the configuration-fetching primitives to channels, observers and policies. """ class MetricConfig: """ Configuration class for the metrics """ def instanceSummarizers(self): """ Return an array with all the summarizers """ # Re-use cached instances if not self.summarizersInstanes is None: return self.summarizersInstanes # Compose instances and cache them self.summarizersInstanes = [] for summConfig in self.summarizers: # De-compose class path to module and class name # The "@" shorthand is referring to the built-in summarizer if summConfig['class'][0] == "@": classPath = 'performance.driver.core.classes.summarizer.BuiltInSummarizer' if not 'name' in summConfig: summConfig['name'] = summConfig['class'][1:] else: classPath = 'performance.driver.classes.{}'.format(summConfig['class']) self.logger.debug('Instantiating {}'.format(classPath)) pathComponents = classPath.split('.') className = pathComponents.pop() modulePath = '.'.join(pathComponents) # Get a reference to the class type self.logger.debug( 'Looking for \'{}\' in module \'{}\''.format(className, modulePath)) module = importlib.import_module(modulePath) classType = getattr(module, className) # Instantiate with the config class as first argument self.summarizersInstanes.append(classType(summConfig)) # Return summarizer instances return self.summarizersInstanes class GeneralConfig: """ General configuration class contains the test-wide configuration parameters """ class RootConfig: """ Root configuration section """ def compileDefinitions(self, cmdlineDefinitions={}): """ Apply template variables to definitions """ self.definitions.update(cmdlineDefinitions) self.definitions = DefinitionsDict( self.definitions.apply( self.definitions.fork( dict([('meta:' + kv[0], kv[1]) for kv in self.meta.items()])))) def policies(self): """ Return all policies in the config """ return map(lambda c: ComponentConfig(c, self, 'policies'), self.config.get('policies', [])) def channels(self): """ Return all channels in the config """ return map(lambda c: ComponentConfig(c, self, 'channels'), self.config.get('channels', [])) def observers(self): """ Return all observers in the config """ return map(lambda c: ComponentConfig(c, self, 'observers'), self.config.get('observers', [])) def trackers(self): """ Return all trackers in the config """ return map(lambda c: ComponentConfig(c, self, 'trackers'), self.config.get('trackers', [])) def tasks(self): """ Return all tasks in the config """ return map(lambda c: ComponentConfig(c, self, 'tasks'), self.config.get('tasks', [])) def reporters(self): """ Return all reporters in the config """ reporters = self.config.get('reporters', []) if len(reporters) == 0: self.logger.warn('Missing `reporters` config section. Using defaults') reporters = [{"class": "@reporter.ConsoleReporter"}] return map(lambda c: ComponentConfig(c, self, 'reporters'), reporters) def general(self): """ Return the general config section """ return GeneralConfig(self.config.get('config', {}), self)
[ 11748, 1330, 8019, 198, 11748, 18931, 198, 11748, 331, 43695, 198, 11748, 28686, 198, 198, 6738, 764, 15596, 10885, 1330, 8558, 16286, 198, 6738, 764, 28243, 1330, 37350, 35, 713, 198, 198, 6738, 2854, 13, 26230, 13, 7295, 13, 26791, 13...
2.839933
2,374
from typing import Optional import torch from sacred import Experiment from experiments.Experiment_utils import idx_maps, add_tensor_board_writers, run_training, create_logger from experiments.data_loading import data_loading_ingredient from src.LSTMLID import LSTMLIDModel LSTM_exp = Experiment('LSTM_experiment', ingredients=[data_loading_ingredient]) # Attach the logger to the experiment LSTM_exp.logger = create_logger() @LSTM_exp.config @LSTM_exp.capture @LSTM_exp.automain
[ 6738, 19720, 1330, 32233, 198, 198, 11748, 28034, 198, 6738, 13626, 1330, 29544, 198, 198, 6738, 10256, 13, 20468, 3681, 62, 26791, 1330, 4686, 87, 62, 31803, 11, 751, 62, 83, 22854, 62, 3526, 62, 34422, 11, 1057, 62, 34409, 11, 2251,...
3.05625
160
from unittest import TestCase from jp.co.coworker.nlp_knock_handson.ch8.preprocessor import PreProcessor
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 474, 79, 13, 1073, 13, 8232, 967, 263, 13, 21283, 79, 62, 15418, 735, 62, 4993, 1559, 13, 354, 23, 13, 3866, 41341, 1330, 3771, 18709, 273, 628 ]
2.815789
38
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : thread_queue_test.py # @Time : 2019/2/15 1:11 # @Author : MaiXiaochai # @Site : https://github.com/MaiXiaochai import time import threading from queue import Queue if __name__ == '__main__': main_var()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 2488, 8979, 220, 220, 220, 1058, 4704, 62, 36560, 62, 9288, 13, 9078, 198, 2, 2488, 7575, 220, 220, 220, 1058, 131...
2.280992
121
#-*- coding: utf-8 -*- import sys import junopy if __name__ == "__main__": main(sys.argv)
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 25064, 198, 11748, 10891, 11081, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 7, 17597, 13, 853, 85, 8, 198 ...
2.155556
45
from datasets.basedataset import BaseDataset from .basedata import DGBaseData import os.path as osp
[ 6738, 40522, 13, 3106, 265, 292, 316, 1330, 7308, 27354, 292, 316, 198, 6738, 764, 3106, 1045, 1330, 360, 4579, 589, 6601, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198 ]
3.225806
31
from matplotlib.pyplot import spy import pandas as pd import questionary import matplotlib.pyplot as plt import fire import utils.gauge as gauge from utils.MCForecastTools import MCSimulation as MCSimulation import utils.alpacaConnect as alpacaConnect import utils.beta_sharpe_functions as stats if __name__ == "__main__": fire.Fire(run)
[ 6738, 2603, 29487, 8019, 13, 9078, 29487, 1330, 13997, 198, 11748, 19798, 292, 355, 279, 67, 220, 198, 11748, 1808, 560, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2046, 220, 198, 11748, 3384, 4487, 13, ...
2.81746
126
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 6738, 42625, 14208, 13, 26791, 13, 5239, 1330, ...
2.957447
47
''' ''' ''' ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ''' import random import numpy as np import abc from Basilisk.utilities import RigidBodyKinematics as rbk import collections
[ 7061, 6, 705, 7061, 198, 7061, 6, 198, 3180, 34, 13789, 628, 15069, 357, 66, 8, 1584, 11, 5231, 38175, 21501, 11998, 3498, 11, 2059, 286, 7492, 379, 27437, 628, 2448, 3411, 284, 779, 11, 4866, 11, 13096, 11, 290, 14, 273, 14983, 4...
3.65019
263
from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Range1d, FuncTickFormatter, FixedTicker from math import pi, floor #ColourOptions = ["red","blue","green","black","yellow","purple"] # define operator[]
[ 6738, 1489, 365, 71, 13, 29487, 889, 1330, 3785, 198, 6738, 1489, 365, 71, 13, 27530, 1330, 29201, 6601, 7416, 11, 13667, 16, 67, 11, 11138, 66, 51, 624, 8479, 1436, 11, 10832, 51, 15799, 198, 6738, 10688, 1330, 31028, 11, 4314, 198...
3.12987
77
from .payment import KeyHashInfo, ScriptHashInfo, PaymentCodeInfo from .registration import Registration from .registration import electron_markdown, opreturn
[ 6738, 764, 37301, 1330, 7383, 26257, 12360, 11, 12327, 26257, 12360, 11, 28784, 10669, 12360, 198, 6738, 764, 2301, 33397, 1330, 24610, 198, 6738, 764, 2301, 33397, 1330, 11538, 62, 4102, 2902, 11, 1034, 7783, 198 ]
4.416667
36
from . import initiate_driver
[ 6738, 764, 1330, 22118, 62, 26230, 198 ]
4.285714
7
file_content = open("3dec-input", 'r') #file_content = ["R75,D30,R83,U83,L12,D49,R71,U7,L72", "U62,R66,U55,R34,D71,R55,D58,R83"] #file_content = ["R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51", "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"] #file_content = ["R8,U5,L5,D3", "U7,R6,D4,L4"] paths = [] for line in file_content: paths.append(trace(line.split(","))) cross = crossings(paths[0], paths[1]) print(shortest_crossing(cross)) file_content.close()
[ 198, 198, 7753, 62, 11299, 796, 1280, 7203, 18, 12501, 12, 15414, 1600, 705, 81, 11537, 198, 2, 7753, 62, 11299, 796, 14631, 49, 2425, 11, 35, 1270, 11, 49, 5999, 11, 52, 5999, 11, 43, 1065, 11, 35, 2920, 11, 49, 4869, 11, 52, ...
1.868313
243
# -*- coding: utf-8 -*- """ This is a wrapper of head and tail projection. To generate sparse_module.so file, please use the following command (suppose you have Linux/MacOS/MacBook): python setup.py build_ext --inplace """ import os import numpy from setuptools import setup from setuptools import find_packages from distutils.core import Extension here = os.path.abspath(os.path.dirname(__file__)) src_files = ['sparse_learn/c/main_wrapper.c', 'sparse_learn/c/head_tail_proj.c', 'sparse_learn/c/fast_pcst.c', 'sparse_learn/c/sort.c'] compile_args = ['-shared', '-Wall', '-g', '-O3', '-fPIC', '-std=c11', '-lm'] with open("README.md", "r") as fh: long_description = fh.read() setup( name="sparse_learn", version="0.1.1", author="Baojian Zhou", author_email="bzhou6@albany.edu", description="A package related with sparse learning methods.", long_description=long_description, long_description_content_type="text/markdown", use_2to3=True, url="https://github.com/baojianzhou/sparse-learn", packages=find_packages(), install_requires=['numpy'], include_dirs=[numpy.get_include()], headers=['sparse_learn/c/head_tail_proj.h', 'sparse_learn/c/fast_pcst.h', 'sparse_learn/c/sort.h'], ext_modules=[ Extension('sparse_learn', sources=src_files, language="C", extra_compile_args=compile_args, include_dirs=[numpy.get_include()])], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], keywords='sparse learning, structure sparsity, head/tail projection')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 1212, 318, 257, 29908, 286, 1182, 290, 7894, 20128, 13, 1675, 7716, 29877, 62, 21412, 13, 568, 198, 7753, 11, 3387, 779, 262, 1708, 3141, 357, 18608, ...
2.329396
762
# Generated by Django 2.1.3 on 2018-11-18 22:58 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 18, 319, 2864, 12, 1157, 12, 1507, 2534, 25, 3365, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
""" Django settings for example project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os APP_URL = '' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w@yelrvm+p(%s6*cki6)f$a0_w9i^%tul$hfm0vhaz_a24j2(1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'dj_field_filemanager', 'documents', 'example', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # corsheaders 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'example.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'example.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # MEDIA_URL = '%s/media/' % APP_URL # # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') # STATIC_ROOT = os.getenv('STATIC_ROOT', STATIC_ROOT) # STATIC_URL = '%s/static/' % APP_URL # corsheaders CORS_ORIGIN_ALLOW_ALL = True FIELD_FILEMANAGER_STORAGE_CONFIG = [ { 'code': 'storage_file_example', 'path': os.path.join(MEDIA_ROOT, 'storage_file_example'), # 'url': os.path.join(MEDIA_URL, 'storage_file_example'), 'thumbnail': { 'path': os.path.join(MEDIA_ROOT, 'storage_file_thumbnails_example'), # 'url': os.path.join(MEDIA_URL, 'storage_file_thumbnails_example'), 'width': 250, 'height': 250 } } ] # Overwrite settings using ENVIRONMENT_NAME ENVIRONMENT_NAME = os.environ.get('ENVIRONMENT_NAME', '') extra_settings_file = 'settings-%s.py' % ENVIRONMENT_NAME extra_settings_dir = os.path.dirname(os.path.abspath(__file__)) extra_settings_path = os.path.join(extra_settings_dir, extra_settings_file) if os.path.exists(extra_settings_path): try: exec(compile(open(extra_settings_path, "rb").read(), extra_settings_path, 'exec'), globals()) except Exception: raise Exception("Failed to import extra settings from %s" % extra_settings_path) # FIXME: python3 only # ) from exc
[ 37811, 198, 35, 73, 14208, 6460, 329, 1672, 1628, 13, 198, 198, 8645, 515, 416, 705, 28241, 14208, 12, 28482, 923, 16302, 6, 1262, 37770, 362, 13, 16, 13, 17, 13, 198, 198, 1890, 517, 1321, 319, 428, 2393, 11, 766, 198, 5450, 1378...
2.334951
1,854
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """History Callback class.""" import numpy as np from mindspore.common.tensor import Tensor from ._callback import Callback class History(Callback): """ Records the network outputs information into a `History` object. The network outputs information will be the loss value if not custimizing the train network or eval network; if the custimized network returns a `Tensor` or `numpy.ndarray`, the mean value of network output will be recorded, if the custimized network returns a `tuple` or `list`, the first element of network outputs will be recorded. Note: Normally used in `mindspore.Model.train`. Examples: >>> from mindspore import Model, nn >>> data = {"x": np.float32(np.random.rand(64, 10)), "y": np.random.randint(0, 5, (64,))} >>> train_dataset = ds.NumpySlicesDataset(data=data).batch(32) >>> net = nn.Dense(10, 5) >>> crit = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') >>> opt = nn.Momentum(net.trainable_params(), 0.01, 0.9) >>> history_cb = History() >>> model = Model(network=net, optimizer=opt, loss_fn=crit, metrics={"recall"}) >>> model.train(2, train_dataset, callbacks=[history_cb]) >>> print(history_cb.epoch) >>> print(history_cb.history) [1, 2] {'net_output': [1.607877, 1.6033841]} """ def begin(self, run_context): """ Initialize the `epoch` property at the begin of training. Args: run_context (RunContext): Context of the `mindspore.Model.train/eval`. """ self.epoch = [] def epoch_end(self, run_context): """ Records the first element of network outputs at the end of epoch. Args: run_context (RunContext): Context of the `mindspore.Model.train/eval`. """ cb_params = run_context.original_args() epoch = cb_params.get("cur_epoch_num", 1) self.epoch.append(epoch) net_output = cb_params.net_outputs if isinstance(net_output, (tuple, list)): if isinstance(net_output[0], Tensor) and isinstance(net_output[0].asnumpy(), np.ndarray): net_output = net_output[0] if isinstance(net_output, Tensor) and isinstance(net_output.asnumpy(), np.ndarray): net_output = np.mean(net_output.asnumpy()) metrics = cb_params.get("metrics") cur_history = {"net_output": net_output} if metrics: cur_history.update(metrics) for k, v in cur_history.items(): self.history.setdefault(k, []).append(v)
[ 2, 15069, 33448, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
2.623408
1,256
import os import sys import py if not sys.platform.startswith('win'): py.test.skip("requires Windows") from pypy.module.posix import interp_nt as nt
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 12972, 198, 198, 361, 407, 25064, 13, 24254, 13, 9688, 2032, 342, 10786, 5404, 6, 2599, 198, 220, 220, 220, 12972, 13, 9288, 13, 48267, 7203, 47911, 3964, 4943, 198, 198, 6738, 279, 44...
2.724138
58
""" `tf.keras.layers.Layer` subclasses. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import functools import tensorflow as tf from forecaster.ops.diff import diff_1_pad from forecaster.ops.diff import diff_pad
[ 37811, 4600, 27110, 13, 6122, 292, 13, 75, 6962, 13, 49925, 63, 850, 37724, 13, 37227, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, ...
3.40625
96
from ows_refactored.common.ows_legend_cfg import ( legend_mean_ndvi_ticks, legend_stddev_ndvi_ticks, ) # colour ramps------------------------------------- mean_cr = [ {"value": -0.0, "color": "#000000", "alpha": 0.0}, {"value": 0.0, "color": "#d73027"}, {"value": 0.1, "color": "#f46d43"}, {"value": 0.2, "color": "#fdae61"}, {"value": 0.3, "color": "#fee08b"}, {"value": 0.4, "color": "#ffffbf"}, {"value": 0.5, "color": "#d9ef8b"}, {"value": 0.6, "color": "#a6d96a"}, {"value": 0.7, "color": "#66bd63"}, {"value": 0.8, "color": "#1a9850"}, {"value": 0.9, "color": "#006837"} ] std_cr = [ {"value": 0.0, "color": "#000004"}, {"value": 0.025, "color": "#0a0822"}, {"value": 0.05, "color": "#1d1147"}, {"value": 0.075, "color": "#36106b"}, {"value": 0.1, "color": "#51127c"}, {"value": 0.125, "color": "#6a1c81"}, {"value": 0.15, "color": "#832681"}, {"value": 0.175, "color": "#9c2e7f"}, {"value": 0.2, "color": "#b73779"}, {"value": 0.225, "color": "#d0416f"}, {"value": 0.25, "color": "#e75263"}, {"value": 0.275, "color": "#f56b5c"}, {"value": 0.3, "color": "#fc8961"}, {"value": 0.325, "color": "#fea772"}, {"value": 0.35, "color": "#fec488"}, {"value": 0.375, "color": "#fde2a3"}, {"value": 0.4, "color": "#fcfdbf"}, ] count_cr = [ {"value": 0, "color": "#FFFFFF", "alpha": 0.0}, {"value": 1, "color": "#f7fbff"}, {"value": 10, "color": "#ebf3fb"}, {"value": 20, "color": "#deebf7"}, {"value": 30, "color": "#d2e3f3"}, {"value": 40, "color": "#c6dbef"}, {"value": 50, "color": "#b2d2e8"}, {"value": 60, "color": "#9ecae1"}, {"value": 70, "color": "#84bcdc"}, {"value": 80, "color": "#6baed6"}, {"value": 90, "color": "#56a0ce"}, {"value": 100, "color": "#4292c6"}, {"value": 110, "color": "#3282be"}, {"value": 120, "color": "#2171b5"}, {"value": 130, "color": "#1461a9"}, {"value": 160, "color": "#08519c"}, {"value": 150, "color": "#084084"}, {"value": 160, "color": "#08306b"}, ] # mean styles------------------------------------------------------ style_ndvi_mean_jan = { "name": "style_ndvi_mean_jan", "title": "Mean NDVI Climatology for January", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_jan"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_jan", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_feb = { "name": "style_ndvi_mean_feb", "title": "Mean NDVI Climatology for February", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_feb"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_feb", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_mar = { "name": "style_ndvi_mean_mar", "title": "Mean NDVI Climatology for March", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_mar"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_mar", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_mar = { "name": "style_ndvi_mean_mar", "title": "Mean NDVI Climatology for March", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_mar"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_mar", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_apr = { "name": "style_ndvi_mean_apr", "title": "Mean NDVI Climatology for April", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_apr"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_apr", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_may = { "name": "style_ndvi_mean_may", "title": "Mean NDVI Climatology for May", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_may"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_may", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_jun = { "name": "style_ndvi_mean_jun", "title": "Mean NDVI Climatology for June", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_jun"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_jun", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_jul = { "name": "style_ndvi_mean_jul", "title": "Mean NDVI Climatology for July", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_jul"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_jul", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_aug = { "name": "style_ndvi_mean_aug", "title": "Mean NDVI Climatology for August", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_aug"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_aug", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_sep = { "name": "style_ndvi_mean_sep", "title": "Mean NDVI Climatology for September", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_sep"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_sep", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_oct = { "name": "style_ndvi_mean_oct", "title": "Mean NDVI Climatology for October", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_oct"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_oct", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_nov = { "name": "style_ndvi_mean_nov", "title": "Mean NDVI Climatology for November", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_nov"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_nov", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } style_ndvi_mean_dec = { "name": "style_ndvi_mean_dec", "title": "Mean NDVI Climatology for December", "abstract": "Long-term Mean NDVI Climatology (1984-2020)", "needed_bands": ["mean_dec"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "mean_dec", }, }, "color_ramp": mean_cr, "legend": legend_mean_ndvi_ticks, } # std dev styles----------------------------------------------------- style_ndvi_std_jan = { "name": "style_ndvi_std_jan", "title": "Std. Dev. NDVI Climatology for January", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_jan"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_jan", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_feb = { "name": "style_ndvi_std_feb", "title": "Std. Dev. NDVI Climatology for February", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_feb"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_feb", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_mar = { "name": "style_ndvi_std_mar", "title": "Std. Dev. NDVI Climatology for March", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_mar"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_mar", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_apr = { "name": "style_ndvi_std_apr", "title": "Std. Dev. NDVI Climatology for April", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_apr"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_apr", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_may = { "name": "style_ndvi_std_may", "title": "Std. Dev. NDVI Climatology for May", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_may"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_may", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_jun = { "name": "style_ndvi_std_jun", "title": "Std. Dev. NDVI Climatology for June", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_jun"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_jun", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_jul = { "name": "style_ndvi_std_jul", "title": "Std. Dev. NDVI Climatology for July", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_jul"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_jul", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_aug = { "name": "style_ndvi_std_aug", "title": "Std. Dev. NDVI Climatology for August", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_aug"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_aug", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_sep = { "name": "style_ndvi_std_sep", "title": "Std. Dev. NDVI Climatology for September", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_sep"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_sep", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_oct = { "name": "style_ndvi_std_oct", "title": "Std. Dev. NDVI Climatology for October", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_oct"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_oct", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_nov = { "name": "style_ndvi_std_nov", "title": "Std. Dev. NDVI Climatology for November", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_nov"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_nov", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } style_ndvi_std_dec = { "name": "style_ndvi_std_dec", "title": "Std. Dev. NDVI Climatology for December", "abstract": "Long-term Standard Deviation NDVI Climatology (1984-2020)", "needed_bands": ["stddev_dec"], "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "stddev_dec", }, }, "color_ramp": std_cr, "range": [0, 0.5], "legend": legend_stddev_ndvi_ticks, } # count styles----------------------------------------------------- style_count_jan = { "name": "style_count_jan", "title": "Clear observation count for January", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_jan", }, }, "needed_bands": ["count_jan"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_feb = { "name": "style_count_feb", "title": "Clear observation count for February", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_feb", }, }, "needed_bands": ["count_feb"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_mar = { "name": "style_count_mar", "title": "Clear observation count for March", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_mar", }, }, "needed_bands": ["count_mar"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_apr = { "name": "style_count_apr", "title": "Clear observation count for April", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_apr", }, }, "needed_bands": ["count_apr"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_may = { "name": "style_count_may", "title": "Clear observation count for May", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_may", }, }, "needed_bands": ["count_may"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_jun = { "name": "style_count_jun", "title": "Clear observation count for June", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_jun", }, }, "needed_bands": ["count_jun"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_jul = { "name": "style_count_jul", "title": "Clear observation count for July", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_jul", }, }, "needed_bands": ["count_jul"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_aug = { "name": "style_count_aug", "title": "Clear observation count for August", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_aug", }, }, "needed_bands": ["count_aug"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_sep = { "name": "style_count_sep", "title": "Clear observation count for September", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_sep", }, }, "needed_bands": ["count_sep"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_oct = { "name": "style_count_oct", "title": "Clear observation count for October", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_oct", }, }, "needed_bands": ["count_oct"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_nov = { "name": "style_count_nov", "title": "Clear observation count for November", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_nov", }, }, "needed_bands": ["count_nov"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, } style_count_dec = { "name": "style_count_dec", "title": "Clear observation count for December", "abstract": "Count of valid observations included in calculations", "index_function": { "function": "datacube_ows.band_utils.single_band", "mapped_bands": True, "kwargs": { "band": "count_dec", }, }, "needed_bands": ["count_dec"], "include_in_feature_info": False, "color_ramp": count_cr, "legend": { "begin": "0", "end": "160", "decimal_places": 0, "ticks_every": 20, "tick_labels": { "160": {"suffix": "<"}, }, }, }
[ 6738, 12334, 82, 62, 5420, 529, 1850, 13, 11321, 13, 1666, 62, 1455, 437, 62, 37581, 1330, 357, 198, 220, 220, 220, 8177, 62, 32604, 62, 358, 8903, 62, 83, 3378, 11, 198, 220, 220, 220, 8177, 62, 301, 1860, 1990, 62, 358, 8903, ...
2.092922
10,568
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn from SCTF import check_user, check_user_auth, FLAG import random import sys import os if __name__ == '__main__': if len(sys.argv) >= 3: addr, port = sys.argv[1], int(sys.argv[2]) else: addr, port = '0.0.0.0', 80 KEY = os.urandom(6).encode('hex') keys = [int(KEY, 16) & 0xffffff, int(KEY, 16) >> 24] CIPHER = IteratedEvenMansour(keys) server = ThreadedHTTPServer((addr, port), IEM_Handler) server.serve_forever()
[ 6738, 7308, 6535, 28820, 18497, 1330, 38288, 18497, 11, 7308, 40717, 18453, 25060, 198, 6738, 47068, 10697, 1330, 14122, 278, 35608, 818, 198, 6738, 311, 4177, 37, 1330, 2198, 62, 7220, 11, 2198, 62, 7220, 62, 18439, 11, 9977, 4760, 198...
2.445887
231
import pytest @pytest.mark.parametrize("given, expected", [ ("", "gluu"), ("my-ns", "my-ns"), ])
[ 11748, 12972, 9288, 628, 198, 31, 9078, 9288, 13, 4102, 13, 17143, 316, 380, 2736, 7203, 35569, 11, 2938, 1600, 685, 198, 220, 220, 220, 5855, 1600, 366, 70, 2290, 84, 12340, 198, 220, 220, 220, 5855, 1820, 12, 5907, 1600, 366, 1820...
2.183673
49
import argparse import os import shutil from subprocess import check_call from tempfile import TemporaryDirectory from PIL import Image from ..common_util.misc import makedirs from ..video_inpainting import create_padded_masked_video_dataset from ..video_inpainting.util import PILImagePadder def _unpad_copy_frames(interim_output_root, final_output_root, padder, raw_resolution): """Unpad and copy intermediate results from the inpainting method to the final output folder.""" makedirs(final_output_root) for image_file_name in sorted(os.listdir(interim_output_root)): if image_file_name.endswith('_pred.png'): padded_image_path = os.path.join(interim_output_root, image_file_name) final_image_path = os.path.join(final_output_root, image_file_name) if not padder.needs_padding(raw_resolution): shutil.copy(padded_image_path, final_image_path) else: image_pad = Image.open(padded_image_path) image = padder.unpad_image(image_pad, raw_resolution) image.save(final_image_path) def _run_inpainting_script(run_path, temp_input_root, temp_output_root): """Run the given script on the temporary inputs and store the results in the temporary output folder.""" exec_dir, script_file_name = os.path.split(run_path) cmd = ['bash', script_file_name, temp_input_root, temp_output_root] check_call(cmd, cwd=exec_dir) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--run_path', type=str, required=True, help='The path to the script that runs the video inpainting method') parser.add_argument('--image_size_divisor', type=int, nargs='+', default=[1], help='The value(s) by which the resolution of the inpainting method input must be divisible. ' 'Can either be one or two integers (width then height for two)') parser.add_argument('--frames_dataset_path', required=True, type=str, help='The path to the tar file or directory containing all video frames in the dataset') parser.add_argument('--masks_dataset_path', required=True, type=str, help='The path to the tar file or directory containing all video masks in the dataset') parser.add_argument('--inpainting_results_root', required=True, type=str, help='The path to the folder that will contain all inpainted results') parser.add_argument('--temp_root', type=str, default=None, help='Path to the temporary directory where intermediate data will be stored') parser.add_argument('--index_range', type=int, nargs=2, default=None, help='The range of video indexes to inpaint (inclusive)') args = parser.parse_args() main(**vars(args))
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 850, 14681, 1330, 2198, 62, 13345, 198, 6738, 20218, 7753, 1330, 46042, 43055, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 6738, 11485, 11321, 62, 22602, 13, ...
2.560459
1,133
from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017") for db_name in client.list_database_names(): print(db_name)
[ 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 198, 16366, 796, 42591, 11792, 7203, 31059, 375, 65, 1378, 36750, 25, 1983, 29326, 4943, 198, 198, 1640, 20613, 62, 3672, 287, 5456, 13, 4868, 62, 48806, 62, 14933, 33529, 198, 220, 220, ...
3.0625
48
from __future__ import absolute_import from pymunk._chipmunk_cffi_abi import ffi, lib, lib_path
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 201, 198, 201, 198, 6738, 279, 4948, 2954, 13557, 35902, 76, 2954, 62, 66, 487, 72, 62, 17914, 1330, 277, 12463, 11, 9195, 11, 9195, 62, 6978, 220, 201, 198, 220, 220, 220, 220 ]
2.5
42
import argparse from westpa.cli.core.w_states import entry_point from unittest import mock from pytest import fixture
[ 11748, 1822, 29572, 198, 198, 6738, 7421, 8957, 13, 44506, 13, 7295, 13, 86, 62, 27219, 1330, 5726, 62, 4122, 198, 6738, 555, 715, 395, 1330, 15290, 198, 6738, 12972, 9288, 1330, 29220, 628 ]
3.529412
34