content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from itertools import product import numpy as np import pandas as pd import pytest from sklearn.metrics import matthews_corrcoef as sk_matthews_corrcoef from evalml.objectives import ( F1, MAPE, MSE, AccuracyBinary, AccuracyMulticlass, BalancedAccuracyBinary, BalancedAccuracyMulticlass, BinaryClassificationObjective, CostBenefitMatrix, ExpVariance, F1Macro, F1Micro, F1Weighted, LogLossBinary, MCCBinary, MCCMulticlass, MeanSquaredLogError, Precision, PrecisionMacro, PrecisionMicro, PrecisionWeighted, Recall, RecallMacro, RecallMicro, RecallWeighted, RootMeanSquaredError, RootMeanSquaredLogError ) from evalml.objectives.utils import ( _all_objectives_dict, get_non_core_objectives ) EPS = 1e-5 all_automl_objectives = _all_objectives_dict() all_automl_objectives = {name: class_() for name, class_ in all_automl_objectives.items() if class_ not in get_non_core_objectives()} def test_calculate_percent_difference_negative_and_equal_numbers(): assert CostBenefitMatrix.calculate_percent_difference(score=5, baseline_score=5) == 0 assert CostBenefitMatrix.calculate_percent_difference(score=-5, baseline_score=-10) == 50 assert CostBenefitMatrix.calculate_percent_difference(score=-10, baseline_score=-5) == -100 assert CostBenefitMatrix.calculate_percent_difference(score=-5, baseline_score=10) == -150 assert CostBenefitMatrix.calculate_percent_difference(score=10, baseline_score=-5) == 300 # These values are not possible for LogLossBinary but we need them for 100% coverage # We might add an objective where lower is better that can take negative values in the future assert LogLossBinary.calculate_percent_difference(score=-5, baseline_score=-10) == -50 assert LogLossBinary.calculate_percent_difference(score=-10, baseline_score=-5) == 100 assert LogLossBinary.calculate_percent_difference(score=-5, baseline_score=10) == 150 assert LogLossBinary.calculate_percent_difference(score=10, baseline_score=-5) == -300 def test_calculate_percent_difference_small(): expected_value = 100 * -1 * np.abs(1e-9 / (1e-9)) assert np.isclose(ExpVariance.calculate_percent_difference(score=0, baseline_score=1e-9), expected_value, atol=1e-8) assert pd.isna(ExpVariance.calculate_percent_difference(score=0, baseline_score=1e-10)) assert pd.isna(ExpVariance.calculate_percent_difference(score=1e-9, baseline_score=0)) assert pd.isna(ExpVariance.calculate_percent_difference(score=0, baseline_score=0))
[ 6738, 340, 861, 10141, 1330, 1720, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 12972, 9288, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 23963, 40645, 62, 10215, 81, 1073, 891, 355, 1341,...
2.677584
977
import os import urllib.parse import eventlet import eventlet.green.socket # eventlet.monkey_patch() import eventlet.websocket import eventlet.wsgi import wspty.pipe from flask import Flask, request, redirect from wspty.EchoTerminal import EchoTerminal from wspty.EncodedTerminal import EncodedTerminal from wspty.WebsocketBinding import WebsocketBinding import config def make_parser(): import argparse parser = argparse.ArgumentParser(description='Websocket Terminal server') parser.add_argument('-l', '--listen', default='', help='Listen on interface (default all)') parser.add_argument('-p', '--port', default=5002, type=int, help='Listen on port') parser.add_argument('--unsafe', action='store_true', help='Allow unauthenticated connections to local machine') return parser def start(interface, port, root_app_handler): conn = (interface, port) listener = eventlet.listen(conn) print('listening on {0}:{1}'.format(*conn)) try: eventlet.wsgi.server(listener, root_app_handler) except KeyboardInterrupt: pass def start_default(interface, port, allow_unsafe=False, root_app_cls=DefaultRootApp): root_app = root_app_cls() root_app.allow_unsafe = allow_unsafe start(interface, port, root_app.handler) app = make_app() if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 2956, 297, 571, 13, 29572, 198, 198, 11748, 1785, 1616, 198, 11748, 1785, 1616, 13, 14809, 13, 44971, 198, 2, 1785, 1616, 13, 49572, 62, 17147, 3419, 198, 11748, 1785, 1616, 13, 732, 1443, 5459, 198, 11748, 1...
2.907127
463
# -*- encoding: utf-8 -*- """ Unit test for roger_promote.py """ import tests.helper import unittest import os import os.path import pytest import requests from mockito import mock, Mock, when from cli.roger_promote import RogerPromote from cli.appconfig import AppConfig from cli.settings import Settings from cli.framework import Framework from cli.frameworkUtils import FrameworkUtils from cli.marathon import Marathon from cli.chronos import Chronos
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 26453, 1332, 329, 686, 1362, 62, 16963, 1258, 13, 9078, 198, 198, 37811, 198, 198, 11748, 5254, 13, 2978, 525, 198, 198, 11748, 555, 715, 395, 198, 11...
3.253521
142
import json import pandas as pd import requests def load_jh_df(csv): ''' Loads a CSV file from JH repository and make some transforms ''' jh_data_path = ( 'https://raw.githubusercontent.com/' 'CSSEGISandData/COVID-19/master/' 'csse_covid_19_data/csse_covid_19_time_series/' ) return ( pd.read_csv( jh_data_path + csv[1] ) .drop(['Lat', 'Long'], axis=1) .groupby('Country/Region') .sum() .reset_index() .rename( columns={'Country/Region':'country'} ) .melt( id_vars=['country'], var_name='date', value_name=csv[0] ) .assign( date=lambda x: pd.to_datetime( x['date'], format='%m/%d/%y' ) ) ) def load_jh_data(): ''' Loads the latest COVID-19 global data from Johns Hopkins University repository ''' cases_csv = ('cases', 'time_series_19-covid-Confirmed.csv') deaths_csv = ('deaths', 'time_series_19-covid-Deaths.csv') recovered_csv = ('recoveries', 'time_series_19-covid-Recovered.csv') return ( pd.merge( pd.merge( load_jh_df(cases_csv), load_jh_df(deaths_csv) ), load_jh_df(recovered_csv) ) .reindex( columns = ['date', 'cases', 'deaths', 'recoveries', 'country'] ) ) if __name__ == '__main__': try: load_dump_covid_19_data() except Exception as e: print(f'Error when collecting COVID-19 cases data: {repr(e)}') try: load_dump_uf_pop() except Exception as e: print(f'Error when collecting population data: {repr(e)}')
[ 11748, 33918, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 7007, 628, 198, 198, 4299, 3440, 62, 73, 71, 62, 7568, 7, 40664, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 8778, 82, 257, 44189, 2393, 422, 449, 39, 16...
1.781457
1,057
import config as cfg import utils import native_code.executor as executor number_performed_tests = 0 expectations_correct = 0 expectations_wrong = 0 # The expect functions don't throw an exception like the assert_* functions # Instead, they just count how often the expected result was true # The expect functions don't throw an exception like the assert_* functions # Instead, they just count how often the expected result was true
[ 11748, 4566, 355, 30218, 70, 198, 11748, 3384, 4487, 198, 11748, 6868, 62, 8189, 13, 18558, 38409, 355, 3121, 273, 628, 198, 198, 17618, 62, 525, 12214, 62, 41989, 796, 657, 198, 1069, 806, 602, 62, 30283, 796, 657, 198, 1069, 806, ...
3.840336
119
from .one import * fruit = 'banana' colour = 'orange' sam['eggs'] = 'plenty' sam.pop('ham')
[ 6738, 764, 505, 1330, 1635, 201, 198, 201, 198, 34711, 796, 705, 3820, 2271, 6, 201, 198, 49903, 796, 705, 43745, 6, 201, 198, 37687, 17816, 33856, 82, 20520, 796, 705, 489, 3787, 6, 201, 198, 37687, 13, 12924, 10786, 2763, 11537, 2...
2.25
44
from django.urls import path, include from rest_framework_jwt.views import obtain_jwt_token from rest_framework.routers import DefaultRouter from .views import NoteViewSet app_name = 'api' router = DefaultRouter(trailing_slash=False) router.register('notes', NoteViewSet) urlpatterns = [ path('jwt-auth/', obtain_jwt_token), path('', include(router.urls)), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 6738, 1334, 62, 30604, 62, 73, 46569, 13, 33571, 1330, 7330, 62, 73, 46569, 62, 30001, 198, 6738, 1334, 62, 30604, 13, 472, 1010, 1330, 15161, 49, 39605, 198, 198, 6738, 7...
2.853846
130
from planning_framework import path import cv2 as cv import numpy as np import argparse import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description="Path Planning Visualisation") parser.add_argument( "-n", "--n_heuristic", default=2, help="Heuristic for A* Algorithm (default = 2). 0 for Dijkstra's Algorithm", ) args = parser.parse_args() N_H = int(args.n_heuristic) drawing = False # true if mouse is pressed mode = "obs" # if True, draw rectangle. Press 'm' to toggle to curve ix, iy = -1, -1 sx, sy = 0, 0 dx, dy = 50, 50 # mouse callback function img = np.zeros((512, 512, 3), np.uint8) inv_im = np.ones(img.shape) * 255 cv.namedWindow("Draw the Occupancy Map") cv.setMouseCallback("Draw the Occupancy Map", draw) while 1: cv.imshow("Draw the Occupancy Map", inv_im - img) if cv.waitKey(20) & 0xFF == 27: break cv.destroyAllWindows() mode = "src" img_ = img cv.namedWindow("Set the Starting Point") cv.setMouseCallback("Set the Starting Point", draw) while 1: cv.imshow("Set the Starting Point", inv_im - img) if cv.waitKey(20) & 0xFF == 27: break # cv.waitKey(20) cv.destroyAllWindows() mode = "dst" end = "Set the End Point" cv.namedWindow(end) cv.setMouseCallback(end, draw) while cv.getWindowProperty(end, 0) >= 0: cv.imshow(end, inv_im - img) if cv.waitKey(20) & 0xFF == 27: break cv.destroyAllWindows() img = cv.resize(img_, (50, 50), interpolation=cv.INTER_AREA) inv_img = np.ones(img.shape) np.savetxt("map.txt", np.array(img[:, :, 0])) plt.imshow(inv_img - img) start = np.array([sx, sy]) * 50 // 512 end = np.array([dx, dy]) * 50 // 512 path(start, end, N_H)
[ 6738, 5410, 62, 30604, 1330, 3108, 198, 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 48610, 796, 1822, 29572, 13...
2.497015
670
n = int(input()) line = list(map(int, input().split())) l = {} res = "" for i, j in enumerate(line): l[j] = i+1 for k in range(n): res += str(l[k+1]) + " " print(res.rstrip())
[ 77, 796, 493, 7, 15414, 28955, 198, 1370, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 4008, 198, 75, 796, 23884, 198, 411, 796, 13538, 198, 198, 1640, 1312, 11, 474, 287, 27056, 378, 7, 1370, 2599, 198, 220, 220, 220...
2.137931
87
import pandas as pd if __name__ == '__main__': main() print('generating y = 3x+6...')
[ 11748, 19798, 292, 355, 279, 67, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198, 220, 220, 220, 3601, 10786, 8612, 803, 331, 796, 513, 87, 10, 21, 986, 11537 ]
2.375
40
import re from pkg_resources import parse_requirements import pathlib from setuptools import find_packages, setup README_FILE = 'README.md' REQUIREMENTS_FILE = 'requirements.txt' VERSION_FILE = 'mtg/_version.py' VERSION_REGEXP = r'^__version__ = \'(\d+\.\d+\.\d+)\'' r = re.search(VERSION_REGEXP, open(VERSION_FILE).read(), re.M) if r is None: raise RuntimeError(f'Unable to find version string in {VERSION_FILE}.') version = r.group(1) long_description = open(README_FILE, encoding='utf-8').read() install_requires = [str(r) for r in parse_requirements(open(REQUIREMENTS_FILE, 'rt'))] setup( name='mtg', version=version, description='mtg is a collection of data science and ml projects for Magic:the Gathering', long_description=long_description, long_description_content_type='text/markdown', author='Ryan Saxe', author_email='ryancsaxe@gmail.com', url='https://github.com/RyanSaxe/mtg', packages=find_packages(), install_requires=install_requires, )
[ 11748, 302, 198, 198, 6738, 279, 10025, 62, 37540, 1330, 21136, 62, 8897, 18883, 198, 11748, 3108, 8019, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 15675, 11682, 62, 25664, 796, 705, 15675, 11682, 13, 9132,...
2.822535
355
from __future__ import annotations from dataclasses import dataclass from avilla.core.platform import Base from avilla.core.resource import Resource, ResourceProvider
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 1196, 5049, 13, 7295, 13, 24254, 1330, 7308, 198, 6738, 1196, 5049, 13, 7295, 13, 31092, 1330, 20857, 11, 20857, 29495, 628,...
4.071429
42
from skimage import data from skimage.filter.rank import median from skimage.morphology import disk from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider, OKCancelButtons, SaveButtons from skimage.viewer.plugins.base import Plugin image = data.coins() viewer = ImageViewer(image) plugin = Plugin(image_filter=median_filter) plugin += Slider('radius', 2, 10, value_type='int') plugin += SaveButtons() plugin += OKCancelButtons() viewer += plugin viewer.show()
[ 6738, 1341, 9060, 1330, 1366, 198, 6738, 1341, 9060, 13, 24455, 13, 43027, 1330, 14288, 198, 6738, 1341, 9060, 13, 24503, 1435, 1330, 11898, 198, 198, 6738, 1341, 9060, 13, 1177, 263, 1330, 7412, 7680, 263, 198, 6738, 1341, 9060, 13, ...
3.223684
152
# Test the buoyancy package and the variable density flows between the lake # and the gwf model. This model has 4 layers and a lake incised within it. # The model is transient and has heads in the aquifer higher than the initial # stage in the lake. As the model runs, the lake and aquifer equalize and # should end up at the same level. The test ensures that the initial and # final water volumes in the entire system are the same. There are three # different cases: # 1. No buoyancy package # 2. Buoyancy package with lake and aquifer density = 1000. # 3. Buoyancy package with lake and aquifer density = 1024.5 import os import pytest import sys import numpy as np try: import flopy except: msg = "Error. FloPy package is not available.\n" msg += "Try installing using the following command:\n" msg += " pip install flopy" raise Exception(msg) from framework import testing_framework from simulation import Simulation ex = ["buy_lak_01a"] # , 'buy_lak_01b', 'buy_lak_01c'] buy_on_list = [False] # , True, True] concbuylist = [0.0] # , 0., 35.] exdirs = [] for s in ex: exdirs.append(os.path.join("temp", s)) # - No need to change any code below if __name__ == "__main__": # print message print("standalone run of {}".format(os.path.basename(__file__))) # run main routine main()
[ 2, 6208, 262, 36675, 3883, 5301, 290, 262, 7885, 12109, 15623, 1022, 262, 13546, 198, 2, 290, 262, 308, 86, 69, 2746, 13, 220, 770, 2746, 468, 604, 11685, 290, 257, 13546, 753, 1417, 1626, 340, 13, 198, 2, 383, 2746, 318, 32361, 2...
3.075342
438
""" 1.0 """ import random if __name__ == '__main__': main()
[ 37811, 198, 220, 220, 220, 220, 198, 220, 220, 220, 352, 13, 15, 198, 37811, 198, 198, 11748, 4738, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2
39
import argparse import logging import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions def run(argv=None, save_main_session=True): """Dummy pipeline to test Python3 operator.""" parser = argparse.ArgumentParser() known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = save_main_session p = beam.Pipeline(options=pipeline_options) # Just a simple test p | 'Create Events' >> beam.Create([1, 2, 3]) result = p.run() result.wait_until_finish() if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()
[ 11748, 1822, 29572, 198, 11748, 18931, 198, 198, 11748, 2471, 4891, 62, 40045, 355, 15584, 198, 6738, 2471, 4891, 62, 40045, 13, 25811, 13, 79, 541, 4470, 62, 25811, 1330, 37709, 29046, 198, 6738, 2471, 4891, 62, 40045, 13, 25811, 13, ...
3.072874
247
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/30 3:02 # @Author : Matrix # @Github : https://github.com/blackmatrix7/ # @Blog : http://www.cnblogs.com/blackmatrix/ # @File : messages.py # @Software: PyCharm import json from ..foundation import * from json import JSONDecodeError __author__ = 'blackmatrix' __all__ = ['async_send_msg', 'get_msg_send_result', 'get_msg_send_progress'] if __name__ == '__main__': pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 1058, 2177, 14, 1157, 14, 1270, 513, 25, 2999, 198, 2, 2488, 13838, 1058, 24936, 198, 2, 2488, 38, 1...
2.581395
172
from setuptools import setup, find_packages from os import path here = path.join(path.abspath(path.dirname(__file__)), 'garpix_page') with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='garpix_page', version='2.23.0', description='', long_description=long_description, url='https://github.com/garpixcms/garpix_page', author='Garpix LTD', author_email='info@garpix.com', license='MIT', packages=find_packages(exclude=['testproject', 'testproject.*']), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], include_package_data=True, zip_safe=False, install_requires=[ 'Django >= 1.11', 'django-polymorphic-tree-for-garpix-page >= 2.1.1', 'django-modeltranslation >= 0.16.2', 'django-multiurl >= 1.4.0', 'djangorestframework >= 3.12.4', 'garpix_utils >= 1.4.0', 'django-tabbed-admin >= 1.0.4', 'model-bakery >= 1.4.0' ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 28686, 1330, 3108, 198, 198, 1456, 796, 3108, 13, 22179, 7, 6978, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 36911, 705, 4563, 79, 844, 62, ...
2.330033
606
# -*- coding: utf-8 -*- """ p2p-streams (c) 2014 enen92 fightnight This file contains the livestream addon engine. It is mostly based on divingmule work on livestreams addon! Functions: xml_lists_menu() -> main menu for the xml list category addlista() -> add a new list. It'll ask for local or remote and processes the given input remove_list(name) -> Remove a list get_groups(url) -> First regex function to parse a given list. Sopcast type list get_channels(name,url) -> Second regex function to parse a given list. Used to general livestreams xml type lists getData(url,fanart) -> Get the item data such as iconimage, fanart, etc getChannelItems(name,url,fanart) -> Function to grab the channel items getItems(items,fanart) -> Function to grab the items from the xml removeNonAscii(s) -> Function to remove non-ascii characters from the list getSoup(url) -> uses beautifulsoup to parse a remote xml addon_log(string) -> Simple log/print function getRegexParsed(regexs, url) -> parse the regex expression list_type(url) -> Checks if the list is xml or m3u parse_m3u(url) -> Parses a m3u type list """ import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmc,xbmcaddon,HTMLParser,time,datetime,os,xbmcvfs,sys from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP from peertopeerutils.pluginxbmc import * from peertopeerutils.webutils import * from peertopeerutils.directoryhandle import * from peertopeerutils.iofile import * """ Main Menu """ """ Add a new list function """ """ Remove a List """ """ Parsing functions """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 279, 17, 79, 12, 5532, 82, 220, 357, 66, 8, 220, 1946, 551, 268, 5892, 1907, 3847, 628, 220, 220, 220, 770, 2393, 4909, 262, 49683, 48557, 3113, 13, 632,...
3.00369
542
from ric.RainItComposite import RainItComposite
[ 6738, 12410, 13, 31443, 1026, 5377, 1930, 578, 1330, 10301, 1026, 5377, 1930, 578, 628 ]
3.266667
15
valor = int(input()) for i in range(valor+1): if(i%2 != 0): print(i)
[ 2100, 273, 796, 493, 7, 15414, 28955, 198, 198, 1640, 1312, 287, 2837, 7, 2100, 273, 10, 16, 2599, 198, 220, 220, 220, 611, 7, 72, 4, 17, 14512, 657, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 7, 72, 8 ]
1.883721
43
#!/usr/bin/env python # ================================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ================================================================ import sys import json import TE TE.Net.setAppTokenFromEnvName("TX_ACCESS_TOKEN") postParams = { "descriptor_id": "4036655176350945", # ID of the descriptor to be updated "reactions": "INGESTED,IN_REVIEW", } showURLs = False dryRun = False validationErrorMessage, serverSideError, responseBody = TE.Net.updateThreatDescriptor( postParams, showURLs, dryRun ) if validationErrorMessage != None: sys.stderr.write(validationErrorMessage + "\n") sys.exit(1) if serverSideError != None: sys.stderr.write(str(serverSideError) + "\n") sys.stderr.write(json.dumps(responseBody) + "\n") sys.exit(1) print(json.dumps(responseBody))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 46111, 4770, 25609, 18604, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 198, 2, 46111, 4770, 25609, 18604, 198, 198, 11748, 25064, 1...
3.013559
295
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for backend.api.shelf_api.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import mock from protorpc import message_types from google.appengine.api import search import endpoints from loaner.web_app.backend.api import root_api # pylint: disable=unused-import from loaner.web_app.backend.api import shelf_api from loaner.web_app.backend.api.messages import shared_messages from loaner.web_app.backend.api.messages import shelf_messages from loaner.web_app.backend.models import device_model from loaner.web_app.backend.models import shelf_model # pylint: disable=unused-import from loaner.web_app.backend.testing import loanertest def test_get_shelf_urlsafe_key(self): """Test getting a shelf using the urlsafe key.""" request = shelf_messages.ShelfRequest(urlsafe_key=self.shelf.key.urlsafe()) shelf = shelf_api.get_shelf(request) self.assertEqual(shelf, self.shelf) def test_get_shelf_using_location(self): """Test getting a shelf using the location.""" request = shelf_messages.ShelfRequest(location=self.shelf.location) shelf = shelf_api.get_shelf(request) self.assertEqual(shelf, self.shelf) def test_get_shelf_using_location_error(self): """Test getting a shelf with an invalid location.""" request = shelf_messages.ShelfRequest(location='Not_Valid') with self.assertRaisesRegexp( endpoints.NotFoundException, shelf_api._SHELF_DOES_NOT_EXIST_MSG % request.location): shelf_api.get_shelf(request) if __name__ == '__main__': loanertest.main()
[ 2, 15069, 2864, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.089532
726
from flask import render_template, jsonify, Flask, redirect, url_for, request from app import app import random import os # import tensorflow as tf # import numpy as np # import sys # import spacy # nlp = spacy.load('en') # sys.path.insert(0, "/content/bert_experimental") # from bert_experimental.finetuning.text_preprocessing import build_preprocessor # from bert_experimental.finetuning.graph_ops import load_graph # restored_graph = load_graph("models/frozen_graph.pb") # graph_ops = restored_graph.get_operations() # input_op, output_op = graph_ops[0].name, graph_ops[-1].name # x = restored_graph.get_tensor_by_name(input_op + ':0') # y = restored_graph.get_tensor_by_name(output_op + ':0') # preprocessor = build_preprocessor("./uncased_L-12_H-768_A-12/vocab.txt", 256) # py_func = tf.numpy_function(preprocessor, [x], [tf.int32, tf.int32, tf.int32], name='preprocessor') # py_func = tf.numpy_function(preprocessor, [x], [tf.int32, tf.int32, tf.int32]) # sess = tf.Session(graph=restored_graph) # delimiter = " ||| "
[ 6738, 42903, 1330, 8543, 62, 28243, 11, 33918, 1958, 11, 46947, 11, 18941, 11, 19016, 62, 1640, 11, 2581, 198, 6738, 598, 1330, 598, 198, 11748, 4738, 198, 11748, 28686, 198, 2, 1330, 11192, 273, 11125, 355, 48700, 198, 2, 1330, 299, ...
2.746667
375
# -*- coding: utf-8 -*- """ Complementary Filter ==================== Attitude quaternion obtained with gyroscope and accelerometer-magnetometer measurements, via complementary filter. First, the current orientation is estimated at time :math:`t`, from a previous orientation at time :math:`t-1`, and a given angular velocity, :math:`\\omega`, in rad/s. This orientation is computed by numerically integrating the angular velocity and adding it to the previous orientation, which is known as an **attitude propagation**. .. math:: \\begin{array}{rcl} \\mathbf{q}_\\omega &=& \\Big(\\mathbf{I}_4 + \\frac{\\Delta t}{2}\\boldsymbol\\Omega_t\\Big)\\mathbf{q}_{t-1} \\\\ &=& \\begin{bmatrix} 1 & -\\frac{\\Delta t}{2}\\omega_x & -\\frac{\\Delta t}{2}\\omega_y & -\\frac{\\Delta t}{2}\\omega_z \\\\ \\frac{\\Delta t}{2}\\omega_x & 1 & \\frac{\\Delta t}{2}\\omega_z & -\\frac{\\Delta t}{2}\\omega_y \\\\ \\frac{\\Delta t}{2}\\omega_y & -\\frac{\\Delta t}{2}\\omega_z & 1 & \\frac{\\Delta t}{2}\\omega_x \\\\ \\frac{\\Delta t}{2}\\omega_z & \\frac{\\Delta t}{2}\\omega_y & -\\frac{\\Delta t}{2}\\omega_x & 1 \\end{bmatrix} \\begin{bmatrix}q_w \\\\ q_x \\\\ q_y \\\\ q_z \\end{bmatrix} \\\\ &=& \\begin{bmatrix} q_w - \\frac{\\Delta t}{2} \\omega_x q_x - \\frac{\\Delta t}{2} \\omega_y q_y - \\frac{\\Delta t}{2} \\omega_z q_z\\\\ q_x + \\frac{\\Delta t}{2} \\omega_x q_w - \\frac{\\Delta t}{2} \\omega_y q_z + \\frac{\\Delta t}{2} \\omega_z q_y\\\\ q_y + \\frac{\\Delta t}{2} \\omega_x q_z + \\frac{\\Delta t}{2} \\omega_y q_w - \\frac{\\Delta t}{2} \\omega_z q_x\\\\ q_z - \\frac{\\Delta t}{2} \\omega_x q_y + \\frac{\\Delta t}{2} \\omega_y q_x + \\frac{\\Delta t}{2} \\omega_z q_w \\end{bmatrix} \\end{array} Secondly, the *tilt* is computed from the accelerometer measurements as: .. math:: \\begin{array}{rcl} \\theta &=& \\mathrm{arctan2}(a_y, a_z) \\\\ \\phi &=& \\mathrm{arctan2}\\big(-a_x, \\sqrt{a_y^2+a_z^2}\\big) \\end{array} Only the pitch, :math:`\\phi`, and roll, :math:`\\theta`, angles are computed, leaving the yaw angle, :math:`\\psi` equal to zero. If a magnetometer sample is available, the yaw angle can be computed. First compensate the measurement using the *tilt*: .. math:: \\begin{array}{rcl} \\mathbf{b} &=& \\begin{bmatrix} \\cos\\theta & \\sin\\theta\\sin\\phi & \\sin\\theta\\cos\\phi \\\\ 0 & \\cos\\phi & -\\sin\\phi \\\\ -\\sin\\theta & \\cos\\theta\\sin\\phi & \\cos\\theta\\cos\\phi \\end{bmatrix} \\begin{bmatrix}m_x \\\\ m_y \\\\ m_z\\end{bmatrix} \\\\ \\begin{bmatrix}b_x \\\\ b_y \\\\ b_z\\end{bmatrix} &=& \\begin{bmatrix} m_x\\cos\\theta + m_y\\sin\\theta\\sin\\phi + m_z\\sin\\theta\\cos\\phi \\\\ m_y\\cos\\phi - m_z\\sin\\phi \\\\ -m_x\\sin\\theta + m_y\\cos\\theta\\sin\\phi + m_z\\cos\\theta\\cos\\phi \\end{bmatrix} \\end{array} Then, the yaw angle, :math:`\\psi`, is obtained as: .. math:: \\begin{array}{rcl} \\psi &=& \\mathrm{arctan2}(-b_y, b_x) \\\\ &=& \\mathrm{arctan2}\\big(m_z\\sin\\phi - m_y\\cos\\phi, \\; m_x\\cos\\theta + \\sin\\theta(m_y\\sin\\phi + m_z\\cos\\phi)\\big) \\end{array} We transform the roll-pitch-yaw angles to a quaternion representation: .. math:: \\mathbf{q}_{am} = \\begin{pmatrix}q_w\\\\q_x\\\\q_y\\\\q_z\\end{pmatrix} = \\begin{pmatrix} \\cos\\Big(\\frac{\\phi}{2}\\Big)\\cos\\Big(\\frac{\\theta}{2}\\Big)\\cos\\Big(\\frac{\\psi}{2}\\Big) + \\sin\\Big(\\frac{\\phi}{2}\\Big)\\sin\\Big(\\frac{\\theta}{2}\\Big)\\sin\\Big(\\frac{\\psi}{2}\\Big) \\\\ \\sin\\Big(\\frac{\\phi}{2}\\Big)\\cos\\Big(\\frac{\\theta}{2}\\Big)\\cos\\Big(\\frac{\\psi}{2}\\Big) - \\cos\\Big(\\frac{\\phi}{2}\\Big)\\sin\\Big(\\frac{\\theta}{2}\\Big)\\sin\\Big(\\frac{\\psi}{2}\\Big) \\\\ \\cos\\Big(\\frac{\\phi}{2}\\Big)\\sin\\Big(\\frac{\\theta}{2}\\Big)\\cos\\Big(\\frac{\\psi}{2}\\Big) + \\sin\\Big(\\frac{\\phi}{2}\\Big)\\cos\\Big(\\frac{\\theta}{2}\\Big)\\sin\\Big(\\frac{\\psi}{2}\\Big) \\\\ \\cos\\Big(\\frac{\\phi}{2}\\Big)\\cos\\Big(\\frac{\\theta}{2}\\Big)\\sin\\Big(\\frac{\\psi}{2}\\Big) - \\sin\\Big(\\frac{\\phi}{2}\\Big)\\sin\\Big(\\frac{\\theta}{2}\\Big)\\cos\\Big(\\frac{\\psi}{2}\\Big) \\end{pmatrix} Finally, after each orientation is estimated independently, they are fused with the complementary filter. .. math:: \\mathbf{q} = (1 - \\alpha) \\mathbf{q}_\\omega + \\alpha\\mathbf{q}_{am} where :math:`\\mathbf{q}_\\omega` is the attitude estimated from the gyroscope, :math:`\\mathbf{q}_{am}` is the attitude estimated from the accelerometer and the magnetometer, and :math:`\\alpha` is the gain of the filter. The filter gain must be a floating value within the range :math:`[0.0, 1.0]`. It can be seen that when :math:`\\alpha=1`, the attitude is estimated entirely with the accelerometer and the magnetometer. When :math:`\\alpha=0`, it is estimated solely with the gyroscope. The values within the range decide how much of each estimation is "blended" into the quaternion. This is actually a simple implementation of `LERP <https://en.wikipedia.org/wiki/Linear_interpolation>`_ commonly used to linearly interpolate quaternions with small differences between them. """ import numpy as np from ..common.orientation import ecompass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 5377, 26908, 560, 25853, 201, 198, 4770, 1421, 201, 198, 201, 198, 8086, 3984, 627, 9205, 295, 6492, 351, 21486, 305, 29982, 290, 8320, 15635, 12, ...
2.214199
2,479
# 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkehpc.endpoint import endpoint_data
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
3.898678
227
# -*- coding: utf-8 -*- # Copyright (c) 2016 Mirantis 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. """Tests for decapod_common.models.execution.""" import pytest from decapod_common.models import execution def test_getting_logfile(new_execution, execution_log_storage): new_execution.logfile execution_log_storage.get.assert_called_once_with(new_execution.model_id) def test_create_logfile(new_execution, execution_log_storage): new_execution.new_logfile.write("1") execution_log_storage.delete.assert_called_once_with( new_execution.model_id ) execution_log_storage.new_file.assert_called_once_with( new_execution.model_id, filename="{0}.log".format(new_execution.model_id), content_type="text/plain" ) execution_log_storage.new_file().write.assert_called_once_with("1")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 1584, 7381, 20836, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
2.98022
455
from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024, 1330, 5436, 11395, 47139, 1352, 11, 1855, 11395, 47139, 1352, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, ...
3.5
58
import numpy as np import hexy as hx if __name__ == "__main__": test_get_hex_line()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 339, 5431, 355, 289, 87, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1332, 62, 1136, 62, 33095, 62, 1370, 3419, 198 ]
2.405405
37
# propagate_2D_integral: Simplification of the Kirchhoff-Fresnel integral. TODO: Very slow and give some problems import numpy from wofry.propagator.wavefront2D.generic_wavefront import GenericWavefront2D from wofry.propagator.propagator import Propagator2D # TODO: check resulting amplitude normalization (fft and srw likely agree, convolution gives too high amplitudes, so needs normalization)
[ 2, 220, 220, 47933, 62, 17, 35, 62, 18908, 1373, 25, 45157, 2649, 286, 262, 7385, 354, 36092, 12, 37, 411, 4954, 19287, 13, 16926, 46, 25, 9576, 3105, 290, 1577, 617, 2761, 198, 198, 11748, 299, 32152, 198, 198, 6738, 266, 1659, 5...
3.42735
117
# https://leetcode.com/problems/delete-and-earn/
[ 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 33678, 12, 392, 12, 451, 77, 14, 198 ]
2.45
20
# Desenvolva um programa que leia o primeiro termo e a razo de uma PA. No final mostre, os 10 primeiros termos dessa prograsso. primeiro = int(input("Primeiro Termo: ")) razao = int(input("Razo: ")) decimo = primeiro + (10 - 1) * razao for c in range(primeiro, decimo + razao, razao): print(f"{c}", end=" -> ") print("Acabou")
[ 2, 2935, 268, 10396, 6862, 23781, 1430, 64, 8358, 443, 544, 267, 6994, 7058, 3381, 78, 304, 257, 374, 44299, 390, 334, 2611, 8147, 13, 1400, 2457, 749, 260, 11, 28686, 838, 6994, 72, 4951, 3381, 418, 288, 21411, 1172, 81, 28372, 13,...
2.507576
132
""" A :py:mod:`filter <tiddlyweb.filters>` type to limit a group of entities using a syntax similar to SQL Limit:: limit=<index>,<count> limit=<count> """ import itertools def limit_parse(count='0'): """ Parse the argument of a ``limit`` :py:mod:`filter <tiddlyweb.filters>` for a count and index argument, return a function which does the limiting. Exceptions while parsing are passed up the stack. """ index = '0' if ',' in count: index, count = count.split(',', 1) index = int(index) count = int(count) return limiter def limit(entities, count=0, index=0): """ Make a slice of a list of entities based on a count and index. """ return itertools.islice(entities, index, index + count)
[ 37811, 198, 32, 1058, 9078, 25, 4666, 25, 63, 24455, 1279, 83, 1638, 306, 12384, 13, 10379, 1010, 29, 63, 2099, 284, 4179, 257, 1448, 286, 12066, 198, 3500, 257, 15582, 2092, 284, 16363, 27272, 3712, 628, 220, 220, 220, 4179, 28, 27...
2.713781
283
""" Simple API to convert models between PyTorch and Keras (Conversions from Keras to PyTorch aren't implemented) """ from . import utility from . import tests from . import io_utils as utils import tensorflow def convert(model, input_shape, weights=True, quiet=True, ignore_tests=False, input_range=None, save=None, filename=None, directory=None): """ Conversion between PyTorch and Keras (Conversions from Keras to PyTorch aren't implemented) Arguments: -model: A Keras or PyTorch model or layer to convert -input_shape: Input shape (list, tuple or int), without batchsize. -weights (bool): Also convert weights. If set to false, only convert model architecture -quiet (bool): If a progress bar and some messages should appear -ignore_tests (bool): If tests should be ignored. If set to True, converted model will still be tested by security. If models are not identical, it will only print a warning. If set to False, and models are not identical, RuntimeWarning will be raised If weights is False, tests are automatically ignored -input_range: Optionnal. A list of 2 elements containing max and min values to give as input to the model when performing the tests. If None, models will be tested on samples from the "standard normal" distribution. -save: If model should be exported to a hdf5 file. -filename: Filename to give to model's hdf5 file. If filename is not None and save is not False, then save will automatically be set to True -directory: Where to save model's hdf5 file. If directory is not None and save is not False, then save will automatically be set to True Raises: -RuntimeWarning: If converted and original model aren't identical, and ignore_tests is False Returns: If model has been exported to a file, it will return the name of the file Else, it returns the converted model """ if (filename is not None or directory is not None) and save is None: save = True if save is None: save = False if weights == False: ignore_tests = True if not quiet: print('\nConversion...') # Converting: newModel = utility.convert(model=utility.LayerRepresentation(model), input_size=input_shape, weights=weights, quiet=quiet) # Actually, newModel is a LayerRepresentation object # Equivalents: torchModel = newModel.equivalent['torch'] kerasModel = newModel.equivalent['keras'] if not quiet: print('Automatically testing converted model reliability...\n') # Checking converted model reliability tested = False try: meanSquaredError = tests.comparison(model1=torchModel, model2=kerasModel, input_shape=input_shape, input_range=input_range, quiet=quiet) tested = True except tensorflow.errors.InvalidArgumentError: print("Warning: tests unavailable!") if tested and meanSquaredError > 0.0001: if ignore_tests: print("Warning: converted and original models aren't identical !\ (mean squared error: {})".format(meanSquaredError)) else: raise RuntimeWarning("Original and converted model do not match !\ \nOn random input data, outputs showed a mean squared error of {} (if should \ be below 1e-10)".format(meanSquaredError)) elif not quiet and tested: print('\n Original and converted models match !\nMean squared err\ or : {}'.format(meanSquaredError)) if save: if not quiet: print('Saving model...') defaultName = 'conversion_{}'.format(newModel.name) if filename is None: filename = defaultName # Formatting filename so that we don't overwrite any existing file file = utils.formatFilename(filename, directory) # Freezing Keras model (trainable = False everywhere) utils.freeze(kerasModel) # Save the entire model kerasModel.save(file + '.h5') if not quiet: print('Done !') return file + '.h5' if not quiet: print('Done !') return kerasModel def convert_and_save(model, input_shape, weights=True, quiet=True, ignore_tests=False, input_range=None, filename=None, directory=None): """ Conversion between PyTorch and Keras, and automatic save (Conversions from Keras to PyTorch aren't implemented) Arguments: -model: A Keras or PyTorch model or layer to convert -input_shape: Input shape (list, tuple or int), without batchsize. -weights (bool): Also convert weights. If set to false, only convert model architecture -quiet (bool): If a progress bar and some messages should appear -ignore_tests (bool): If tests should be ignored. If set to True, converted model will still be tested by security. If models are not identical, it will only print a warning. If set to False, and models are not identical, RuntimeWarning will be raised If weights is False, tests are automatically ignored -input_range: Optionnal. A list of 2 elements containing max and min values to give as input to the model when performing the tests. If None, models will be tested on samples from the "standard normal" distribution. -filename: Filename to give to model's hdf5 file. If filename is not None and save is not False, then save will automatically be set to True -directory: Where to save model's hdf5 file. If directory is not None and save is not False, then save will automatically be set to True Returns: Name of created hdf5 file """ return convert(model=model, input_shape=input_shape, weights=weights, quiet=quiet, ignore_tests=ignore_tests, input_range=input_range, save=True, filename=filename, directory=directory)
[ 37811, 198, 26437, 7824, 284, 10385, 4981, 1022, 9485, 15884, 354, 290, 17337, 292, 198, 198, 7, 3103, 47178, 422, 17337, 292, 284, 9485, 15884, 354, 3588, 470, 9177, 8, 198, 37811, 198, 6738, 764, 1330, 10361, 198, 6738, 764, 1330, 5...
2.281118
3,077
# -*- coding: utf-8 -*- """ Notifications ------------- Example showing how to add notifications to a characteristic and handle the responses. Updated on 2019-07-03 by hbldh <henrik.blidh@gmail.com> """ import sys import logging import asyncio import platform from bleak import BleakClient from bleak import _logger as logger CHARACTERISTIC_UUID = "f000aa65-0451-4000-b000-000000000000" # <--- Change to the characteristic you want to enable notifications from. ADDRESS = ( "24:71:89:cc:09:05" # <--- Change to your device's address here if you are using Windows or Linux if platform.system() != "Darwin" else "B9EA5233-37EF-4DD6-87A8-2A875E821C46" # <--- Change to your device's address here if you are using macOS ) if len(sys.argv) == 3: ADDRESS = sys.argv[1] CHARACTERISTIC_UUID = sys.argv[2] def notification_handler(sender, data): """Simple notification handler which prints the data received.""" print("{0}: {1}".format(sender, data)) if __name__ == "__main__": import os os.environ["PYTHONASYNCIODEBUG"] = str(1) loop = asyncio.get_event_loop() # loop.set_debug(True) loop.run_until_complete(run(ADDRESS, True))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 3673, 6637, 198, 32501, 198, 198, 16281, 4478, 703, 284, 751, 19605, 284, 257, 16704, 290, 5412, 262, 9109, 13, 198, 198, 17354, 319, 13130, 12, 2998, 12, ...
2.753488
430
#!/usr/bin/python import socket my_listener = Listener("localhost",1234) my_listener.run()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 17802, 628, 198, 1820, 62, 4868, 877, 796, 7343, 877, 7203, 36750, 1600, 1065, 2682, 8, 198, 1820, 62, 4868, 877, 13, 5143, 3419 ]
2.735294
34
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Convert Dialogflow history to spreadsheet User must manually copy the history from the browser and save this in a text file. This reads the textfile, parses the data, and saves it to a spreadsheet. Example training sample: USER Nov 4, 11:19 PM AGENT No matched intent Nov 4, 11:19 PM more_vert """ import argparse import os from simple_report import SimpleReport # constants FIELDS = ["Date", "User", "Agent"] if __name__ == "__main__": # collect arguments PARSER = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) PARSER.add_argument("filename", help="History text file") ARGS = PARSER.parse_args() # generate report filename, file_extension = os.path.splitext(ARGS.filename) REPORT = SimpleReport(filename, FIELDS) # step each line of history text file with open(ARGS.filename, 'r') as fp: num_lines = sum(1 for line in open(ARGS.filename)) rows = int(num_lines / 7) print("Reading {} lines of text.".format(num_lines)) print("Writing {} rows.".format(rows)) for row in range(1, rows): user_utterance = fp.readline().strip() # USER UTTERANCE date = fp.readline().strip() # DATE agent_intent = fp.readline().strip() # AGENT INTENT date = fp.readline().strip() # DATE _ = fp.readline().strip() # 'more_vert' utterance = user_utterance.split("USER", 1)[1] intent = agent_intent.split("AGENT", 1)[1] if not intent: intent = "Intent found" print("[{}] {} {} {}".format(row, date, utterance, intent)) # add row to report REPORT.add("Date", row, date, date) REPORT.add("User", row, utterance) REPORT.add("Agent", row, intent) REPORT.close()
[ 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, 37811, 38240, 21269, 519, 11125, 2106, 284, 30117, 198, 198, 12982, 1276, 14500, 4866, 262, 2106, 422, 262, 64...
2.363745
833
from django.shortcuts import render,redirect from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 from django.contrib import messages from django.contrib.auth.models import User import cv2 import dlib import imutils from imutils import face_utils from imutils.video import VideoStream from imutils.face_utils import rect_to_bb from imutils.face_utils import FaceAligner import time from attendance_system_facial_recognition.settings import BASE_DIR import os import face_recognition from face_recognition.face_recognition_cli import image_files_in_folder import pickle from sklearn.preprocessing import LabelEncoder from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC import numpy as np from django.contrib.auth.decorators import login_required import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.manifold import TSNE import datetime from django_pandas.io import read_frame from users.models import Present, Time import seaborn as sns import pandas as pd from django.db.models import Count #import mpld3 import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters from matplotlib import rcParams import math mpl.use('Agg') #utility functions: #used #used #used #used # Create your views here. def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat') #Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER svc_save_path="face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor , desiredFaceWidth = 96) encoder=LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1,128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src=0).start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame ,width = 800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame,0) for face in faces: print("INFO : inside for loop") (x,y,w,h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame,gray_frame,face) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1) (pred,prob)=predict(face_aligned,svc) if(pred!=[-1]): person_name=encoder.inverse_transform(np.ravel([pred]))[0] pred=person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred,0) + 1 if count[pred] == 4 and (time.time()-start[pred]) > 1.2: count[pred] = 0 else: #if count[pred] == 4 and (time.time()-start) <= 1.5: present[pred] = True log_time[pred] = datetime.datetime.now() count[pred] = count.get(pred,0) + 1 print(pred, present[pred], count[pred]) cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) else: person_name="unknown" cv2.putText(frame, str(person_name), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) #cv2.putText() # Before continuing to the next loop, I want to give it a little pause # waitKey of 100 millisecond #cv2.waitKey(50) #Showing the image in another window #Creates a window with window name "Face" and with the image img cv2.imshow("Mark Attendance - In - Press q to exit",frame) #Before closing it we need to give a wait command, otherwise the open cv wont work # @params with the millisecond of delay 1 #cv2.waitKey(1) #To get out of the loop key=cv2.waitKey(50) & 0xFF if(key==ord("q")): break #Stoping the videostream vs.stop() # destroying all the windows cv2.destroyAllWindows() update_attendance_in_db_in(present) return redirect('home') def mark_your_attendance_out(request): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat') #Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER svc_save_path="face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor , desiredFaceWidth = 96) encoder=LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1,128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src=0).start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame ,width = 800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame,0) for face in faces: print("INFO : inside for loop") (x,y,w,h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame,gray_frame,face) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1) (pred,prob)=predict(face_aligned,svc) if(pred!=[-1]): person_name=encoder.inverse_transform(np.ravel([pred]))[0] pred=person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred,0) + 1 if count[pred] == 4 and (time.time()-start[pred]) > 1.5: count[pred] = 0 else: #if count[pred] == 4 and (time.time()-start) <= 1.5: present[pred] = True log_time[pred] = datetime.datetime.now() count[pred] = count.get(pred,0) + 1 print(pred, present[pred], count[pred]) cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) else: person_name="unknown" cv2.putText(frame, str(person_name), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) #cv2.putText() # Before continuing to the next loop, I want to give it a little pause # waitKey of 100 millisecond #cv2.waitKey(50) #Showing the image in another window #Creates a window with window name "Face" and with the image img cv2.imshow("Mark Attendance- Out - Press q to exit",frame) #Before closing it we need to give a wait command, otherwise the open cv wont work # @params with the millisecond of delay 1 #cv2.waitKey(1) #To get out of the loop key=cv2.waitKey(50) & 0xFF if(key==ord("q")): break #Stoping the videostream vs.stop() # destroying all the windows cv2.destroyAllWindows() update_attendance_in_db_out(present) return redirect('home')
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 445, 1060, 198, 6738, 764, 23914, 1330, 20579, 8479, 11, 10430, 8479, 11, 5842, 13292, 1870, 10430, 8479, 11, 7536, 8479, 62, 17, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, ...
2.376543
2,916
import re import string DATA = '05.txt' code1() code2()
[ 11748, 302, 201, 198, 11748, 4731, 201, 198, 201, 198, 201, 198, 26947, 796, 705, 2713, 13, 14116, 6, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 8189, 16, 3419, 201, 198, 8189, 17, 3419, 201, 198 ]
1.829268
41
import abc import contextlib import os import sys from functools import partial from itertools import chain import fbuild import fbuild.db import fbuild.path import fbuild.temp from . import platform # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def check_version(ctx, builder, version_function, *, requires_version=None, requires_at_least_version=None, requires_at_most_version=None): """Helper function to simplify checking the version of a builder.""" if any(v is not None for v in ( requires_version, requires_at_least_version, requires_at_most_version)): ctx.logger.check('checking %s version' % builder) version_str = version_function() # Convert the version into a tuple version = [] for i in version_str.split('.'): try: version.append(int(i)) except ValueError: # The subversion isn't a number, so just convert it to a # string. version.append(i) version = tuple(version) if requires_version is not None and requires_version != version: msg = 'version %s required; found %s' % ( '.'.join(str(i) for i in requires_version), version_str) ctx.logger.failed(msg) raise fbuild.ConfigFailed(msg) if requires_at_least_version is not None and \ requires_at_least_version > version: msg = 'at least version %s required; found %s' % ( '.'.join(str(i) for i in requires_at_least_version), version_str) ctx.logger.failed(msg) raise fbuild.ConfigFailed(msg) if requires_at_most_version is not None and \ requires_at_most_version < version: msg = 'at most version %s required; found %s' % ( '.'.join(str(i) for i in requires_at_most_version), version_str) ctx.logger.failed(msg) raise fbuild.ConfigFailed(msg) ctx.logger.passed(version_str) # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ def check_link_lib(self, code, msg, *args, **kwargs): self.ctx.logger.check(msg) if self.try_link_lib(code, *args, **kwargs): self.ctx.logger.passed() return True else: self.ctx.logger.failed() return False # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
[ 11748, 450, 66, 198, 11748, 4732, 8019, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 198, 11748, 277, 11249, 198, 11748, 277, 11249, 13, 9945, 198, 11748, 2...
2.649867
1,131
import json import cherrypy import engine
[ 11748, 33918, 198, 198, 11748, 23612, 9078, 198, 198, 11748, 3113, 628, 628 ]
3.615385
13
from typing import Union from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.core import Term, Atom from tuprolog.solve import ExecutionContext, Signature ExistenceError = errors.ExistenceError ObjectType = ExistenceError.ObjectType OBJECT_PROCEDURE = ObjectType.PROCEDURE OBJECT_SOURCE_SINK = ObjectType.SOURCE_SINK OBJECT_RESOURCE = ObjectType.RESOURCE OBJECT_STREAM = ObjectType.STREAM OBJECT_OOP_ALIAS = ObjectType.OOP_ALIAS OBJECT_OOP_METHOD = ObjectType.OOP_METHOD OBJECT_OOP_CONSTRUCTOR = ObjectType.OOP_CONSTRUCTOR OBJECT_OOP_PROPERTY = ObjectType.OOP_PROPERTY logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.ExistenceError.*")
[ 6738, 19720, 1330, 4479, 198, 6738, 256, 929, 40329, 1330, 49706, 198, 2, 645, 1040, 14978, 9485, 3118, 411, 5634, 19927, 198, 11748, 474, 79, 2981, 13, 320, 3742, 198, 2, 645, 1040, 14978, 9485, 3118, 411, 5634, 19927, 198, 11748, 34...
2.93617
282
from __future__ import annotations from typing import TYPE_CHECKING import pkg_resources from bs4 import BeautifulSoup from requests import session from cptk.scrape import PageInfo from cptk.scrape import Website from cptk.utils import cptkException if TYPE_CHECKING: from cptk.scrape import Problem
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 11748, 279, 10025, 62, 37540, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 7007, 1330, 6246, 198, 198, 6738, 269, 457, ...
3.344086
93
import pybullet as p import pybullet_data import gym from gym import spaces from gym.utils import seeding import numpy as np from math import sqrt import random import time import math import cv2 import torch import os def random_crop(imgs, out): """ args: imgs: shape (B,C,H,W) out: output size (e.g. 84) """ n, c, h, w = imgs.shape crop_max = h - out + 1 w1 = np.random.randint(0, crop_max, n) h1 = np.random.randint(0, crop_max, n) cropped = np.empty((n, c, out, out), dtype=imgs.dtype) for i, (img, w11, h11) in enumerate(zip(imgs, w1, h1)): cropped[i] = img[:, h11:h11 + out, w11:w11 + out] return cropped if __name__ == '__main__': # baseline import matplotlib.pyplot as plt env = KukaReachVisualEnv(is_render=False) env = CustomSkipFrame(env) print(env.observation_space.shape) print(env.action_space.shape) print(env.action_space.n) # for _ in range(20): # action=env.action_space.sample() # print(action) # env.step(action) # # state = env.reset() # print(state.shape) # img = state[0][0] # plt.imshow(img, cmap='gray') # plt.show()
[ 11748, 12972, 15065, 1616, 355, 279, 201, 198, 11748, 12972, 15065, 1616, 62, 7890, 201, 198, 11748, 11550, 201, 198, 6738, 11550, 1330, 9029, 201, 198, 6738, 11550, 13, 26791, 1330, 384, 8228, 201, 198, 11748, 299, 32152, 355, 45941, 2...
2.088333
600
--- setup.py.orig 2019-07-02 19:13:39 UTC +++ setup.py elif ( - sys.platform.startswith("linux") - or sys.platform.startswith("gnu") - or sys.platform.startswith("freebsd") + sys.platform.startswith("nothing") ): for dirname in _find_library_dirs_ldconfig(): _add_directory(library_dirs, dirname)
[ 6329, 9058, 13, 9078, 13, 11612, 197, 23344, 12, 2998, 12, 2999, 678, 25, 1485, 25, 2670, 18119, 198, 45340, 9058, 13, 9078, 198, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 1288, 361, 357, 198, 12, 220, 220, 220, 220, 220, ...
1.935644
202
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ from mindspore.ops import Primitive from mindspore.ops import operations as P from mindspore.ops.operations import _grad_ops as G from mindspore.ops import _constants as Constants # pylint: disable=unused-variable tuple_getitem = Primitive(Constants.kTupleGetItem) add = P.Add() allreduce = P.AllReduce() allreduce.add_prim_attr('fusion', 1) make_tuple = Primitive("make_tuple") conv = P.Conv2D(out_channel=64, kernel_size=7, mode=1, pad_mode="valid", pad=0, stride=1, dilation=1, group=1) bn = P.FusedBatchNorm() relu = P.ReLU() conv_bn1 = Primitive('ConvBN1') bn2_add_relu = Primitive('BN2AddRelu') bn2_relu = Primitive('BN2Relu') fused_bn1 = Primitive('FusedBN1') fused_bn2 = Primitive('FusedBN2') fused_bn3 = Primitive('FusedBN3') bn_grad = G.FusedBatchNormGrad() bn_grad1 = Primitive('BNGrad1') bn_grad2 = Primitive('BNGrad2') bn_grad3 = Primitive('BNGrad3') def test_bn_split(tag): """ test_split_bn_fusion """ fns = FnDict() return fns[tag] def test_bn_grad_split(tag): """ test_bn_grad_split """ fns = FnDict() return fns[tag] def test_all_reduce_fusion_all(tag): """ test_all_reduce_fusion_all """ fns = FnDict() return fns[tag] def test_all_reduce_fusion_group(tag): """ test_all_reduce_fusion_group """ fns = FnDict() return fns[tag]
[ 2, 15069, 13130, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
2.79745
706
from abc import ABC from typing import Dict from redbot.core import Config from redbot.core.bot import Red from trainerdex.client import Client
[ 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 2266, 13645, 13, 7295, 1330, 17056, 198, 6738, 2266, 13645, 13, 7295, 13, 13645, 1330, 2297, 198, 6738, 21997, 67, 1069, 13, 16366, 1330, 20985, 628 ]
3.65
40
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import pandas as pd import numpy as np import altair as alt import vega_datasets alt.data_transformers.enable('default') alt.data_transformers.disable_max_rows() app = dash.Dash(__name__, assets_folder='assets', external_stylesheets=[dbc.themes.BOOTSTRAP]) # Boostrap CSS. app.css.append_css({'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'}) # noqa: E501 server = app.server app.title = 'Dash app with pure Altair HTML' df = pd.read_csv('data/Police_Department_Incidents_-_Previous_Year__2016_.csv') # df = pd.read_csv("https://raw.github.ubc.ca/MDS-2019-20/DSCI_531_lab4_anas017/master/data/Police_Department_Incidents_-_Previous_Year__2016_.csv?token=AAAHQ0dLxUd74i7Zhzh1SJ_UuOaFVI3_ks5d5dT3wA%3D%3D") df['datetime'] = pd.to_datetime(df[["Date","Time"]].apply(lambda x: x[0].split()[0] +" "+x[1], axis=1), format="%m/%d/%Y %H:%M") df['hour'] = df['datetime'].dt.hour df.dropna(inplace=True) top_4_crimes = df['Category'].value_counts()[:6].index.to_list() top_4_crimes top_4_crimes.remove("NON-CRIMINAL") top_4_crimes.remove("OTHER OFFENSES") # top 4 crimes df subset df_t4 = df[df["Category"].isin(top_4_crimes)].copy() body = dbc.Container( [ dbc.Row( [ dbc.Col( [ html.H2("San Francisco Crime"), html.P( """\ When looking for a place to live or visit, one important factor that people will consider is the safety of the neighborhood. Searching that information district by district could be time consuming and exhausting. It is even more difficult to compare specific crime statistics across districts such as the crime rate at a certain time of day. It would be useful if people can look up crime related information across district on one application. Our app aims to help people make decisions when considering their next trip or move to San Francisco, California via visually exploring a dataset of crime statistics. The app provides an overview of the crime rate across neighborhoods and allows users to focus on more specific information through filtering of geological location, crime rate, crime type or time of the crime. Use the box below to choose crimes of interest. """ ), dcc.Dropdown( id = 'drop_selection_crime', options=[{'label': i, 'value': i} for i in df_t4['Category'].unique() ], style={'height': '20px', 'width': '400px'}, value=df_t4['Category'].unique(), multi=True) ], md=5, ), dbc.Col( [ dbc.Row( [ html.Iframe( sandbox = "allow-scripts", id = "plot_top", height = "500", width = "650", style = {"border-width": "0px"}, srcDoc = make_plot_top().to_html() ) ] ) ] ), ] ), dbc.Row( html.Iframe( sandbox='allow-scripts', id='plot_bot', height='500', width='1200', style={'border-width': '0px'}, srcDoc= make_plot_bot().to_html() ) ) ], className="mt-4", ) app.layout = html.Div(body) if __name__ == '__main__': app.run_server(debug=False)
[ 11748, 14470, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 11748, 19798, 292, 355, 279, ...
1.791954
2,461
# coding=utf-8 from .subspaces import *
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 764, 7266, 2777, 2114, 1330, 1635, 198 ]
2.666667
15
import json import math from PIL import Image,ImageDraw import pandas as pd import glob import argparse import copy import numpy as np import matplotlib.pyplot as plt import pickle import cv2 from PIL import ImageEnhance import chainer from chainer.datasets import ConcatenatedDataset from chainer.datasets import TransformDataset from chainer.optimizer_hooks import WeightDecay from chainer import serializers from chainer import training from chainer.training import extensions from chainer.training import triggers from chainercv.datasets import voc_bbox_label_names from chainercv.datasets import VOCBboxDataset from chainercv.extensions import DetectionVOCEvaluator from chainercv.links.model.ssd import GradientScaling from chainercv.links.model.ssd import multibox_loss from chainercv.links import SSD300 from chainercv.links import SSD512 from chainercv import transforms from chainercv.utils import read_image from chainercv.links.model.ssd import random_crop_with_bbox_constraints from chainercv.links.model.ssd import random_distort from chainercv.links.model.ssd import resize_with_random_interpolation import queue if __name__ == '__main__': main()
[ 11748, 33918, 201, 198, 11748, 10688, 201, 198, 6738, 350, 4146, 1330, 7412, 11, 5159, 25302, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 15095, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 4866, 201, 198, 11748, 299, ...
3.014815
405
import os import pdb import warnings import numpy as np import torch import torch.nn as nn import torch.utils.data import torch.backends.cudnn import torch.optim as optim import dataloaders from utils.utils import AverageMeter from utils.loss import build_criterion from utils.metrics import Evaluator from utils.step_lr_scheduler import Iter_LR_Scheduler from retrain_model.build_autodeeplab import Retrain_Autodeeplab from config_utils.re_train_autodeeplab import obtain_retrain_autodeeplab_args if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 279, 9945, 198, 11748, 14601, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 26791, 13, 7890, 198, 11748, 28034, 13, 1891, 2412, 1...
2.98895
181
sol = Solution() A = [1] B = [-1] C = [0] D = [1] result = sol.fourSumCount(A, B, C, D) print("Test 1: {0}".format(result)) A = [1, 2] B = [-2, -1] C = [-1, 2] D = [0, 2] result = sol.fourSumCount(A, B, C, D) print("Test 2: {0}".format(result))
[ 198, 34453, 796, 28186, 3419, 198, 32, 796, 685, 16, 60, 198, 33, 796, 25915, 16, 60, 198, 34, 796, 685, 15, 60, 198, 35, 796, 685, 16, 60, 198, 20274, 796, 1540, 13, 14337, 13065, 12332, 7, 32, 11, 347, 11, 327, 11, 360, 8, ...
1.968
125
# The MIT License (MIT) # Copyright (c) 2021 Tom J. Sun # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import machine from pmu import axp192 from context import Context from login import Login from home import Home import settings pmu = axp192() # Enable power management so that if power button is held down 6 secs, # it shuts off as expected pmu.enablePMICSleepMode(True) ctx = Context() ctx.display.flash_text(settings.load('splash', ( 'Krux' ), strip=False)) while True: if not Login(ctx).run(): break if not Home(ctx).run(): break ctx.display.flash_text(( 'Shutting down..' )) ctx.clear() pmu.setEnterSleepMode() machine.reset()
[ 2, 383, 17168, 13789, 357, 36393, 8, 198, 198, 2, 15069, 357, 66, 8, 33448, 4186, 449, 13, 3825, 198, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, ...
3.467909
483
import re import six from smartfields.processors.base import ExternalFileProcessor from smartfields.utils import ProcessingError __all__ = [ 'FFMPEGProcessor' ]
[ 11748, 302, 198, 11748, 2237, 198, 198, 6738, 4451, 25747, 13, 14681, 669, 13, 8692, 1330, 34579, 8979, 18709, 273, 198, 6738, 4451, 25747, 13, 26791, 1330, 28403, 12331, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 577...
3.34
50
## Program: VMTK ## Language: Python ## Date: January 12, 2018 ## Version: 1.4 ## Copyright (c) Richard Izzo, Luca Antiga, All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notices for more information. ## Note: this code was contributed by ## Richard Izzo (Github @rlizzo) ## University at Buffalo import pytest import vmtk.vmtksurfaceconnectivity as connectivity import os
[ 2235, 6118, 25, 569, 13752, 42, 198, 2235, 15417, 25, 220, 11361, 198, 2235, 7536, 25, 220, 220, 220, 220, 220, 3269, 1105, 11, 2864, 198, 2235, 10628, 25, 220, 220, 352, 13, 19, 198, 198, 2235, 220, 220, 15069, 357, 66, 8, 6219, ...
3.066327
196
from django import forms from nocaptcha_recaptcha.fields import NoReCaptchaField
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 299, 420, 2373, 11693, 62, 8344, 2373, 11693, 13, 25747, 1330, 1400, 3041, 19209, 11693, 15878, 198 ]
3.375
24
#! /bin/python3 # simple run menu import os import stat if __name__ == "__main__": print([command_to_name(i) for i in get_files_in_dir('') if is_file_executable(i)])
[ 2, 0, 1220, 8800, 14, 29412, 18, 198, 2, 2829, 1057, 6859, 198, 198, 11748, 28686, 198, 11748, 1185, 198, 197, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 4798, 26933, 21812, 62, 1462, 62, 3672, 7, 72, ...
2.422535
71
# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Joan Massich <mailsik@gmail.com> # # License: BSD-3-Clause import os.path as op import numpy as np from numpy.testing import assert_array_equal import pytest from mne import pick_types from mne.datasets import testing from mne.io.tests.test_raw import _test_raw_reader from mne.io.cnt import read_raw_cnt from mne.annotations import read_annotations data_path = testing.data_path(download=False) fname = op.join(data_path, 'CNT', 'scan41_short.cnt')
[ 198, 2, 6434, 25, 13790, 461, 7204, 1004, 381, 461, 648, 292, 1279, 73, 3609, 576, 381, 31, 50139, 13, 73, 24767, 13, 12463, 29, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 26640, 5674, 488, 1279, 26165, 1134, 31, 14816, 13, ...
2.623116
199
import urllib.request, json import pandas as pd baseUrl = 'https://avoindata.eduskunta.fi/api/v1/tables/VaskiData' parameters = 'rows?columnName=Eduskuntatunnus&columnValue=LA%25&perPage=100' page = 0 df = '' while True: print(f'Fetching page number {page}') with urllib.request.urlopen(f'{baseUrl}/{parameters}&page={page}') as url: data = json.loads(url.read().decode()) if page == 0: columns = data['columnNames'] df = pd.DataFrame(columns=columns) dataRows = data['rowData'] df = df.append(pd.DataFrame(dataRows, columns=data['columnNames']), ignore_index=True) if data['hasMore'] == False: break page = page + 1 df.to_csv('./data/parliament_proposals_raw.csv', sep=';', encoding='utf-8')
[ 11748, 2956, 297, 571, 13, 25927, 11, 33918, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 8692, 28165, 796, 705, 5450, 1378, 615, 78, 521, 1045, 13, 276, 17990, 44424, 13, 12463, 14, 15042, 14, 85, 16, 14, 83, 2977, 14, 53, 209...
2.269341
349
# -*- coding: utf-8 -*- """ Created on Mon Sep 20 16:15:37 2021 @author: em42363 """ # In[1]: Import functions ''' CatBoost is a high-performance open source library for gradient boosting on decision trees ''' from catboost import CatBoostRegressor from sklearn.model_selection import train_test_split import pandas as pd import seaborn as sns import numpy as np import os os.chdir(os.path.dirname(__file__)) import sys sys.path.insert(0, r'C:\Users\eduar\OneDrive\PhD\UTuning') sys.path.insert(0, r'C:\Users\em42363\OneDrive\PhD\UTuning') from UTuning import scorer, plots #df = pd.read_csv(r'C:\Users\eduar\OneDrive\PhD\UTuning\dataset\unconv_MV.csv') df = pd.read_csv(r'C:\Users\em42363\OneDrive\PhD\UTuning\dataset\unconv_MV.csv') import random import matplotlib.pyplot as plt # In[1]: Split train test ''' Perform split train test ''' y = df['Production'].values X = df[['Por', 'LogPerm', 'Brittle', 'TOC']].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) # In[6]: Regressor ''' Define the regressor, fit the model and predict the estimates ''' model = CatBoostRegressor(iterations=1000, learning_rate=0.2, loss_function='RMSEWithUncertainty', verbose=False, random_seed=0) model.fit(X_train, y_train) estimates = model.predict(X_test) # In[9]: Plot error line ''' Use UTuning to plot error lines ''' plots.error_line(estimates[:, 0], y_test, np.sqrt(estimates[:, 1]), Frac=1) # %% Define the virtual ensemble # %% n_quantiles = 11 perc = np.linspace(0.0, 1.00, n_quantiles) Samples = 10 ens_preds=virt_ensemble(X_train,y_train, num_samples=Samples) Pred_array = ens_preds[:,:,0] Knowledge_u=np.sqrt(np.var(Pred_array,axis=1)) #Knowledge uncertainty Data_u=np.sqrt(np.mean(ens_preds[:,:,1],axis=1)) #Data uncertainty Sigma=Knowledge_u+Data_u # %% ''' We use UTuning to return the Indicator Function and plot the accuracy plot and diagnose our model. ''' scorer = scorer.scorer(Pred_array, y_test, Sigma) IF_array = scorer.IndicatorFunction() avgIF = np.mean(IF_array,axis=0) # % Second plot test plots.error_accuracy_plot(perc,IF_array,Pred_array,y_test,Sigma) # % print('Accuracy = {0:2.2f}'.format(scorer.Accuracy())) print('Precision = {0:2.2f}'.format(scorer.Precision())) print('Goodness = {0:2.2f}'.format(scorer.Goodness()))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 8621, 1160, 1467, 25, 1314, 25, 2718, 33448, 198, 198, 31, 9800, 25, 795, 43356, 5066, 198, 37811, 198, 2, 554, 58, 16, 5974, 17267, 5499...
2.493018
931
import logging from platform import system from tqdm import tqdm from multiprocessing import Lock loggers = {} # https://stackoverflow.com/questions/38543506/ def setup_custom_logger(name): """ Create a logger with a certain name and level """ global loggers if loggers.get(name): return loggers.get(name) formatter = logging.Formatter( fmt='%(levelname)s: %(message)s' ) handler = TqdmLoggingHandler() handler.setFormatter(formatter) if system() not in ['Windows', 'cli']: logging.addLevelName(logging.ERROR, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.ERROR)) logging.addLevelName(logging.WARNING, "\033[1;33m%s\033[1;0m" % logging.getLevelName(logging.WARNING)) logging.addLevelName(logging.INFO, "\033[1;34m%s\033[1;0m" % logging.getLevelName(logging.INFO)) logging.addLevelName(logging.DEBUG, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.DEBUG)) logger = logging.getLogger(name) logger.setLevel(logging.WARNING) # if (logger.hasHandlers()): # logger.handlers.clear() if logger.handlers: logger.handlers = [] logger.addHandler(handler) loggers.update(dict(name=logger)) return logger
[ 11748, 18931, 198, 6738, 3859, 1330, 1080, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 6738, 18540, 305, 919, 278, 1330, 13656, 198, 198, 6404, 5355, 796, 23884, 628, 198, 2, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138...
2.459725
509
import cv2 import sys import playsound face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml') # capture video using cv2 video_capture = cv2.VideoCapture(0) while True: # capture frame by frame, i.e, one by one ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # for each face on the projected on the frame faces = face_cascade.detectMultiScale( gray, scaleFactor = 1.1, minNeighbors = 5, # minSize(35, 35) ) # loop through the video faces for detection for (x, y, w, h) in faces: point1 = x+w point2 = y+h frame_color = (50, 50, 200) rectangleBox = cv2.rectangle(frame, (x, y), (point1, point2), frame_color, 2) cv2.imshow('video', frame) if faces.any(): playsound.playsound('openDoorAlert.mp3', True) if len(faces) > 1: print("There are " + str(len(faces)) + " peoples at the gate") else: print("There is " + str(len(faces)) + " person at the gate") else: pass if cv2.waitKey(1) & 0xFF == ord('q'): sys.exit()
[ 11748, 269, 85, 17, 198, 11748, 25064, 198, 11748, 5341, 633, 198, 198, 2550, 62, 66, 28966, 796, 269, 85, 17, 13, 34, 28966, 9487, 7483, 10786, 66, 3372, 2367, 14, 3099, 5605, 28966, 62, 8534, 1604, 558, 62, 12286, 13, 19875, 11537...
2.017857
616
# vim:set et sw=4 ts=4: import logging import sys import jmespath from . import sis, classes # logging logging.basicConfig(stream=sys.stdout, level=logging.WARNING) logger = logging.getLogger(__name__) # SIS endpoint enrollments_uri = "https://apis.berkeley.edu/sis/v2/enrollments" # apparently some courses have LAB without LEC (?) section_codes = ['LEC', 'SES', 'WBL'] def section_id(section): '''Return a section's course ID, e.g. "15807".''' return section['id'] def section_subject_area(section): '''Return a section's subject area, e.g. "STAT".''' return jmespath.search('class.course.subjectArea.code', section) def section_catalog_number(section): '''Return a section's formatted catalog number, e.g. "215B".''' return jmespath.search('class.course.catalogNumber.formatted', section) def section_display_name(section): '''Return a section's displayName, e.g. "STAT 215B".''' return jmespath.search('class.course.displayName', section) def section_is_primary(section): '''Return a section's primary status.''' return jmespath.search('association.primary', section) def enrollment_campus_uid(enrollment): '''Return an enrollent's campus UID.''' expr = "student.identifiers[?disclose && type=='campus-uid'].id | [0]" return jmespath.search(expr, enrollment) def enrollment_campus_email(enrollment): '''Return an enrollment's campus email if found, otherwise return any other email.''' expr = "student.emails[?type.code=='CAMP'].emailAddress | [0]" email = jmespath.search(expr, enrollment) if email: return email expr = "student.emails[?type.code=='OTHR'].emailAddress | [0]" return jmespath.search(expr, enrollment) def get_enrollment_uids(enrollments): '''Given an SIS enrollment, return the student's campus UID.''' return list(map(lambda x: enrollment_campus_uid(x), enrollments)) def get_enrollment_emails(enrollments): '''Given an SIS enrollment, return the student's campus email.''' return list(map(lambda x: enrollment_campus_email(x), enrollments)) def enrollment_status(enrollment): '''Return an enrollment's status, e.g. 'E', 'W', or 'D'.''' return jmespath.search('enrollmentStatus.status.code', enrollment) def filter_enrollment_status(enrollments, status): return list(filter(lambda x: enrollment_status(x) == status, enrollments)) def status_code(constituents): return {'enrolled':'E', 'waitlisted':'W', 'dropped':'D'}[constituents] def filter_lectures(sections, relevant_codes=section_codes): ''' Given a list of SIS sections: [{'code': '32227', 'description': '2019 Spring ASTRON 128 001 LAB 001'}] return only the section codes which are lectures. ''' codes = [] for section in sections: if 'description' not in section: continue desc_words = set(section['description'].split()) if len(set(desc_words) & set(relevant_codes)) > 0: codes.append(section['code']) return codes
[ 2, 43907, 25, 2617, 2123, 1509, 28, 19, 40379, 28, 19, 25, 198, 11748, 18931, 198, 11748, 25064, 198, 198, 11748, 474, 6880, 6978, 198, 198, 6738, 764, 1330, 264, 271, 11, 6097, 198, 198, 2, 18931, 198, 6404, 2667, 13, 35487, 16934,...
2.841856
1,056
from flask import Flask, render_template, request, redirect, url_for from os.path import join from stego import Steganography app = Flask(__name__) UPLOAD_FOLDER = 'static/files/' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} if __name__ == '__main__': app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 198, 6738, 336, 1533, 78, 1330, 2441, 1030, 4867, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8...
2.566929
127
from flatland.envs.agent_utils import RailAgentStatus from flatland.envs.malfunction_generators import malfunction_from_params, MalfunctionParameters from flatland.envs.observations import GlobalObsForRailEnv from flatland.envs.rail_env import RailEnv from flatland.envs.rail_generators import sparse_rail_generator from flatland.envs.schedule_generators import sparse_schedule_generator from flatland.utils.rendertools import RenderTool import random import sys import os import time import msgpack import json from PIL import Image import argparse as ap #env = create_test_env(RandomTestParams_small, 0, "train-envs-small/Test_0") if __name__=="__main__": main2()
[ 6738, 6228, 1044, 13, 268, 14259, 13, 25781, 62, 26791, 1330, 12950, 36772, 19580, 198, 6738, 6228, 1044, 13, 268, 14259, 13, 76, 1604, 4575, 62, 8612, 2024, 1330, 35654, 62, 6738, 62, 37266, 11, 32197, 4575, 48944, 198, 6738, 6228, 1...
2.854902
255
# -*- coding: utf-8 -*- # Generated by Django 2.2.4 on 2019-08-21 19:53 # this file is auto-generated so don't do flake8 on it # flake8: noqa from __future__ import absolute_import, unicode_literals from django.db import migrations, models import django.utils.timezone
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 19, 319, 13130, 12, 2919, 12, 2481, 678, 25, 4310, 198, 198, 2, 428, 2393, 318, 8295, 12, 27568, 523, 836, 470, 466, 781...
2.806122
98
"""Support for HTTP or web server issues."""
[ 37811, 15514, 329, 14626, 393, 3992, 4382, 2428, 526, 15931, 198 ]
4.090909
11
import torch.nn as nn from utils.BBBlayers import BBBConv2d, BBBLinearFactorial, FlattenLayer
[ 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 3384, 4487, 13, 15199, 3629, 6962, 1330, 12597, 2749, 261, 85, 17, 67, 11, 12597, 9148, 259, 451, 29054, 5132, 11, 1610, 41769, 49925 ]
2.818182
33
import os from tensorflow.contrib.learn.python.learn.datasets import base import numpy as np import IPython from subprocess import call from keras.preprocessing import image from influence.dataset import DataSet from influence.inception_v3 import preprocess_input BASE_DIR = 'data' # TODO: change
[ 11748, 28686, 198, 198, 6738, 11192, 273, 11125, 13, 3642, 822, 13, 35720, 13, 29412, 13, 35720, 13, 19608, 292, 1039, 1330, 2779, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 6101, 7535, 198, 198, 6738, 850, 14681, 1330, 869, 198, ...
3.161616
99
# Copyright 2020 Carsten Blank # # 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 json import logging from datetime import datetime, timedelta from braket.device_schema.device_service_properties_v1 import DeviceCost from typing import List, Dict, Optional, Any, Union, Tuple from botocore.response import StreamingBody from braket.aws import AwsDevice, AwsQuantumTask, AwsSession from braket.circuits import Circuit from braket.device_schema import DeviceCapabilities from braket.device_schema.ionq import IonqDeviceCapabilities from braket.device_schema.rigetti import RigettiDeviceCapabilities from braket.device_schema.simulators import GateModelSimulatorDeviceCapabilities from qiskit.providers import BaseBackend, JobStatus from qiskit.providers.models import QasmBackendConfiguration, BackendProperties, BackendStatus from qiskit.qobj import QasmQobj from . import awsjob from . import awsprovider from .conversions_configuration import aws_device_2_configuration from .conversions_properties import aws_ionq_to_properties, aws_rigetti_to_properties, aws_simulator_to_properties from .transpilation import convert_qasm_qobj logger = logging.getLogger(__name__)
[ 2, 15069, 12131, 1879, 26400, 31990, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 7...
3.592275
466
import OpenPNM import numpy as np import OpenPNM.Physics.models as pm
[ 11748, 4946, 13137, 44, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4946, 13137, 44, 13, 2725, 23154, 13, 27530, 355, 9114, 628 ]
3.086957
23
# MIT No Attribution # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import boto3 import os
[ 2, 17168, 1400, 45336, 198, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 198, 2, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340, 284, 1730, 287, 262, 10442, 1...
3.741935
248
# # Copyright (c) 2019-2022, NVIDIA CORPORATION. # # 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 bdb_tools.utils import ( benchmark, gpubdb_argparser, train_clustering_model, run_query, ) from bdb_tools.q26_utils import ( Q26_CATEGORY, Q26_ITEM_COUNT, N_CLUSTERS, CLUSTER_ITERATIONS, N_ITER, read_tables ) import numpy as np from dask import delayed def agg_count_distinct(df, group_key, counted_key): """Returns a Series that is the result of counting distinct instances of 'counted_key' within each 'group_key'. The series' index will have one entry per unique 'group_key' value. Workaround for lack of nunique aggregate function on Dask df. """ return ( df.drop_duplicates([group_key, counted_key]) .groupby(group_key)[counted_key] .count() ) if __name__ == "__main__": from bdb_tools.cluster_startup import attach_to_cluster config = gpubdb_argparser() client, bc = attach_to_cluster(config) run_query(config=config, client=client, query_func=main)
[ 2, 198, 2, 15069, 357, 66, 8, 13130, 12, 1238, 1828, 11, 15127, 23929, 44680, 6234, 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, ...
2.84755
551
from optimizer.utils.intbounds import IntBounds
[ 6738, 6436, 7509, 13, 26791, 13, 600, 65, 3733, 1330, 2558, 33, 3733, 628 ]
3.5
14
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals try: from unittest import mock except ImportError: import mock from tdclient import models from tdclient.test.test_helper import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 555, 715, 395, 1330, ...
3.226667
75
from setuptools import setup dependencies = [ 'numpy', 'scipy', 'scikit-learn', ] setup( name='fireTS', version='0.0.7', description='A python package for multi-variate time series prediction', long_description=open('README.md').read(), long_description_content_type="text/markdown", url='https://github.com/jxx123/fireTS.git', author='Jinyu Xie', author_email='xjygr08@gmail.com', license='MIT', packages=['fireTS'], install_requires=dependencies, include_package_data=True, zip_safe=False)
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 45841, 3976, 796, 685, 198, 220, 220, 220, 705, 77, 32152, 3256, 198, 220, 220, 220, 705, 1416, 541, 88, 3256, 198, 220, 220, 220, 705, 36216, 15813, 12, 35720, 3256, 198, 60, 198, 198,...
2.524887
221
# https://projecteuler.net/problem=19 day_19000101 = 1 days_1900 = year_days(1900) day_next_day1 = (day_19000101 + days_1900)%7 print(day_19000101, days_1900, day_next_day1) sum = 0 for i in range(1901, 2001): for j in range(1, 13): if day_next_day1 == 0: print(i, j) sum = sum + 1 days = month_days(j, i) day_next_day1 = (day_next_day1 + days)%7 #print(i, j, days, day_next_day1) print(sum)
[ 2, 3740, 1378, 16302, 68, 18173, 13, 3262, 14, 45573, 28, 1129, 628, 198, 820, 62, 1129, 18005, 486, 796, 352, 198, 12545, 62, 48104, 796, 614, 62, 12545, 7, 48104, 8, 198, 198, 820, 62, 19545, 62, 820, 16, 796, 357, 820, 62, 11...
1.974138
232
"""A simple address book.""" from ._tools import generate_uuid
[ 37811, 32, 2829, 2209, 1492, 526, 15931, 198, 6738, 47540, 31391, 1330, 7716, 62, 12303, 312, 628, 198 ]
3.611111
18
import keras import numpy as np import pandas as pd import cv2 import os import json import pdb import argparse import math import copy from vis.visualization import visualize_cam, overlay, visualize_activation from vis.utils.utils import apply_modifications from shutil import rmtree import matplotlib.cm as cm from matplotlib import pyplot as plt from sklearn import metrics import keras.backend as K from keras import activations from keras.applications.inception_v3 import preprocess_input as inception_pre from keras.applications.mobilenet import preprocess_input as mobilenet_pre from keras.applications.resnet50 import preprocess_input as resnet_pre from keras.applications.densenet import preprocess_input as densenet_pre from datagenerator import ImageDataGenerator from utils import load_model if __name__ == "__main__": main()
[ 11748, 41927, 292, 220, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 279, 9945, 198, 11748, 1822, 29572, 198, 11748, 10688, 198, 117...
3.366534
251
from libTask import Queue from common import configParams from common import common if __name__ == '__main__': main()
[ 6738, 9195, 25714, 1330, 4670, 518, 198, 6738, 2219, 1330, 4566, 10044, 4105, 198, 6738, 2219, 1330, 2219, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419 ]
3.378378
37
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 13 18:52:28 2018 @author: amajidsinar """ from sklearn import datasets import matplotlib.pyplot as plt import numpy as np plt.style.use('seaborn-white') iris = datasets.load_iris() dataset = iris.data # only take 0th and 1th column for X data_known = iris.data[:,:2] # y label_known = iris.target # the hard part # so matplotlib does not readily support labeling based on class # but we know that one of the feature of plt is that a plt call would give those set of number # the same color category = np.unique(label_known) for i in category: plt.scatter(data_known[label_known==i][:,0],data_known[label_known==i][:,1],label=i) # Unknown class of a data data_unknown = np.array([[5.7,3.3],[5.6,3.4],[6.4,3],[8.2,2.2]]) plt.scatter(data_unknown[:,0],data_unknown[:,1], label='?') plt.legend() #------------- # Euclidean Distance diff = data_known - data_unknown.reshape(data_unknown.shape[0],1,data_unknown.shape[1]) distance = (diff**2).sum(2) #return sorted index of distance dist_index = np.argsort(distance) label = label_known[dist_index] #for k in [1,2,3,4,5,6,7,8,9,10]: #keep the rank k = 10 label = label[:,:k] label_predict = [] for i in range(data_unknown.shape[0]): values,counts = np.unique(label[i], return_counts=True) ind = np.argmax(counts) label_predict.append(values[ind])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 3158, 1511, 1248, 25, 4309, 25, 2078, 2864, 198, 198, 31, 9800, 25, 716, 1228, 234...
2.512411
564
import torch, torchvision import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import os, json, cv2, random # import some common detectron2 utilities from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog, DatasetCatalog import argparse, time if __name__ == "__main__": args = parse_args() start_segment(args)
[ 11748, 28034, 11, 28034, 10178, 201, 198, 201, 198, 11748, 4886, 1313, 17, 201, 198, 6738, 4886, 1313, 17, 13, 26791, 13, 6404, 1362, 1330, 9058, 62, 6404, 1362, 201, 198, 40406, 62, 6404, 1362, 3419, 201, 198, 201, 198, 2, 1330, 61...
3.068783
189
"""AMQP Table Encoding/Decoding""" import struct import decimal import calendar from datetime import datetime from pika import exceptions from pika.compat import unicode_type, PY2, long, as_bytes def encode_short_string(pieces, value): """Encode a string value as short string and append it to pieces list returning the size of the encoded value. :param list pieces: Already encoded values :param value: String value to encode :type value: str or unicode :rtype: int """ encoded_value = as_bytes(value) length = len(encoded_value) # 4.2.5.3 # Short strings, stored as an 8-bit unsigned integer length followed by zero # or more octets of data. Short strings can carry up to 255 octets of UTF-8 # data, but may not contain binary zero octets. # ... # 4.2.5.5 # The server SHOULD validate field names and upon receiving an invalid field # name, it SHOULD signal a connection exception with reply code 503 (syntax # error). # -> validate length (avoid truncated utf-8 / corrupted data), but skip null # byte check. if length > 255: raise exceptions.ShortStringTooLong(encoded_value) pieces.append(struct.pack('B', length)) pieces.append(encoded_value) return 1 + length if PY2: def decode_short_string(encoded, offset): """Decode a short string value from ``encoded`` data at ``offset``. """ length = struct.unpack_from('B', encoded, offset)[0] offset += 1 # Purely for compatibility with original python2 code. No idea what # and why this does. value = encoded[offset:offset + length] try: value = bytes(value) except UnicodeEncodeError: pass offset += length return value, offset else: def decode_short_string(encoded, offset): """Decode a short string value from ``encoded`` data at ``offset``. """ length = struct.unpack_from('B', encoded, offset)[0] offset += 1 value = encoded[offset:offset + length].decode('utf8') offset += length return value, offset def encode_table(pieces, table): """Encode a dict as an AMQP table appending the encded table to the pieces list passed in. :param list pieces: Already encoded frame pieces :param dict table: The dict to encode :rtype: int """ table = table or {} length_index = len(pieces) pieces.append(None) # placeholder tablesize = 0 for (key, value) in table.items(): tablesize += encode_short_string(pieces, key) tablesize += encode_value(pieces, value) pieces[length_index] = struct.pack('>I', tablesize) return tablesize + 4 def encode_value(pieces, value): """Encode the value passed in and append it to the pieces list returning the the size of the encoded value. :param list pieces: Already encoded values :param any value: The value to encode :rtype: int """ if PY2: if isinstance(value, basestring): if isinstance(value, unicode_type): value = value.encode('utf-8') pieces.append(struct.pack('>cI', b'S', len(value))) pieces.append(value) return 5 + len(value) else: # support only str on Python 3 if isinstance(value, str): value = value.encode('utf-8') pieces.append(struct.pack('>cI', b'S', len(value))) pieces.append(value) return 5 + len(value) if isinstance(value, bool): pieces.append(struct.pack('>cB', b't', int(value))) return 2 if isinstance(value, long): pieces.append(struct.pack('>cq', b'l', value)) return 9 elif isinstance(value, int): pieces.append(struct.pack('>ci', b'I', value)) return 5 elif isinstance(value, decimal.Decimal): value = value.normalize() if value.as_tuple().exponent < 0: decimals = -value.as_tuple().exponent raw = int(value * (decimal.Decimal(10) ** decimals)) pieces.append(struct.pack('>cBi', b'D', decimals, raw)) else: # per spec, the "decimals" octet is unsigned (!) pieces.append(struct.pack('>cBi', b'D', 0, int(value))) return 6 elif isinstance(value, datetime): pieces.append(struct.pack('>cQ', b'T', calendar.timegm(value.utctimetuple()))) return 9 elif isinstance(value, dict): pieces.append(struct.pack('>c', b'F')) return 1 + encode_table(pieces, value) elif isinstance(value, list): p = [] for v in value: encode_value(p, v) piece = b''.join(p) pieces.append(struct.pack('>cI', b'A', len(piece))) pieces.append(piece) return 5 + len(piece) elif value is None: pieces.append(struct.pack('>c', b'V')) return 1 else: raise exceptions.UnsupportedAMQPFieldException(pieces, value) def decode_table(encoded, offset): """Decode the AMQP table passed in from the encoded value returning the decoded result and the number of bytes read plus the offset. :param str encoded: The binary encoded data to decode :param int offset: The starting byte offset :rtype: tuple """ result = {} tablesize = struct.unpack_from('>I', encoded, offset)[0] offset += 4 limit = offset + tablesize while offset < limit: key, offset = decode_short_string(encoded, offset) value, offset = decode_value(encoded, offset) result[key] = value return result, offset def decode_value(encoded, offset): """Decode the value passed in returning the decoded value and the number of bytes read in addition to the starting offset. :param str encoded: The binary encoded data to decode :param int offset: The starting byte offset :rtype: tuple :raises: pika.exceptions.InvalidFieldTypeException """ # slice to get bytes in Python 3 and str in Python 2 kind = encoded[offset:offset + 1] offset += 1 # Bool if kind == b't': value = struct.unpack_from('>B', encoded, offset)[0] value = bool(value) offset += 1 # Short-Short Int elif kind == b'b': value = struct.unpack_from('>B', encoded, offset)[0] offset += 1 # Short-Short Unsigned Int elif kind == b'B': value = struct.unpack_from('>b', encoded, offset)[0] offset += 1 # Short Int elif kind == b'U': value = struct.unpack_from('>h', encoded, offset)[0] offset += 2 # Short Unsigned Int elif kind == b'u': value = struct.unpack_from('>H', encoded, offset)[0] offset += 2 # Long Int elif kind == b'I': value = struct.unpack_from('>i', encoded, offset)[0] offset += 4 # Long Unsigned Int elif kind == b'i': value = struct.unpack_from('>I', encoded, offset)[0] offset += 4 # Long-Long Int elif kind == b'L': value = long(struct.unpack_from('>q', encoded, offset)[0]) offset += 8 # Long-Long Unsigned Int elif kind == b'l': value = long(struct.unpack_from('>Q', encoded, offset)[0]) offset += 8 # Float elif kind == b'f': value = long(struct.unpack_from('>f', encoded, offset)[0]) offset += 4 # Double elif kind == b'd': value = long(struct.unpack_from('>d', encoded, offset)[0]) offset += 8 # Decimal elif kind == b'D': decimals = struct.unpack_from('B', encoded, offset)[0] offset += 1 raw = struct.unpack_from('>i', encoded, offset)[0] offset += 4 value = decimal.Decimal(raw) * (decimal.Decimal(10) ** -decimals) # Short String elif kind == b's': value, offset = decode_short_string(encoded, offset) # Long String elif kind == b'S': length = struct.unpack_from('>I', encoded, offset)[0] offset += 4 value = encoded[offset:offset + length].decode('utf8') offset += length # Field Array elif kind == b'A': length = struct.unpack_from('>I', encoded, offset)[0] offset += 4 offset_end = offset + length value = [] while offset < offset_end: v, offset = decode_value(encoded, offset) value.append(v) # Timestamp elif kind == b'T': value = datetime.utcfromtimestamp(struct.unpack_from('>Q', encoded, offset)[0]) offset += 8 # Field Table elif kind == b'F': (value, offset) = decode_table(encoded, offset) # Null / Void elif kind == b'V': value = None else: raise exceptions.InvalidFieldTypeException(kind) return value, offset
[ 37811, 2390, 48, 47, 8655, 14711, 7656, 14, 10707, 7656, 37811, 198, 11748, 2878, 198, 11748, 32465, 198, 11748, 11845, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 279, 9232, 1330, 13269, 198, 6738, 279, 9232, 13, 5589, 265...
2.409079
3,701
from pylaas_core.abstract.abstract_service import AbstractService import time from pylaas_core.interface.technical.container_configurable_aware_interface import ContainerConfigurableAwareInterface
[ 6738, 279, 2645, 64, 292, 62, 7295, 13, 397, 8709, 13, 397, 8709, 62, 15271, 1330, 27741, 16177, 198, 11748, 640, 198, 198, 6738, 279, 2645, 64, 292, 62, 7295, 13, 39994, 13, 47944, 13, 34924, 62, 11250, 11970, 62, 9685, 62, 39994, ...
3.901961
51
from django.urls import reverse_lazy, reverse from django.utils.decorators import method_decorator from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView from .models import BlogPost from django.contrib.auth.decorators import login_required
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 62, 75, 12582, 11, 9575, 198, 6738, 42625, 14208, 13, 26791, 13, 12501, 273, 2024, 1330, 2446, 62, 12501, 273, 1352, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 11, 42...
3.597403
77
#! /usr/bin/env python # ******************************************************************** # Software License Agreement (BSD License) # # Copyright (c) 2015, University of Colorado, Boulder # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the University of Colorado Boulder # nor the names of its contributors may be # used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ********************************************************************/ import cv2 import os import numpy as np if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("proposal_path", type=str, help="relative path from python script to proposals, no slash") parser.add_argument("--view", default=None, help="true/1 shows each masked image") args = parser.parse_args() # args.proposal_path = "../test_proposals" # args.proposal_path = args.proposal_path included_extenstions = ['txt'] image_names = [fn[0:len(fn)-4] for fn in os.listdir(args.proposal_path) if any(fn.endswith(ext) for ext in included_extenstions)] for image_name in image_names: load_path = args.proposal_path + '/' + image_name image = cv2.imread(load_path + ".jpeg") data = np.loadtxt(load_path + ".txt", str) # If there is only one line, force data to be a list of lists anyway # Note, only works for our data as first list item is a string if isinstance(data[0], basestring): data = [data] # If any line does not conform to classification tl_x tl_y br_x br_y # then forget about it skip = False for line in data: if len(line) < 5: skip = True if skip: continue for i, proposal in zip(range(0,len(data)),data): mask = cv2.imread(load_path + '_mask{0:04d}.jpeg'.format(i)) mask = np.invert(mask) maskGray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) ret, maskGray = cv2.threshold(maskGray,128,255,cv2.THRESH_BINARY) print load_path + '_mask{0:04d}.jpeg'.format(i) cropped = image[float(proposal[2]):float(proposal[4]), float(proposal[1]):float(proposal[3])] masked = cv2.bitwise_and(cropped, cropped, mask = maskGray) if args.view: cv2.imshow("original", masked) cv2.waitKey(0) mask_directory = args.proposal_path + '/masked/' + proposal[0]; crop_directory = args.proposal_path + '/cropped/' + proposal[0]; if not os.path.exists(mask_directory): os.makedirs(mask_directory) if not os.path.exists(crop_directory): os.makedirs(crop_directory) cv2.imwrite(mask_directory + '/{}_{}.jpeg'.format(image_name,i), masked) cv2.imwrite(crop_directory + '/{}_{}.jpeg'.format(image_name,i), cropped) # item = data[] # cropped = image[70:170, 440:540] # startY:endY, startX:endX # startX:startY, endX:endY #
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 41906, 17174, 2466, 198, 2, 10442, 13789, 12729, 357, 21800, 13789, 8, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 1853, 11, 2059, 286, 7492, 11, 27437, 198, 2, 220, 1439, 2489, ...
2.52038
1,791
import numpy as np; import sys import matplotlib.pyplot as plt; from matplotlib import cm; from termcolor import colored; if __name__=="__main__": print "hello world"
[ 11748, 299, 32152, 355, 45941, 26, 198, 11748, 25064, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 26, 198, 6738, 2603, 29487, 8019, 1330, 12067, 26, 198, 6738, 3381, 8043, 1330, 16396, 26, 628, 198, 361, 11593, 3672, ...
3.053571
56
from EasyLogin import EasyLogin from pprint import pprint if __name__ == "__main__": #pprint(peptidecutter("SERVELAT")) import sys pprint(peptidecutter_more(sys.argv[1]))
[ 6738, 16789, 47790, 1330, 16789, 47790, 201, 198, 6738, 279, 4798, 1330, 279, 4798, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 1303, 381, 22272, 7, 431, 457, 485, 8968, 353, ...
2.353659
82
import unittest from .. import utils
[ 11748, 555, 715, 395, 198, 6738, 11485, 1330, 3384, 4487, 628 ]
3.454545
11
# Copyright (c) 2016 Hitachi Data Systems, Inc. # 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. import copy import ddt import mock from manila.common import constants from manila import context from manila import db from manila import exception from manila.share import snapshot_access from manila import test from manila.tests import db_utils from manila import utils
[ 2, 15069, 357, 66, 8, 1584, 7286, 14299, 6060, 11998, 11, 3457, 13, 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, ...
3.528736
261
# This sample tests the type checker's reportUnnecessaryCast feature. from typing import cast, Union c: Union[int, str] = "hello" d = cast(int, c)
[ 2, 770, 6291, 5254, 262, 2099, 2198, 263, 338, 989, 3118, 49986, 19248, 3895, 13, 198, 198, 6738, 19720, 1330, 3350, 11, 4479, 628, 198, 198, 66, 25, 4479, 58, 600, 11, 965, 60, 796, 366, 31373, 1, 198, 67, 796, 3350, 7, 600, 11...
3.145833
48
combinador()
[ 198, 785, 8800, 7079, 3419 ]
2.6
5
from http import HTTPStatus from typing import Iterable, Union, Mapping from flask import request from flask_restful import Resource, fields, marshal from metadata_service.proxy import get_proxy_client popular_table_fields = { 'database': fields.String, 'cluster': fields.String, 'schema': fields.String, 'table_name': fields.String(attribute='name'), 'table_description': fields.String(attribute='description'), # Optional } popular_tables_fields = { 'popular_tables': fields.List(fields.Nested(popular_table_fields)) }
[ 6738, 2638, 1330, 14626, 19580, 198, 6738, 19720, 1330, 40806, 540, 11, 4479, 11, 337, 5912, 198, 198, 6738, 42903, 1330, 2581, 198, 6738, 42903, 62, 2118, 913, 1330, 20857, 11, 7032, 11, 22397, 282, 198, 198, 6738, 20150, 62, 15271, ...
3.241176
170
import requests import logging import cfscrape import os from manhwaDownloader.constants import CONSTANTS as CONST logging.basicConfig(level=logging.DEBUG) folderPath = os.path.join(CONST.OUTPUTPATH, 'serious-taste-of-forbbiden-fruit') logging.info(len([file for file in os.walk(folderPath)])) walkList = [file for file in os.walk(folderPath)] chapterDicts = dict() for folder, _, files in walkList[1:]: chapterDicts.update({folder: files}) print(chapterDicts)
[ 11748, 7007, 198, 11748, 18931, 198, 11748, 30218, 1416, 13484, 198, 11748, 28686, 198, 6738, 582, 71, 10247, 10002, 263, 13, 9979, 1187, 1330, 7102, 2257, 1565, 4694, 355, 7102, 2257, 198, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28...
2.919255
161
# define custom R2 metrics for Keras backend from keras import backend as K # base model architecture definition ################K2 import pandas as pd import numpy as np from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV from sklearn.model_selection import GridSearchCV from sklearn.preprocessing import RobustScaler from keras import backend as K from keras.models import Sequential from keras.layers import Dense, InputLayer, GaussianNoise from keras.wrappers.scikit_learn import KerasRegressor train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') # # Data preparation # y_train = train['y'].values id_test = test['ID'] num_train = len(train) df_all = pd.concat([train, test]) df_all.drop(['ID', 'y'], axis=1, inplace=True) # One-hot encoding of categorical/strings df_all = pd.get_dummies(df_all, drop_first=True) # Sscaling features scaler = RobustScaler() df_all = scaler.fit_transform(df_all) train = df_all[:num_train] test = df_all[num_train:] # Keep only the most contributing features sfm = SelectFromModel(LassoCV()) sfm.fit(train, y_train) train = sfm.transform(train) test = sfm.transform(test) print ('Number of features : %d' % train.shape[1]) # # Tuning model parameters # model = KerasRegressor(build_fn=build_model_fn, epochs=75, verbose=0) gsc = GridSearchCV( estimator=model, param_grid={ #'neurons': range(18,31,4), 'noise': [x/20.0 for x in range(3, 7)], }, #scoring='r2', scoring='neg_mean_squared_error', cv=5 ) grid_result = gsc.fit(train, y_train) print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) for test_mean, test_stdev, train_mean, train_stdev, param in zip( grid_result.cv_results_['mean_test_score'], grid_result.cv_results_['std_test_score'], grid_result.cv_results_['mean_train_score'], grid_result.cv_results_['std_train_score'], grid_result.cv_results_['params']): print("Train: %f (%f) // Test : %f (%f) with: %r" % (train_mean, train_stdev, test_mean, test_stdev, param)) # # Train model with best params for submission # model = build_model_fn(**grid_result.best_params_) model.fit(train, y_train, epochs=75, verbose=2) y_test = model.predict(test).flatten() df_sub = pd.DataFrame({'ID': id_test, 'y': y_test}) df_sub.to_csv('mercedes-submission.csv', index=False) ######################### import pandas as pd import numpy as np from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor from sklearn.decomposition import PCA, FastICA from sklearn.preprocessing import RobustScaler from sklearn.pipeline import make_pipeline, Pipeline, _name_estimators from sklearn.linear_model import ElasticNet, ElasticNetCV from sklearn.model_selection import cross_val_score, KFold from sklearn.metrics import r2_score from sklearn.base import BaseEstimator, TransformerMixin import xgboost as xgb train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') y_train = train['y'].values y_mean = np.mean(y_train) id_test = test['ID'] num_train = len(train) df_all = pd.concat([train, test]) df_all.drop(['ID', 'y'], axis=1, inplace=True) # One-hot encoding of categorical/strings df_all = pd.get_dummies(df_all, drop_first=True) train = df_all[:num_train] test = df_all[num_train:] # # Model/pipeline with scaling,pca,svm # svm_pipe = LogExpPipeline(_name_estimators([RobustScaler(), PCA(), SVR(kernel='rbf', C=1.0, epsilon=0.05)])) # results = cross_val_score(svm_pipe, train, y_train, cv=5, scoring='r2') # print("SVM score: %.4f (%.4f)" % (results.mean(), results.std())) # exit() # # Model/pipeline with scaling,pca,ElasticNet # en_pipe = LogExpPipeline(_name_estimators([RobustScaler(), PCA(n_components=125), ElasticNet(alpha=0.001, l1_ratio=0.1)])) # # XGBoost model # xgb_model = xgb.sklearn.XGBRegressor(max_depth=4, learning_rate=0.005, subsample=0.921, objective='reg:linear', n_estimators=1300, base_score=y_mean) xgb_pipe = Pipeline(_name_estimators([AddColumns(transform_=PCA(n_components=10)), AddColumns(transform_=FastICA(n_components=10, max_iter=500)), xgb_model])) # results = cross_val_score(xgb_model, train, y_train, cv=5, scoring='r2') # print("XGB score: %.4f (%.4f)" % (results.mean(), results.std())) # # Random Forest # rf_model = RandomForestRegressor(n_estimators=250, n_jobs=4, min_samples_split=25, min_samples_leaf=25, max_depth=3) # results = cross_val_score(rf_model, train, y_train, cv=5, scoring='r2') # print("RF score: %.4f (%.4f)" % (results.mean(), results.std())) # # Now the training and stacking part. In previous version i just tried to train each model and # find the best combination, that lead to a horrible score (Overfit?). Code below does out-of-fold # training/predictions and then we combine the final results. # # Read here for more explanation (This code was borrowed/adapted) : # stack = Ensemble(n_splits=5, #stacker=ElasticNetCV(l1_ratio=[x/10.0 for x in range(1,10)]), stacker=ElasticNet(l1_ratio=0.1, alpha=1.4), base_models=(svm_pipe, en_pipe, xgb_pipe, rf_model)) y_test = stack.fit_predict(train, y_train, test) df_sub = pd.DataFrame({'ID': id_test, 'y': y_test}) df_sub.to_csv('submission.csv', index=False) ############################# '''This example demonstrates the use of Convolution1D for text classification. Gets to 0.89 test accuracy after 2 epochs. 90s/epoch on Intel i5 2.4Ghz CPU. 10s/epoch on Tesla K40 GPU. ''' from __future__ import print_function from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import Embedding from keras.layers import Conv1D, GlobalMaxPooling1D from keras.datasets import imdb # set parameters: max_features = 5000 maxlen = 400 batch_size = 32 embedding_dims = 50 filters = 250 kernel_size = 3 hidden_dims = 250 epochs = 2 print('Loading data...') (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features) print(len(x_train), 'train sequences') print(len(x_test), 'test sequences') print('Pad sequences (samples x time)') x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_test = sequence.pad_sequences(x_test, maxlen=maxlen) print('x_train shape:', x_train.shape) print('x_test shape:', x_test.shape) print('Build model...') model = Sequential() # we start off with an efficient embedding layer which maps # our vocab indices into embedding_dims dimensions model.add(Embedding(max_features, embedding_dims, input_length=maxlen)) model.add(Dropout(0.2)) # we add a Convolution1D, which will learn filters # word group filters of size filter_length: model.add(Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)) # we use max pooling: model.add(GlobalMaxPooling1D()) # We add a vanilla hidden layer: model.add(Dense(hidden_dims)) model.add(Dropout(0.2)) model.add(Activation('relu')) # We project onto a single unit output layer, and squash it with a sigmoid: model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))
[ 2, 8160, 2183, 371, 17, 20731, 329, 17337, 292, 30203, 198, 6738, 41927, 292, 1330, 30203, 355, 509, 198, 220, 220, 220, 220, 198, 2, 2779, 2746, 10959, 6770, 198, 220, 220, 220, 220, 198, 14468, 42, 17, 198, 11748, 19798, 292, 355,...
2.346176
3,400
# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np import pytest import mindspore as ms from mindspore import context, Tensor, Parameter from mindspore.common.api import _cell_graph_executor from mindspore.nn import Cell, TrainOneStepCell, Momentum from mindspore.ops import operations as P from mindspore.common.initializer import initializer _x = Tensor(np.ones([8, 8]), dtype=ms.int32) _b = Tensor(np.ones([64, 8]), dtype=ms.float32)
[ 2, 15069, 12131, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
3.691525
295
from bot.api.api_client import ApiClient from bot.api.base_route import BaseRoute import typing as t from bot.models import Tag
[ 6738, 10214, 13, 15042, 13, 15042, 62, 16366, 1330, 5949, 72, 11792, 198, 6738, 10214, 13, 15042, 13, 8692, 62, 38629, 1330, 7308, 43401, 198, 198, 11748, 19720, 355, 256, 198, 6738, 10214, 13, 27530, 1330, 17467, 628 ]
3.421053
38
# -*- coding: utf-8 -*- """ Created on Mon Sep 7 10:59:00 2020 @author: user """ import numpy as np import multiprocessing as mp import matplotlib.pyplot as plt import time import itertools import ctypes if __name__ == '__main__': AL_dist_flat = np.load(r'./AL_dist_flat.npy') n = np.shape(AL_dist_flat)[0] m = np.shape(AL_dist_flat)[1] q_range = np.logspace(-2,3,100) # r_x = np.array([1, 0, 0]) # q_range_glo = mp.Array(ctypes.c_double, q_range) AL_dist_flat_glo = mp.Array(ctypes.c_double, AL_dist_flat.flatten()) n_glo = mp.Value(ctypes.c_int, n) m_glo = mp.Value(ctypes.c_int, m) # r_x_glo = mp.Array(ctypes.c_double, r_x) paramlist = list(itertools.product(range(100), range(n))) pool = mp.Pool(20, initializer=parallelinit, initargs=(AL_dist_flat_glo, n_glo, m_glo)) t1 = time.time() results = pool.map(formfactor, paramlist) pool.close() t2 = time.time() print(t2-t1) np.save(r'./AL_results.npy', results) Pq = 2*np.divide(np.sum(np.array(results).reshape(100, n), axis=1), n) # fig = plt.figure(figsize=(8,6)) # plt.plot(q_range, Pq, lw=3, color='tab:orange') # plt.xscale('log') # plt.xlabel('$q$', fontsize=15) # plt.ylabel('$P(q)$', fontsize=15) # plt.tight_layout() # plt.savefig(r'./AL_form_factor.pdf', dpi=300, bbox_inches='tight') # plt.show() fig = plt.figure(figsize=(8,6)) plt.plot(q_range, Pq, lw=3, color='tab:orange') plt.xscale('log') plt.yscale('log') plt.xlabel('$q$', fontsize=15) plt.ylabel('$P(q)$', fontsize=15) plt.tight_layout() plt.savefig(r'./AL_form_factor_log.pdf', dpi=300, bbox_inches='tight') plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 8621, 220, 767, 838, 25, 3270, 25, 405, 12131, 198, 198, 31, 9800, 25, 2836, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11...
1.97973
888
# coding: utf-8 import io import cairo # pycairo import cairocffi from pycairo_to_cairocffi import _UNSAFE_pycairo_context_to_cairocffi from cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo import pango_example if __name__ == '__main__': test()
[ 2, 19617, 25, 3384, 69, 12, 23, 201, 198, 201, 198, 11748, 33245, 201, 198, 11748, 1275, 7058, 220, 1303, 12972, 66, 18131, 201, 198, 11748, 1275, 7058, 66, 487, 72, 201, 198, 201, 198, 6738, 12972, 66, 18131, 62, 1462, 62, 66, 18...
2.142857
133
import random goat1 = random.randint(1, 3) goat2 = random.randint(1, 3) while goat1 == goat2: goat2 = random.randint(1, 3) success = 0 tries = 1_000_000 for _ in range(tries): options = [1, 2, 3] choice = random.randint(1, 3) options.remove(choice) if choice == goat1: options.remove(goat2) else: options.remove(goat1) choice = options[0] if choice != goat1 and choice != goat2: success = success + 1 print(success / tries)
[ 11748, 4738, 198, 198, 2188, 265, 16, 796, 4738, 13, 25192, 600, 7, 16, 11, 513, 8, 198, 2188, 265, 17, 796, 4738, 13, 25192, 600, 7, 16, 11, 513, 8, 198, 198, 4514, 26917, 16, 6624, 26917, 17, 25, 198, 220, 220, 220, 26917, 1...
2.29717
212