content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from blockworld_walkway import BlockworldWalkway from bigworld import BlockworldBigworld # from blockworld_env.envs.walkway import BlockworldWalkwayEnv
[ 6738, 2512, 6894, 62, 11152, 1014, 1330, 9726, 6894, 35963, 1014, 198, 6738, 1263, 6894, 1330, 9726, 6894, 12804, 6894, 198, 198, 2, 422, 2512, 6894, 62, 24330, 13, 268, 14259, 13, 11152, 1014, 1330, 9726, 6894, 35963, 1014, 4834, 85, ...
3.642857
42
import rpy2.robjects as ro from rpy2.robjects.packages import importr from rpy2.robjects import pandas2ri from rpy2.robjects.conversion import localconverter
[ 11748, 374, 9078, 17, 13, 22609, 752, 82, 355, 686, 198, 6738, 374, 9078, 17, 13, 22609, 752, 82, 13, 43789, 1330, 1330, 81, 198, 6738, 374, 9078, 17, 13, 22609, 752, 82, 1330, 19798, 292, 17, 380, 198, 6738, 374, 9078, 17, 13, ...
2.854545
55
""" Server """ import asyncio import logging import os from typing import Optional from hypercorn.asyncio import serve from hypercorn.config import Config import uvicorn from sysmon.app import make_application LOGGER = logging.getLogger(__name__) def initialise_logging() -> None: """Initialise logging""" logging.config.dictConfig({ 'version': 1, 'formatters': { 'simple': { 'format': "%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, 'handlers': { 'stdout': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'stream': 'ext://sys.stdout' } }, 'loggers': { __name__: { 'level': 'DEBUG', 'handlers': ['stdout'], 'propagate': False }, 'bareasgi_graphql_next': { 'level': 'DEBUG', 'handlers': ['stdout'], 'propagate': False }, 'bareasgi': { 'level': 'DEBUG', 'handlers': ['stdout'], 'propagate': False } }, 'root': { 'level': 'DEBUG', 'handlers': ['stdout'] } }) def start_uvicorn_server( host: str, port: int, ssl_enabled: bool = False, keyfile: Optional[str] = None, certfile: Optional[str] = None ) -> None: """Start the uvicorn server""" app = make_application() kwargs = { 'host': host, 'port': port, # 'loop': 'asyncio' } if ssl_enabled: kwargs['ssl_keyfile'] = keyfile kwargs['ssl_certfile'] = certfile uvicorn.run(app, **kwargs) def start_hypercorn_server( host: str, port: int, ssl_enabled: bool = False, keyfile: Optional[str] = None, certfile: Optional[str] = None ) -> None: """Start the hypercorn server""" app = make_application() web_config = Config() web_config.bind = [f'{host}:{port}'] if ssl_enabled: web_config.keyfile = keyfile web_config.certfile = certfile asyncio.run(serve(app, web_config)) # type: ignore def start_http_server( http_server: str, host: str, port: int, ssl_enabled: bool = False, keyfile: Optional[str] = None, certfile: Optional[str] = None ) -> None: """Start the http server""" if http_server == "uvicorn": start_uvicorn_server(host, port, ssl_enabled, keyfile, certfile) elif http_server == "hypercorn": start_hypercorn_server(host, port, ssl_enabled, keyfile, certfile) else: LOGGER.error('Unknown http server "%s"', http_server) raise Exception(f'Unknown http server "{http_server}"') def start_server() -> None: """Start the server""" http_server = 'hypercorn' # 'hypercorn' or 'uvicorn' host = '0.0.0.0' port = 9009 ssl_enabled = False certfile = os.path.expanduser('~/.keys/server.crt') keyfile = os.path.expanduser('~/.keys/server.key') # certfile = os.path.expanduser('~/.keys/www.jetblack.net.crt') # keyfile = os.path.expanduser('~/.keys/www.jetblack.net.key') initialise_logging() start_http_server(http_server, host, port, ssl_enabled, keyfile, certfile) logging.shutdown() if __name__ == "__main__": start_server()
[ 37811, 198, 10697, 198, 37811, 198, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 8718, 20772, 13, 292, 13361, 952, 1330, 4691, 198, 6738, 8718, 20772, 13, 11250, 1330, 17056,...
2.072619
1,680
# Copyright 2016 EMC Corporation # 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. """The volumes snapshots V3 api.""" import ast from oslo_log import log as logging from cinder.api import common from cinder.api.openstack import wsgi from cinder.api.v2 import snapshots as snapshots_v2 from cinder.api.v3.views import snapshots as snapshot_views from cinder import utils LOG = logging.getLogger(__name__) class SnapshotsController(snapshots_v2.SnapshotsController): """The Snapshots API controller for the OpenStack API.""" _view_builder_class = snapshot_views.ViewBuilder def _get_snapshot_filter_options(self): """returns tuple of valid filter options""" return 'status', 'volume_id', 'name', 'metadata' def _format_snapshot_filter_options(self, search_opts): """Convert valid filter options to correct expected format""" # Get the dict object out of queried metadata # convert metadata query value from string to dict if 'metadata' in search_opts.keys(): try: search_opts['metadata'] = ast.literal_eval( search_opts['metadata']) except (ValueError, SyntaxError): LOG.debug('Could not evaluate value %s, assuming string', search_opts['metadata']) @common.process_general_filtering('snapshot') def _process_snapshot_filtering(self, context=None, filters=None, req_version=None): """Formats allowed filters""" # if the max version is less than or same as 3.21 # metadata based filtering is not supported if req_version.matches(None, "3.21"): filters.pop('metadata', None) # Filter out invalid options allowed_search_options = self._get_snapshot_filter_options() utils.remove_invalid_filter_options(context, filters, allowed_search_options) def _items(self, req, is_detail=True): """Returns a list of snapshots, transformed through view builder.""" context = req.environ['cinder.context'] req_version = req.api_version_request # Pop out non search_opts and create local variables search_opts = req.GET.copy() sort_keys, sort_dirs = common.get_sort_params(search_opts) marker, limit, offset = common.get_pagination_params(search_opts) # process filters self._process_snapshot_filtering(context=context, filters=search_opts, req_version=req_version) # process snapshot filters to appropriate formats if required self._format_snapshot_filter_options(search_opts) req_version = req.api_version_request if req_version.matches("3.30", None) and 'name' in sort_keys: sort_keys[sort_keys.index('name')] = 'display_name' # NOTE(thingee): v3 API allows name instead of display_name if 'name' in search_opts: search_opts['display_name'] = search_opts.pop('name') snapshots = self.volume_api.get_all_snapshots(context, search_opts=search_opts, marker=marker, limit=limit, sort_keys=sort_keys, sort_dirs=sort_dirs, offset=offset) req.cache_db_snapshots(snapshots.objects) if is_detail: snapshots = self._view_builder.detail_list(req, snapshots.objects) else: snapshots = self._view_builder.summary_list(req, snapshots.objects) return snapshots
[ 2, 15069, 1584, 412, 9655, 10501, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
2.285641
1,943
# encoding: utf8 from django.http.response import JsonResponse from .throttling import AnonRateThrottle from .settings import THROTTLE_TRIGGER_RESPONSE
[ 2, 21004, 25, 3384, 69, 23, 198, 198, 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 449, 1559, 31077, 198, 198, 6738, 764, 26110, 926, 1359, 1330, 49347, 32184, 817, 305, 23296, 198, 6738, 764, 33692, 1330, 35383, 29089, 2538, 62, 54...
3.1
50
from django.contrib import admin from .models import User # Register your models here. @admin.register(User)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 11787, 198, 2, 17296, 534, 4981, 994, 13, 198, 31, 28482, 13, 30238, 7, 12982, 8, 198 ]
3.548387
31
dictionary = dict()
[ 67, 14188, 796, 8633, 3419, 628 ]
3.5
6
### migrates data from titanic.csv to postgresql # load titanic data import pandas as pd url = 'https://raw.githubusercontent.com/jonDuke/DS-Unit-3-Sprint-2-SQL-and-Databases/master/module2-sql-for-analysis/titanic.csv' df = pd.read_csv(url) # df.columns = ['Survived', 'Pclass', 'Name', 'Sex', 'Age', # 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare'] # load environment variables import os from dotenv import load_dotenv load_dotenv() DB_NAME=os.getenv('DB_NAME', default='OOPS') DB_USER=os.getenv('DB_USER') DB_PASSWORD=os.getenv('DB_PASSWORD') DB_HOST=os.getenv('DB_HOST') # open the PostGreSQL connection import psycopg2 from psycopg2.extras import execute_values conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST) cursor = conn.cursor() # create enum we will use (does nothing if the enum already exists) enum_query = """ DO $$ BEGIN CREATE TYPE sex AS ENUM ('male', 'female'); EXCEPTION WHEN duplicate_object THEN null; END $$; """ cursor.execute(enum_query) # create the table if it doesn't already exist # SMALLINT limits: [-32768,32768] # longest name entry in this file is 81 characters table_query = """ CREATE TABLE IF NOT EXISTS titanic ( id SERIAL PRIMARY KEY, survived SMALLINT, class SMALLINT, name VARCHAR(100), sex sex, age SMALLINT, siblings_spouses SMALLINT, parents_children SMALLINT, fare NUMERIC );""" cursor.execute(table_query) # set up the insertion query cols = 'survived, class, name, sex, age, siblings_spouses, parents_children, fare' insertion_query = f'INSERT INTO titanic ({cols}) VALUES %s' # set up the data array data = [] for i in range(len(df)): # data.append(df.iloc[i].tolist()) # I wish this worked # psycopg2 doesn't recognize datatype numpy.int64, so convert types myself row = df.iloc[i] data.append([int(row['Survived']), int(row['Pclass']), row['Name'], row['Sex'], int(row['Age']), int(row['Siblings/Spouses Aboard']), int(row['Parents/Children Aboard']), float(row['Fare'])]) # insert rows into the table execute_values(cursor, insertion_query, data) # commit changes conn.commit() # close the connection once we're done cursor.close() conn.close()
[ 21017, 15720, 689, 1366, 422, 5259, 26277, 13, 40664, 284, 1281, 34239, 13976, 201, 198, 201, 198, 2, 3440, 5259, 26277, 1366, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6371, 796, 705, 5450, 1378, 1831, 13, 12567, 43667, 13...
2.456231
971
import os from typing import List def filtered_search_list(search: str, keys) -> List[str]: """ Filters the search list by a search string :param search: the string prefix :param keys: the list of strings to search :return: filtered list """ return list(filter(lambda x: (search.lower()) in x.lower(), keys)) def where_am_i(cmd_line, word_before_cursor): """ Tells the autocomplete which word it is completing. It requires a little extra care because we want to differentiate when a space is pressed. :param cmd_line: the list of command line words :param word_before_cursor: word_before_cursor parsed from the document :return: the position of the word we are on. """ if len(cmd_line) == 1 and cmd_line[0] == '': return 0 elif word_before_cursor == '': return len(cmd_line) + 1 else: return len(cmd_line) def position_util(cmd_line: List[str], word_position: int, word_before_cursor: str) -> bool: """ Util method for autocompletion conditions. Makes autocomplete work well. :param cmd_line: the list of command line words :param word_position: the position of the word we are attempting to autocomplete :param word_before_cursor: word_before_cursor parsed from the document :return: True if we should try to autocomplete this word. """ # Special case for no characters typed yet (we send in [''] as cmd_line which fucks with the logic) if word_position == 1 and len(cmd_line) == 1 and cmd_line[0] == '': return True # Don't keep completing after the word position # Don't complete if we just hit space after the word position # Don't complete on the previous word position until there is a space return len(cmd_line) < word_position + 1\ and not (len(cmd_line) == word_position and word_before_cursor == '')\ and not (len(cmd_line) == word_position - 1 and word_before_cursor != '') def complete_path(file_type: str): """ Completion of file paths. """ filenames = [] for filename in os.listdir(): if not filename.lower().endswith(file_type): continue else: filenames.append(filename) return filenames
[ 11748, 28686, 198, 198, 6738, 19720, 1330, 7343, 628, 198, 4299, 29083, 62, 12947, 62, 4868, 7, 12947, 25, 965, 11, 8251, 8, 4613, 7343, 58, 2536, 5974, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 7066, 1010, 262, 2989, 1351, 416...
2.853875
787
# -*- coding: utf-8 -*- """ Numerical Methods, lab 2 """ import sympy as sy from sympy import Rational as syR from sympy import exp, sin, cos, sqrt, log, ln from sympy import pi, cot, sinh, cosh, atan, tan # Это был Task_db Tasks_db = { 'Task1': [ # 2.1.1 {'f': lambda x: sin(x)**2 - syR(5, 6)*sin(x) + syR(1, 6), 'g': lambda x: sin(x)**2 - sin(x) + syR(1, 4), 'a': 0, 'b': 1 }, # 2.1.2 {'f': lambda x: sin(x)**2 + syR(7, 12)*sin(x) + syR(1, 12), 'g': lambda x: sin(x)**2 + syR(2, 3)*sin(x) + syR(1, 9), 'a': -1, 'b': 0 }, # 2.1.3 {'f': lambda x: sin(x)**2 - syR(1, 30)*sin(x) - syR(1, 30), 'g': lambda x: sin(x)**2 - syR(2, 5)*sin(x) + syR(1, 25), 'a': -0.5, 'b': 0.5 }, # 2.1.4 {'f': lambda x: cos(x)**2 + syR(2, 35)*cos(x) - syR(1, 35), 'g': lambda x: cos(x)**2 - syR(2, 7)*cos(x) + syR(1, 49), 'a': 0, 'b': 2 }, # 2.1.5 {'f': lambda x: cos(x)**2 - (1/sqrt(2)+syR(1, 4))*cos(x) + (1/4*sqrt(2)), 'g': lambda x: cos(x)**2 - (2/sqrt(2))*cos(x) + syR(1, 2), 'a': 0, 'b': 1.5 }, # 2.1.6 {'f': lambda x: cos(x)**2 + syR(1, 2)*cos(x) + syR(1, 18), 'g': lambda x: cos(x)**2 + syR(1, 3)*cos(x) + syR(1, 36), 'a': 0, 'b': 2 }, # 2.1.7 {'f': lambda x: ln(x)**2 - 5*ln(x) + 6, 'g': lambda x: ln(x)**2 - 4*ln(x) + 4, 'a': 5, 'b': 25 }, # 2.1.8 {'f': lambda x: ln(x)**2 - ln(x) - 2, 'g': lambda x: ln(x)**2 + 2*ln(x) + 1, 'a': 0.1, 'b': 10 }, # 2.1.9 {'f': lambda x: ln(x)**2 - syR(3, 4)*ln(x) + syR(1, 8), 'g': lambda x: ln(x)**2 - ln(x) + syR(1, 4), 'a': 0.1, 'b': 2 }, # 2.1.10 {'f': lambda x: tan(x)**2 + (sqrt(3) - 1)*tan(x) - sqrt(3), 'g': lambda x: tan(x)**2 - 2*tan(x) + 1, 'a': -1.2, 'b': 1 }, # 2.1.11 {'f': lambda x: tan(x)**2 - (syR(28, 9)*tan(x) + syR(1, 3)), 'g': lambda x: tan(x)**2 - 6*tan(x) + 9, 'a': 0, 'b': 1.5 }, # 2.1.12 {'f': lambda x: tan(x)**2 - syR(53, 6)*tan(x) - syR(3, 2), 'g': lambda x: tan(x)**2 - syR(1, 3)*tan(x) + syR(1, 36), 'a': -0.5, 'b': 1.5 }, # 2.1.13 {'f': lambda x: x**4 - 7*x**2 +10, 'g': lambda x: x**4 - 4*x**2 + 4, 'a': 0, 'b': 3 }, # 2.1.14 {'f': lambda x: x**4 - syR(10, 3)*x**2 + 1, 'g': lambda x: x**4 - 6*x**2 + 9, 'a': 0, 'b': 2 }, # 2.1.15 {'f': lambda x: x**4 - syR(13, 2)*x**2 + 3, 'g': lambda x: x**4 - x**2 + syR(1, 4), 'a': 0, 'b': 3 }, # 2.1.16 {'f': lambda x: sin(x)**2 + syR(5, 6)*sin(x) + syR(1, 6), 'g': lambda x: sin(x)**2 + syR(2, 3)*sin(x) + syR(1, 9), 'a': -1, 'b': 0 }, # 2.1.17 {'f': lambda x: sin(x)**2 - syR(7, 12)*sin(x) + syR(1, 12), 'g': lambda x: sin(x)**2 - syR(1, 2)*sin(x) + syR(1, 16), 'a': 0, 'b': 1 }, # 2.1.18 {'f': lambda x: sin(x)**2 + syR(1, 30)*sin(x) - syR(1, 30), 'g': lambda x: x**4 + syR(1, 3)*x**2 + syR(1, 36), 'a': -0.5, 'b': 0.5 }, # 2.1.19 {'f': lambda x: cos(x)**2 - syR(2, 35)*cos(x) - syR(1, 35), 'g': lambda x: cos(x)**2 - syR(2, 5)*cos(x) + syR(1, 25), 'a': 0, 'b': 3 }, # 2.1.20 {'f': lambda x: cos(x)**2 + ((1/sqrt(2)) - syR(1, 4))*cos(x) - (1/4*sqrt(2)), 'g': lambda x: cos(x)**2 - syR(1, 2)*cos(x) + syR(1, 16), 'a': 0, 'b': 2 }, # 2.1.21 {'f': lambda x: cos(x)**2 - syR(1, 2)*cos(x) + syR(1, 18), 'g': lambda x: cos(x)**2 - syR(2, 3)*cos(x) + syR(1, 9), 'a': 0, 'b': 2 }, # 2.1.22 {'f': lambda x: log(x, 10)**2 + syR(5, 3)*log(x, 10) - syR(2, 3), 'g': lambda x: log(x, 10)**2 - syR(2, 3)*log(x, 10) + syR(1, 9), 'a': 0.001, 'b': 3 }, # 2.1.23 {'f': lambda x: log(x, 10)**2 - log(x, 10) - syR(3, 4), 'g': lambda x: log(x, 10)**2 - 3*log(x, 10) + syR(9, 4), 'a': 0.1, 'b': 35 }, # 2.1.24 {'f': lambda x: log(x, 10)**2 + syR(3, 4)*log(x, 10) - syR(1, 4), 'g': lambda x: log(x, 10)**2 + 2*log(x, 10) + 1, 'a': 0.01, 'b': 3 }, # 2.1.25 {'f': lambda x: tan(x)**2 - (1 + (1/sqrt(3)))*tan(x) + (1/sqrt(3)), 'g': lambda x: tan(x)**2 - 2*tan(x) + 1, 'a': 0, 'b': 1 }, # 2.1.26 {'f': lambda x: tan(x)**2 - syR(7, 4)*tan(x) - syR(1, 2), 'g': lambda x: tan(x)**2 + syR(1, 2)*tan(x) + syR(1, 16), 'a': -0.5, 'b': 1.5 }, # 2.1.27 {'f': lambda x: tan(x)**2 + syR(37, 6)*tan(x) + 1, 'g': lambda x: tan(x)**2 + 12*tan(x) + 36, 'a': -1.5, 'b': 0 }, # 2.1.28 {'f': lambda x: x**4 - 11*x**2 + 24, 'g': lambda x: x**4 - 6*x**2 + 9, 'a': 1, 'b': 3 }, # 2.1.29 {'f': lambda x: x**4 - syR(26, 5)*x**2 + 1, 'g': lambda x: x**4 - 10*x**2 + 25, 'a': 0, 'b': 3 }, # 2.1.30 {'f': lambda x: x**4 - syR(21, 2)*x**2 + 5, 'g': lambda x: x**4 - x**2 + syR(1, 4), 'a': 0, 'b': 5 } ], 'Task2': [ # 2.2.1 {'f': lambda x: exp(-x) - 2 + x**2, 'which': 'отрицательный'}, # 2.2.2 {'f': lambda x: x*exp(-x) - x - 1, 'which': 'положительный'}, # 2.2.3 {'f': lambda x: exp(x) + 1 - sqrt(9 - x**2), 'which': 'положительный'}, # 2.2.4 {'f': lambda x: (x+1)*exp(x+1) - x - 2, 'which': 'наибольший по модулю'}, # 2.2.5 {'f': lambda x: sqrt(x) - cos(x), 'which': 'все корни'} ], 'Task3': [ # 2.3.1 {'f': lambda x: sin(x) + 2*x**2 + 4*x}, # 2.3.2 {'f': lambda x: exp(-x) - lg(1-x**2) -2}, # 2.3.3 {'f': lambda x: sin(x+2) - x**2 + 2*x - 1}, # 2.3.4 {'f': lambda x: (x-1)*sinh(x+1) - x}, # 2.3.5 {'f': lambda x: x - exp(-x**2)} ] }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 45, 6975, 605, 25458, 11, 2248, 362, 198, 37811, 198, 198, 11748, 10558, 88, 355, 827, 198, 6738, 10558, 88, 1330, 46863, 355, 827, 49, 198, 6738, 10558, 8...
1.511923
4,026
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np; a = np.array([3.0, 3.0, 2.0, 4.9, 100.2, -8.9]); # 数值微分求标准差梯度 grad = gradient(); print(grad); n1 = func2(0); n2 = func2(1); n3 = func2(2); n4 = func2(3); n5 = func2(4); n6 = func2(5); b = [n1, n2, n3, n4, n5, n6]; print(b);
[ 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, 11748, 299, 32152, 355, 45941, 26, 198, 198, 64, 796, 45941, 13, 18747, 26933, 18, 13, 15, 11, 513, 13, 15...
1.609626
187
import argparse import json import numpy as np from utils.file_utils import read_jsonl_lines, read_lines if __name__ == '__main__': parser = argparse.ArgumentParser( description='Script to compute corpus satistics') # Required Parameters parser.add_argument('--input_file', type=str, help='Location of data', default=None) parser.add_argument('--label_file', type=str, help='Location of data', default=None) args = parser.parse_args() print('====Input Arguments====') print(json.dumps(vars(args), indent=2, sort_keys=True)) print("=======================") main(args)
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 3384, 4487, 13, 7753, 62, 26791, 1330, 1100, 62, 17752, 75, 62, 6615, 11, 1100, 62, 6615, 628, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624,...
2.957143
210
from django.db import models from api.user.models import CustomUser from api.product.models import Product # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 40391, 13, 7220, 13, 27530, 1330, 8562, 12982, 198, 6738, 40391, 13, 11167, 13, 27530, 1330, 8721, 198, 2, 13610, 534, 4981, 994, 13, 628, 198 ]
3.885714
35
from bilibili import bilibili from login import login import time import datetime import asyncio from printer import Printer # 因为休眠时间差不多,所以放到这里,此为实验性功能
[ 6738, 275, 22282, 2403, 1330, 275, 22282, 2403, 198, 6738, 17594, 1330, 17594, 198, 11748, 640, 198, 11748, 4818, 8079, 198, 11748, 30351, 952, 198, 6738, 20632, 1330, 1736, 3849, 628, 628, 220, 220, 220, 1303, 10263, 249, 254, 10310, 1...
1.870588
85
# 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. import os try: import json except ImportError: import simplejson from libcloud.common.base import Response from libcloud.resource.lb.base import LB, LBNode, LBDriver from libcloud.resource.lb.types import Provider, LBState from libcloud.common.rackspace import (AUTH_HOST_US, RackspaceBaseConnection)
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428, 670, 329, 3224, 1321, 5115, 6634, 9238, 13, 198, 2, 383, 7054, 37, ...
3.773973
292
# coding=utf-8 """ 文件处理读取写入 """ from __future__ import print_function from __future__ import division from __future__ import absolute_import import logging import os import shutil from contextlib import contextmanager import functools import pandas as pd from .ABuDTUtil import warnings_filter # noinspection PyUnresolvedReferences from ..CoreBu.ABuFixes import pickle, Pickler, Unpickler, as_bytes """HDF5_COMP_LEVEL:压缩级别:0-9,如果修改了压缩级别,需要删除之前的物理文件""" HDF5_COMP_LEVEL = 4 """ HDF5_COMP_LIB: 使用的压缩库:'blosc', 'bzip2', 'lzo', 'zlib', 如果修改了压缩库,需要删除之前的物理文件""" HDF5_COMP_LIB = 'blosc' """HDF5内部存贮依然会使用pickle,即python版本切换,本地文件会有协议冲突:使用所支持的最高协议进行dump""" K_SET_PICKLE_HIGHEST_PROTOCOL = False """HDF5内部存贮依然会使用pickle,即python版本切换,本地文件会有协议冲突:python2, python3协议兼容模式,使用protocol=0""" K_SET_PICKLE_ZERO_PROTOCOL = False def ensure_dir(a_path): """ 确保a_path所在路径文件夹存在,如果a_path是文件将确保它上一级 文件夹的存在 :param a_path: str对象, 相对路径或者绝对路径 """ if os.path.isdir(a_path): a_dir = a_path else: a_dir = os.path.dirname(a_path) if not os.path.exists(a_dir): os.makedirs(a_dir) def ensure_file(a_path): """ 确保a_path所在路径文件存在,首先会使用ensure_dir确保文件夹存在, 确定a_path是file会确保文件存在 :param a_path: str对象, 相对路径或者绝对路径 :return: """ ensure_dir(a_path) open(a_path, 'a+').close() def file_exist(a_path): """ a_path是否存在 :param a_path: str对象, 相对路径或者绝对路径 """ return os.path.exists(a_path) def copy_file(source, target_dir): """ 拷贝文件操作,支持文件夹拷贝操作 :param source: 文件名或者文件夹,str对象, 相对路径或者绝对路径 :param target_dir: 文件名或者文件夹,str对象, 相对路径或者绝对路径 """ if os.path.exists(source): logging.error('copy_file source={} not exists!'.format(source)) return ensure_dir(target_dir) if os.path.isdir(source): shutil.copytree(source, target_dir) else: shutil.copy(source, target_dir) def del_file(a_path): """ 删除文件操作,支持文件夹删除操作 :param a_path: 文件名或者文件夹,str对象, 相对路径或者绝对路径 """ if not file_exist(a_path): return if os.path.isdir(a_path): shutil.rmtree(a_path) else: os.remove(a_path) def load_pickle(file_name): """ 读取python序列化的本地文件 :param file_name: 文件名,str对象, 相对路径或者绝对路径 :return: """ if not file_exist(file_name): logging.error('load_pickle file_name={} not exists!'.format(file_name)) return None # TODO 根据文件大小,决定这里是否需要tip wait print('please wait! load_pickle....:', file_name) try: with open(file_name, "rb") as unpickler_file: unpickler = Unpickler(unpickler_file) ret = unpickler.load() except EOFError: print('unpickler file with EOFError, please check {} is 0kb!!!'.format(file_name)) ret = {} return ret def dump_pickle(input_obj, file_name, how='normal'): """ 存贮python序列化的本地文件 :param input_obj: 需要进行序列化的对象 :param file_name: 文件名,str对象, 相对路径或者绝对路径 :param how: 序列化协议选择,默认normal不特殊处理, zero使用python2, python3协议兼容模式,使用protocol=0, high使用支持的最高协议 """ ensure_dir(file_name) print('please wait! dump_pickle....:', file_name) try: with open(file_name, "wb") as pick_file: if K_SET_PICKLE_HIGHEST_PROTOCOL or how == 'high': """使用所支持的最高协议进行dump""" pickle.dump(input_obj, pick_file, pickle.HIGHEST_PROTOCOL) elif K_SET_PICKLE_ZERO_PROTOCOL or how == 'zero': """python2, python3协议兼容模式,使用protocol=0""" pickle.dump(input_obj, pick_file, 0) else: pickler = Pickler(pick_file) pickler.dump(input_obj) except Exception as e: logging.exception(e) """hdf5批量处理时保存HDFStore对象,为避免反复open,close""" __g_batch_h5s = None def __start_batch_h5s(file_name, mode): """ 使用pd.HDFStore打开file_name对象保存在全局__g_batch_h5s中 :param file_name: hdf5文件路径名 :param mode: 打开hdf5文件模式。eg:w, r, a """ global __g_batch_h5s __g_batch_h5s = pd.HDFStore(file_name, mode, complevel=HDF5_COMP_LEVEL, complib=HDF5_COMP_LIB) def __end_batch_h5s(): """ 如果__g_batch_h5s中hdf5对象仍然是打开的,进行flush,后close """ global __g_batch_h5s if __g_batch_h5s is not None and __g_batch_h5s.is_open: __g_batch_h5s.flush() __g_batch_h5s.close() __g_batch_h5s = None def batch_h5s(h5_fn, mode='a'): """ 使用装饰器方式对hdf5操作进行批量处理,外部使用: eg: 详见ABuSymbolPd.py @batch_h5s(h5s_fn) def _batch_save(): for df_dict in df_dicts: # 每一个df_dict是一个并行的序列返回的数据 for ind, (key_tuple, df) in enumerate(df_dict.values()): # (key_tuple, df)是保存kl需要的数据, 迭代后直接使用save_kline_df save_kline_df(df, *key_tuple) if df is not None: print("save kl {}_{}_{} {}/{}".format(key_tuple[0].value, key_tuple[1], key_tuple[2], ind, df.shape[0])) # 完成一层循环一次,即批量保存完一个并行的序列返回的数据后,进行清屏 do_clear_output() :param h5_fn: hdf5文件路径名, 如果为None。即忽略整个批处理流程 :param mode: 打开hdf5文件模式。eg:w, r, a :return: """ return _batch_h5s @contextmanager def batch_ctx_h5s(h5_fn, mode='a'): """ 使用上下文管理器方式对hdf5操作进行批量处理,与装饰器模式batch_h5s 功能相同,为外部不方便封装为具体操作函数时使用 eg: with batch_ctx_h5s(h5s_fn): for df_dict in df_dicts: # 每一个df_dict是一个并行的序列返回的数据 for ind, (key_tuple, df) in enumerate(df_dict.values()): # (key_tuple, df)是保存kl需要的数据, 迭代后直接使用save_kline_df save_kline_df(df, *key_tuple) if df is not None: print("save kl {}_{}_{} {}/{}".format(key_tuple[0].value, key_tuple[1], key_tuple[2], ind, df.shape[0])) # 完成一层循环一次,即批量保存完一个并行的序列返回的数据后,进行清屏 do_clear_output() :param h5_fn: hdf5文件路径名, 如果为None。即忽略整个批处理流程 :param mode: 打开hdf5文件模式。eg:w, r, a :return: """ if h5_fn is not None: __start_batch_h5s(h5_fn, mode) yield if h5_fn is not None: __end_batch_h5s() @warnings_filter def dump_del_hdf5(file_name, dump_dict, del_array=None): """ 对hdf5进行删除和保存操作,del_array中的key先删除,后保存dump_dict 字典中的数据 :param file_name: hdf5文件路径名 :param dump_dict: 需要保存到hdf5中的数据字典 :param del_array: 需要从hdf5中删除的key序列 """ global __g_batch_h5s def do_dump_del_hdf5(h5s): """ 对hdf5进行删除和保存操作执行函数 :param h5s: hdf5对象句柄 :return: """ if del_array is not None: # 先执行删除操作 for del_key in del_array: if h5s.__contains__(del_key): del h5s[del_key] for input_key in dump_dict: input_obj = dump_dict[input_key] h5s[input_key] = input_obj if __g_batch_h5s is None: # 如果批处理句柄没有打着,使用with pd.HDFStore先打开 with pd.HDFStore(file_name, 'a', complevel=HDF5_COMP_LEVEL, complib=HDF5_COMP_LIB) as h5s_obj: do_dump_del_hdf5(h5s_obj) else: # 使用批处理句柄__g_batch_h5s操作 do_dump_del_hdf5(__g_batch_h5s) @warnings_filter def dump_hdf5(file_name, input_obj, input_key): """ 对hdf5进行保存操作 :param file_name: hdf5文件路径名 :param input_obj: 保存的数据对象 :param input_key: 保存的数据key """ global __g_batch_h5s if __g_batch_h5s is None: # 如果批处理句柄没有打着,使用with pd.HDFStore先打开 with pd.HDFStore(file_name, 'a', complevel=HDF5_COMP_LEVEL, complib=HDF5_COMP_LIB) as h5s: h5s[input_key] = input_obj else: # 使用批处理句柄__g_batch_h5s操作 __g_batch_h5s[input_key] = input_obj def del_hdf5(file_name, key): """ 对hdf5进行删除操作 :param file_name: hdf5文件路径名 :param key: 保存的数据key """ if not file_exist(file_name): return if __g_batch_h5s is None: # 如果批处理句柄没有打着,使用with pd.HDFStore先打开 with pd.HDFStore(file_name, 'a', complevel=HDF5_COMP_LEVEL, complib=HDF5_COMP_LIB) as h5s: if h5s.__contains__(key): del h5s[key] else: # 使用批处理句柄__g_batch_h5s操作 if __g_batch_h5s.__contains__(key): del __g_batch_h5s[key] def load_hdf5(file_name, key): """ 读取hdf5中的数据 :param file_name: df5文件路径名 :param key: 保存的数据key """ global __g_batch_h5s if not file_exist(file_name): return None if __g_batch_h5s is None: # 如果批处理句柄没有打着,使用with pd.HDFStore先打开 with pd.HDFStore(file_name, 'a', complevel=HDF5_COMP_LEVEL, complib=HDF5_COMP_LIB) as h5s_obj: return _load_hdf5(h5s_obj) else: # 使用批处理句柄__g_batch_h5s操作 return _load_hdf5(__g_batch_h5s) def dump_df_csv(file_name, df): """ 将pd.DataFrame对象保存在csv中 :param file_name: 保存csv的文件名称 :param df: 需要保存的pd.DataFrame对象 """ if df is not None: # TODO 为效率,不应该在函数内部ensure_dir,确保使用dump_df_csv需要在外部ensure_dir ensure_dir(file_name) df.to_csv(file_name, columns=df.columns, index=True, encoding='utf-8') def load_df_csv(file_name): """ 从csv文件中实例化pd.DataFrame对象 :param file_name: 保存csv的文件名称 :return: pd.DataFrame对象 """ if file_exist(file_name): return pd.read_csv(file_name, index_col=0) return None def save_file(ct, file_name): """ 将内容ct保存文件 :param ct: 内容str对象 :param file_name: 保存的文件名称 :return: """ ensure_dir(file_name) with open(file_name, 'wb') as f: f.write(ct)
[ 2, 19617, 28, 40477, 12, 23, 198, 37811, 198, 220, 220, 220, 10545, 244, 229, 20015, 114, 13783, 226, 49426, 228, 46237, 119, 20998, 244, 37863, 247, 17739, 98, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738...
1.382236
7,014
# -*- coding: utf-8 -*- from django.contrib import admin from extra_settings.forms import SettingForm from extra_settings.models import Setting admin.site.register(Setting, SettingAdmin)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 3131, 62, 33692, 13, 23914, 1330, 25700, 8479, 198, 6738, 3131, 62, 33692, 13, 27530, 1330, 25700, 6...
3.350877
57
import sqlite3 import re import scrapy from scrapy import Request # 这个类在最终整合后不再使用
[ 11748, 44161, 578, 18, 198, 11748, 302, 198, 11748, 15881, 88, 198, 6738, 15881, 88, 1330, 19390, 198, 198, 2, 5525, 123, 247, 10310, 103, 163, 109, 119, 28839, 101, 17312, 222, 163, 119, 230, 46763, 112, 28938, 230, 28938, 236, 38834...
1.729167
48
"""A global object for debug rendering into images without around.""" import cv2 # ----------------------------------------------------------------------------- # Copyright (C) 2018 Angelos Evripiotis. # # 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. # ------------------------------ END-OF-FILE ----------------------------------
[ 37811, 32, 3298, 2134, 329, 14257, 14837, 656, 4263, 1231, 1088, 526, 15931, 198, 198, 11748, 269, 85, 17, 628, 198, 198, 2, 16529, 32501, 198, 2, 15069, 357, 34, 8, 2864, 3905, 418, 4319, 5528, 5151, 271, 13, 198, 2, 198, 2, 4996...
4.310881
193
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info >= (2, 7, 0): _ephemeris_converter = swig_import_helper() del swig_import_helper elif _swig_python_version_info >= (2, 6, 0): _ephemeris_converter = swig_import_helper() del swig_import_helper else: import _ephemeris_converter del _swig_python_version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. try: import builtins as __builtin__ except ImportError: import __builtin__ try: _object = object _newclass = 1 except __builtin__.Exception: _newclass = 0 SwigPyIterator_swigregister = _ephemeris_converter.SwigPyIterator_swigregister SwigPyIterator_swigregister(SwigPyIterator) new_doubleArray = _ephemeris_converter.new_doubleArray delete_doubleArray = _ephemeris_converter.delete_doubleArray doubleArray_getitem = _ephemeris_converter.doubleArray_getitem doubleArray_setitem = _ephemeris_converter.doubleArray_setitem new_longArray = _ephemeris_converter.new_longArray delete_longArray = _ephemeris_converter.delete_longArray longArray_getitem = _ephemeris_converter.longArray_getitem longArray_setitem = _ephemeris_converter.longArray_setitem new_intArray = _ephemeris_converter.new_intArray delete_intArray = _ephemeris_converter.delete_intArray intArray_getitem = _ephemeris_converter.intArray_getitem intArray_setitem = _ephemeris_converter.intArray_setitem new_shortArray = _ephemeris_converter.new_shortArray delete_shortArray = _ephemeris_converter.delete_shortArray shortArray_getitem = _ephemeris_converter.shortArray_getitem shortArray_setitem = _ephemeris_converter.shortArray_setitem new_boolArray = _ephemeris_converter.new_boolArray delete_boolArray = _ephemeris_converter.delete_boolArray boolArray_getitem = _ephemeris_converter.boolArray_getitem boolArray_setitem = _ephemeris_converter.boolArray_setitem IntVector_swigregister = _ephemeris_converter.IntVector_swigregister IntVector_swigregister(IntVector) DoubleVector_swigregister = _ephemeris_converter.DoubleVector_swigregister DoubleVector_swigregister(DoubleVector) StringVector_swigregister = _ephemeris_converter.StringVector_swigregister StringVector_swigregister(StringVector) StringSet_swigregister = _ephemeris_converter.StringSet_swigregister StringSet_swigregister(StringSet) intSet_swigregister = _ephemeris_converter.intSet_swigregister intSet_swigregister(intSet) ConstCharVector_swigregister = _ephemeris_converter.ConstCharVector_swigregister ConstCharVector_swigregister(ConstCharVector) MultiArray_swigregister = _ephemeris_converter.MultiArray_swigregister MultiArray_swigregister(MultiArray) map_string_string_swigregister = _ephemeris_converter.map_string_string_swigregister map_string_string_swigregister(map_string_string) SysModel_swigregister = _ephemeris_converter.SysModel_swigregister SysModel_swigregister(SysModel) EphemerisConverter_swigregister = _ephemeris_converter.EphemerisConverter_swigregister EphemerisConverter_swigregister(EphemerisConverter) EphemerisIntMsg_swigregister = _ephemeris_converter.EphemerisIntMsg_swigregister EphemerisIntMsg_swigregister(EphemerisIntMsg) sizeof_EphemerisIntMsg = _ephemeris_converter.sizeof_EphemerisIntMsg import sys protectAllClasses(sys.modules[__name__]) # This file is compatible with both classic and new-style classes.
[ 2, 770, 2393, 373, 6338, 7560, 416, 12672, 3528, 357, 4023, 1378, 2503, 13, 2032, 328, 13, 2398, 737, 198, 2, 10628, 513, 13, 15, 13, 1065, 198, 2, 198, 2, 2141, 407, 787, 2458, 284, 428, 2393, 4556, 345, 760, 644, 345, 389, 180...
2.882448
1,242
""" Do not import this file. NOTE: THIS RUNS ON PYTHON 3.10 """ # exit codes: # 0: success # 1: indeterminate error # 2: module not resolvable # 3: attribute does not exist # 4: invalid characters, not a valid object path # 5: dynamically created object # 6: is a builtin object, prints module name # 7: invalid metadata # 8: unsupported package (does not use github) # 9: module found but cannot find class definition if __name__ == "__main__": import importlib import importlib.metadata import importlib.util import inspect import pathlib import pkgutil import sys import tracemalloc import types # establish the object itself object_name = """REPLACE_THIS_STRING_WITH_THE_OBJECT_NAME""" tracemalloc.start() try: src = pkgutil.resolve_name(object_name) except ModuleNotFoundError: sys.exit(2) except AttributeError: sys.exit(3) except ValueError: sys.exit(4) except Exception: raise trace = tracemalloc.get_object_traceback(src) tracemalloc.stop() # get the source of the object try: filename = inspect.getsourcefile(src) except TypeError: if isinstance(src, types.BuiltinFunctionType): sys.exit(6) # if we have to use tracemalloc we have a bit of a problem # the code is dynamically created # this means that we need to establish the file, where the def starts, and where it ends if not trace: sys.exit(5) frame = trace[-1] filename = frame.filename first_lineno = frame.lineno lines_extension = f"#L{frame.lineno}" parents = [] try: name = src.__qualname__ except AttributeError: name = object_name.rsplit(".", 1)[-1] else: if "." in name: parents, name = name.rsplit(".", 1) parents = parents.split(".") try: with open(filename) as f: sourcecode = f.read() except FileNotFoundError: sys.exit(5) # Once we know where the definition starts, we can hopefully use ast for parsing the file import ast parsed = ast.parse(sourcecode, filename=filename) node = None _endlines: set[tuple[int, int]] = set() for node in ast.walk(parsed): if not hasattr(node, "lineno"): continue if node.lineno < first_lineno: continue if isinstance(node, ast.Assign): target = node.targets[0] elif isinstance(node, ast.AnnAssign): target = node.target else: continue if parents: if getattr(target, "attr", None) != name: continue elif getattr(target, "id", None) != name: continue _endlines.add((node.lineno, node.end_lineno)) if _endlines: lineno, end_lineno = sorted(_endlines, key=lambda i: i[0])[0] lines_extension = f"#L{lineno}" if end_lineno > lineno: lines_extension += f"-L{end_lineno}" module_name = object_name.split(":", 1)[0] if ":" in object_name else object_name.rsplit(".", 1)[0] else: if not inspect.ismodule(src): try: lines, first_lineno = inspect.getsourcelines(src) except OSError: print(filename) sys.exit(9) lines_extension = f"#L{first_lineno}-L{first_lineno+len(lines)-1}" else: lines_extension = "" module_name = "" if not filename: sys.exit(6) if not module_name: module_name = inspect.getmodule(src).__name__ top_module_name = module_name.split(".", 1)[0] # determine the actual file name try: filename = str( pathlib.Path(filename).relative_to( pathlib.Path(inspect.getsourcefile(importlib.import_module(top_module_name))).parent.parent ) ) except ValueError: sys.exit(5) # get the version and link to the source of the module if top_module_name in sys.stdlib_module_names: if top_module_name in sys.builtin_module_names: sys.exit(6) # handle the object being part of the stdlib import platform python_version = f"python{platform.python_version().rsplit('.', 1)[0]}/" if filename.startswith(python_version): filename = filename.split("/", 1)[-1] url = f"https://github.com/python/cpython/blob/v{platform.python_version()}/Lib/{filename}{lines_extension}" else: # assume that the source is github try: metadata = importlib.metadata.metadata(top_module_name) except importlib.metadata.PackageNotFoundError: print(f"Sorry, I can't find the metadata for `{object_name}`.") sys.exit(7) # print(metadata.keys()) version = metadata["Version"] for url in [metadata.get("Home-page"), *metadata.json.get("project_url", [])]: url = url.split(",", 1)[-1].strip().rstrip("/") # there are 4 `/` in a github link if url.startswith(("https://github.com/", "http://github.com/")) and url.count("/") == 4: break else: print("This package isn't supported right now.") sys.exit(8) if top_module_name not in ("arrow", "databases", "ormar"): version = f"v{version}" url += f"/blob/{version}/{filename}{lines_extension}" # used to be able to slice code to ignore import side-effects print("#" * 80) print(url)
[ 37811, 198, 5211, 407, 1330, 428, 2393, 13, 198, 198, 16580, 25, 12680, 32494, 50, 6177, 350, 56, 4221, 1340, 513, 13, 940, 198, 37811, 628, 198, 2, 8420, 12416, 25, 198, 2, 657, 25, 1943, 198, 2, 352, 25, 773, 13221, 378, 4049, ...
2.182197
2,640
from .base import * DEBUG = True ALLOWED_HOSTS = ['*'] THIRD_PARTY_APPS += ('debug_toolbar',) # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases MIDDLEWARE.insert(3, 'debug_toolbar.middleware.DebugToolbarMiddleware') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
[ 6738, 764, 8692, 1330, 1635, 198, 198, 30531, 796, 6407, 198, 198, 7036, 3913, 1961, 62, 39, 10892, 50, 796, 37250, 9, 20520, 198, 198, 4221, 46833, 62, 30709, 56, 62, 2969, 3705, 15853, 19203, 24442, 62, 25981, 5657, 3256, 8, 198, ...
2.19209
177
import sortingview as sv import spikeextractors as se recording, sorting = se.example_datasets.toy_example(K=11, duration=60, seed=6) R = sv.LabboxEphysRecordingExtractor.from_memory(recording, serialize=True, serialize_dtype='float32') S = sv.LabboxEphysSortingExtractor.from_memory(sorting, serialize=True) W = sv.create_workspace() recording_id = W.add_recording(label='recording1', recording=R) sorting_id = W.add_sorting(recording_id=recording_id, label='true', sorting=S) W.precalculate() # W._precalculate_debug() F = W.figurl() url = F.url(label='Test workspace') print(url) W.set_sorting_curation_authorized_users(sorting_id=sorting_id, user_ids=['jmagland@flatironinstitute.org']) url2 = W.experimental_spikesortingview(recording_id=recording_id, sorting_id=sorting_id, label='Test workspace', include_curation=True) print(url2)
[ 11748, 29407, 1177, 355, 38487, 198, 11748, 20240, 2302, 974, 669, 355, 384, 198, 198, 8344, 1284, 11, 29407, 796, 384, 13, 20688, 62, 19608, 292, 1039, 13, 83, 726, 62, 20688, 7, 42, 28, 1157, 11, 9478, 28, 1899, 11, 9403, 28, 21...
2.699681
313
import binascii import os from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ __all__ = [ 'MultiToken', ] # Prior to Django 1.5, the AUTH_USER_MODEL setting does not exist. # Note that we don't perform this code in the compat module due to # bug report #1297 # See: https://github.com/tomchristie/django-rest-framework/issues/1297 AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') class MultiToken(models.Model): """ The multi token model with user agent and IP address. """ id = models.AutoField( primary_key=True ) key = models.CharField( _("Key"), max_length=64, db_index=True, unique=True ) user = models.ForeignKey( AUTH_USER_MODEL, related_name='auth_tokens', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField( _("Created"), auto_now_add=True ) last_known_ip = models.GenericIPAddressField( _("The IP address of this session"), default="127.0.0.1" ) user_agent = models.CharField( max_length=256, verbose_name=_("HTTP User Agent"), default="" ) @staticmethod def generate_key(): """ generates a pseudo random code using os.urandom and binascii.hexlify """ return binascii.hexlify(os.urandom(32)).decode()
[ 11748, 9874, 292, 979, 72, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, ...
2.386513
608
import argparse import glob import itertools import multiprocessing as mp import os from functools import partial from subprocess import run import numpy as np import pandas as pd from qpputils import dataparser as dp from Timer import Timer from crossval import InterTopicCrossValidation from query_features import features_loader LAMBDA = np.linspace(start=0, stop=1, num=11) C_PARAMETERS = [0.01, 0.1, 1, 10] PREDICTORS_WO_QF = ['clarity', 'wig', 'nqc', 'smv', 'rsd', 'uef/clarity', 'uef/wig', 'uef/nqc', 'uef/smv'] PRE_RET_PREDICTORS = ['preret/AvgIDF', 'preret/AvgSCQTFIDF', 'preret/AvgVarTFIDF', 'preret/MaxIDF', 'preret/MaxSCQTFIDF', 'preret/MaxVarTFIDF'] PREDICTORS_QF = ['qf', 'uef/qf'] PREDICTORS = PREDICTORS_WO_QF + PRE_RET_PREDICTORS + PREDICTORS_QF SIMILARITY_FUNCTIONS = {'Jac_coefficient': 'jac', 'Top_10_Docs_overlap': 'sim', 'RBO_EXT_100': 'rbo', 'RBO_FUSED_EXT_100': 'rbof'} parser = argparse.ArgumentParser(description='Query Prediction Using Reference lists', usage='python3.6 qpp_ref.py -c CORPUS ... <parameter files>', epilog='Unless --generate is given, will try loading the files') parser.add_argument('-c', '--corpus', type=str, default=None, help='corpus to work with', choices=['ROBUST', 'ClueWeb12B']) parser.add_argument('-p', '--predictor', default=None, type=str, help='Choose the predictor to use', choices=PREDICTORS + ['all']) parser.add_argument('--uef', help='Add this if the predictor is in uef framework', action="store_true") parser.add_argument('-g', '--group', help='group of queries to predict', choices=['top', 'low', 'title', 'medh', 'medl']) parser.add_argument('--quantile', help='quantile of query variants to use for prediction', default='all', choices=['all', 'low', 'low-0', 'high', 'cref']) parser.add_argument('--corr_measure', default='pearson', type=str, choices=['pearson', 'spearman', 'kendall'], help='features JSON file to load') parser.add_argument('--generate', help='use ltr to generate SVM-Rank predictions, or calc to calc predictions', choices=['ltr', 'calc', 'oracle']) class QueryPredictionRef: """The class reads the queries intended for prediction, it's named inside the class as queries_group or qgroup - e.g "title" / "top" .. Also reads a file with the variations without the queries to be predicted, and a file with the features constructed for the relevant queries with the relevant variations""" @classmethod def __set_paths(cls, corpus, predictor, qgroup, vars_quantile): """This method sets the default paths of the files and the working directories, it assumes the standard naming convention of the project""" cls.predictor = predictor _base_dir = f'~/QppUqvProj/Results/{corpus}/uqvPredictions/' cls.vars_results_dir = dp.ensure_dir(f'{_base_dir}/raw/{predictor}/predictions/') if qgroup == 'title': _orig_dir = dp.ensure_dir(f'~/QppUqvProj/Results/{corpus}/basicPredictions/title') cls.base_results_dir = f'{_orig_dir}/{predictor}/predictions/' cls.output_dir = dp.ensure_dir(f'{_base_dir}/referenceLists/{qgroup}/{vars_quantile}_vars/') _test_dir = f'~/QppUqvProj/Results/{corpus}/test' cls.folds = dp.ensure_file(f'{_test_dir}/2_folds_30_repetitions.json') cls.ap_file = dp.ensure_file(f'{_test_dir}/ref/QLmap1000-{qgroup}') # cls.features = '{}/raw/query_features_{}_uqv_legal.JSON'.format(_test_dir, corpus) # cls.features = f'{_test_dir}/ref/{qgroup}_query_features_{corpus}_uqv.JSON' cls.features = dp.ensure_file( f'{_test_dir}/ref/{qgroup}_query_{vars_quantile}_variations_features_{corpus}_uqv.JSON') cls.geo_mean_file = dp.ensure_file( f'{_base_dir}/raw/geo/predictions/predictions-20000') # The variations file is used in the filter function - it consists of all the vars w/o the query at hand _query_vars = f'~/QppUqvProj/data/{corpus}/queries_{corpus}_UQV_wo_{qgroup}.txt' cls.query_vars_file = os.path.normpath(os.path.expanduser(_query_vars)) dp.ensure_file(cls.query_vars_file) _queries2predict = f'~/QppUqvProj/data/{corpus}/queries_{corpus}_{qgroup}.txt' cls.queries2predict_file = dp.ensure_file(_queries2predict) if vars_quantile == 'all': cls.quantile_vars_file = cls.query_vars_file else: _quantile_vars = f'~/QppUqvProj/data/{corpus}/queries_{corpus}_UQV_{vars_quantile}_variants.txt' cls.quantile_vars_file = os.path.normpath(os.path.expanduser(_quantile_vars)) dp.ensure_file(cls.quantile_vars_file) cls.real_ap_file = dp.ensure_file(f'~/QppUqvProj/Results/{corpus}/test/raw/QLmap1000') cls.geo_predictions_dir = dp.ensure_dir( f'{_base_dir}/referenceLists/{qgroup}/{vars_quantile}_vars/sim_as_pred/geo/predictions') @classmethod def __set_graph_paths(cls, corpus, predictor, qgroup, direct, n): """This method sets the default paths of the files and the working directories, it assumes the standard naming convention of the project""" cls.predictor = predictor _corpus_res_dir = dp.ensure_dir(f'~/QppUqvProj/Results/{corpus}/uqvPredictions/') _corpus_dat_dir = dp.ensure_dir(f'~/QppUqvProj/data/{corpus}') _graphs_base_dir = dp.ensure_dir(f'~/QppUqvProj/Graphs/{corpus}') _graphs_dat_dir = dp.ensure_dir(f'{_graphs_base_dir}/data/{direct}') # Prediction results of all UQV query variants cls.vars_results_dir = dp.ensure_dir(f'{_corpus_res_dir}/raw/{predictor}/predictions/') # Prediction results of the queries to be predicted _orig_dir = dp.ensure_dir(f'~/QppUqvProj/Results/{corpus}/basicPredictions/{qgroup}') cls.base_results_dir = f'{_orig_dir}/{predictor}/predictions/' # The directory to save the new results cls.output_dir = dp.ensure_dir(f'{_graphs_base_dir}/referenceLists/{qgroup}/{direct}/{n}_vars') # The files for used for the LTR and CV _test_dir = f'~/QppUqvProj/Results/{corpus}/test' cls.folds = dp.ensure_file(f'{_test_dir}/2_folds_30_repetitions.json') cls.ap_file = dp.ensure_file(f'{_test_dir}/ref/QLmap1000-{qgroup}') # The features file used for prediction cls.features = dp.ensure_file( f'{_graphs_dat_dir}/features/{qgroup}_query_{n}_variations_features_{corpus}_uqv.JSON') cls.geo_mean_file = dp.ensure_file( f'QppUqvProj/Results/{corpus}/uqvPredictions/raw/geo/predictions/predictions-20000') # The variations file is used in the filter function - it consists of all the vars w/o the query at hand cls.query_vars_file = dp.ensure_file(f'{_graphs_dat_dir}/queries/queries_wo_{qgroup}_{n}_vars.txt') cls.quantile_vars_file = cls.query_vars_file _queries2predict = f'~/QppUqvProj/data/{corpus}/queries_{corpus}_{qgroup}.txt' cls.queries2predict_file = dp.ensure_file(_queries2predict) cls.real_ap_file = dp.ensure_file(f'~/QppUqvProj/Results/{corpus}/test/raw/QLmap1000') cls.geo_predictions_dir = dp.ensure_dir( f'{_corpus_res_dir}/referenceLists/{qgroup}/all_vars/sim_as_pred/geo/predictions') def __initialize_features_df(self, quantile_vars, features_df): """This method filters from features df only the ones conjunction with the relevant variations self.query_vars - consists of all the variations :except the queries group being predicted :rtype: pd.DataFrame""" _quant_vars = quantile_vars.queries_df['qid'].tolist() _vars_list = self.query_vars.queries_df.loc[self.query_vars.queries_df['qid'].isin(_quant_vars)]['qid'] _features_df = features_df.reset_index() _features_df = _features_df.loc[_features_df['qid'].isin(_vars_list)] _features_df.set_index(['topic', 'qid'], inplace=True) return _features_df def __initialize_var_scores_df(self, topic_df, vars_results_df): """This method filters from query variations df only the ones relevant for prediction""" _var_scores_df = pd.merge(topic_df, vars_results_df, on='qid') _var_scores_df = _var_scores_df.loc[_var_scores_df['qid'].isin(self.features_df.index.get_level_values('qid'))] # print(_var_scores_df.loc[_var_scores_df['topic'] == '361']) _var_scores_df.set_index(['topic', 'qid'], inplace=True) return _var_scores_df def __initialize_geo_scores_df(self, topic_df, geo_scores_df): """This method filters from query variations df only the ones relevant for prediction""" _geo_scores_df = pd.concat([geo_scores_df, self.features_df.reset_index('topic')['topic']], axis=1, join='inner').reset_index() return _geo_scores_df.set_index(['topic', 'qid']) def __calc_sim_oracle(self, features_df, lambda_param): """This method will calculate the prediction value using real AP values of the variants, in order to set the upper bound for the full potential of the method""" _result_df = self.real_ap_df.multiply(features_df, axis=0, level='qid') _result_df = _result_df.groupby('topic').sum() _result_df = (1 - lambda_param) * _result_df _base_predictions = lambda_param * self.base_results_df return _base_predictions.add(_result_df['ap'], axis=0) def calc_integrated(self, score_param): """The function receives a column name from the scores df, in the shape of score_n used for the LTR method Basically it implements the calculations specified in section 3.1.1 in the paper and returns a DF with the feature values (and the basic predictions score)""" _df = self.features_df.multiply(self.var_scores_df[score_param], axis=0, level='qid') _df = _df.groupby('topic').sum() _res_df = _df.join(self.base_results_df[score_param], on='topic') return _res_df class LearningSimFunctions: """This class creates data sets and splits them into train and test, afterwards running svmRank to learn""" def generate_data_sets_fine_tune(self): """This method will create the data sets with all the available hyper parameters of the qpp predictions""" # TODO: add prompt with list of files before delete # run(f'rm -rfv {self.output_dir}*', shell=True) for set_id in self.folds_df.index: for subset in ['a', 'b']: for col in self.results_df.columns: h = col.split('_')[-1] features_df = self._create_data_set(col) train_df, test_df = self._split_data_set(features_df, set_id, subset) train_str = self._df_to_str(train_df, col) test_str = self._df_to_str(test_df, col) self.write_str_to_file(train_str, f'train_{set_id}_{subset}-d_{h}.dat') self.write_str_to_file(test_str, f'test_{set_id}_{subset}-d_{h}.dat') def generate_data_sets(self): """This method will create the data sets with a single hyper parameter for the qpp predictions, which will be chosen based on the best result on the train set""" run(f'rm -rfv {self.output_dir}*', shell=True) for set_id in self.folds_df.index: for subset in ['a', 'b']: param = self.parameters_df.loc[set_id][subset] features_df = self._create_data_set(param) train_df, test_df = self._split_data_set(features_df, set_id, subset) train_str = self._df_to_str(train_df) test_str = self._df_to_str(test_df) self.write_str_to_file(train_str, f'train_{set_id}_{subset}.dat') self.write_str_to_file(test_str, f'test_{set_id}_{subset}.dat') @staticmethod def write_basic_predictions(df: pd.DataFrame, corpus, qgroup, predictor): """The function is used to save results in basic predictions format of a given queries set""" for col in df.columns: _file_path = f'~/QppUqvProj/Results/{corpus}/basicPredictions/{qgroup}/{predictor}/predictions/' dp.ensure_dir(os.path.normpath(os.path.expanduser(_file_path))) _file_name = col.replace('score_', 'predictions-') file_name = f'{_file_path}{_file_name}' df[col].to_csv(file_name, sep=" ", header=False, index=True) if __name__ == '__main__': args = parser.parse_args() overall_timer = Timer('Total runtime') main(args) overall_timer.stop()
[ 11748, 1822, 29572, 198, 11748, 15095, 198, 11748, 340, 861, 10141, 198, 11748, 18540, 305, 919, 278, 355, 29034, 198, 11748, 28686, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 850, 14681, 1330, 1057, 198, 198, 11748, 299, 32152,...
2.235961
5,734
from setuptools import setup import os import sys SRC_ROOT, _ = os.path.split(__file__) PROJECT_ROOT = os.path.dirname(SRC_ROOT) REVISION = '0.0.1' PROJECT_NAME = 'neowrapper' PROJECT_AUTHORS = "Salim Fadhley" # Please see readme.rst for a complete list of contributors PROJECT_EMAILS = 'salimfadhley@gmail.com' PROJECT_URL = "" SHORT_DESCRIPTION = '' python_version = (sys.version_info.major, sys.version_info.minor) DEPENDENCIES = \ ['py2neo', ] + \ (['typing'] if python_version < (3, 5) else []) try: DESCRIPTION = open(os.path.join(PROJECT_ROOT, "README.md")).read() except IOError: DESCRIPTION = SHORT_DESCRIPTION GLOBAL_ENTRY_POINTS = { "console_scripts": [] } setup( name=PROJECT_NAME.lower(), version=REVISION, author=PROJECT_AUTHORS, author_email=PROJECT_EMAILS, packages=['neowrapper'], zip_safe=True, include_package_data=False, install_requires=DEPENDENCIES, test_suite='nose.collector', tests_require=['mock', 'nose', 'coverage'], entry_points=GLOBAL_ENTRY_POINTS, url=PROJECT_URL, description=SHORT_DESCRIPTION, long_description=DESCRIPTION, license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing', ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 50, 7397, 62, 13252, 2394, 11, 4808, 796, 28686, 13, 6978, 13, 35312, 7, 834, 7753, 834, 8, 198, 31190, 23680, 62, 13252, 2394, 796, 28686, 13, 6978,...
2.243537
735
from upguard import UpGuardObject
[ 6738, 510, 14864, 1330, 3205, 24502, 10267, 198 ]
4.25
8
from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Any, Optional import jwt from .exceptions import InvalidPastaportoError from .tokens import decode_pastaporto @dataclass @dataclass
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 4377, 11, 32233, 198, 198, 11748, 474, 46569, 198, 198, 6738, 764, 1069...
3.394737
76
from re import error from django.db import models from ..login.models import User # Create your models here.
[ 6738, 302, 1330, 4049, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 11485, 38235, 13, 27530, 1330, 11787, 198, 2, 13610, 534, 4981, 994, 13 ]
4
27
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-03 07:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 17, 319, 2177, 12, 2998, 12, 3070, 8753, 25, 1731, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
RESOURCE_NOT_FOUND_EXCEPTION = "ResourceNotFoundException"
[ 19535, 31033, 62, 11929, 62, 37, 15919, 62, 6369, 42006, 2849, 796, 366, 26198, 3673, 21077, 16922, 1, 198 ]
3.105263
19
from osim.env import L2M2019CtrlEnv from osim.control.osim_loco_reflex_song2019 import OsimReflexCtrl import sys import numpy as np trial_name = 'trial_190501_L2M2019CtrlEnv_2D_' params = np.ones(37) #params = np.loadtxt('./data/cma/trial_181029_walk_3D_noStand_8_best.txt') if __name__ == '__main__': prob = CMATrain() from cmaes.solver_cma import CMASolver solver = CMASolver(prob) solver.options.set("popsize", 16) # 8 = 4 + floor(3*log(37)) solver.options.set("maxiter", 400) solver.options.set("verb_filenameprefix", 'data/cma/' + trial_name) solver.set_verbose(True) x0 = params sigma = .01 res = solver.solve(x0, sigma) print(res)
[ 6738, 267, 14323, 13, 24330, 1330, 406, 17, 44, 23344, 40069, 4834, 85, 198, 6738, 267, 14323, 13, 13716, 13, 418, 320, 62, 17946, 78, 62, 5420, 2588, 62, 34050, 23344, 1330, 8834, 320, 8134, 2588, 40069, 198, 198, 11748, 25064, 198, ...
2.269737
304
self.description = "check file type without mtree" self.filesystem = [ "bar/", "foo -> bar/" ] pkg = pmpkg("dummy") pkg.files = [ "foo/" ] self.addpkg2db("local",pkg) self.args = "-Qk" self.addrule("PACMAN_RETCODE=1") self.addrule("PACMAN_OUTPUT=warning.*(File type mismatch)")
[ 944, 13, 11213, 796, 366, 9122, 2393, 2099, 1231, 285, 21048, 1, 198, 198, 944, 13, 16624, 6781, 796, 685, 366, 5657, 14, 1600, 366, 21943, 4613, 2318, 30487, 2361, 198, 198, 35339, 796, 279, 3149, 10025, 7203, 67, 13513, 4943, 198, ...
2.540541
111
import math import torch from torch import nn from ..utils.helpers import wrap_class, null_context from .operations import t, relative_error from ..tensor_network import SingleTensor class MF(nn.Module): """Base module for matrix factorization. X ≈ U t(V), U, V ∈ S """ class TF(nn.Module): """Base module for tensor factorization. Decompose a tensor X into an arbitrary tensor network, i.e., X ≈ TensorNework(U1, ..., UM) """
[ 11748, 10688, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 198, 6738, 11485, 26791, 13, 16794, 364, 1330, 14441, 62, 4871, 11, 9242, 62, 22866, 198, 6738, 764, 3575, 602, 1330, 256, 11, 3585, 62, 18224, 198, 6738, 114...
2.796407
167
"""Logger """ import logging import logging.config logging.config.fileConfig("logging.ini")
[ 37811, 11187, 1362, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 18931, 13, 11250, 628, 198, 6404, 2667, 13, 11250, 13, 7753, 16934, 7203, 6404, 2667, 13, 5362, 4943, 628 ]
3.2
30
# Copyright (c) 2016-2017 Anki, Inc. # # 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 in the file LICENSE.txt or 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. '''Camera image annotation. .. image:: ../images/annotate.jpg This module defines an :class:`ImageAnnotator` class used by :class:`cozmo.world.World` to add annotations to camera images received by Cozmo. This can include the location of cubes, faces and pets that Cozmo currently sees, along with user-defined custom annotations. The ImageAnnotator instance can be accessed as :attr:`cozmo.world.World.image_annotator`. ''' # __all__ should order by constants, event classes, other classes, functions. __all__ = ['DEFAULT_OBJECT_COLORS', 'TOP_LEFT', 'TOP_RIGHT', 'BOTTOM_LEFT', 'BOTTOM_RIGHT', 'RESAMPLE_MODE_NEAREST', 'RESAMPLE_MODE_BILINEAR', 'ImageText', 'Annotator', 'ObjectAnnotator', 'FaceAnnotator', 'PetAnnotator', 'TextAnnotator', 'ImageAnnotator', 'add_img_box_to_image', 'add_polygon_to_image', 'annotator'] import collections import functools try: from PIL import Image, ImageDraw except ImportError: ImageDraw = None from . import event from . import objects DEFAULT_OBJECT_COLORS = { objects.LightCube: 'yellow', objects.CustomObject: 'purple', 'default': 'red' } LEFT = 1 RIGHT = 2 TOP = 4 BOTTOM = 8 #: Top left position TOP_LEFT = TOP | LEFT #: Bottom left position BOTTOM_LEFT = BOTTOM | LEFT #: Top right position TOP_RIGHT = TOP | RIGHT #: Bottom right position BOTTOM_RIGHT = BOTTOM | RIGHT if ImageDraw is not None: #: Fastest resampling mode, use nearest pixel RESAMPLE_MODE_NEAREST = Image.NEAREST #: Slower, but smoother, resampling mode - linear interpolation from 2x2 grid of pixels RESAMPLE_MODE_BILINEAR = Image.BILINEAR else: RESAMPLE_MODE_NEAREST = None RESAMPLE_MODE_BILINEAR = None class ImageText: '''ImageText represents some text that can be applied to an image. The class allows the text to be placed at various positions inside a bounding box within the image itself. Args: text (string): The text to display; may contain newlines position (int): Where on the screen to render the text - A constant such at TOP_LEFT or BOTTOM_RIGHT align (string): Text alignment for multi-line strings color (string): Color to use for the text - see :mod:`PIL.ImageColor` font (:mod:`PIL.ImageFont`): Font to use (None for a default font) line_spacing (int): The vertical spacing for multi-line strings outline_color (string): Color to use for the outline - see :mod:`PIL.ImageColor` - use None for no outline. full_outline (bool): True if the outline should surround the text, otherwise a cheaper drop-shadow is displayed. Only relevant if outline_color is specified. ''' def render(self, draw, bounds): '''Renders the text onto an image within the specified bounding box. Args: draw (:class:`PIL.ImageDraw.ImageDraw`): The drawable surface to write on bounds (tuple of int) (top_left_x, top_left_y, bottom_right_x, bottom_right_y): bounding box Returns: The same :class:`PIL.ImageDraw.ImageDraw` object as was passed-in with text applied. ''' (bx1, by1, bx2, by2) = bounds text_width, text_height = draw.textsize(self.text, font=self.font) if self.position & TOP: y = by1 else: y = by2 - text_height if self.position & LEFT: x = bx1 else: x = bx2 - text_width # helper method for each draw call below if self.outline_color is not None: # Pillow doesn't support outlined or shadowed text directly. # We manually draw the text multiple times to achieve the effect. if self.full_outline: _draw_text((x-1, y), self.outline_color) _draw_text((x+1, y), self.outline_color) _draw_text((x, y-1), self.outline_color) _draw_text((x, y+1), self.outline_color) else: # just draw a drop shadow (cheaper) _draw_text((x+1, y+1), self.outline_color) _draw_text((x,y), self.color) return draw def add_img_box_to_image(image, box, color, text=None): '''Draw a box on an image and optionally add text. This will draw the outline of a rectangle to the passed in image in the specified color and optionally add one or more pieces of text along the inside edge of the rectangle. Args: image (:class:`PIL.Image.Image`): The image to draw on box (:class:`cozmo.util.ImageBox`): The ImageBox defining the rectangle to draw color (string): A color string suitable for use with PIL - see :mod:`PIL.ImageColor` text (instance or iterable of :class:`ImageText`): The text to display - may be a single ImageText instance, or any iterable (eg a list of ImageText instances) to display multiple pieces of text. ''' d = ImageDraw.Draw(image) x1, y1 = box.left_x, box.top_y x2, y2 = box.right_x, box.bottom_y d.rectangle([x1, y1, x2, y2], outline=color) if text is not None: if isinstance(text, collections.Iterable): for t in text: t.render(d, (x1, y1, x2, y2)) else: text.render(d, (x1, y1, x2, y2)) def add_polygon_to_image(image, poly_points, scale, line_color, fill_color=None): '''Draw a polygon on an image This will draw a polygon on the passed-in image in the specified colors and scale. Args: image (:class:`PIL.Image.Image`): The image to draw on poly_points: A sequence of points representing the polygon, where each point has float members (x, y) scale (float): Scale to multiply each point to match the image scaling line_color (string): The color for the outline of the polygon. The string value must be a color string suitable for use with PIL - see :mod:`PIL.ImageColor` fill_color (string): The color for the inside of the polygon. The string value must be a color string suitable for use with PIL - see :mod:`PIL.ImageColor` ''' if len(poly_points) < 2: # Need at least 2 points to draw any lines return d = ImageDraw.Draw(image) # Convert poly_points to the PIL format and scale them to the image pil_poly_points = [] for pt in poly_points: pil_poly_points.append((pt.x * scale, pt.y * scale)) d.polygon(pil_poly_points, fill=fill_color, outline=line_color) class Annotator: '''Annotation base class Subclasses of Annotator handle applying a single annotation to an image. ''' #: int: The priority of the annotator - Annotators with lower numbered # priorities are applied first. priority = 100 def apply(self, image, scale): '''Applies the annotation to the image.''' # should be overriden by a subclass raise NotImplementedError() class ObjectAnnotator(Annotator): '''Adds object annotations to an Image. This handles :class:`cozmo.objects.LightCube` objects as well as custom objects. ''' priority = 100 object_colors = DEFAULT_OBJECT_COLORS def label_for_obj(self, obj): '''Fetch a label to display for the object. Override or replace to customize. ''' return ImageText(obj.descriptive_name) class FaceAnnotator(Annotator): '''Adds annotations of currently detected faces to a camera image. This handles the display of :class:`cozmo.faces.Face` objects. ''' priority = 100 box_color = 'green' def label_for_face(self, obj): '''Fetch a label to display for the face. Override or replace to customize. ''' expression = obj.known_expression if len(expression) > 0: # if there is a specific known expression, then also show the score # (display a % to make it clear the value is out of 100) expression += "=%s%% " % obj.expression_score if obj.name: return ImageText('%s%s (%d)' % (expression, obj.name, obj.face_id)) return ImageText('(unknown%s face %d)' % (expression, obj.face_id)) class PetAnnotator(Annotator): '''Adds annotations of currently detected pets to a camera image. This handles the display of :class:`cozmo.pets.Pet` objects. ''' priority = 100 box_color = 'lightgreen' def label_for_pet(self, obj): '''Fetch a label to display for the pet. Override or replace to customize. ''' return ImageText('%d: %s' % (obj.pet_id, obj.pet_type)) class TextAnnotator(Annotator): '''Adds simple text annotations to a camera image. ''' priority = 50 def annotator(f): '''A decorator for converting a regular function/method into an Annotator. The wrapped function should have a signature of ``(image, scale, img_annotator=None, world=None, **kw)`` ''' @functools.wraps(f) return wrapper class ImageAnnotator(event.Dispatcher): '''ImageAnnotator applies annotations to the camera image received from the robot. This is instantiated by :class:`cozmo.world.World` and is accessible as :class:`cozmo.world.World.image_annotator`. By default it defines three active annotators named ``objects``, ``faces`` and ``pets``. The ``objects`` annotator adds a box around each object (such as light cubes) that Cozmo can see. The ``faces`` annotator adds a box around each person's face that Cozmo can recognize. The ``pets`` annotator adds a box around each pet face that Cozmo can recognize. Custom annotations can be defined by calling :meth:`add_annotator` with a name of your choosing and an instance of a :class:`Annotator` subclass, or use a regular function wrapped with the :func:`annotator` decorator. Individual annotations can be disabled and re-enabled using the :meth:`disable_annotator` and :meth:`enable_annotator` methods. All annotations can be disabled by setting the :attr:`annotation_enabled` property to False. Eg. to disable face annotations, call ``coz.world.image_annotator.disable_annotator('faces')`` Annotators each have a priority number associated with them. Annotators with a larger priority number are rendered first and may be overdrawn by those with a lower/smaller priority number. ''' def add_annotator(self, name, annotator): '''Adds a new annotator for display. Annotators are enabled by default. Args: name (string): An arbitrary name for the annotator; must not already be defined annotator (:class:`Annotator` or callable): The annotator to add may either by an instance of Annotator, or a factory callable that will return an instance of Annotator. The callable will be called with an ImageAnnotator instance as its first argument. Raises: :class:`ValueError` if the annotator is already defined. ''' if name in self._annotators: raise ValueError('Annotator "%s" is already defined' % (name)) if not isinstance(annotator, Annotator): annotator = annotator(self) self._annotators[name] = annotator self._sort_annotators() def remove_annotator(self, name): '''Remove an annotator. Args: name (string): The name of the annotator to remove as passed to :meth:`add_annotator`. Raises: KeyError if the annotator isn't registered ''' del self._annotators[name] self._sort_annotators() def get_annotator(self, name): '''Return a named annotator. Args: name (string): The name of the annotator to return Raises: KeyError if the annotator isn't registered ''' return self._annotators[name] def disable_annotator(self, name): '''Disable a named annotator. Leaves the annotator as registered, but does not include its output in the annotated image. Args: name (string): The name of the annotator to disable ''' if name in self._annotators: self._annotators[name].enabled = False def enable_annotator(self, name): '''Enabled a named annotator. (re)enable an annotator if it was previously disabled. Args: name (string): The name of the annotator to enable ''' self._annotators[name].enabled = True def add_static_text(self, name, text, color='white', position=TOP_LEFT): '''Add some static text to annotated images. This is a convenience method to create a :class:`TextAnnnotator` and add it to the image. Args: name (string): An arbitrary name for the annotator; must not already be defined text (str or :class:`ImageText` instance): The text to display may be a plain string, or an ImageText instance color (string): Used if text is a string; defaults to white position (int): Used if text is a string; defaults to TOP_LEFT ''' if isinstance(text, str): text = ImageText(text, position=position, color=color) self.add_annotator(name, TextAnnotator(self, text)) def annotate_image(self, image, scale=None, fit_size=None, resample_mode=RESAMPLE_MODE_NEAREST): '''Called by :class:`~cozmo.world.World` to annotate camera images. Args: image (:class:`PIL.Image.Image`): The image to annotate scale (float): If set then the base image will be scaled by the supplied multiplier. Cannot be combined with fit_size fit_size (tuple of int): If set, then scale the image to fit inside the supplied (width, height) dimensions. The original aspect ratio will be preserved. Cannot be combined with scale. resample_mode (int): The resampling mode to use when scaling the image. Should be either :attr:`RESAMPLE_MODE_NEAREST` (fast) or :attr:`RESAMPLE_MODE_BILINEAR` (slower, but smoother). Returns: :class:`PIL.Image.Image` ''' if ImageDraw is None: return image if scale is not None: if scale == 1: image = image.copy() else: image = image.resize((int(image.width * scale), int(image.height * scale)), resample=resample_mode) elif fit_size is not None: if fit_size == (image.width, image.height): image = image.copy() scale = 1 else: img_ratio = image.width / image.height fit_width, fit_height = fit_size fit_ratio = fit_width / fit_height if img_ratio > fit_ratio: fit_height = int(fit_width / img_ratio) elif img_ratio < fit_ratio: fit_width = int(fit_height * img_ratio) scale = fit_width / image.width image = image.resize((fit_width, fit_height)) else: scale = 1 if not self.annotation_enabled: return image for an in self._sorted_annotators: if an.enabled: an.apply(image, scale) return image
[ 2, 15069, 357, 66, 8, 1584, 12, 5539, 1052, 4106, 11, 3457, 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, 351, 2...
2.487258
6,553
import argparse import json import random import numpy as np import os import torch.cuda from datetime import datetime import src.utils.interface_file_io as file_io
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 28034, 13, 66, 15339, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 12351, 13, 26791, 13, 39994, 62, 7753, ...
3.44898
49
import sys import argparse import pathlib import yaml import subprocess import re COAST_dir = pathlib.Path(__file__).resolve().parent.parent tests_dir = COAST_dir / "tests" # Compile the benchmark for x86 using provided opt_passes # Run the x86 compiled benchmark (must call compile first) if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 1822, 29572, 198, 11748, 3108, 8019, 198, 11748, 331, 43695, 198, 11748, 850, 14681, 198, 11748, 302, 198, 198, 8220, 11262, 62, 15908, 796, 3108, 8019, 13, 15235, 7, 834, 7753, 834, 737, 411, 6442, 22446, 8000...
3.1
110
# # Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM # # 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. # import random from senpy.plugins import EmotionPlugin from senpy.models import EmotionSet, Emotion, Entry class EmoRand(EmotionPlugin): '''A sample plugin that returns a random emotion annotation''' name = 'emotion-random' author = '@balkian' version = '0.1' url = "https://github.com/gsi-upm/senpy-plugins-community" onyx__usesEmotionModel = "emoml:big6"
[ 2, 198, 2, 220, 220, 220, 15069, 1946, 25665, 7501, 390, 311, 396, 368, 292, 8180, 47096, 274, 357, 38, 11584, 8, 360, 2043, 11, 471, 5868, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 35...
3.038462
338
import os import glob from setuptools import find_packages, setup about = {} here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(os.path.dirname(__file__), "README.md")).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) extra_files = package_files("recipe_parser/ingredient_parser/models/ner") setup( name="recipe_parser", url="https://github.com/tyler-a-cox/recipe_parser/", version="0.0.1", author="Tyler Cox", author_email="tyler.a.cox@berkeley.edu", description="Python package, scraping recipes from all over the internet", keywords="python recipes scraper harvest recipe-scraper recipe-scrapers", long_description=README, long_description_content_type="text/x-rst", install_requires=["beautifulsoup4", "extruct", "requests", "spacy"], packages=["recipe_parser"], include_package_data=True, package_data={"": extra_files}, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Operating System :: OS Independent", "Topic :: Internet :: WWW/HTTP", ], python_requires=">=3.6", )
[ 11748, 28686, 198, 11748, 15095, 198, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 10755, 796, 23884, 198, 1456, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, ...
2.633833
467
# # (C) 2014-2017 Seiji Matsuoka # Licensed under the MIT License (MIT) # http://opensource.org/licenses/MIT # from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import rdFMCS from rdkit import DataStructs from chorus.model.graphmol import Compound from chorus.model.atom import Atom, atom_number from chorus.model.bond import Bond from chorus import molutil # TODO: stereo, aromatic etc def to_rdmol(mol): """Convert molecule to RDMol""" rwmol = Chem.RWMol(Chem.MolFromSmiles('')) key_to_idx = {} bond_type = {1: Chem.BondType.SINGLE, 2: Chem.BondType.DOUBLE, 3: Chem.BondType.TRIPLE} conf = Chem.Conformer(rwmol.GetNumAtoms()) for k, a in mol.atoms_iter(): i = rwmol.AddAtom(Chem.Atom(atom_number(a.symbol))) key_to_idx[k] = i conf.SetAtomPosition(i, a.coords) rwmol.AddConformer(conf) for u, v, b in mol.bonds_iter(): ui = key_to_idx[u] vi = key_to_idx[v] rwmol.AddBond(ui, vi, bond_type[b.order]) Chem.GetSSSR(rwmol) # Ring recognition is required for fingerprint rwmol.UpdatePropertyCache(strict=False) return rwmol.GetMol() def from_rdmol(rdmol, assign_descriptor=True): """Convert RDMol to molecule""" mol = Compound() conf = rdmol.GetConformer() Chem.Kekulize(rdmol) for atom in rdmol.GetAtoms(): key = atom.GetIdx() a = Atom(atom.GetSymbol()) a.coords = conf.GetAtomPosition(key) mol.add_atom(key, a) for bond in rdmol.GetBonds(): u = bond.GetBeginAtomIdx() v = bond.GetEndAtomIdx() b = Bond() b.order = int(bond.GetBondTypeAsDouble()) mol.add_bond(u, v, b) if assign_descriptor: molutil.assign_descriptors(mol) return mol def morgan_sim(mol1, mol2, radius=2, digit=3): """Calculate morgan fingerprint similarity by using RDKit radius=2 roughly equivalent to ECFP4 """ rdmol1 = to_rdmol(mol1) rdmol2 = to_rdmol(mol2) fp1 = AllChem.GetMorganFingerprint(rdmol1, radius) fp2 = AllChem.GetMorganFingerprint(rdmol2, radius) return round(DataStructs.DiceSimilarity(fp1, fp2), digit)
[ 2, 198, 2, 357, 34, 8, 1946, 12, 5539, 1001, 20770, 337, 19231, 17411, 198, 2, 49962, 739, 262, 17168, 13789, 357, 36393, 8, 198, 2, 2638, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 36393, 198, 2, 198, 198, 6738, 374, 67, 1...
2.19799
995
from django.core.management.base import BaseCommand from fjord.feedback.models import purge_data
[ 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 198, 198, 6738, 277, 73, 585, 13, 12363, 1891, 13, 27530, 1330, 35714, 62, 7890, 628 ]
3.535714
28
import numpy as np from config.draco3_config import WalkingState from pnc.state_machine import StateMachine from pnc.planner.locomotion.dcm_planner.footstep import Footstep from pnc.draco3_pnc.draco3_state_provider import Draco3StateProvider
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 4566, 13, 7109, 10602, 18, 62, 11250, 1330, 21276, 9012, 198, 6738, 279, 10782, 13, 5219, 62, 30243, 1330, 1812, 37573, 198, 6738, 279, 10782, 13, 11578, 1008, 13, 17946, 296, 9650, 13, 6...
3.128205
78
from math import ceil, floor, sqrt from pathlib import Path from random import randint import matplotlib.pyplot as plt import numpy as np import tensorflow as tf
[ 6738, 10688, 1330, 2906, 346, 11, 4314, 11, 19862, 17034, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198,...
3.288462
52
# %% import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.python.keras.layers.core import Dropout #%% model = tf.keras.models.Sequential([ tf.keras.Input(shape=(2,)), tf.keras.layers.Dense(80, activation='sigmoid'), tf.keras.layers.Dense(2) ]) # %% # x_train=tf.reshape(tf.constant([6.1723,2.3504,7.3475,3.7095,8.5227,3.8935,9.6979,2.9022,10.8731,4.2614,12.0483,4.4453,13.2235,3.454,14.3987,4.8132]),[-1,2]) # y_train=tf.reshape(tf.constant([0,0,1,1,2,2,3,0,4,1,5,2,6,0,7,1]),[-1,2]) # x_test=tf.reshape(tf.constant([15.5739,6.1723]),[-1,2]) # y_test=tf.reshape(tf.constant([8,2]),[-1,2]) import numpy as np data=np.genfromtxt('Data.csv',delimiter=',') y=tf.transpose(data[:2]) x=tf.transpose(data[2:]) n=int(len(x)*0.8) x_train=x[0:10000] x_test=x[10000:] y_train=y[0:10000] y_test=y[10000:] # %% loss_fn =tf.keras.losses.MeanSquaredError() model.compile(optimizer='adam' ,loss=loss_fn # ,metrics=['accuracy'] ) #%% i=0 es=1e-4 maxi=100 epochs=10 while True: i+=1 print("#%d..." % i,end="") model.fit(x_train, y_train, epochs=epochs,verbose=1) print("done") loss=model.evaluate(x_train, y_train) if (loss<es or i>=maxi): break #%% model.evaluate(x_test, y_test) #%% model.predict([[1.3259,3.3203]])#0,2 #%% model.predict([[-1.1374,-1.971]])#-1,-2 #%% model.predict([[-1.0988,-1.8649]])#-1.-1.92 #%% model.predict([[0.78459,2.96976]])#0,1.92 #%% model.predict([[1,0]]) #%% model.predict([[-1,0]]) # %% model.save("jy_817.h5") # %% model=tf.keras.models.load_model("jy2.h5")
[ 2, 43313, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 1330, 11685, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 6122, 292, 13, 75, 6962, 13, 7...
1.873696
863
import random import stillleben as sl import sl_cutscenes.constants as CONSTANTS def get_lightmap(map_name="random"): """ Fetches the right lightmap given command line argument. """ assert map_name in ["default", "random"] + list(CONSTANTS.ALL_LIGHTMAPS.keys()), f"Unknown lightmap {map_name}..." if map_name == "random": map_name = random.choice(list(CONSTANTS.ALL_LIGHTMAPS.keys())) elif map_name == "default": map_name = "Subway_Lights" lightmap = sl.LightMap(CONSTANTS.ALL_LIGHTMAPS[map_name]) return lightmap
[ 11748, 4738, 198, 11748, 991, 293, 11722, 355, 1017, 198, 11748, 1017, 62, 8968, 28123, 13, 9979, 1187, 355, 7102, 2257, 1565, 4694, 628, 198, 4299, 651, 62, 2971, 8899, 7, 8899, 62, 3672, 2625, 25120, 1, 2599, 198, 220, 220, 220, 3...
2.572727
220
from .llvm_type import ( char_pointer, i8, i32, i64, ) from .objc import ( objc_ivar, objc_ivar_list, ) __all__ = [ 'char_pointer', 'i8', 'i32', 'i64', 'objc_ivar', 'objc_ivar_list', ]
[ 6738, 764, 297, 14761, 62, 4906, 1330, 357, 198, 220, 220, 220, 1149, 62, 29536, 11, 198, 220, 220, 220, 1312, 23, 11, 198, 220, 220, 220, 1312, 2624, 11, 198, 220, 220, 220, 1312, 2414, 11, 198, 8, 198, 198, 6738, 764, 26801, 6...
1.710145
138
import datetime import json import pprint from django.test import TestCase from scraper import scraper pp = pprint.PrettyPrinter(indent=4)
[ 11748, 4818, 8079, 198, 11748, 33918, 198, 11748, 279, 4798, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 19320, 525, 1330, 19320, 525, 198, 198, 381, 796, 279, 4798, 13, 35700, 6836, 3849, 7, 521, 298, 2...
3.130435
46
import logging from sith_score_handler import SithScoreHandler from raidtickets_lifetime_handler import RaidticketsLifetimeHandler from guildtickets_lifetime_handler import GuildticketsLifetimeHandler from territory_battle_total_score_handler import TerritoryBattleTotalScoreHandler from territory_battle_total_combat_waves_handler import TerritoryBattleTotalCombatWavesHandler from territory_battle_area_score_handler import TerritoryBattleAreaScoreHandler from dbx_handler import DbxHandler logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 6738, 264, 342, 62, 26675, 62, 30281, 1330, 26455, 26595, 25060, 198, 6738, 9513, 83, 15970, 62, 36195, 8079, 62, 30281, 1330, 12448, 83, 15970, 43, 361, 8079, 25060, 198, 6738, 19806, 83, 15970, 62, 36195, 8079, 62, ...
4.030303
132
''' @author: Dallas Fraser @id: 20652186 @class: CS686 @date: 2016-02-13 @note: contains a player using a repeat (Pavlov) strategy ''' from DallasPlayers.player import COOPERATE, Player, DEFECT import unittest class RepeatOutcomePlayer(Player): """ Repeat Outcome Player - repeat last choice if good outcome """
[ 7061, 6, 198, 31, 9800, 25, 8533, 28059, 198, 31, 312, 25, 1160, 43193, 25096, 198, 31, 4871, 25, 9429, 33808, 198, 31, 4475, 25, 1584, 12, 2999, 12, 1485, 198, 31, 11295, 25, 4909, 257, 2137, 1262, 257, 9585, 357, 47, 615, 27086,...
3.114286
105
from adain.cfg.config import Config __all__ = ['Config']
[ 6738, 512, 391, 13, 37581, 13, 11250, 1330, 17056, 201, 198, 201, 198, 834, 439, 834, 796, 37250, 16934, 20520, 201, 198 ]
2.772727
22
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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. # from collections import OrderedDict import os import re from typing import Callable, Dict, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.iam_credentials_v1.types import common from google.protobuf import duration_pb2 as duration # type: ignore from google.protobuf import timestamp_pb2 as timestamp # type: ignore from .transports.base import IAMCredentialsTransport from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport class IAMCredentialsClientMeta(type): """Metaclass for the IAMCredentials client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IAMCredentialsTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class IAMCredentialsClient(metaclass=IAMCredentialsClientMeta): """A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google APIs, so that the users aren't directly involved. Service account credentials are used to temporarily assume the identity of the service account. Supported credential types include OAuth 2.0 access tokens, OpenID Connect ID tokens, self- signed JSON Web Tokens (JWTs), and more. """ @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "iamcredentials.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: {@api.name}: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file def __init__( self, *, credentials: credentials.Credentials = None, transport: Union[str, IAMCredentialsTransport] = None, client_options: ClientOptions = None, ) -> None: """Instantiate the iam credentials client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.IAMCredentialsTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint, this is the default value for the environment variable) and "auto" (auto switch to the default mTLS endpoint if client SSL credentials is present). However, the ``api_endpoint`` property takes precedence if provided. (2) The ``client_cert_source`` property is used to provide client SSL credentials for mutual TLS transport. If not provided, the default SSL credentials will be used if present. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = ClientOptions.from_dict(client_options) if client_options is None: client_options = ClientOptions.ClientOptions() if client_options.api_endpoint is None: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") if use_mtls_env == "never": client_options.api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": has_client_cert_source = ( client_options.client_cert_source is not None or mtls.has_default_client_cert_source() ) client_options.api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if has_client_cert_source else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, IAMCredentialsTransport): # transport is a IAMCredentialsTransport instance. if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) if client_options.scopes: raise ValueError( "When providing a transport instance, " "provide its scopes directly." ) self._transport = transport else: Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, host=client_options.api_endpoint, scopes=client_options.scopes, api_mtls_endpoint=client_options.api_endpoint, client_cert_source=client_options.client_cert_source, quota_project_id=client_options.quota_project_id, ) def generate_access_token( self, request: common.GenerateAccessTokenRequest = None, *, name: str = None, delegates: Sequence[str] = None, scope: Sequence[str] = None, lifetime: duration.Duration = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. Args: request (:class:`~.common.GenerateAccessTokenRequest`): The request object. name (:class:`str`): Required. The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. delegates (:class:`Sequence[str]`): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``delegates`` field on the ``request`` instance; if ``request`` is provided, this should not be set. scope (:class:`Sequence[str]`): Required. Code to identify the scopes to be included in the OAuth 2.0 access token. See https://developers.google.com/identity/protocols/googlescopes for more information. At least one value required. This corresponds to the ``scope`` field on the ``request`` instance; if ``request`` is provided, this should not be set. lifetime (:class:`~.duration.Duration`): The desired lifetime duration of the access token in seconds. Must be set to a value less than or equal to 3600 (1 hour). If a value is not specified, the token's lifetime will be set to a default value of one hour. This corresponds to the ``lifetime`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.common.GenerateAccessTokenResponse: """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([name, delegates, scope, lifetime]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) request = common.GenerateAccessTokenRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if delegates is not None: request.delegates = delegates if scope is not None: request.scope = scope if lifetime is not None: request.lifetime = lifetime # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method.wrap_method( self._transport.generate_access_token, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, client_info=_client_info, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def generate_id_token( self, request: common.GenerateIdTokenRequest = None, *, name: str = None, delegates: Sequence[str] = None, audience: str = None, include_email: bool = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. Args: request (:class:`~.common.GenerateIdTokenRequest`): The request object. name (:class:`str`): Required. The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. delegates (:class:`Sequence[str]`): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``delegates`` field on the ``request`` instance; if ``request`` is provided, this should not be set. audience (:class:`str`): Required. The audience for the token, such as the API or account that this token grants access to. This corresponds to the ``audience`` field on the ``request`` instance; if ``request`` is provided, this should not be set. include_email (:class:`bool`): Include the service account email in the token. If set to ``true``, the token will contain ``email`` and ``email_verified`` claims. This corresponds to the ``include_email`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.common.GenerateIdTokenResponse: """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([name, delegates, audience, include_email]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) request = common.GenerateIdTokenRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if delegates is not None: request.delegates = delegates if audience is not None: request.audience = audience if include_email is not None: request.include_email = include_email # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method.wrap_method( self._transport.generate_id_token, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, client_info=_client_info, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def sign_blob( self, request: common.SignBlobRequest = None, *, name: str = None, delegates: Sequence[str] = None, payload: bytes = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. Args: request (:class:`~.common.SignBlobRequest`): The request object. name (:class:`str`): Required. The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. delegates (:class:`Sequence[str]`): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``delegates`` field on the ``request`` instance; if ``request`` is provided, this should not be set. payload (:class:`bytes`): Required. The bytes to sign. This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.common.SignBlobResponse: """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([name, delegates, payload]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) request = common.SignBlobRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if delegates is not None: request.delegates = delegates if payload is not None: request.payload = payload # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method.wrap_method( self._transport.sign_blob, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, client_info=_client_info, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def sign_jwt( self, request: common.SignJwtRequest = None, *, name: str = None, delegates: Sequence[str] = None, payload: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. Args: request (:class:`~.common.SignJwtRequest`): The request object. name (:class:`str`): Required. The resource name of the service account for which the credentials are requested, in the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. delegates (:class:`Sequence[str]`): The sequence of service accounts in a delegation chain. Each service account must be granted the ``roles/iam.serviceAccountTokenCreator`` role on its next service account in the chain. The last service account in the chain must be granted the ``roles/iam.serviceAccountTokenCreator`` role on the service account that is specified in the ``name`` field of the request. The delegates must have the following format: ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``. The ``-`` wildcard character is required; replacing it with a project ID is invalid. This corresponds to the ``delegates`` field on the ``request`` instance; if ``request`` is provided, this should not be set. payload (:class:`str`): Required. The JWT payload to sign: a JSON object that contains a JWT Claims Set. This corresponds to the ``payload`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.common.SignJwtResponse: """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([name, delegates, payload]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) request = common.SignJwtRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if delegates is not None: request.delegates = delegates if payload is not None: request.payload = payload # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method.wrap_method( self._transport.sign_jwt, default_retry=retries.Retry( initial=0.1, maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, client_info=_client_info, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response try: _client_info = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-iam",).version, ) except pkg_resources.DistributionNotFound: _client_info = gapic_v1.client_info.ClientInfo() __all__ = ("IAMCredentialsClient",)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 12131, 3012, 11419, 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, 4...
2.296251
12,989
# Copyright 2016 RedHat, Inc. # # 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. from os_testr import regex_builder import re def construct_list(blacklist_file, whitelist_file, regex, black_regex, print_exclude): """Filters the discovered test cases :retrun: iterable of strings. The strings are full test cases names, including tags like.: "project.api.TestClass.test_case[positive]" """ if not regex: regex = '' # handle the other false things if whitelist_file: white_re = regex_builder.get_regex_from_whitelist_file(whitelist_file) else: white_re = '' if not regex and white_re: regex = white_re elif regex and white_re: regex = '|'.join((regex, white_re)) if blacklist_file: black_data = black_reader(blacklist_file) else: black_data = None if black_regex: msg = "Skipped because of regex provided as a command line argument:" record = (re.compile(black_regex), msg, []) if black_data: black_data.append(record) else: black_data = [record] search_filter = re.compile(regex) # NOTE(afazekas): we do not want to pass a giant re # to an external application due to the arg length limitatios list_of_test_cases = [test_case for test_case in regex_builder._get_test_list('') if search_filter.search(test_case)] set_of_test_cases = set(list_of_test_cases) if not black_data: return set_of_test_cases # NOTE(afazekas): We might use a faster logic when the # print option is not requested for (rex, msg, s_list) in black_data: for test_case in list_of_test_cases: if rex.search(test_case): # NOTE(mtreinish): In the case of overlapping regex the test # case might have already been removed from the set of tests if test_case in set_of_test_cases: set_of_test_cases.remove(test_case) s_list.append(test_case) if print_exclude: for (rex, msg, s_list) in black_data: if s_list: print_skips(rex, msg, s_list) return set_of_test_cases
[ 2, 15069, 1584, 2297, 40483, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743...
2.442004
1,138
from functions_framework._cli import _cli _cli(prog_name="python -m functions_framework")
[ 6738, 5499, 62, 30604, 13557, 44506, 1330, 4808, 44506, 198, 198, 62, 44506, 7, 1676, 70, 62, 3672, 2625, 29412, 532, 76, 5499, 62, 30604, 4943, 198 ]
3.37037
27
# Generated by Django 2.2 on 2019-06-03 10:27 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 319, 13130, 12, 3312, 12, 3070, 838, 25, 1983, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
import threading from .interface import show_message import time def stop_queue(): " Stop all tasks. " for thread in threading.enumerate(): if isinstance(thread, Task): thread.stop() show_message('%s stopped.' % thread.title) def add_task(target, callback=None, buffer=None, title=None, *args, **kwargs): " Add all tasks. " task = Task(buffer, title=title, target=target, callback=callback, args=args, kwargs=kwargs) task.daemon = True task.start() show_message('%s started.' % task.title) def check_task(): " Check tasks for result. " for thread in threading.enumerate(): if isinstance(thread, Task): if thread.finished: thread.stop() thread.callback(thread.result) else: show_message('%s %s%%' % (thread.title, thread.done))
[ 11748, 4704, 278, 198, 6738, 764, 39994, 1330, 905, 62, 20500, 198, 11748, 640, 628, 198, 198, 4299, 2245, 62, 36560, 33529, 198, 220, 220, 220, 366, 13707, 477, 8861, 13, 366, 198, 220, 220, 220, 329, 4704, 287, 4704, 278, 13, 268,...
2.395664
369
""" 基于内存进行去重,非持久 """ from base import BaseFilter
[ 37811, 198, 161, 253, 118, 12859, 236, 37863, 227, 27764, 246, 32573, 249, 26193, 234, 43889, 119, 34932, 235, 171, 120, 234, 165, 251, 252, 162, 234, 223, 20046, 227, 198, 37811, 198, 6738, 2779, 1330, 7308, 22417, 628, 628, 198 ]
1.292683
41
from .cli import create, execute from .benefactor_permissions_report import BenefactorPermissionsReport from .benefactor_view import BenefactorView
[ 6738, 764, 44506, 1330, 2251, 11, 12260, 198, 6738, 764, 36934, 11218, 62, 525, 8481, 62, 13116, 1330, 19899, 11218, 5990, 8481, 19100, 198, 6738, 764, 36934, 11218, 62, 1177, 1330, 19899, 11218, 7680, 198 ]
4.228571
35
""" In here we create a discrete state space representation which can be used in learning algorithms such as Q-Learning. The state space is intended to represent a single transaction sufficiently, meaning it should include all relevant information that an agent could use when making a decision; and it should not include any unnecessary information. """ # the number of different amount categories we use NUM_AMOUNT_CAT = 6 NUM_CURRENCY_CAT = 4 # the actual size of the state space; the product of the above SIZE = NUM_AMOUNT_CAT def get_state(customer): """ Given to the authenticator is the customer, which holds all the information about the current transaction. :param customer: :return: """ amount_cat = get_amount_category(customer.curr_amount) return amount_cat
[ 37811, 198, 818, 994, 356, 2251, 257, 28810, 1181, 2272, 10552, 198, 4758, 460, 307, 973, 287, 4673, 16113, 884, 355, 1195, 12, 41730, 13, 198, 464, 1181, 2272, 318, 5292, 284, 2380, 257, 2060, 8611, 17338, 11, 198, 24815, 340, 815, ...
3.684932
219
from system.forms import Forms from system.logger import * from dialogs.select_dialog import * @class_wrapper @class_wrapper class NewPurchaseForm(_edit_purch_form): ''' ''' @class_wrapper class EditPurchaseForm(_edit_purch_form): ''' '''
[ 6738, 1080, 13, 23914, 1330, 39196, 198, 6738, 1080, 13, 6404, 1362, 1330, 1635, 198, 6738, 17310, 82, 13, 19738, 62, 38969, 519, 1330, 1635, 198, 198, 31, 4871, 62, 48553, 198, 198, 31, 4871, 62, 48553, 198, 4871, 968, 47651, 8479, ...
2.755319
94
from time import process_time, sleep from PyQt5.QtCore import pyqtRemoveInputHook from exec import pomodoro as pomodoro import gui3 import gui31 from threading import Thread import os import psutil import sys if __name__ == "__main__": #print("buscu") worker1() #worker2() t2 =Thread(target = worker2) t3 =Thread(target = worker3) t2.start() t3.start() #Kill all process while True: sleep(1) if (t2.is_alive()== False): psutil.Process(os.getpid()).kill() break
[ 6738, 640, 1330, 1429, 62, 2435, 11, 3993, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 12972, 39568, 27914, 20560, 39, 566, 201, 198, 6738, 2452, 1330, 279, 296, 375, 16522, 355, 279, 296, 375, 16522, 201, 198, 11748,...
2.214286
252
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from app import app data = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four' } layout = html.Div([ html.H1('Hello World!'), dcc.Slider(id='demo-slider', min=1, max=4, value=1), html.H3(data[1], id='demo-text') ]) @app.callback( Output('demo-text', 'children'), Input('demo-slider', 'value') )
[ 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 6738, 14470, 13, 45841, 3976, 1330, 23412, 11, 25235, 198, 198, 6738, 598, 1330, 598, 198, 198, 7890, 796, 1391, 198,...
2.319372
191
#!/usr/bin/env python import json import os from watson_developer_cloud import PersonalityInsightsV3 def insights(user_text): """ Analyze text using IBM Personality Insights. ``pip install --upgrade watson-developer-cloud`` This code is based on the `IBM Watson Python SDK`_ docs. Environment variables must be set with Personality Insights authentication data before this function is invoked. Where do I get or generate an API key? The `IBM API KEY`_ docs are confusing. .. _IBM Watson Python SDK: https://github.com/watson-developer-cloud/python-sdk .. _IBM API KEY: https://console.bluemix.net/docs/resources/service_credentials.html#service_credentials """ insights = PersonalityInsightsV3( version = '2017-10-13', username = os.environ.get("PI_USERNAME"), password = os.environ.get("PI_PASSWORD") #iam_api_key = os.environ.get("PI_API_KEY") ) return insights.profile( user_text, content_type = 'text/plain;charset=utf-8', raw_scores = True, consumption_preferences = True ) text = """Ipsum lorem. """ * 100 insightful_json = insights(text) print(json.dumps(insightful_json, indent=2))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 33918, 198, 11748, 28686, 198, 198, 6738, 266, 13506, 62, 16244, 263, 62, 17721, 1330, 30472, 20376, 2337, 53, 18, 628, 198, 4299, 17218, 7, 7220, 62, 5239, 2599, 198, 220,...
2.889163
406
from microbit import * sleep(10000) display.scroll(str(button_a.get_presses()))
[ 6738, 4580, 2545, 1330, 1635, 198, 42832, 7, 49388, 8, 198, 13812, 13, 48728, 7, 2536, 7, 16539, 62, 64, 13, 1136, 62, 8439, 274, 3419, 4008 ]
2.925926
27
VERSION = "0.2.2-SNAPSHOT"
[ 198, 43717, 796, 366, 15, 13, 17, 13, 17, 12, 15571, 2969, 9693, 2394, 1, 198 ]
1.75
16
__author__ = 'sibirrer' from astrofunc.LensingProfiles.spp import SPP from astrofunc.LensingProfiles.spemd_smooth import SPEMD_SMOOTH class SPEMD(object): """ class for smooth power law ellipse mass density profile """ def mass_3d_lens(self, r, theta_E, gamma, q, phi_G): """ computes the spherical power-law mass enclosed (with SPP routiune) :param r: :param theta_E: :param gamma: :param q: :param phi_G: :return: """ return self.spp.mass_3d_lens(r, theta_E, gamma) def convert_params(self, theta_E, gamma, q): """ :param theta_E: Einstein radius :param gamma: power law slope :param q: axis ratio :return: prefactor to SPEMP profile for FASTELL """ return self.spemd_smooth.convert_params(theta_E, gamma, q)
[ 834, 9800, 834, 796, 705, 82, 571, 343, 11751, 6, 198, 198, 6738, 6468, 305, 20786, 13, 43, 26426, 15404, 2915, 13, 82, 381, 1330, 6226, 47, 198, 6738, 6468, 305, 20786, 13, 43, 26426, 15404, 2915, 13, 2777, 368, 67, 62, 5796, 522...
2.142157
408
import gspread import gspread.utils
[ 11748, 308, 43639, 198, 11748, 308, 43639, 13, 26791, 628, 198 ]
3.454545
11
from __future__ import unicode_literals # Python 2/3 compatibility # from __future__ import print_function # Python 2/3 compatibility # import sys import argparse import modelio from parser import TokenParser from trainer import MarkovTrainer from generator import MarkovGenerator parser = argparse.ArgumentParser(description='Markov model trainer.') subparsers = parser.add_subparsers(help='sub-command help') # 'train' command parser train_parser = subparsers.add_parser('train', help='train model using text data') train_parser.add_argument('model', help='output model', nargs=1) train_parser.add_argument('text', help='training data', nargs='*', type=argparse.FileType('r'), default=sys.stdin) train_parser.add_argument('-d', '--depth', help='memory depth', nargs=1, type=int, default=[1]) train_parser.add_argument('--matrix', help='matrix format', action="store_true") def train(args): """Command for training a new Markov model.""" if args.depth[0] < 0: exit('{0}: error: argument -d/--depth: invalid negative value: {1}'.format(sys.argv[0], args.depth[0])) Trainer = MarkovTrainer(args.depth[0]) for data in args.text: Trainer.train(TokenParser(data)) if args.matrix: modelio.write_matrix(args.model[0], Trainer.model()) else: modelio.write_sparse(args.model[0], Trainer.model()) train_parser.set_defaults(func=train) # 'random' command parser random_parser = subparsers.add_parser('random', help='generate random text using model') random_parser.add_argument('model', help='input model', nargs=1) random_parser.add_argument('count', help='token count', nargs='?', type=int, default=100) random_parser.add_argument('-d', '--depth', help='memory depth', nargs=1, type=int, default=[1]) random_parser.add_argument('--matrix', help='matrix format', action="store_true") def random(args): """Command for generating random data using a Markov model.""" if args.depth[0] < 0: exit('{0}: error: argument -d/--depth: invalid negative value: {1}'.format(sys.argv[0], args.depth[0])) if args.count <= 0: exit('{0}: error: token count must be positive, got: {1}.'.format(sys.argv[0], args.count)) if args.matrix: model = modelio.read_matrix(args.model[0]) args.depth[0] = 1 # Force depth 1 for matrix format else: model = modelio.read_sparse(args.model[0]) Generator = MarkovGenerator(model, depth=args.depth[0]) print(' '.join([Generator.next() for i in range(args.count)])) random_parser.set_defaults(func=random) args = parser.parse_args() args.func(args)
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 1303, 11361, 362, 14, 18, 17764, 1303, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 220, 220, 1303, 11361, 362, 14, 18, 17764, 1303, 198, 198, 11748, 25064, 198, 11748, ...
2.764706
952
import qsharp from BB84 import Start import onetimepad success, aliceKey, BobKey = Start.simulate() binaryKeyAlice = "" binaryKeyBob = "" for each in aliceKey: if each is True: binaryKeyAlice = binaryKeyAlice + "1" else: binaryKeyAlice = binaryKeyAlice + "0" for each in BobKey: if each is True: binaryKeyBob = binaryKeyBob + "1" else: binaryKeyBob = binaryKeyBob + "0" message = "hello quantum world" cipher = onetimepad.encrypt(message, binaryKeyAlice) print("Cipher Text: ", cipher) # Decryption plaintext = onetimepad.decrypt(cipher, binaryKeyBob) print(plaintext)
[ 11748, 10662, 48554, 198, 6738, 12597, 5705, 1330, 7253, 198, 11748, 319, 8079, 15636, 198, 198, 13138, 11, 435, 501, 9218, 11, 5811, 9218, 796, 7253, 13, 14323, 5039, 3419, 198, 198, 39491, 9218, 44484, 796, 13538, 198, 39491, 9218, 18...
2.69697
231
from django.contrib.auth import get_user_model import factory DEFAULT_USER_PASSWORD = 'password'
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 198, 11748, 8860, 628, 198, 7206, 38865, 62, 29904, 62, 47924, 54, 12532, 796, 705, 28712, 6, 628 ]
3.060606
33
"""Exceptions related to PopNet. """ class PopNetError(Exception): """Generic class for exceptions related to PopNet.""" pass class FormatError(PopNetError): """Exceptions related to formatting errors in files handled by PopNet.""" pass class PopNetWarning(Warning): """Generic class for warnings related to PopNet.""" pass
[ 37811, 3109, 11755, 3519, 284, 8099, 7934, 13, 201, 198, 201, 198, 37811, 201, 198, 201, 198, 4871, 8099, 7934, 12331, 7, 16922, 2599, 201, 198, 220, 220, 220, 37227, 46189, 1398, 329, 13269, 3519, 284, 8099, 7934, 526, 15931, 201, 19...
3.049587
121
# Generated by Django 3.2.7 on 2021-11-15 17:12 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 22, 319, 33448, 12, 1157, 12, 1314, 1596, 25, 1065, 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
# Copyright (c) 2021, Mahmood Sharif, Keane Lucas, Michael K. Reiter, Lujo Bauer, and Saurabh Shintre # This file is code used in Malware Makeover """ Code to develop/test code-displacement transformations. """ import random import time random.seed(time.time()) import sys sys.path.append('orp') import peLib import copy import func import inp import disp import semnops from randtoolkit import reanalyze_functions, patch VER="0.3" if __name__=="__main__": binary_paths = [\ 'test/caffeine/caffeine.exe', \ 'test/checksum-cygwin/cksum.exe', \ # 'test/diff-cygwin/diff.exe', \ # 'test/find-cygwin/find.exe', \ # 'test/grep-cygwin/grep.exe', \ # 'test/info-cygwin/info.exe', \ # 'test/less-cygwin/less.exe', \ # 'test/mv-cygwin/mv.exe', \ 'test/python/python.exe', \ 'test/pip/pip.exe' ] for bin_path in binary_paths: print('====================') print('Testing with "%s"...'%(bin_path)) # displace(bin_path, n_randomize=5) test_displace_w_budget(bin_path)
[ 2, 15069, 357, 66, 8, 33448, 11, 31556, 702, 44144, 11, 46160, 15257, 11, 3899, 509, 13, 797, 2676, 11, 6026, 7639, 41971, 11, 290, 46197, 397, 71, 911, 600, 260, 198, 2, 770, 2393, 318, 2438, 973, 287, 4434, 1574, 6889, 2502, 198...
2.067138
566
#!/usr/bin/env python3.8 # Copyright 2021 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Suggests OWNERS for projects in a jiri manifest without owners. For each project in a given jiri manifest file, do the following: 1. Check if it has an OWNERS file at the root path. If so, skip. 2. Find references to the project via `gn refs`. If none, skip. 3. Find immediate owners for all referrers. If none, for each referrer travel one directory up and continue the search. Ignore root owners. Example usage: $ fx set ... $ scripts/owner/suggest_owners.py \ --jiri_manifest integration/third_party/flower """ import argparse import os import re import subprocess import sys import xml.etree.ElementTree as ET # Matches a valid email address, more or less. EMAIL = re.compile("^[\w%+-]+@[\w.-]+\.[a-zA-Z]{2,}$") if __name__ == "__main__": sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 23, 198, 2, 15069, 33448, 383, 376, 37533, 544, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, ...
3.160131
306
import json with open("Data/sarcasm.json", 'r') as f: datastore = json.load(f) sentences = [] labels = [] urls = [] for item in datastore: sentences.append(item['headline']) labels.append(item['is_sarcastic']) urls.append(item['article_link']) from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences #Tokenizer tokenizer = Tokenizer(oov_token="<OOV>") tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index print(len(word_index)) print(word_index) #Padding sequences = tokenizer.texts_to_sequences(sentences) padded = pad_sequences(sequences, padding='post') print(padded[0]) print(padded.shape)
[ 11748, 33918, 201, 198, 201, 198, 4480, 1280, 7203, 6601, 14, 82, 5605, 8597, 13, 17752, 1600, 705, 81, 11537, 355, 277, 25, 201, 198, 220, 220, 220, 4818, 459, 382, 796, 33918, 13, 2220, 7, 69, 8, 201, 198, 201, 198, 34086, 3007,...
2.486395
294
from __future__ import absolute_import, print_function import torch import torch.nn as nn import torch.nn.functional as F from code.models.backbone.ResNet_Dilated import _ConvBnReLU from collections import OrderedDict
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 2438, 13, 27530, 13, 1891, 15992, 13...
3.421875
64
import os import glob from .env import IS_WINDOWS, IS_CONDA, CONDA_DIR, check_negative_env_flag, gather_paths, lib_paths_from_base from .cuda import USE_CUDA, CUDA_HOME USE_CUDNN = False CUDNN_LIB_DIR = None CUDNN_INCLUDE_DIR = None CUDNN_LIBRARY = None WITH_STATIC_CUDNN = os.getenv("USE_STATIC_CUDNN") if USE_CUDA and not check_negative_env_flag('USE_CUDNN'): lib_paths = list(filter(bool, [ os.getenv('CUDNN_LIB_DIR') ] + lib_paths_from_base(CUDA_HOME) + [ '/usr/lib/x86_64-linux-gnu/', '/usr/lib/powerpc64le-linux-gnu/', '/usr/lib/aarch64-linux-gnu/', ] + gather_paths([ 'LIBRARY_PATH', ]) + gather_paths([ 'LD_LIBRARY_PATH', ]))) include_paths = list(filter(bool, [ os.getenv('CUDNN_INCLUDE_DIR'), os.path.join(CUDA_HOME, 'include'), '/usr/include/', ] + gather_paths([ 'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH', ]))) # Add CUDA related dirs to candidate list if IS_CONDA: lib_paths.append(os.path.join(CONDA_DIR, 'lib')) include_paths.append(os.path.join(CONDA_DIR, 'include')) for path in include_paths: if path is None or not os.path.exists(path): continue include_file_path = os.path.join(path, 'cudnn.h') CUDNN_INCLUDE_VERSION = None if os.path.exists(include_file_path): CUDNN_INCLUDE_DIR = path with open(include_file_path) as f: for line in f: if "#define CUDNN_MAJOR" in line: CUDNN_INCLUDE_VERSION = int(line.split()[-1]) break if CUDNN_INCLUDE_VERSION is None: raise AssertionError("Could not find #define CUDNN_MAJOR in " + include_file_path) break if CUDNN_INCLUDE_VERSION is None: pass # Check for standalone cuDNN libraries if CUDNN_INCLUDE_DIR is not None: cudnn_path = os.path.join(os.path.dirname(CUDNN_INCLUDE_DIR)) cudnn_lib_paths = lib_paths_from_base(cudnn_path) lib_paths.extend(cudnn_lib_paths) for path in lib_paths: if path is None or not os.path.exists(path): continue if IS_WINDOWS: library = os.path.join(path, 'cudnn.lib') if os.path.exists(library): CUDNN_LIBRARY = library CUDNN_LIB_DIR = path break else: if WITH_STATIC_CUDNN is not None: search_name = 'libcudnn_static.a' else: search_name = 'libcudnn*' + str(CUDNN_INCLUDE_VERSION) + "*" libraries = sorted(glob.glob(os.path.join(path, search_name))) if libraries: CUDNN_LIBRARY = libraries[0] CUDNN_LIB_DIR = path break # Specifying the library directly will overwrite the lib directory library = os.getenv('CUDNN_LIBRARY') if library is not None and os.path.exists(library): CUDNN_LIBRARY = library CUDNN_LIB_DIR = os.path.dirname(CUDNN_LIBRARY) if not all([CUDNN_LIBRARY, CUDNN_LIB_DIR, CUDNN_INCLUDE_DIR]): CUDNN_LIBRARY = CUDNN_LIB_DIR = CUDNN_INCLUDE_DIR = None else: real_cudnn_library = os.path.realpath(CUDNN_LIBRARY) real_cudnn_lib_dir = os.path.realpath(CUDNN_LIB_DIR) assert os.path.dirname(real_cudnn_library) == real_cudnn_lib_dir, ( 'cudnn library and lib_dir must agree') USE_CUDNN = True
[ 11748, 28686, 198, 11748, 15095, 198, 198, 6738, 764, 24330, 1330, 3180, 62, 33207, 11, 3180, 62, 10943, 5631, 11, 7102, 5631, 62, 34720, 11, 2198, 62, 31591, 62, 24330, 62, 32109, 11, 6431, 62, 6978, 82, 11, 9195, 62, 6978, 82, 62,...
1.924209
1,834
# # NOTE: This is the settings file for the server at https://testing.onepercentclub.com # This is not for running tests! # try: from .secrets import * except ImportError: import sys sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.') from .server import * # # Put testing environment specific overrides below. # COWRY_RETURN_URL_BASE = 'https://testing.onepercentclub.com' COWRY_LIVE_PAYMENTS = False # Send email for real EMAIL_BACKEND = 'bluebottle.utils.email_backend.TestMailBackend' SESSION_COOKIE_NAME = 'bb-testing-session-id' SOUTH_TESTS_MIGRATE = False try: print "DEBUG", DEBUG except: pass
[ 2, 198, 2, 24550, 25, 770, 318, 262, 6460, 2393, 329, 262, 4382, 379, 3740, 1378, 33407, 13, 505, 25067, 18664, 13, 785, 198, 2, 220, 220, 220, 220, 220, 220, 770, 318, 407, 329, 2491, 5254, 0, 198, 2, 198, 198, 28311, 25, 198, ...
2.757202
243
from unittest import TestCase, mock from click.testing import CliRunner from kfk.commands.configs import kfk from kfk.kubectl_command_builder import Kubectl from kfk.constants import * from kfk.messages import *
[ 6738, 555, 715, 395, 1330, 6208, 20448, 11, 15290, 198, 6738, 3904, 13, 33407, 1330, 1012, 72, 49493, 198, 6738, 479, 69, 74, 13, 9503, 1746, 13, 11250, 82, 1330, 479, 69, 74, 198, 6738, 479, 69, 74, 13, 74, 549, 478, 75, 62, 21...
2.958333
72
'''Create a conftest.py Define the fixture functions in this file to make them accessible across multiple test files. ''' from pathlib import Path import pytest from tempfile import mkdtemp from beetools import rm_tree # from github import Github, GithubException as gh_exc _DESC = __doc__.split('\n')[0] _PATH = Path(__file__) # _CLASSIFIERS = [ # 'Development Status :: 1 - Planning', # 'Intended Audience :: Developers', # 'Intended Audience :: System Administrators', # 'Topic :: Software Development', # 'Topic :: System :: Systems Administration', # 'License :: OSI Approved :: MIT License', # 'Programming Language :: Python :: 3.0', # 'Programming Language :: Python :: 3.9', # 'Programming Language :: Python :: 3.10', # ] # _INDEX_RST_BADGE_CODECOV = \ # '''.. image:: https://img.shields.io/codecov/c/gh/hendrikdutoit/sqlalchemyexample # :alt: CodeCov # :target: https://app.codecov.io/gh/hendrikdutoit/sqlalchemyexample # # ''' # _INDEX_RST_BADGE_GITHUB_CI = \ # '''.. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/sqlalchemyexample/CI # :alt: GitHub Actions - CI # :target: https://github.com/hendrikdutoit/sqlalchemyexample/actions/workflows/ci.yaml # # ''' # _INDEX_RST_BADGE_GITHUB_HITS = \ # '''.. image:: https://img.shields.io/github/search/hendrikdutoit/sqlalchemyexample/GitHub hit # :alt: GitHub Searches # # ''' # _INDEX_RST_BADGE_GITHUB_LICENSE = \ # '''.. image:: https://img.shields.io/github/license/hendrikdutoit/sqlalchemyexample # :alt: License # # ''' # _INDEX_RST_BADGE_GITHUB_ISSUES = \ # '''.. image:: https://img.shields.io/github/issues-raw/hendrikdutoit/sqlalchemyexample # :alt: GitHub issues # # ''' # _INDEX_RST_BADGE_GITHUB_PRE_COMMIT = \ # '''.. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/sqlalchemyexample/Pre-Commit # :alt: GitHub Actions - Pre-Commit # :target: https://github.com/hendrikdutoit/sqlalchemyexample/actions/workflows/pre-commit.yaml # # ''' # _INDEX_RST_BADGE_GITHUB_RELEASE = \ # '''.. image:: https://img.shields.io/github/v/release/hendrikdutoit/sqlalchemyexample # :alt: GitHub release (latest by date) # # ''' # _INDEX_RST_BADGE_PYPI_VERSION = \ # '''.. image:: https://img.shields.io/testpypi/v/sqlalchemyexample # :alt: PyPi # # ''' # _INDEX_RST_BADGE_PYPI_DL = \ # '''.. image:: https://img.shields.io/pypi/dm/sqlalchemyexample # :alt: PyPI - Downloads # # ''' # _INDEX_RST_BADGE_PYPI_STATUS = \ # '''.. image:: https://img.shields.io/pypi/status/sqlalchemyexample # :alt: PyPI - Status # # ''' # _INDEX_RST_BADGE_PYPI_WHEEL = \ # '''.. image:: https://img.shields.io/pypi/wheel/sqlalchemyexample # :alt: PyPI - Wheel # # ''' # _INDEX_RST_BADGE_PYVERSIONS = \ # '''.. image:: https://img.shields.io/pypi/pyversions/sqlalchemyexample # :alt: PyPI - Python Version # # ''' # _INDEX_RST_CONTENTS = '''.. ====================================================== # .. This file is auto generated by PackageIt. Any changes # .. to it will be over written # .. ====================================================== # # ================================ # sqlalchemyexample # ================================ # # .. image:: https://img.shields.io/pypi/status/sqlalchemyexample # :alt: PyPI - Status # # .. image:: https://img.shields.io/pypi/wheel/sqlalchemyexample # :alt: PyPI - Wheel # # .. image:: https://img.shields.io/pypi/pyversions/sqlalchemyexample # :alt: PyPI - Python Version # # .. image:: https://img.shields.io/github/v/release/hendrikdutoit/sqlalchemyexample # :alt: GitHub release (latest by date) # # .. image:: https://img.shields.io/github/license/hendrikdutoit/sqlalchemyexample # :alt: License # # .. image:: https://img.shields.io/github/issues-raw/hendrikdutoit/sqlalchemyexample # :alt: GitHub issues # # .. image:: https://img.shields.io/pypi/dm/sqlalchemyexample # :alt: PyPI - Downloads # # .. image:: https://img.shields.io/github/search/hendrikdutoit/sqlalchemyexample/GitHub hit # :alt: GitHub Searches # # .. image:: https://img.shields.io/codecov/c/gh/hendrikdutoit/sqlalchemyexample # :alt: CodeCov # :target: https://app.codecov.io/gh/hendrikdutoit/sqlalchemyexample # # .. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/sqlalchemyexample/Pre-Commit # :alt: GitHub Actions - Pre-Commit # :target: https://github.com/hendrikdutoit/sqlalchemyexample/actions/workflows/pre-commit.yaml # # .. image:: https://img.shields.io/github/workflow/status/hendrikdutoit/sqlalchemyexample/CI # :alt: GitHub Actions - CI # :target: https://github.com/hendrikdutoit/sqlalchemyexample/actions/workflows/ci.yaml # # .. image:: https://img.shields.io/testpypi/v/sqlalchemyexample # :alt: PyPi # # Project Header Description (default ini) # # Project long description goes in here (default ini) # # ------------ # Installation # ------------ # # .. code-block:: bash # # $ pip install . # # ----- # Usage # ----- # # .. code-block:: bash # # Insert text in Usage.rst # # ------- # Support # ------- # # .. code-block:: bash # # Insert text in Support.rst # # .. toctree:: # :maxdepth: 2 # :caption: Contents # :numbered: # # conventions # api # donotexist # # ''' # _PROJECT_CLASSIFIERS = [ # 'Development Status :: 1 - Planning', # 'Intended Audience :: Developers', # 'Topic :: Software Development', # 'License :: OSI Approved :: MIT License', # 'Programming Language :: Python :: 3.0', # 'Programming Language :: Python :: 3.10', # ] _PROJECT_NAME = "sqlalchemyexample" _RELEASE_YAML_PROD = '''name: Build distribution on: [push, pull_request] jobs: ReleaseToPyPi: runs-on: "ubuntu-latest" steps: - name: Checkout source uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install build dependencies run: python -m pip install build wheel - name: Build distributions shell: bash -l sqlalchemyexample run: python setup.py sdist bdist_wheel - name: Publish package to PyPI uses: pypa/gh-action-pypi-publish@master with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} repository_url: https://upload.pypi.org/legacy/ verbose: true ''' _RELEASE_YAML_TEST = '''name: Build distribution on: [push, pull_request] jobs: ReleaseToPyPi: runs-on: "ubuntu-latest" steps: - name: Checkout source uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install build dependencies run: python -m pip install build wheel - name: Build distributions shell: bash -l sqlalchemyexample run: python setup.py sdist bdist_wheel - name: Publish package to PyPI uses: pypa/gh-action-pypi-publish@master with: user: __token__ password: ${{ secrets.TEST_PYPI_API_TOKEN }} repository_url: https://test.pypi.org/legacy/ verbose: true ''' @pytest.fixture def env_setup_self_destruct(): '''Set up the environment base structure''' setup_env = EnvSetUp() yield setup_env rm_tree(setup_env.dir, p_crash=False) @pytest.fixture def env_setup_with_project_ini_self_destruct(): '''Set up the environment base structure''' setup_env = EnvSetUp(p_make_project_ini=True) yield setup_env rm_tree(setup_env.dir, p_crash=False) @pytest.fixture def working_dir_self_destruct(): '''Set up the environment base structure''' working_dir = WorkingDir() yield working_dir rm_tree(working_dir.dir, p_crash=False)
[ 7061, 6, 16447, 257, 369, 701, 395, 13, 9078, 201, 198, 201, 198, 7469, 500, 262, 29220, 5499, 287, 428, 2393, 284, 787, 606, 9857, 1973, 3294, 1332, 3696, 13, 201, 198, 7061, 6, 201, 198, 6738, 3108, 8019, 1330, 10644, 201, 198, ...
2.339672
3,471
from pipelining.pipe_root import ConfigRoot from etl import maxqdata_manager, gold_data_transform_rules from pipelining import data_flow_registry from IPython import embed import main
[ 6738, 7347, 417, 3191, 13, 34360, 62, 15763, 1330, 17056, 30016, 198, 6738, 2123, 75, 1330, 3509, 80, 7890, 62, 37153, 11, 3869, 62, 7890, 62, 35636, 62, 38785, 198, 6738, 7347, 417, 3191, 1330, 1366, 62, 11125, 62, 2301, 4592, 198, ...
3.596154
52
useless_array = [' ','\n','\t','%']
[ 198, 84, 10950, 62, 18747, 796, 37250, 705, 4032, 59, 77, 41707, 59, 83, 41707, 4, 20520 ]
2.117647
17
from django.db import models from django.contrib.auth.models import User # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 198, 2, 13610, 534, 4981, 994, 13, 198, 220, 220 ]
3.322581
31
from luna.dataset.luna_dataset import LunaDataset from luna.dataset.exceptions import LunaDatasetNotSupportedException, LunaInvalidConfigException class LunaAzureMLFileDataset(LunaFileDataset): """ Download file(s) from Azure ML file dataset. Only supported when running in an Azure ML workspace. """ _azureml_dataset_name = "" def download(self, path): """ Download file(s) from Azure ML file dataset """ pass def upload(self, path): """ Upload function is not supported in LunaAzureMLFileDataset """ raise LunaDatasetNotSupportedException("Upload function is not supported in LunaAzureMLFileDataset")
[ 6738, 300, 9613, 13, 19608, 292, 316, 13, 75, 9613, 62, 19608, 292, 316, 1330, 23694, 27354, 292, 316, 198, 6738, 300, 9613, 13, 19608, 292, 316, 13, 1069, 11755, 1330, 23694, 27354, 292, 316, 3673, 48181, 16922, 11, 23694, 44651, 169...
2.713178
258
#!/usr/bin/python # Copyright 2019 Northern.tech AS # # 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. import pytest import subprocess from common import * @pytest.mark.commercial @pytest.mark.min_mender_version("2.1.0")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 13130, 8342, 13, 13670, 7054, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 345, 743...
3.257642
229
# -*- coding: utf-8 -*- """Test cascade.""" from compath.constants import EQUIVALENT_TO from compath.models import User from tests.constants import DatabaseMixin, KEGG, REACTOME class TestCascades(DatabaseMixin): """Test that votes are cascaded properly.""" def setUp(self): """Create fakes emails.""" super().setUp() self.u1 = User(email='my_email', id=1) self.u2 = User(email='my_email_fake', id=2) self.manager.session.add_all([self.u1, self.u2]) self.manager.session.commit() self.mapping_1, created_1 = self.manager.get_or_create_mapping( KEGG, '1', 'kegg pathway', REACTOME, '2', 'reactome pathway', EQUIVALENT_TO, self.u1 ) self.mapping_2, created_1 = self.manager.get_or_create_mapping( KEGG, '1', 'kegg pathway 2', REACTOME, '2', 'reactome pathway 2', EQUIVALENT_TO, self.u2 ) _ = self.manager.get_or_create_vote(self.u2, self.mapping_1) _ = self.manager.get_or_create_vote(self.u1, self.mapping_2) self.manager.session.commit() self.assertEqual(2, self.manager.count_users()) self.assertEqual(2, self.manager.count_mappings()) self.assertEqual(4, self.manager.count_votes()) def test_drop_all_mappings(self): """Test dropping all mappings.""" self.manager.delete_all_mappings() self.assertEqual(2, self.manager.count_users()) self.assertEqual(0, self.manager.count_mappings()) self.assertEqual(0, self.manager.count_votes()) def test_drop_mapping(self): """Test dropping a mapping.""" self.assertEqual(2, self.manager.count_users()) self.assertEqual(2, self.manager.count_mappings()) self.assertEqual(4, self.manager.count_votes()) self.assertEqual(2, self.manager.count_mapping_user()) self.manager.session.delete(self.mapping_1) self.manager.session.commit() self.assertEqual(2, self.manager.count_users()) self.assertEqual(1, self.manager.count_mappings()) self.assertEqual(2, self.manager.count_votes()) self.assertEqual(1, self.manager.count_mapping_user())
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 14402, 44847, 526, 15931, 628, 198, 6738, 552, 776, 13, 9979, 1187, 1330, 46886, 3824, 1847, 3525, 62, 10468, 198, 6738, 552, 776, 13, 27530, 1330, 11787, 19...
2.108326
1,117
import random import pokeconfig import pokemon_new import pokelist import pokeutils import pokemoves import movelist from telegram.ext import CommandHandler, CallbackQueryHandler from telegram import InputMediaPhoto from datetime import datetime typeTrans = { 'Grass': '🌱', 'Fire': '🔥', 'Water': '💧', 'Electric': '⚡', 'Normal': '🌐', 'Ice': '❄️', 'Fighting': '🥊', 'Poison': '☠️', 'Ground': '⛰', 'Flying': '🕊', 'Psychic': '🌀', 'Bug': '🐛', 'Rock': '🪨', 'Ghost': '👻', 'Dragon': '🐉', 'Dark': '🌑', 'Steel': '⚙️', 'Fairy': '🦄' } game = pokeconfig.CONFIG["pk"]
[ 11748, 4738, 198, 11748, 22620, 11250, 198, 11748, 43962, 62, 3605, 198, 11748, 22620, 4868, 198, 11748, 22620, 26791, 198, 11748, 22620, 76, 5241, 198, 11748, 6941, 626, 396, 198, 6738, 573, 30536, 13, 2302, 1330, 9455, 25060, 11, 4889, ...
2.093645
299
""" This settings file is an example of what you need to do to use the channels backend. """ from .base import * INSTALLED_APPS += ['channels'] TASK_RUNNER_BACKEND = 'fabric_bolt.task_runners.channels.ChannelsBackend'
[ 37811, 198, 1212, 6460, 2393, 318, 281, 1672, 286, 644, 345, 761, 284, 466, 284, 779, 262, 9619, 30203, 13, 198, 37811, 198, 198, 6738, 764, 8692, 1330, 1635, 198, 198, 38604, 7036, 1961, 62, 2969, 3705, 15853, 37250, 354, 8961, 20520...
2.986486
74
from . import util
[ 6738, 764, 1330, 7736, 628, 628 ]
3.666667
6
# -*- coding: utf-8 -*- import random from dataclasses import dataclass from aiohttp import web from mtpylon import Schema @dataclass schema = Schema(constructors=[Reply], functions=[echo])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 4738, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 257, 952, 4023, 1330, 3992, 198, 198, 6738, 285, 34788, 15158, 1330, 10011, 2611, 628, ...
2.940299
67
# ================================================================================== # Copyright (c) 2019 Nokia # Copyright (c) 2018-2019 AT&T Intellectual Property. # # 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. # ================================================================================== import pytest from ricxappframe.entities.rnib.nb_identity_pb2 import NbIdentity # These are here just to reduce the size of the code in test_rmr so those (important) tests are more readable; in theory these dicts could be large # The actual value of the constants should be ignored by the tests; all we should care # about is that the constant value was returned by the RMR function. Further, we should # not consider it an error if RMR returns more than what is listed here; these are the # list of what is/could be used by this package. @pytest.fixture @pytest.fixture @pytest.fixture
[ 2, 38093, 4770, 28, 198, 2, 220, 220, 220, 220, 220, 220, 15069, 357, 66, 8, 13130, 26182, 198, 2, 220, 220, 220, 220, 220, 220, 15069, 357, 66, 8, 2864, 12, 23344, 5161, 5, 51, 42443, 14161, 13, 198, 2, 198, 2, 220, 220, 4996...
3.827957
372
import tensorflow as tf import numpy as np import argparse import os import random import string import pickle as pkl import glob import design_bench as db from datetime import datetime if __name__ == "__main__": baseline_to_iteration = { "autofocused-cbas": 20, "cbas": 20, "bo-qei": 10, "cma-es": 0, "gradient-ascent": 200, "gradient-ascent-min-ensemble": 200, "gradient-ascent-mean-ensemble": 200, "mins": 0, "reinforce": 200 } parser = argparse.ArgumentParser() parser.add_argument("--input-dir", type=str, default="/home/btrabucco/mbo-results") parser.add_argument("--input-pkl", type=str, default="final_output.pkl") parser.add_argument("--out", type=str, default="/home/btrabucco/final-results") args = parser.parse_args() now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") digits_and_letters = list(string.digits) + list(string.ascii_letters) task = db.make("CIFARNAS-Exact-v0") task.map_to_logits() task.map_normalize_x() with open(args.input_pkl, "rb") as f: input_dict = pkl.load(f) for baseline, step in baseline_to_iteration.items(): solution_files = glob.glob(os.path.join( args.input_dir, f"{baseline}-nas/*/*/data/solution.npy")) step = tf.cast(tf.convert_to_tensor( baseline_to_iteration[baseline]), tf.int64) for solution_file in solution_files: solution = np.load(solution_file) if solution.shape == (128, 64, 4): solution = task.to_integers(task.denormalize_x(solution)) perf = [input_dict["-".join([str(xi) for xi in x])] for x in solution.tolist()] perf_50 = np.percentile(perf, 50) perf_80 = np.percentile(perf, 80) perf_90 = np.percentile(perf, 90) perf_100 = np.percentile(perf, 100) print(baseline, perf_50, perf_80, perf_90, perf_100) sweep_folder_name = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(solution_file)))) seed_folder_name = os.path.basename(os.path.dirname(os.path.dirname(solution_file))) output_dir = os.path.join( args.out, f"{baseline}-cifar-nas/" f"{sweep_folder_name}/{seed_folder_name}/data/") step = tf.cast(tf.convert_to_tensor( baseline_to_iteration[baseline]), tf.int64) tf.io.gfile.makedirs(output_dir) writer = tf.summary.create_file_writer(output_dir) with writer.as_default(): tf.summary.scalar( f'score/50th', perf_50, step=step) tf.summary.scalar( f'score/80th', perf_80, step=step) tf.summary.scalar( f'score/90th', perf_90, step=step) tf.summary.scalar( f'score/100th', perf_100, step=step)
[ 11748, 11192, 273, 11125, 355, 48700, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 28686, 201, 198, 11748, 4738, 201, 198, 11748, 4731, 201, 198, 11748, 2298, 293, 355, 279, 41582, 201, 198, 11...
1.923412
1,606
import gi gi.require_version('Handy', '0.0') gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Handy, Gio, GObject Handy.init() # Create Window window = Gtk.Window(title="LibHandy List example") window.set_border_width(10) # Create a Button # button = Gtk.Button.new_from_icon_name('battery-good', Gtk.IconSize.MENU ) button.set_label("Battery") button.connect("clicked", button_clicked) button.set_valign(Gtk.Align.CENTER) # Build Action Row # row1 = Handy.ActionRow() row1.set_icon_name('firefox-symbolic') row1.set_title("Action Row") row1.set_subtitle("this is a subtitle") row1.add_action(button) # Create List Store store = Gio.ListStore() store.append(Flatpak("flatseal", "flathub")) store.append(Flatpak("music", "flathub")) # Build Combo Row # row2 = Handy.ComboRow() row2.set_icon_name('face-wink') row2.set_title("Combo Row") row2.set_subtitle("this is a subtitle") row2.bind_name_model(store, bind_model_func) label = Gtk.Label.new("This is shown when expanded. This is hidden when not expanded") # Build Expandable Row # https://lazka.github.io/pgi-docs/#Handy-0.0/classes/ExpanderRow.html row3 = Handy.ExpanderRow() row3.set_icon_name('battery-good') row3.set_title("Expander Row") row3.set_subtitle("this is a subtitle") row3.set_expanded(False) row3.set_show_enable_switch(False) row3.add(label) row3.show_all() # Create List Box # https://lazka.github.io/pgi-docs/Gtk-3.0/classes/ListBox.html box = Gtk.ListBox() box.set_selection_mode(Gtk.SelectionMode.NONE) # Add Rows to List Box # https://lazka.github.io/pgi-docs/Gtk-3.0/classes/ListBox.html#Gtk.ListBox.insert box.insert(row1, -1) box.insert(row2, -1) box.insert(row3, -1) # Add List Box window.add(box) window.connect("destroy", Gtk.main_quit) window.show_all() Gtk.main()
[ 11748, 308, 72, 198, 198, 12397, 13, 46115, 62, 9641, 10786, 39, 10757, 3256, 705, 15, 13, 15, 11537, 198, 12397, 13, 46115, 62, 9641, 10786, 38, 30488, 3256, 705, 18, 13, 15, 11537, 198, 198, 6738, 308, 72, 13, 260, 1930, 37765, ...
2.455274
749
import unittest from tgl.utils import delete_user_data from tests.utils import setup_credentials, run_command, tgl_stop if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 256, 4743, 13, 26791, 1330, 12233, 62, 7220, 62, 7890, 198, 6738, 5254, 13, 26791, 1330, 9058, 62, 66, 445, 14817, 11, 1057, 62, 21812, 11, 256, 4743, 62, 11338, 628, 198, 198, 361, 11593, 3672,...
2.803279
61
import unittest from utils import *
[ 11748, 555, 715, 395, 198, 6738, 3384, 4487, 1330, 1635, 198 ]
3.272727
11
from ..utils import Object class SetAlarm(Object): """ Succeeds after a specified amount of time has passed. Can be called before authorization. Can be called before initialization Attributes: ID (:obj:`str`): ``SetAlarm`` Args: seconds (:obj:`float`): Number of seconds before the function returns Returns: Ok Raises: :class:`telegram.Error` """ ID = "setAlarm" @staticmethod
[ 198, 198, 6738, 11485, 26791, 1330, 9515, 628, 198, 4871, 5345, 2348, 1670, 7, 10267, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 47352, 2707, 82, 706, 257, 7368, 2033, 286, 640, 468, 3804, 13, 1680, 307, 1444, 878, 19601, ...
2.551913
183
import dateutil.utils from alice_blue import * import conf import logging from datetime import datetime import statistics from time import sleep logging.basicConfig(level=logging.DEBUG) ltp = 0 EMA_CROSS_SCRIP = 'INFY' NIFTY_BANK_IDX = '' lots = 1 sl_percentage = 0.25 # exit if it goes more than 25% on either size of our straddle if __name__ == '__main__': global socket_opened, bn_call, order_placed, ce_price, pe_price socket_opened = False access_token, alice = generate_key_token() if socket_opened == False: open_socket() get_bank_nifty_month() alice.subscribe(banknifty_script,LiveFeedType.MARKET_DATA) sleep(10) order_placed = False while datetime.now().time() <= time(9,30): sleep(60) try: while order_placed == False: curr_ltp = ltp atm_ce,atm_pe = int(curr_ltp/100)*100, int(curr_ltp/100)*100 alice.unsubscribe(banknifty_script, LiveFeedType.MARKET_DATA) get_data_curr_expiry(atm_ce) get_ce_curr_price(atm_ce) get_pe_curr_price(atm_pe) order_placed = True except Exception as e: print(e)
[ 11748, 3128, 22602, 13, 26791, 198, 6738, 435, 501, 62, 17585, 1330, 1635, 198, 11748, 1013, 198, 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 7869, 198, 6738, 640, 1330, 3993, 198, 198, 6404, 2667, 13, 35487, 1693...
2.230476
525
from src.server.token import devFlag import unittest
[ 6738, 12351, 13, 15388, 13, 30001, 1330, 1614, 34227, 201, 198, 11748, 555, 715, 395, 201, 198, 201, 198 ]
3
19
import os from dotenv import load_dotenv as ld
[ 11748, 28686, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 355, 300, 67, 198 ]
3
16
from setuptools import setup, find_packages setup(name='sproutnet', version='0.3.0', author='Sharpkoi', author_email='sharpkoi1222@gmail.com', license='LICENSE', description='neural network for learning and education.', packages=find_packages())
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 3672, 11639, 34975, 448, 3262, 3256, 198, 220, 220, 220, 220, 220, 2196, 11639, 15, 13, 18, 13, 15, 3256, 198, 220, 220, 220, 220, 220, 1772, 11639, 44336...
2.62037
108