content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding:UTF-8 -*- import pandas as pd from minepy import MINE import seaborn as sns import matplotlib.pyplot as plt from sklearn.ensemble import ExtraTreesClassifier import xgboost as xgb import operator from sklearn.utils import shuffle from Common.ModelCommon import ModelCV from sklearn import svm import numpy as np # # rate0rate*1 # repeat1 # train_datacvsample # iswholeTrueTARGETFalseTARGET
[ 2, 532, 9, 12, 19617, 25, 48504, 12, 23, 532, 9, 12, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 6164, 9078, 1330, 337, 8881, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458...
2.952055
146
import xml.etree.ElementTree as ET import pytest from .helpers import utils def test_widevine_pssh_cpd_no_rotation(widevine_pssh_cpd_response): root_cpix = ET.fromstring(widevine_pssh_cpd_response) drm_system_list_element = root_cpix.find('./{urn:dashif:org:cpix}DRMSystemList') drm_system_elements = drm_system_list_element.findall('./{urn:dashif:org:cpix}DRMSystem') for drm_system_element in drm_system_elements: pssh_data_bytes = drm_system_element.find('./{urn:dashif:org:cpix}PSSH') content_protection_data_bytes = drm_system_element.find('./{urn:dashif:org:cpix}ContentProtectionData') content_protection_data_string = utils.decode_b64_bytes(content_protection_data_bytes.text) pssh_in_cpd = ET.fromstring(content_protection_data_string) # Assert pssh in cpd is same as pssh box assert pssh_data_bytes.text == pssh_in_cpd.text, \ "Content in PSSH box and the requested content in ContentProtectionData are expected to be the same" # Validate presence of HLSSignalingData and PSSH when those elements are present in the request
[ 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 12972, 9288, 198, 6738, 764, 16794, 364, 1330, 3384, 4487, 628, 628, 198, 198, 4299, 1332, 62, 4421, 26818, 62, 79, 45824, 62, 13155, 67, 62, 3919, 62, 10599, 341, ...
2.555809
439
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628, 628 ]
3.571429
7
# -*- coding: utf-8 -*- """ Perform Bluetooth LE Scan. Based on https://github.com/hbldh/bleak/blob/master/bleak/backends/dotnet/discovery.py by Created by hbldh <henrik.blidh@nedomkull.com> """ import logging logger = logging.getLogger('bleak_scanner') import asyncio import queue from bleak.backends.device import BLEDevice # Import of Bleak CLR->UWP Bridge. It is not needed here, but it enables loading of Windows.Devices from BleakBridge import Bridge from System import Array, Byte from Windows.Devices.Bluetooth.Advertisement import \ BluetoothLEAdvertisementWatcher, BluetoothLEScanningMode from Windows.Storage.Streams import DataReader, IBuffer QUEUE_SIZE = 100 ###############################################################################
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 5990, 687, 19263, 12509, 20937, 13, 198, 198, 15001, 319, 3740, 1378, 12567, 13, 785, 14, 71, 65, 335, 71, 14, 903, 461, 14, 2436, 672, 14, 9866, 14, 903...
3.401786
224
import tkinter as tk from PIL import Image, ImageTk import numpy as np import os import time app=MyAPP()
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 51, 74, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 640, 198, 198, 1324, 28, 3666, 24805, 3419, 198 ]
2.864865
37
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The command group for Cloud API Gateway CLI.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.ml_engine import flags from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.core import resources
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 13130, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198...
3.7603
267
countries = {'Russia' : 'Europe', 'Germany' : 'Europe', 'Australia' : 'Australia'} sqrs = {} sqrs[1] = 1 sqrs[2] = 4 sqrs[10] = 100 print(sqrs) myDict = dict([['key1', 'value1'], ('key2', 'value2')]) print(myDict) phones = {'police' : 102, 'ambulance' : 103, 'firefighters' : 101} print(phones['police']) phones = {'police' : 102, 'ambulance' : 103, 'firefighters' : 101} del phones['police'] print(phones) phones = {'police' : 102, 'ambulance' : 103, 'firefighters' : 101} for service in phones: print(service, phones[service]) phones = {'police' : 102, 'ambulance' : 103, 'firefighters' : 101} for service, phone in phones.items(): print(service, phone) seq = map(int, input().split()) countDict = {} for elem in seq: countDict[elem] = countDict.get(elem, 0) + 1 for key in sorted(countDict): print(key, countDict[key], sep=' : ') n = int(input()) latinEnglish = {} for i in range(n): line = input() english = line[:line.find('-')].strip() latinsStr = line[line.find('-') + 1:].strip() latins = map(lambda s : s.strip(), latinsStr.split(',')) for latin in latins: if latin not in latinEnglish: latinEnglish[latin] = [] latinEnglish[latin].append(english) print(len(latinEnglish)) for latin in sorted(latinEnglish): print(latin, '-', ', '.join(sorted(latinEnglish[latin])))
[ 9127, 1678, 796, 1391, 6, 16347, 6, 1058, 705, 16112, 3256, 705, 27079, 6, 1058, 705, 16112, 3256, 705, 27429, 6, 1058, 705, 27429, 6, 92, 198, 198, 31166, 3808, 796, 23884, 198, 31166, 3808, 58, 16, 60, 796, 352, 198, 31166, 3808, ...
2.481618
544
""" Runtime: 47 ms, faster than 89.57% of Python3 online submissions for Regular Expression Matching. Memory Usage: 15.2 MB, less than 6.45% of Python3 online submissions for Regular Expression Matching. """ from typing import List from typing import Optional if __name__ == "__main__": main()
[ 37811, 198, 41006, 25, 6298, 13845, 11, 5443, 621, 9919, 13, 3553, 4, 286, 11361, 18, 2691, 22129, 329, 23603, 41986, 13225, 278, 13, 198, 30871, 29566, 25, 1315, 13, 17, 10771, 11, 1342, 621, 718, 13, 2231, 4, 286, 11361, 18, 2691,...
3.691358
81
#Desafio019 ( aplicao randomica para determinar que aluno vai no quadro. import random al01 = str('joao'),('maria'),('pdro'),('paula') print(random.choice(al01))
[ 2, 5960, 1878, 952, 30484, 357, 257, 489, 3970, 78, 4738, 3970, 31215, 3416, 283, 8358, 435, 36909, 410, 1872, 645, 15094, 305, 13, 198, 11748, 4738, 198, 198, 282, 486, 796, 965, 10786, 7639, 5488, 33809, 10786, 3876, 544, 33809, 107...
2.672131
61
#!/usr/bin/python from ansible.module_utils.basic import * from jdll import API ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: book author: "Yanis Guenane (@Spredzy)" version_added: "2.3" short_description: Gerer des resources books de notre API de test. description: - Ce module interagit avec le endpoint /books de notre API de test. options: state: required: false default: "present" choices: [ present, absent ] description: - Si la resource book doit etre presente ou absente. id: required: false description: - L'identifieur de la resource book. author: required: false description: - Le nom de l'auteur de book. title: required: false description: - Titre du book. summary: required: true description: - Resume du book. ''' EXAMPLES = ''' # Create a new book - book: title: A title author: An author summary: A summary # Update a specific book - book: id: XXXX title: Un titre alternatif # Delete a book - book: id: XXX state: absent ''' RETURN = ''' title: description: The title of the book returned: - changed - success type: string sample: A title summary: description: The summary of the book returned: - changed - success type: string sample: A summary id: description: ID of the book returned: - changed - success type: string sample: XXXXX ''' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 9093, 856, 13, 21412, 62, 26791, 13, 35487, 1330, 1635, 198, 6738, 474, 12736, 1330, 7824, 198, 198, 15037, 34563, 62, 47123, 2885, 13563, 796, 1391, 6, 13376, 10354, 37250, 3866, ...
2.274045
759
from menu_design import * from PySide6.QtWidgets import QApplication, QMainWindow from PySide6.QtCore import Qt, QEasingCurve # Local files from reologicalOne.reological import RModel from reologicalTwo.reologicalDB import RModelDB from density.density import Density import sys # class for menu if __name__ == "__main__": app = QApplication(sys.argv) mi_app = Global() mi_app.show() sys.exit(app.exec())
[ 6738, 6859, 62, 26124, 1330, 1635, 198, 6738, 9485, 24819, 21, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416, 11, 1195, 13383, 27703, 198, 6738, 9485, 24819, 21, 13, 48, 83, 14055, 1330, 33734, 11, 1195, 36, 2313, 26628, 303, 198, 1...
2.898649
148
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys reload(sys) sys.setdefaultencoding('utf-8') import ExcelUtil from jinja2 import Template import re
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 628, 198, 11748, 28686, 198, 11748, 25064, 198, 260, 2220, 7, 17597, 8, 198, 17597, 13, 2617, 12286, 12685, 7656, 10786, 40477, ...
2.640625
64
from keras.preprocessing import image import keras.applications.resnet50 as resnet50 import numpy as np app = None
[ 6738, 41927, 292, 13, 3866, 36948, 1330, 2939, 198, 11748, 41927, 292, 13, 1324, 677, 602, 13, 411, 3262, 1120, 355, 581, 3262, 1120, 198, 11748, 299, 32152, 355, 45941, 198, 198, 1324, 796, 6045, 628, 628, 198 ]
3.157895
38
import re from camp_real_engine.abstract.abc_subst_realizer import ABC_subst_realizer from camp_real_engine.model.realization import RegExpFileSubstNode from camp_real_engine.dao.daos import FileContentCommiter from camp_real_engine.abstract.abc_real_data_model import ABCSubstitutionNode
[ 11748, 302, 198, 198, 6738, 1413, 62, 5305, 62, 18392, 13, 397, 8709, 13, 39305, 62, 7266, 301, 62, 5305, 7509, 1330, 9738, 62, 7266, 301, 62, 5305, 7509, 198, 6738, 1413, 62, 5305, 62, 18392, 13, 19849, 13, 5305, 1634, 1330, 3310, ...
3.197802
91
#!/usr/bin/env python2 ''' Created on Sep 21, 2016 @author: David Zwicker <dzwicker@seas.harvard.edu> ''' from __future__ import division import argparse import sys import os # add the root of the video-analysis project to the path script_path = os.path.split(os.path.realpath(__file__))[0] package_path = os.path.abspath(os.path.join(script_path, '..', '..')) sys.path.append(package_path) video_analysis_path_guess = os.path.join(package_path, '..', 'video-analysis') sys.path.append(os.path.abspath(video_analysis_path_guess)) from mouse_burrows.simple import load_result_file def get_info(result_file, parameters=False): """ show information about an analyzed antfarm video `result_file` is the file where the results from the video analysis are stored. This is usually a *.yaml file `parameters` is a flag that indicates whether the parameters of the result file are shown """ # load the respective result file analyzer = load_result_file(result_file) info = {} if parameters: info['Parameters'] = analyzer.params.to_dict() return info def main(): """ main routine of the script """ # setup the argument parsing parser = argparse.ArgumentParser( description='Program that outputs information about the analysis of ' 'antfarm processing.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('-r', '--result_file', metavar='FILE', type=str, required=True, help='filename of video analysis result') parser.add_argument('-p', '--parameters', action='store_true', help='show all parameters') # fetch the arguments and build the parameter list args = parser.parse_args() # obtain information from data info = get_info(result_file=args.result_file, parameters=args.parameters) # TODO: add other output methods, like json, yaml, python dict from pprint import pprint pprint(info) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 7061, 6, 198, 41972, 319, 8621, 2310, 11, 1584, 198, 198, 31, 9800, 25, 3271, 1168, 86, 15799, 1279, 67, 89, 86, 15799, 31, 325, 292, 13, 9869, 10187, 13, 15532, 29, 198, 7061,...
2.624384
812
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict import functools import re from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.networkmanagement_v1beta1.services.reachability_service import pagers from google.cloud.networkmanagement_v1beta1.types import connectivity_test from google.cloud.networkmanagement_v1beta1.types import reachability from google.protobuf import empty_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ReachabilityServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport from .client import ReachabilityServiceClient try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-networkmanagement", ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ( "ReachabilityServiceAsyncClient", )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2...
3.235119
672
from django.urls import path from rest_framework import viewsets from rest_framework import routers from . import views from django.urls import include from rest_framework.routers import DefaultRouter router=DefaultRouter() router.register('hello-viewset',views.HelloViewSet,basename='hello-viewset') router.register('profile',views.UserProfileViewSet) router.register('login',views.LoginViewSet,basename='login') router.register('task',views.TaskViewset) urlpatterns = [ path('helloview/',views.HelloAPIView.as_view()), path('',include(router.urls)), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 1334, 62, 30604, 1330, 5009, 1039, 198, 6738, 1334, 62, 30604, 1330, 41144, 198, 6738, 764, 1330, 5009, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 2291, 198, 6738, 1334, 62, 3...
3.162921
178
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI
[ 6738, 1277, 13, 12942, 1662, 1958, 1330, 4128, 3673, 1958, 22289, 198, 6738, 1277, 13, 17080, 6169, 13, 20344, 6169, 10267, 20185, 1330, 4307, 6169, 10267, 20185, 198 ]
4.357143
28
import os print(os.curdir)
[ 11748, 28686, 198, 198, 4798, 7, 418, 13, 66, 2799, 343, 8 ]
2.25
12
from setuptools import setup from pathlib import Path from typing import Dict HERE = Path(__file__).parent version: Dict[str, str] = {} version_file = HERE / "src" / "thermostate" / "_version.py" exec(version_file.read_text(), version) setup(version=version["__version__"], package_dir={"": "src"})
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 198, 198, 39, 9338, 796, 10644, 7, 834, 7753, 834, 737, 8000, 198, 198, 9641, 25, 360, 713, 58, 2536, 11, 965, 60, 796, 23884...
2.990099
101
''' _ _._ _..._ .-', _.._(`)) '-. ` ' /-._.-' ',/ ) \ '. / _ _ | \ | a a / | \ .-. ; '-('' ).-' ,' ; '-; | .' \ \ / | 7 .__ _.-\ \ | | | ``/ /` / /,_| | /,_/ / /,_/ '`-' ----------------------------------------- injured face like Duke Nukem /moving hostages panic children as terrorists! with RPGs /taking cover /Claymore 700 ball bearings night shootouts mp7 rifle with silencer /2 images for hostages /Barrett Browning M82 CQ /go through walls, kill tango commandos with one shot /see through walls with scope ?tablet version Fellow shooters with Ai /medical kits shoot and shatter glass guards and /trigger waypoints long distance shooting! sniper rifle! show dead bodies in 3 positions: left, right, upside down! assassinations deeper missions scenario announcement scenario chooser improve tango generation background music show next mission give a summary of the performance /fight against special forces who take 5 shots before dying /weapons restriction! /pause that pauses the bullets - important! /campaign mode /reset stats F1 key 13.3.2015 /prevent hero from going off screen 14.3.2015 pi day tango random shooters tango intelligent fire tango intelligent movement, flanking! game suicide bombers /game hostages hostage with timer shootings /different rates of auto fire small message window bullets that can shoot through the walls! blow cover away with bombs /Hero cursor wasd movement /Tangos will target Hero RPG countdown to explosion tangos hostages cover sniper rifle and distances blood? /headshots /leg shots shield for storming rooms weapon accuracy range rate of auto fire Pistol Name Graphic Aiming cursor Sound firing Sound hit Safe, Semi Number of rounds Reload() Choose() Draw() DrawRounds() Fire() Selector() Knife - sheathed, stab/slash/throw Silenced Pistol Glock automatic pistol Samurai sword Parachute avoid 'obstacles' Maze grid when covert missions Rifle Safe Semi Auto Sniper Rifle Safe Semi Mini-gun 50 round a second! 4400 round box SAW safe Auto Shotgun spread shot Stun granade safe armed Grenade Safe Armed Rocket Safe Semi Artillery Coords Confirm auto fire --------------- explosion objects Grenades as well. Grenade multiple launcher use proper consts better structure for changing weapons use hash to get to weapons instead of if-then-else ''' import pyglet from pyglet.window import key from pyglet import clock import random #import Tkinter, tkMessageBox gSound = Sounds() gmw = MessageWin('Battle Report') gBattleRep = BattleReport() #gBattleRep.numberbodyhit += 1 #BattleReport.bullshit = 37 #print gBattleRep.numberbodyhit, BattleReport.bullshit #gBattleRep.report() #tkMessageBox.showinfo('Battle Report','Stuff') #gmw.switch_to() #gmw.show() #gmw.setText('fuck'+' pap',0) ''' Bystanders Movement all over the place stats explosions bullets ''' ''' Hostages Moving / stationary crying sounds statistics tracked different looks statistics drawing ''' ''' animate explosions sound handled elsewhere ''' def HandleModeSelect(modes,currMode): #print Const.foo i = 0 while i < len(modes): if currMode == modes[i] and i < len(modes)-1: return modes[i+1] i += 1 return modes[0] def withinrect( x,y,r): x1,y1=r[0],r[1] x2,y2=r[2],r[3] if x>x1 and x<x2 and y>y1 and y<y2: return True return False ''' man figure must go past to trigger red to green 1 2 3 ''' ''' goes in front of the tangos to provide cover for bullets typeofcover ''' ''' ninja stealth five bullets to kill one cannot be killed by grenade dead bodies list ''' #class TargetBoard0(): #def __init__(self,x,y): #self.target = SpriteLoad(Const.folder+'target.jpg') #self.target.scale = 0.25 #self.target.set_position(x,y) ##self.target.rotation = -90.0 ##self.hitlist = [] #print 'init Target' #print self.target.width, self.target.height #def move(self,w,h): ##print 'move',self.target.x,w,h #d = GetDirection() #tw = self.target.width #th = self.target.height #x = self.target.x #y = self.target.y #self.target.x,self.target.y = MoveXY(d, x,y,tw, th, w, h) #pass #def Hit(self,x,y): #tx = self.target.x #ty = self.target.y #l = tx #t = ty + self.target.height/4*3 #r = tx + self.target.width #b = ty + self.target.height #recthead = [l, t, r, b] #l = tx #t = ty + self.target.height/4 #r = tx + self.target.width #b = ty + self.target.height/4*3 #rectbody = [l, t, r, b] #l = tx #t = ty #r = tx + self.target.width #b = ty + self.target.height/4 #rectlegs = [l, t, r, b] #if withinrect( x, y, recthead): #print 'head hit' #return True #elif withinrect( x, y, rectbody): #print 'body hit' ##self.sound.Play(self.sound.pain) #return True #elif withinrect( x, y, rectlegs): #print 'leg hit' ##self.sound.Play(self.sound.pain) #return True #else: ##print 'miss' #return False #def Draw(self): #self.target.draw() ''' appear near hero dot moves randomly dot moves toward hero tries to hit hero number skill speed location of hero add attacks timed attacks, then end each check hit RPG sound of hero hit /graphic ''' ''' to allow the number keys to be programmed with different weapons as to the mission at hand. ''' ''' Place where stuff that can be shot at are placed. Tango Hostages Cover can be distant and nearby distant for sniper How to account for the shot? Scoring? ''' #class ShootingGallery(): #gTargetBoard = TargetBoard() gShootGallery = ShootingGallery() gBulletHoles = BulletHoles() #class Pistol(): #def __init__(self, #name, ##sound, ##bulletholes, #): #self.name = name #print 'pistol init' #self.mode = Const.pistolSafe #self.data = Const.folder #weapondata = self.Database(name) #self.drawing = SpriteLoad(self.data+weapondata[0]) #self.drawing.scale = weapondata[1] #self.sound = gSound #self.bulleth = gBulletHoles #self.mousex = 0 #self.mousey = 0 #self.magazine = weapondata[2] #self.ammo = self.magazine #self.reloadweapon = False #self.status = pyglet.text.Label('Hello, world', #font_name='Times New Roman', #font_size=24, #x=220, y = 20) #self.SetText() #self.reticle = weapondata[3] #pass #def Database(self,name): ##filename,scale,magazine capacity, #if name == Const.pistol1911: #return 'm1911pistol.jpg',0.25,15,'reticlePistol1911.png' #else: #raise Exception("pistol Weapon not exist!") #def reloadCall(self,dt): #if self.reloadweapon: #self.reloadtime -= 1 #if self.reloadtime < 1: #self.ammo = self.magazine #self.SetText() #clock.unschedule(self.reloadCall) #self.reloadweapon = False #def mouse(self,x,y): #if self.mode != Const.pistolSafe: #self.trigger = True #self.mousex = x #self.mousey = y #self.Fire() #def mouseup(self,x,y): #self.trigger = False #def mousedrag(self,x,y): ##pistol got no drag #pass #def Fire(self): #if self.ammo > 0: ##self.sound.Play(self.sound.sar21) #self.sound.Play(self.sound.m1911) #x = self.mousex #y = self.mousey #self.bulleth.record(x,y) #self.ammo -= 1 #self.SetText() ##gTargetBoard.Hit(x, y) #gShootGallery.Hit(x, y) #def SetText(self): #self.report = self.name + ' ' + self.mode + ' ' + str(self.ammo) #self.status.text = self.report #def select(self): ##print 'pistol mode' #self.mode = HandleModeSelect(Const.pistolModes, self.mode) ##print self.mode #self.SetText() ##print self.mode #def draw(self): #self.drawing.draw() #self.bulleth.draw() #self.status.draw() #pass #def Reload(self): #self.sound.Player(self.sound.reLoad) #self.reloadweapon = True #self.reloadtime = 3 #clock.schedule_interval(self.reloadCall, 1.0) #def SetSights(self,win): #image = pyglet.image.load(Const.folder+self.reticle) #cursor = pyglet.window.ImageMouseCursor(image, 25, 25) #win.set_mouse_cursor( cursor) #pass #class CurrentGame(): if __name__ == "__main__": #gmw = MessageWin('Messages') #gmw2 = MessageWin('Main') m = FPSWin() pyglet.app.run()
[ 628, 198, 7061, 6, 628, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 4808, 198, 4808, 13557, 4808, 986, 62, 764, 12, 3256, 220, 220, 220, 220, 4808, 492,...
2.099283
4,603
# (c) 2018, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import collections from ansible.module_utils.six import iteritems, string_types from ansible.errors import AnsibleUndefinedVariable
[ 2, 357, 66, 8, 2864, 11, 28038, 856, 416, 2297, 10983, 11, 753, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 357, 3826, 27975, 45761, 393, 3740, 1378, 2503, 13, 41791, 13, 2398, 14, 677, 4541, 14, 70, 489, 12, 18, 13, ...
3.230263
152
from Redy.Opt import feature, constexpr import timeit print(f1(1)(2)) print(f2(1)(2)) # 3 # 3 # mk closure print(timeit.timeit("f(1)", globals=dict(f=f1))) print(timeit.timeit("f(1)", globals=dict(f=f2))) # 0.15244655999958923 # 0.16590227899905585 f1_ = f1(2) f2_ = f2(2) print(timeit.timeit("f(1)", globals=dict(f=f1_))) print(timeit.timeit("f(1)", globals=dict(f=f2_))) # 0.08070355000018026 # 0.20936105600048904 # So, use builtin closures instead of making our own
[ 6738, 2297, 88, 13, 27871, 1330, 3895, 11, 1500, 31937, 198, 11748, 640, 270, 628, 628, 628, 198, 4798, 7, 69, 16, 7, 16, 5769, 17, 4008, 198, 4798, 7, 69, 17, 7, 16, 5769, 17, 4008, 198, 2, 513, 198, 2, 513, 198, 198, 2, 33...
2.162162
222
def f(x): '''Does nothing. :type x: a.C ''' pass
[ 4299, 277, 7, 87, 2599, 198, 220, 220, 220, 705, 7061, 13921, 2147, 13, 628, 220, 220, 220, 1058, 4906, 2124, 25, 257, 13, 34, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 1208, 198 ]
1.783784
37
# this should accept a command as a string, and raturn a string detailing the issue # if <command> is not a valid vanilla minecraft command. None otherwise.
[ 2, 428, 815, 2453, 257, 3141, 355, 257, 4731, 11, 290, 4227, 700, 257, 4731, 22976, 262, 2071, 198, 2, 611, 1279, 21812, 29, 318, 407, 257, 4938, 16858, 6164, 3323, 3141, 13, 6045, 4306, 13, 628 ]
4.27027
37
print("One") print("Two") print("Three")
[ 4798, 7203, 3198, 4943, 198, 198, 4798, 7203, 7571, 4943, 198, 198, 4798, 7203, 12510, 4943, 628 ]
2.588235
17
"""AI is creating summary for """ from frontend import main_window from PyQt5 import QtWidgets from frontend import input_system from PyQt5.QtWidgets import QInputDialog, qApp from qt_material import apply_stylesheet style_sheets = ['dark_amber.xml', 'dark_blue.xml', 'dark_cyan.xml', 'dark_lightgreen.xml', 'dark_pink.xml', 'dark_purple.xml', 'dark_red.xml', 'dark_teal.xml', 'dark_yellow.xml', 'light_amber.xml', 'light_blue.xml', 'light_cyan.xml', 'light_cyan_500.xml', 'light_lightgreen.xml', 'light_pink.xml', 'light_purple.xml', 'light_red.xml', 'light_teal.xml', 'light_yellow.xml']
[ 37811, 20185, 318, 4441, 10638, 329, 220, 198, 37811, 198, 198, 6738, 2166, 437, 1330, 1388, 62, 17497, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 54, 312, 11407, 198, 6738, 2166, 437, 1330, 5128, 62, 10057, 198, 6738, 9485, 48, 83, ...
1.73622
508
import mss import numpy as np from PIL import Image from config import BOARD_HEIGHT, BOARD_WIDTH CELL_SIZE = 22 BOARD_X = 14 BOARD_Y = 111 COLOR_CODES = { (0, 0, 255): 1, (0, 123, 0): 2, (255, 0, 0): 3, (0, 0, 123): 4, (123, 0, 0): 5, (0, 123, 123): 6, (0, 0, 0): 7, (123, 123, 123): 8, (189, 189, 189): 0 #unopened/opened blank }
[ 11748, 285, 824, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 4566, 1330, 16494, 9795, 62, 13909, 9947, 11, 16494, 9795, 62, 54, 2389, 4221, 198, 5222, 3069, 62, 33489, 796, 2534, 198, 8202, 9795, 6...
2.029762
168
import pytest from stack_and_queue_brackets.stack_and_queue_brackets import validate_brackets
[ 11748, 12972, 9288, 198, 6738, 8931, 62, 392, 62, 36560, 62, 1671, 25180, 13, 25558, 62, 392, 62, 36560, 62, 1671, 25180, 1330, 26571, 62, 1671, 25180, 628, 628, 628, 628, 198 ]
3.1875
32
""" from https://github.com/keithito/tacotron """ _pad = '_' #_punctuation = '!\'(),.:;? ' _punctuation = '!",.:;? ' _special = '-' #_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' _letters = "" symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters)
[ 37811, 422, 3740, 1378, 12567, 13, 785, 14, 365, 342, 10094, 14, 83, 330, 313, 1313, 37227, 198, 198, 62, 15636, 220, 220, 220, 220, 220, 220, 220, 796, 705, 62, 6, 198, 2, 62, 79, 16260, 2288, 796, 705, 0, 43054, 22784, 11207, ...
2.19403
134
"""Hello from the abyss."""
[ 37811, 15496, 422, 262, 37678, 526, 15931, 198 ]
3.5
8
# The MIT License (MIT) # # Copyright (c) 2015 by Teradata # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import unittest import os import teradata from teradata import tdodbc, util configFiles = [os.path.join(os.path.dirname(__file__), 'udaexec.ini')] udaExec = teradata.UdaExec(configFiles=configFiles, configureLogging=False) dsn = 'ODBC' odbcConfig = udaExec.config.section(dsn) system = odbcConfig['system'] super_username = odbcConfig['username'] super_password = odbcConfig['password'] if __name__ == '__main__': unittest.main()
[ 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 1853, 416, 3813, 14706, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290...
3.474273
447
import sys input = sys.stdin.readline w, h = map(int, input().split()) if w / h == 4 / 3: ans = '4:3' else: ans = '16:9' print(ans)
[ 11748, 25064, 198, 15414, 796, 25064, 13, 19282, 259, 13, 961, 1370, 198, 198, 86, 11, 289, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 198, 361, 266, 1220, 289, 6624, 604, 1220, 513, 25, 198, 220, 220, 220, 9093, 796, ...
2.072464
69
import setuptools long_description = "" with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( author='Josiah Bradley', author_email='JosiahBradley@gmail.com', name="mod2win", url="https://github.com/JosiahBradley/mod2win", version="0.0.1", entry_points={ 'console_scripts': [ 'play = mod2win.levels.level_launcher:launch', 'compile = mod2win.levels.level_launcher:_compile', 'scrub = mod2win.levels.level_launcher:scrub', 'restore = mod2win.levels.level_launcher:restore', 'spiral = mod2win.levels.spiral_test:main', ] }, package_dir={'': 'src'}, packages=setuptools.find_packages('src'), include_package_data=True, long_description=long_description, long_description_content_type="text/markdown", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache License", "Operating System :: OS Independent", ], )
[ 11748, 900, 37623, 10141, 198, 198, 6511, 62, 11213, 796, 13538, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 2617, ...
2.322799
443
# encoding: utf-8 # module Autodesk.Revit.UI.Plumbing calls itself Plumbing # from RevitAPIUI,Version=17.0.0.0,Culture=neutral,PublicKeyToken=null # by generator 1.145 # no doc # no imports # no functions # classes
[ 2, 21004, 25, 3384, 69, 12, 23, 201, 198, 2, 8265, 5231, 4147, 74, 13, 18009, 270, 13, 10080, 13, 3646, 28149, 3848, 2346, 1345, 28149, 201, 198, 2, 422, 5416, 270, 17614, 10080, 11, 14815, 28, 1558, 13, 15, 13, 15, 13, 15, 11, ...
2.447917
96
from django.apps import AppConfig from django.db.models.signals import post_migrate from django.utils.translation import gettext_lazy as _
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 76, 42175, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808, 628, ...
3.2
45
from sqlalchemy import MetaData, Table, Index, Column, Integer meta = MetaData()
[ 6738, 44161, 282, 26599, 1330, 30277, 6601, 11, 8655, 11, 12901, 11, 29201, 11, 34142, 198, 198, 28961, 796, 30277, 6601, 3419, 628, 198 ]
3.5
24
#!/usr/bin/env python """ Subrequests to do things like range requests, content negotiation checks, and validation. This is the base class for all subrequests. """ from abc import ABCMeta, abstractmethod from configparser import SectionProxy from typing import List, Tuple, Type, Union, TYPE_CHECKING from redbot.resource.fetch import RedFetcher from redbot.speak import Note, levels, categories from redbot.type import StrHeaderListType if TYPE_CHECKING: from redbot.resource import ( HttpResource, ) # pylint: disable=cyclic-import,unused-import
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 7004, 8897, 3558, 284, 466, 1243, 588, 2837, 7007, 11, 2695, 24462, 8794, 11, 198, 392, 21201, 13, 198, 198, 1212, 318, 262, 2779, 1398, 329, 477, 850, 8897, 3558, 1...
3.306358
173
import getopt a = "asdf asdf" option,args = getopt.getopt(a,"","") print(option,type(args))
[ 11748, 651, 8738, 198, 64, 796, 366, 292, 7568, 355, 7568, 1, 198, 18076, 11, 22046, 796, 651, 8738, 13, 1136, 8738, 7, 64, 553, 2430, 4943, 198, 4798, 7, 18076, 11, 4906, 7, 22046, 4008, 198 ]
2.486486
37
"""Additional GitHub specific tools. """
[ 37811, 17699, 21722, 2176, 4899, 13, 198, 37811, 198 ]
4.555556
9
""" # -------------------------------------------------------------------------------------------------- # Page APIs # -------------------------------------------------------------------------------------------------- """ import os import tempfile import re import json import collections import mimetypes import urllib import urllib.parse import common from file_api import FILE_API from child_pages import CHILD_PAGES from page_cache import PAGE_CACHE from globals import LOGGER from globals import SPACE_KEY from globals import CONFLUENCE_API_URL from globals import SIMULATE from globals import ANCESTOR PAGE_API = _PageApi()
[ 37811, 198, 2, 16529, 3880, 438, 198, 2, 7873, 23113, 198, 2, 16529, 3880, 438, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 302, 198, 11748, 33918, 198, 11748, 17268, 198, 11748, 17007, 2963, 12272, 198, 117...
4.386207
145
from copy import deepcopy import pytest from quartical.data_handling.predict import (parse_sky_models, daskify_sky_model_dict, get_support_tables) import dask.array as da import numpy as np from numpy.testing import assert_array_almost_equal expected_clusters = {"DIE": {"point": 22, "gauss": 24}, "B290": {"point": 1, "gauss": 2}, "C242": {"point": 0, "gauss": 1}, "G195": {"point": 0, "gauss": 1}, "H194": {"point": 0, "gauss": 2}, "I215": {"point": 0, "gauss": 1}, "R283": {"point": 1, "gauss": 0}, "V317": {"point": 0, "gauss": 1}} # -----------------------------parse_sky_models-------------------------------- # -------------------------daskify_sky_model_dict------------------------------ # ----------------------------get_support_tables------------------------------- # ---------------------------------predict------------------------------------- # NOTE: No coverage attempt is made for the predict internals copied from # https://github.com/ska-sa/codex-africanus. This is because the majority # of this functionality should be tested by codex-africanus. We do check that # both the direction-independent predict and direction-dependent predict work # for a number of different input values. # -----------------------------------------------------------------------------
[ 6738, 4866, 1330, 2769, 30073, 198, 11748, 12972, 9288, 198, 6738, 28176, 605, 13, 7890, 62, 4993, 1359, 13, 79, 17407, 1330, 357, 29572, 62, 15688, 62, 27530, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.62862
587
import numpy N,M,P = map(int,input().split()) p_cols1 =numpy.array([input().split() for _ in range(N)],int) p_cols1.shape = (N,P) p_cols2 =numpy.array([input().split() for _ in range(M)],int) p_cols2.shape = (M,P) concatenated = numpy.concatenate((p_cols1, p_cols2), axis = 0) print(concatenated)
[ 11748, 299, 32152, 198, 198, 45, 11, 44, 11, 47, 796, 3975, 7, 600, 11, 15414, 22446, 35312, 28955, 198, 79, 62, 4033, 82, 16, 796, 77, 32152, 13, 18747, 26933, 15414, 22446, 35312, 3419, 329, 4808, 287, 2837, 7, 45, 8, 4357, 600,...
2.142857
140
from colorama import Fore, init, Style import requests import random import ctypes import time import os ctypes.windll.kernel32.SetConsoleTitleW('Discord Status Changer') init(convert=True, autoreset=True) SuccessCounter = 0 ErrorCounter = 0 os.system('cls') print(Fore.RED + '\n[' + Fore.WHITE + Style.BRIGHT + '0' + Style.RESET_ALL + Fore.RED + '] ' + Fore.WHITE + Style.BRIGHT + 'Discord Status Changer by vragon') print(Fore.GREEN + '\n[' + Fore.WHITE + Style.BRIGHT + '1' + Style.RESET_ALL + Fore.GREEN + '] ' + Fore.WHITE + Style.BRIGHT + 'Text') print(Fore.GREEN + '[' + Fore.WHITE + Style.BRIGHT + '2' + Style.RESET_ALL + Fore.GREEN + '] ' + Fore.WHITE + Style.BRIGHT + 'Text including emoji') try: option = int(input(Fore.GREEN + '\n> ' + Fore.WHITE + Style.BRIGHT)) except ValueError as e: print(' ') print(Fore.RED + '[ERROR] ' + Fore.WHITE + Style.BRIGHT + str(e)) input() quit() if option == 1: os.system('cls') print(Fore.WHITE + Style.BRIGHT + '\nToken:') token = str(input(Fore.GREEN + '> ' + Fore.WHITE + Style.BRIGHT)) print(' ') while True: ChangeStatus() elif option == 2: os.system('cls') print(Fore.WHITE + Style.BRIGHT + '\nToken:') token = str(input(Fore.GREEN + '> ' + Fore.WHITE + Style.BRIGHT)) print(Fore.WHITE + Style.BRIGHT + '\nEmoji name:') EmojiName = str(input(Fore.GREEN + '> ' + Fore.WHITE + Style.BRIGHT)) print(Fore.WHITE + Style.BRIGHT + '\nEmoji ID:') try: EmojiID = int(input(Fore.GREEN + '> ' + Fore.WHITE + Style.BRIGHT)) except ValueError as e: print(' ') print(Fore.RED + '[ERROR] ' + Fore.WHITE + Style.BRIGHT + str(e)) input() quit() print(' ') while True: ChangeStatus()
[ 6738, 3124, 1689, 1330, 4558, 11, 2315, 11, 17738, 201, 198, 11748, 7007, 201, 198, 11748, 4738, 201, 198, 11748, 269, 19199, 201, 198, 11748, 640, 201, 198, 11748, 28686, 201, 198, 201, 198, 310, 9497, 13, 7972, 297, 13, 33885, 2624,...
2.348958
768
# GCT634 (2018) HW1 # # Mar-18-2018: initial version # # Juhan Nam # import sys import os import numpy as np import matplotlib.pyplot as plt data_path = './dataset/' mfcc_path = './mfcc/' MFCC_DIM = 20 if __name__ == '__main__': train_data = mean_mfcc('train') valid_data = mean_mfcc('valid') plt.figure(1) plt.subplot(2,1,1) plt.imshow(train_data, interpolation='nearest', origin='lower', aspect='auto') plt.colorbar(format='%+2.0f dB') plt.subplot(2,1,2) plt.imshow(valid_data, interpolation='nearest', origin='lower', aspect='auto') plt.colorbar(format='%+2.0f dB') plt.show()
[ 2, 402, 4177, 21, 2682, 357, 7908, 8, 44884, 16, 220, 198, 2, 198, 2, 1526, 12, 1507, 12, 7908, 25, 4238, 2196, 198, 2, 220, 198, 2, 449, 7456, 272, 17871, 198, 2, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 299, 3215...
2.157191
299
# Copyright 2021 QuantumBlack Visual Analytics Limited # # 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 # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND # NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS # BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. """`kedro_viz.services.layers` defines layers-related logic.""" import logging from collections import defaultdict from typing import Dict, List, Set from toposort import CircularDependencyError, toposort_flatten from kedro_viz.models.graph import GraphNode logger = logging.getLogger(__name__) def sort_layers( nodes: Dict[str, GraphNode], dependencies: Dict[str, Set[str]] ) -> List[str]: """Given a DAG represented by a dictionary of nodes, some of which have a `layer` attribute, along with their dependencies, return the list of all layers sorted according to the nodes' topological order, i.e. a layer should appear before another layer in the list if its node is a dependency of the other layer's node, directly or indirectly. For example, given the following graph: node1(layer=a) -> node2 -> node4 -> node6(layer=d) | ^ v | node3(layer=b) -> node5(layer=c) The layers ordering should be: [a, b, c, d] In theory, this is a problem of finding the [transitive closure](https://en.wikipedia.org/wiki/Transitive_closure) in a graph of layers and then toposort them. The algorithm below follows a repeated depth-first search approach: * For every node, find all layers that depends on it in a depth-first search. * While traversing, build up a dictionary of {node_id -> layers} for the node that have already been visited. * Turn the final {node_id -> layers} into a {layer -> layers} to represent the layers' dependencies. Note: the key is a layer and the values are the parents of that layer, just because that's the format toposort requires. * Feed this layers dictionary to ``toposort`` and return the sorted values. * Raise CircularDependencyError if the layers cannot be sorted topologically, i.e. there are cycles among the layers. Args: nodes: A dictionary of {node_id -> node} represents the nodes in the graph. dependencies: A dictionary of {node_id -> set(child_ids)} represents the direct dependencies between nodes in the graph. Returns: The list of layers sorted based on topological order. Raises: CircularDependencyError: When the layers have cyclic dependencies. """ node_layers: Dict[str, Set[str]] = {} # map node_id to the layers that depend on it def find_child_layers(node_id: str) -> Set[str]: """For the given node_id, find all layers that depend on it in a depth-first manner. Build up the node_layers dependency dictionary while traversing so each node is visited only once. Note: Python's default recursive depth limit is 1000, which means this algorithm won't work for pipeline with more than 1000 nodes. However, we can rewrite this using stack if we run into this limit in practice. """ if node_id in node_layers: return node_layers[node_id] node_layers[node_id] = set() # The layer of the current node can also be considered as depending on that node. # This is to cater for the edge case where all nodes are completely disjoint from each other # and no dependency graph for layers can be constructed, # yet the layers still need to be displayed. node_layer = getattr(nodes[node_id], "layer", None) if node_layer is not None: node_layers[node_id].add(node_layer) # for each child node of the given node_id, # mark its layer and all layers that depend on it as child layers of the given node_id. for child_node_id in dependencies[node_id]: child_node = nodes[child_node_id] child_layer = getattr(child_node, "layer", None) if child_layer is not None: node_layers[node_id].add(child_layer) node_layers[node_id].update(find_child_layers(child_node_id)) return node_layers[node_id] # populate node_layers dependencies for node_id in nodes: find_child_layers(node_id) # compute the layer dependencies dictionary based on the node_layers dependencies, # represented as {layer -> set(parent_layers)} layer_dependencies = defaultdict(set) for node_id, child_layers in node_layers.items(): node_layer = getattr(nodes[node_id], "layer", None) # add the node's layer as a parent layer for all child layers. # Even if a child layer is the same as the node's layer, i.e. a layer is marked # as its own parent, toposort still works so we don't need to check for that explicitly. if node_layer is not None: for layer in child_layers: layer_dependencies[layer].add(node_layer) # toposort the layer_dependencies to find the layer order. # Note that for string, toposort_flatten will default to alphabetical order for tie-break. try: return toposort_flatten(layer_dependencies) except CircularDependencyError: logger.warning( "Layers visualisation is disabled as circular dependency detected among layers." ) return []
[ 2, 15069, 33448, 29082, 9915, 15612, 30437, 15302, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 19...
2.919214
2,290
#!/usr/bin/python # importing libraries import json from copy import deepcopy from decimal import Decimal import time if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 201, 198, 2, 33332, 12782, 201, 198, 11748, 33918, 201, 198, 6738, 4866, 1330, 2769, 30073, 201, 198, 6738, 32465, 1330, 4280, 4402, 201, 198, 11748, 640, 201, 198, 201, 198, 201, 198, ...
2.676923
65
#!/usr/bin/env python3 # 52digest.py import re import sys # Write a program that performs an EcoRI digest on the SARS-COV2 genome # The program should have 2 arguments # 1. The genome file # 2. The restriction pattern # The output should be the sizes of the restriction fragments originseen = False seq = '' digest = sys.argv[2] filename = sys.argv[1] with open(filename) as fp: for line in fp.readlines(): if line.startswith('ORIGIN'): originseen = True if originseen: words = line.split() seq += ''.join(words[1:]) #print(len(seq)) count = 0 k = len(sys.argv[2]) match = re.search(digest, seq) for i in range(len(seq)-k+1): scope = seq[i:i+k] if scope == "gaattc": print(count) if scope == "gaattc": count = 0 count += 1 """ python3 52digest.py ../Data/sars-cov2.gb gaattc 1160 10573 5546 448 2550 2592 3569 2112 1069 """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 6740, 12894, 395, 13, 9078, 198, 198, 11748, 302, 198, 11748, 25064, 198, 198, 2, 19430, 257, 1430, 326, 17706, 281, 38719, 7112, 16274, 319, 262, 311, 27415, 12, 8220, 53, 17...
2.5
342
# coding: utf-8 from ..utils import ExtractorError from .common import InfoExtractor
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 11485, 26791, 1330, 29677, 273, 12331, 198, 6738, 764, 11321, 1330, 14151, 11627, 40450, 628 ]
3.583333
24
""" Entry point defined here """
[ 37811, 21617, 966, 5447, 994, 37227 ]
5.333333
6
import folium from folium.plugins import MarkerCluster import pandas as pd import datetime from pathlib import Path # pd.options.display.max_columns = 50 if __name__ == "__main__": project_dir = str(Path(__file__).resolve().parents[2]) main(project_dir)
[ 11748, 5955, 1505, 198, 6738, 5955, 1505, 13, 37390, 1330, 2940, 263, 2601, 5819, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 2, 279, 67, 13, 25811, 13, 13812, 13, 9806, ...
2.858696
92
#! /usr/bin/python import sys """ This script accepts the final annotation file and the lineage marker SNPs file """ """ and infers the lineage and possible sublineage classification of the isolate """ """ it requires a sample ID name (string) and an output file name(string) """ """ Author: Matthew Ezewudo CPTR ReSeqTB Project - Critical Path Institute """ input1 = sys.argv[1] input2 = sys.argv[2] input3 = sys.argv[3] input4 = sys.argv[4] fh1 = open(input1, 'r') sublinn = "" (lineage,position,ref,alt) = ([],[],[],[]) prevlin = [] prevsub = [] tribes = ["lineages","Indo-Oceanic","East-Asian","East-African-Indian","Euro-American","West-Africa 1","West-Africa 2","Ethiopian"] (concord,discord,concord1,discord1,count) = (0,0,0,0,0) discordance = False sublinneage = False linfour = "" hrv37 = "" BOV = "" BOV_AFRI = "" for lines in fh1: if lines.startswith('#'): continue fields = lines.rstrip("\r\n").split("\t") lineage.append(fields[0]) position.append(fields[1]) ref.append(fields[2]) alt.append(fields[3]) fh1.close() fh2 = open(input2,'r') for lines in fh2: count += 1 fields = lines.rstrip("\r\n").split("\t") if fields[2] == '931123': linfour = fields[2] if fields[2] == '1759252': hrv37 = fields[2] if fields[2] == '2831482': BOV = fields[2] if fields[2] == '1882180': BOV_AFRI = '1882180' if fields[2] in position: ind = position.index(fields[2]) if alt[ind] == fields[4]: if len(lineage[ind]) > 1: sublin = lineage[ind] prevsub.append(sublin) sublinn = prevsub[0] print "SNP" + " " + position[ind] + " " + "suggests sub-lineage: " + lineage[ind] if prevsub[0] != sublin: discord += 1 else: concord +=1 for i in range(0,len(prevsub)): if len(sublinn) < len(prevsub[i]) : sublinn = prevsub[i] else: lin = lineage[ind] prevlin.append(lin) print "SNP" + " " + position[ind] + " " + "suggests lineage: " + lineage[ind] if prevlin[0] != lin: discord1 += 1 else: concord1 += 1 fh2.close() fh3 = open(input3,'w') print >> fh3, "Sample ID" + "\t" + "Lineage" + "\t" + "Lineage Name" + "\t" + "Sublineage" split_first = ['NA'] if len(prevsub) > 0: split_first = sublinn.split(".") sublinneage = True if len(prevlin) == 0: if len(BOV) > 0: print "Lineage: " + "BOV" print >> fh3, input4 + "\t" + "BOV" + "\t" + "Bovis" + "\t" + "NA" if len(BOV) == 0 or len(BOV_AFRI) == 0: for i in range(0,len(prevsub)): split_lin = prevsub[i].split(".") if split_lin[0] != split_first[0]: discordance = True if split_lin[1] != split_first[1]: discordance = True if discordance: print "no precise lineage inferred" print >> fh3, "no precise lineage inferred" sys.exit(1) else: if len(split_first) > 1: print "Lineage: " + split_first[0] + " : " + tribes[int(split_first[0])] print "Sub-lineage: " + sublinn print >> fh3, input4 + "\t" + split_first[0] + "\t" + tribes[int(split_first[0])] + "\t" + sublinn elif len(linfour) < 2: print "Absence of SNP 931123 suggests lineage 4" print "Lineage: " + "4" + " : " + "Euro-American" if len(hrv37) > 2: print >> fh3, input4 + "\t" + "4" + "\t" + "Euro American" + "\t" + "NA" elif len(hrv37) < 2: print "Absence of SNP 1759252 suggests sublineage 4.9" print >> fh3, input4 + "\t" + "4" + "\t" + "Euro American" + "\t" + "4.9" else: print "No Informative SNPs detected" print >> fh3, "No Informative SNPs detected" else: if len(prevlin) > 1: for j in range(0,len(prevlin)): if prevlin[0] != prevlin[j]: discordance = True if discordance == True: print "no concordance between predicted lineage and sublineage(s)" print >> fh3, "no concordance between predicted lineage and sublineage(s)" sys.exit(1) else: if len(sublinn) < 1: print "Lineage: " + prevlin[0] + " " + tribes[int(prevlin[0])] print >> fh3, input4 + "\t" + prevlin[0] + "\t" + tribes[int(prevlin[0])] + "\t" + "NA" elif len(sublinn) > 1: for i in range(0,len(prevsub)): split_lin = prevsub[i].split(".") if split_lin[0] != prevlin[0] and split_lin[0] != 'BOV_AFRI': discordance = True if split_lin[0] != split_first[0]: discordance = True if discordance: print "no precise lineage inferred" print >> fh3, "no precise lineage inferred" sys.exit(1) else: print "Lineage: " + prevlin[0] + " " + tribes[int(prevlin[0])] if sublinn.startswith('BOV_A'): print >> fh3, input4 + "\t" + prevlin[0] + "\t" + tribes[int(prevlin[0])] + "\t" + "NA" else: print "Sub-lineage: " + sublinn print >> fh3, input4 + "\t" + prevlin[0] + "\t" + tribes[int(prevlin[0])] + "\t" + sublinn
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 198, 11748, 25064, 198, 198, 37811, 770, 4226, 18178, 262, 2457, 23025, 2393, 290, 262, 31144, 18364, 11346, 12016, 2393, 220, 37227, 198, 37811, 290, 1167, 364, 262, 31144, 290, 1744, 850, 1370, ...
1.976156
2,768
from rdr_service import clock, config from rdr_service.code_constants import EHR_CONSENT_QUESTION_CODE, PPI_SYSTEM, RACE_QUESTION_CODE, UNMAPPED from rdr_service.dao.code_dao import CodeDao from rdr_service.dao.database_utils import get_sql_and_params_for_array, replace_isodate from rdr_service.dao.hpo_dao import HPODao from rdr_service.field_mappings import NON_EHR_QUESTIONNAIRE_MODULE_FIELD_NAMES from rdr_service.model.base import get_column_name from rdr_service.model.participant_summary import ParticipantSummary from rdr_service.offline.metrics_config import ANSWER_FIELD_TO_QUESTION_CODE from rdr_service.offline.sql_exporter import SqlExporter # from rdr_service.offline.metrics_pipeline import MetricsPipeline from rdr_service.participant_enums import QuestionnaireStatus, TEST_EMAIL_PATTERN, TEST_HPO_NAME # TODO: filter out participants that have withdrawn in here _PARTICIPANTS_CSV = "participants_%d.csv" _HPO_IDS_CSV = "hpo_ids_%d.csv" _ANSWERS_CSV = "answers_%d.csv" _ALL_CSVS = [_PARTICIPANTS_CSV, _HPO_IDS_CSV, _ANSWERS_CSV] _QUEUE_NAME = "metrics-pipeline" _PARTICIPANT_SQL_TEMPLATE = """ SELECT p.participant_id, ps.date_of_birth date_of_birth, (SELECT ISODATE[MIN(bo.created)] FROM biobank_order bo WHERE bo.participant_id = p.participant_id AND bo.order_status is null or bo.order_status <> 2) first_order_date, (SELECT ISODATE[MIN(bs.confirmed)] FROM biobank_stored_sample bs WHERE bs.biobank_id = p.biobank_id) first_samples_arrived_date, (SELECT ISODATE[MIN(pm.finalized)] FROM physical_measurements pm WHERE pm.participant_id = p.participant_id AND pm.finalized is not null AND pm.status is null or pm.status <> 2) first_physical_measurements_date, (SELECT ISODATE[MIN(bss.confirmed)] FROM biobank_stored_sample bss WHERE bss.biobank_id = p.biobank_id AND bss.test IN {}) first_samples_to_isolate_dna_date, {} FROM participant p, participant_summary ps WHERE p.participant_id = ps.participant_id AND p.participant_id % :num_shards = :shard_number AND p.hpo_id != :test_hpo_id AND p.withdrawal_status != 2 AND NOT ps.email LIKE :test_email_pattern AND p.is_test_participant != TRUE """ # Find HPO ID changes in participant history. _HPO_ID_QUERY = """ SELECT ph.participant_id participant_id, hpo.name hpo, ISODATE[ph.last_modified] last_modified FROM participant_history ph, hpo, participant p WHERE ph.participant_id % :num_shards = :shard_number AND ph.hpo_id = hpo.hpo_id AND ph.participant_id = p.participant_id AND ph.hpo_id != :test_hpo_id AND p.hpo_id != :test_hpo_id AND p.withdrawal_status != 2 AND p.is_test_participant != TRUE AND NOT EXISTS (SELECT * FROM participant_history ph_prev WHERE ph_prev.participant_id = ph.participant_id AND ph_prev.version = ph.version - 1 AND ph_prev.hpo_id = ph.hpo_id) AND NOT EXISTS (SELECT * FROM participant_summary ps WHERE ps.participant_id = ph.participant_id AND ps.email LIKE :test_email_pattern) """ _ANSWER_QUERY = """ SELECT qr.participant_id participant_id, ISODATE[qr.created] start_time, qc.value question_code, (SELECT CASE WHEN ac.mapped THEN ac.value ELSE :unmapped END FROM code ac WHERE ac.code_id = qra.value_code_id) answer_code, qra.value_string answer_string FROM questionnaire_response_answer qra, questionnaire_response qr, questionnaire_question qq, code qc, participant p WHERE qra.questionnaire_response_id = qr.questionnaire_response_id AND qra.question_id = qq.questionnaire_question_id AND qq.code_id = qc.code_id AND qq.code_id in ({}) AND qr.participant_id % :num_shards = :shard_number AND qr.participant_id = p.participant_id AND p.hpo_id != :test_hpo_id AND p.withdrawal_status != 2 AND p.is_test_participant != TRUE AND NOT EXISTS (SELECT * FROM participant_summary ps WHERE ps.participant_id = p.participant_id AND ps.email LIKE :test_email_pattern) ORDER BY qr.participant_id, qr.created, qc.value """
[ 6738, 374, 7109, 62, 15271, 1330, 8801, 11, 4566, 198, 6738, 374, 7109, 62, 15271, 13, 8189, 62, 9979, 1187, 1330, 412, 17184, 62, 10943, 50, 3525, 62, 35780, 2849, 62, 34, 16820, 11, 350, 11901, 62, 23060, 25361, 11, 371, 11598, 62...
2.576456
1,563
# -*- coding: utf-8 -*- from ...client import get_api_client def get_player_detail_stats(player_id): """ player_idID int dict """ if get_player_data_status(player_id)==2: client=get_api_client() uri="/fundata-dota2-free/v2/player/"+str(player_id)+"/detail_stats" return client.api(uri,{}) else: print("player_id=%i has no data"%player_id) return 0 def get_player_data_status(player_id): """ player_idID int dict: status, 21 """ client=get_api_client() uri="/fundata-dota2-free/v2/player/"+str(player_id)+"/data_status" res=client.api(uri,{}) if res["retcode"]==200 and res["data"]["status"]==2: return 2 else: return 1
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 2644, 16366, 1330, 651, 62, 15042, 62, 16366, 628, 198, 4299, 651, 62, 7829, 62, 49170, 62, 34242, 7, 7829, 62, 312, 2599, 198, 197, 37811, 198, 197, 7829, ...
2.320285
281
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Ambari Agent """ import sys from resource_management import * from yarn import yarn from service import service if __name__ == "__main__": Resourcemanager().execute()
[ 37811, 198, 26656, 15385, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 273, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 17080, 6169, 351, 428, 670, 329, 3224, 1321, 198, 2301, 13493, 6634, 9238, 13...
4.017167
233
''' Created on Jul 19, 2012 @author: Chris '''
[ 7061, 6, 198, 41972, 319, 5979, 678, 11, 2321, 198, 198, 31, 9800, 25, 5180, 198, 7061, 6 ]
2.611111
18
from PyQt5 import QtGui, QtWidgets import seaborn as sns from gui import trimming as tri from gui import boxes as BOX import matplotlib.image as mpimg from math import floor, ceil
[ 6738, 9485, 48, 83, 20, 1330, 33734, 8205, 72, 11, 33734, 54, 312, 11407, 628, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 198, 6738, 11774, 1330, 15797, 2229, 355, 1333, 198, 6738, 11774, 1330, 10559, 355, 45216, 198, 11748, 2603...
3.172414
58
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 201, 198, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 201, 198, 201, 198 ]
2.454545
44
# 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 mock import requests import manilaclient from manilaclient.common import httpclient from manilaclient import exceptions from manilaclient.tests.unit import utils fake_user_agent = "fake" fake_response = utils.TestResponse({ "status_code": 200, "text": '{"hi": "there"}', }) mock_request = mock.Mock(return_value=(fake_response)) bad_400_response = utils.TestResponse({ "status_code": 400, "text": '{"error": {"message": "n/a", "details": "Terrible!"}}', }) bad_400_request = mock.Mock(return_value=(bad_400_response)) bad_401_response = utils.TestResponse({ "status_code": 401, "text": '{"error": {"message": "FAILED!", "details": "DETAILS!"}}', }) bad_401_request = mock.Mock(return_value=(bad_401_response)) bad_500_response = utils.TestResponse({ "status_code": 500, "text": '{"error": {"message": "FAILED!", "details": "DETAILS!"}}', }) bad_500_request = mock.Mock(return_value=(bad_500_response)) retry_after_response = utils.TestResponse({ "status_code": 413, "text": '', "headers": { "retry-after": "5" }, }) retry_after_mock_request = mock.Mock(return_value=retry_after_response) retry_after_no_headers_response = utils.TestResponse({ "status_code": 413, "text": '', }) retry_after_no_headers_mock_request = mock.Mock( return_value=retry_after_no_headers_response) retry_after_non_supporting_response = utils.TestResponse({ "status_code": 403, "text": '', "headers": { "retry-after": "5" }, }) retry_after_non_supporting_mock_request = mock.Mock( return_value=retry_after_non_supporting_response)
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
2.794308
773
import unittest from count_anagram_substrings import count_anagram_substrings tests = ( ( ( 'esleastealaslatet', ('tesla',), ), (3,), ), ( ( 'lrldrrrllddrrlllrddd', ('ldl', 'rld'), ), (1, 3), ), ( ( 'kkkkkvvuvkvkkkvuuvkuukkuvvkukkvkkvuvukuk', ('vkuk', 'uvku', 'kukk'), ), (5, 6, 1), ), ( ( 'trhtrthtrthhhrtthrtrhhhtrrrhhrthrrrttrrttrthhrrrrtrtthhhhrrrtrtthrttthrthhthrhrh', ('rrrht', 'tttrr', 'rttrr', 'rhrrr'), ), (6, 5, 6, 1), ), ( ( 'hjjijjhhhihhjjhjjhijjihjjihijiiihhihjjjihjjiijjijjhhjijjiijhjihiijjiiiijhihihhiihhiiihhiijhhhiijhijj', ('jihjhj', 'hhjiii', 'ihjhhh', 'jjjiji'), ), (10, 6, 2, 2), ), ) if __name__ == '__main__': res = unittest.main(verbosity = 3, exit = False)
[ 11748, 555, 715, 395, 198, 6738, 954, 62, 272, 6713, 62, 7266, 37336, 220, 220, 1330, 954, 62, 272, 6713, 62, 7266, 37336, 198, 198, 41989, 796, 357, 198, 220, 220, 220, 357, 198, 220, 220, 220, 220, 220, 220, 220, 357, 198, 220, ...
1.546326
626
""" System Identification (SI) https://arxiv.org/abs/1702.02453 Examples of two types: 1. Off-line SI: in sim2real_policies.sys_id.common.utils 2. On-line SI """ from sim2real_policies.sys_id.common.operations import * from sim2real_policies.sys_id.common.utils import * from sim2real_policies.utils.rl_utils import load, load_model from sim2real_policies.utils.choose_env import choose_env def stack_data(traj, length): traj = np.array(traj) return traj[-length:, :].reshape(-1) if __name__ == '__main__': ENV_NAME =['SawyerReach', 'SawyerPush', 'SawyerSlide'][0] osi = OSI(env_name = ENV_NAME, length=3, context_dim=3, Projection=False, CAT_INTERNAL=True) osi.osi_train()
[ 37811, 198, 11964, 38657, 357, 11584, 8, 198, 5450, 1378, 283, 87, 452, 13, 2398, 14, 8937, 14, 1558, 2999, 13, 40839, 4310, 198, 198, 27730, 286, 734, 3858, 25, 198, 16, 13, 3242, 12, 1370, 25861, 25, 287, 985, 17, 5305, 62, 79, ...
2.452632
285
import picamera from time import sleep IMG_WIDTH = 800 IMG_HEIGHT = 600 IMAGE_DIR = "/home/pi/Desktop/" IMG = "snap.jpg" # https://www.raspberrypi.org/learning/tweeting-babbage/worksheet/ ###################################################### # picamera default values: ###################################################### # camera.sharpness = 0 # camera.contrast = 0 # camera.brightness = 50 # camera.saturation = 0 # camera.ISO = 0 # camera.video_stabilization = False # camera.exposure_compensation = 0 # camera.exposure_mode = 'auto' # camera.meter_mode = 'average' # camera.awb_mode = 'auto' # camera.image_effect = 'none' # camera.color_effects = None # camera.rotation = 180 # camera.hflip = False # camera.vflip = False # camera.crop = (0.0, 0.0, 1.0, 1.0) ###################################################### # video will record 5 seconds ###################################################### # camera.start_recording('video.h264') # sleep(5) # camera.stop_recording() ###################################################### # add text to video: ###################################################### #camera.start_preview() #camera.annotate_text = "Doorbell pressed!" #camera.annotate_text_size = 50 #sleep(5) #camera.capture('/home/pi/Desktop/text.jpg') #camera.stop_preview() ###################################################### # loop over camera effects: ###################################################### #camera = picamera.PiCamera() #camera.vflip = True #camera.hflip = True #camera.start_preview() #for effect in camera.IMAGE_EFFECTS: # camera.image_effect = effect # camera.annotate_text = "Effect: %s" % effect # sleep(1) #camera.stop_preview()
[ 11748, 8301, 18144, 198, 6738, 640, 1330, 3993, 198, 198, 3955, 38, 62, 54, 2389, 4221, 796, 10460, 198, 3955, 38, 62, 13909, 9947, 796, 10053, 198, 3955, 11879, 62, 34720, 796, 12813, 11195, 14, 14415, 14, 36881, 30487, 198, 3955, 38...
3.194805
539
#!/usr/bin/env python # Copyright 2017 ARC Centre of Excellence for Climate Systems Science # author: Scott Wales <scott.wales@unimelb.edu.au> # # 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 __future__ import print_function from flask_sqlalchemy import SQLAlchemy import os from datetime import datetime db = SQLAlchemy() netcdf_variable_association = db.Table('netcdf_variable_association', db.Model.metadata, db.Column('netcdf_id', db.Integer, db.ForeignKey('netcdf_content.id')), db.Column('concretevar_id', db.Integer, db.ForeignKey('concrete_variable.id')) )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 2177, 43928, 9072, 286, 42525, 329, 13963, 11998, 5800, 198, 2, 1772, 25, 4746, 11769, 1279, 1416, 1252, 13, 86, 2040, 31, 403, 320, 417, 65, 13, 15532, 13, 559, 29, 198, ...
3.264881
336
# Mikoo - UserBot # Copyright (c) 2022 Mikoo-Userbot # Credits: @divarvian || https://github.com/divarvian # # This file is a part of < https://github.com/divarvian/Mikoo-Userbot/ > # t.me/MikooUserbot & t.me/MikooUserbot from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped from pytgcalls.types.input_stream.quality import ( HighQualityAudio, HighQualityVideo, LowQualityVideo, MediumQualityVideo, ) from userbot import LOGS, call_py from userbot.core.vcbot.queues import QUEUE, clear_queue, get_queue, pop_an_item
[ 2, 17722, 2238, 532, 11787, 20630, 198, 2, 15069, 357, 66, 8, 33160, 17722, 2238, 12, 12982, 13645, 198, 2, 29501, 25, 2488, 7146, 283, 85, 666, 8614, 3740, 1378, 12567, 13, 785, 14, 7146, 283, 85, 666, 198, 2, 198, 2, 770, 2393, ...
2.697561
205
""" Copyright 2021 Novartis Institutes for BioMedical Research 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. """ NAME="JAEGER" TITLE="**JAEGER**: JT-VAE Generative Modeling" JAEGER_HOME="/path/to/models" BASE_DIR=JAEGER_HOME+"/assays" TRAINING_DIR=JAEGER_HOME+"/training_data" AVAIL_MODELS=JAEGER_HOME+"/jaeger_avail_models.csv" ### JAEGER import pandas as pd import numpy as np from sklearn.decomposition import PCA import os # --- RDKIT imports import rdkit.Chem as Chem import rdkit # --- TORCH imports import torch # --- JTVAE imports from jtnn import * from jtnn.jtprop_vae import JTPropVAE # --- TOXSQUAD imports from toxsquad.data import modelling_data_from_csv import sys import os PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) # --- JAEGER imports from jaeger.utils.jtvae_utils import compute_properties from jaeger.utils.jtvae_utils import get_vocab from jaeger.utils.jtvae_utils import get_neighbors_along_directions_tree_then_graph from jaeger.utils.jtvae_utils import check_for_similarity from jaeger.utils.jtvae_utils import check_for_similarity_to_collection_fp # --- utils import argparse ### HERE I HAVE MOSTLY STREAMLIT CACHED FUNCTIONS #try: import streamlit as st #@st.cache def load_avail_models(): avail_models_file = AVAIL_MODELS available_models = pd.read_csv(avail_models_file, index_col='assay_id') return available_models #except: # e = sys.exc_info()[0] # print("Unexpected error") # print(e)
[ 37811, 198, 15269, 33448, 5267, 433, 271, 33656, 329, 16024, 37158, 4992, 3457, 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, ...
2.826846
745
# coding: utf-8 """ NetBox API API to access NetBox # noqa: E501 OpenAPI spec version: 2.8 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import netbox_client from netbox_client.models.vlan_group import VLANGroup # noqa: E501 from netbox_client.rest import ApiException if __name__ == '__main__': unittest.main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 3433, 14253, 7824, 628, 220, 220, 220, 7824, 284, 1895, 3433, 14253, 220, 1303, 645, 20402, 25, 412, 33548, 628, 220, 220, 220, 4946, 17614, 1020, 2196, 25, 362, ...
2.652174
161
# For Time Logging import time from contextlib import contextmanager import logging
[ 2, 1114, 3862, 5972, 2667, 198, 11748, 640, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 11748, 18931, 628 ]
4.473684
19
import os import shutil path = './ALL/' outpath = "./rename/" outb = "./b/" outc = "./c/" for f in os.listdir(path): print(f) name,ext = os.path.splitext(f) a,ext2 = name.split('_') if ext2.endswith('b'): print(outb+f) shutil.copy(path+f,outb+f) elif ext2.endswith('c'): print(outc+f) shutil.copy(path+f,outc+f) print(a) #shutil.copy(path+f,outpath+a+ext)
[ 11748, 28686, 198, 11748, 4423, 346, 198, 6978, 796, 705, 19571, 7036, 14, 6, 198, 448, 6978, 796, 366, 19571, 918, 480, 30487, 198, 448, 65, 796, 366, 19571, 65, 30487, 198, 448, 66, 796, 366, 19571, 66, 30487, 198, 198, 1640, 277,...
1.840708
226
import socket import threading import concurrent.futures from colorama import Fore, Style
[ 11748, 17802, 198, 11748, 4704, 278, 198, 11748, 24580, 13, 69, 315, 942, 198, 6738, 3124, 1689, 1330, 4558, 11, 17738 ]
4.238095
21
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created by: PyQt5 UI code generator 5.12.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 2797, 7803, 13, 9019, 6, 198, 2, 198, 2, 15622, 416, 25, 9485, 48, 83, 20, 12454, 2438, 17301, 642, 13, 10...
2.825581
86
#!/usr/bin/env python # coding=utf-8 from pyecharts.chart import Chart from pyecharts.option import get_all_options
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 198, 6738, 12972, 3055, 5889, 13, 40926, 1330, 22086, 198, 6738, 12972, 3055, 5889, 13, 18076, 1330, 651, 62, 439, 62, 25811, 628 ]
3.025641
39
import json class AliceResponse(object):
[ 11748, 33918, 628, 198, 198, 4871, 14862, 31077, 7, 15252, 2599, 198 ]
3.666667
12
import yfinance as yf import pandas as pd import Utils from Utils import scrape_utils
[ 11748, 331, 69, 14149, 355, 331, 69, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 7273, 4487, 198, 6738, 7273, 4487, 1330, 42778, 62, 26791, 198 ]
3.185185
27
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2016 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np from pymor.core.interfaces import ImmutableInterface from pymor.core.logger import getLogger from pymor.reductors.basic import reduce_generic_rb from pymor.reductors.residual import reduce_residual, reduce_implicit_euler_residual from pymor.operators.constructions import IdentityOperator from pymor.algorithms.timestepping import ImplicitEulerTimeStepper def reduce_parabolic(discretization, RB, product=None, coercivity_estimator=None, disable_caching=True, extends=None): r"""Reductor for parabolic equations. This reductor uses :meth:`~pymor.reductors.basic.reduce_generic_rb` for the actual RB-projection. The only addition is the assembly of an error estimator which bounds the discrete l2-in time / energy-in space error similar to [GP05]_, [HO08]_ as follows: .. math:: \left[ C_a^{-1}(\mu)\|e_N(\mu)\|^2 + \sum_{n=1}^{N} \Delta t\|e_n(\mu)\|^2_e \right]^{1/2} \leq \left[ C_a^{-1}(\mu)\Delta t \sum_{n=1}^{N}\|\mathcal{R}^n(u_n(\mu), \mu)\|^2_{e,-1} + C_a^{-1}(\mu)\|e_0\|^2 \right]^{1/2} Here, :math:`\|\cdot\|` denotes the norm induced by the problem's mass matrix (e.g. the L^2-norm) and :math:`\|\cdot\|_e` is an arbitrary energy norm w.r.t. which the space operator :math:`A(\mu)` is coercive, and :math:`C_a(\mu)` is a lower bound for its coercivity constant. Finally, :math:`\mathcal{R}^n` denotes the implicit Euler timestepping residual for the (fixed) time step size :math:`\Delta t`, .. math:: \mathcal{R}^n(u_n(\mu), \mu) := f - M \frac{u_{n}(\mu) - u_{n-1}(\mu)}{\Delta t} - A(u_n(\mu), \mu), where :math:`M` denotes the mass operator and :math:`f` the source term. The dual norm of the residual is computed using the numerically stable projection from [BEOR14]_. .. warning:: The reduced basis `RB` is required to be orthonormal w.r.t. the given energy product. If not, the projection of the initial values will be computed incorrectly. .. [GP05] M. A. Grepl, A. T. Patera, A Posteriori Error Bounds For Reduced-Basis Approximations Of Parametrized Parabolic Partial Differential Equations, M2AN 39(1), 157-181, 2005. .. [HO08] B. Haasdonk, M. Ohlberger, Reduced basis method for finite volume approximations of parametrized evolution equations, M2AN 42(2), 277-302, 2008. Parameters ---------- discretization The |InstationaryDiscretization| which is to be reduced. RB |VectorArray| containing the reduced basis on which to project. product The energy inner product |Operator| w.r.t. the reduction error is estimated. RB must be to be orthonomrmal w.r.t. this product! coercivity_estimator `None` or a |Parameterfunctional| returning a lower bound :math:`C_a(\mu)` for the coercivity constant of `discretization.operator` w.r.t. `product`. disable_caching If `True`, caching of solutions is disabled for the reduced |Discretization|. extends Set by :meth:`~pymor.algorithms.greedy.greedy` to the result of the last reduction in case the basis extension was `hierarchic` (used to prevent re-computation of residual range basis vectors already obtained from previous reductions). Returns ------- rd The reduced |Discretization|. rc The reconstructor providing a `reconstruct(U)` method which reconstructs high-dimensional solutions from solutions `U` of the reduced |Discretization|. reduction_data Additional data produced by the reduction process (compare the `extends` parameter). """ assert extends is None or len(extends) == 3 assert isinstance(discretization.time_stepper, ImplicitEulerTimeStepper) logger = getLogger('pymor.reductors.parabolic.reduce_parabolic') old_residual_data = extends[2].pop('residual') if extends else None old_initial_resdidual_data = extends[2].pop('initial_residual') if extends else None with logger.block('RB projection ...'): rd, rc, data = reduce_generic_rb(discretization, RB, vector_product=product, disable_caching=disable_caching, extends=extends) dt = discretization.T / discretization.time_stepper.nt with logger.block('Assembling error estimator ...'): residual, residual_reconstructor, residual_data = reduce_implicit_euler_residual( discretization.operator, discretization.mass, dt, discretization.rhs, RB, product=product, extends=old_residual_data ) initial_residual, initial_residual_reconstructor, initial_residual_data = reduce_residual( IdentityOperator(discretization.solution_space), discretization.initial_data, RB, False, product=discretization.l2_product, extends=old_initial_resdidual_data ) estimator = ReduceParabolicEstimator(residual, residual_data.get('residual_range_dims', None), initial_residual, initial_residual_data.get('residual_range_dims', None), coercivity_estimator) rd = rd.with_(estimator=estimator) data.update(residual=(residual, residual_reconstructor, residual_data), initial_residual=(initial_residual, initial_residual_reconstructor, initial_residual_data)) return rd, rc, data
[ 2, 770, 2393, 318, 636, 286, 262, 12972, 44, 1581, 1628, 357, 4023, 1378, 2503, 13, 9078, 4491, 13, 2398, 737, 198, 2, 15069, 2211, 12, 5304, 12972, 44, 1581, 6505, 290, 20420, 13, 1439, 2489, 10395, 13, 198, 2, 13789, 25, 347, 10...
2.509154
2,294
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import get_datetime from frappe.core.doctype.scheduled_job_type.scheduled_job_type import sync_jobs
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 13130, 11, 39313, 27768, 21852, 290, 25767, 669, 198, 2, 4091, 5964, 13, 14116, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, ...
3.020833
96
# menu_text.py # # simple python menu # https://stackoverflow.com/questions/19964603/creating-a-menu-in-python # city_menu = { '1': 'Chicago', '2': 'New York', '3': 'Washington', 'x': 'Exit'} month_menu = {'0': 'All', '1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', 'x': 'Exit'} weekday_menu = {'0': 'All', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', '7': 'Sunday', 'x': 'Exit'} if __name__ == "__main__": main()
[ 2, 6859, 62, 5239, 13, 9078, 198, 2, 198, 2, 2829, 21015, 6859, 198, 2, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 19104, 2414, 35642, 14, 20123, 278, 12, 64, 12, 26272, 12, 259, 12, 29412, 198, 2, 198, 198, 192...
1.624481
482
from src.books.models import Book from src.books.schema import BookOut from ninja import Router router = Router()
[ 6738, 12351, 13, 12106, 13, 27530, 1330, 4897, 198, 6738, 12351, 13, 12106, 13, 15952, 2611, 1330, 4897, 7975, 198, 198, 6738, 37049, 1330, 48538, 198, 198, 472, 353, 796, 48538, 3419, 628 ]
3.545455
33
from getratings.models.ratings import Ratings
[ 6738, 651, 10366, 654, 13, 27530, 13, 10366, 654, 1330, 36826, 201, 198, 201, 198 ]
3.266667
15
# generated by datamodel-codegen: # filename: Organization.schema.json # timestamp: 1985-10-26T08:21:00+00:00 from __future__ import annotations from pydantic import BaseModel, Field
[ 2, 7560, 416, 4818, 321, 375, 417, 12, 8189, 5235, 25, 198, 2, 220, 220, 29472, 25, 220, 12275, 13, 15952, 2611, 13, 17752, 198, 2, 220, 220, 41033, 25, 12863, 12, 940, 12, 2075, 51, 2919, 25, 2481, 25, 405, 10, 405, 25, 405, ...
2.938462
65
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from tablo import GEOM_FIELD_NAME, WEB_MERCATOR_SRID forward_sql = """ DO $$ DECLARE table_name name; BEGIN FOR table_name IN SELECT tablo_featureservicelayer.table FROM tablo_featureservicelayer LOOP EXECUTE format('ALTER TABLE %I ALTER COLUMN {geom_col} TYPE geometry(''GEOMETRY'', {srid});', table_name); END LOOP; END; $$ LANGUAGE plpgsql; """.format(geom_col=GEOM_FIELD_NAME, srid=WEB_MERCATOR_SRID)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 198, 6738, 7400, 5439, 1330, 22319, 2662, 62, ...
2.16
275
import torch import torch.nn as nn from torch.autograd import Variable import torch.functional as F from torch.nn.init import xavier_normal_ import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) import numpy as np from numpy.random import RandomState from collections import defaultdict import time from tkge.data.dataset import SplitDataset from tkge.data.custom_dataset import ICEWS14AtiseDatasetProcessor from tkge.eval.metrics import Evaluation from tkge.train.sampling import NonNegativeSampler from Dataset import KnowledgeGraph randseed = 9999 np.random.seed(randseed) torch.manual_seed(randseed) model_path = "/home/gengyuan/workspace/baseline/ATISE/icews14/ATISE/timediscrete0/dim500/lr0.0000/neg_num10/3day/gamma120/cmin0.0030/params.pkl" model = ATISE(7129, 460, 500, 64, 0, 120, 0.003, 0.3, True) model_state_dict = torch.load(model_path) model.load_state_dict(model_state_dict) if __name__ == '__main__': test()
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 28034, 13, 45124, 355, 376, 198, 6738, 28034, 13, 20471, 13, 15003, 1330, 2124, 19492, 62, 11265, 62, 198, 198, ...
2.710456
373
# -*- coding: utf-8 -*- import pytest from six import iteritems
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 12972, 9288, 198, 6738, 2237, 1330, 11629, 23814, 628, 198 ]
2.64
25
import json from typing import Union, Optional, Tuple, List import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from shared import LANG_TO_INT
[ 11748, 33918, 198, 6738, 19720, 1330, 4479, 11, 32233, 11, 309, 29291, 11, 7343, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 1330, 360, 713, 38469, 7509, 198, 6738, 1341, 35720, 13, 30053,...
3.60396
101
#!/usr/bin/python #Sorts based on top 50 CMetric, all callPaths - CMetric #, all call paths - call path count and all samples from __future__ import print_function from bcc import BPF, PerfType, PerfSWConfig from bcc import BPF import sys import ctypes as ct # For mapping the 'C' structure to Python import argparse #For parsing command line arguments import datetime import os import operator import subprocess import re # arg validation parser = argparse.ArgumentParser(description="Generates stack traces for critical code sections") parser.add_argument("-x", metavar="<Path to executable>", dest = "targetPath", required = True, help = "Full path to the executable file to be profiled - Required") parser.add_argument("-t", metavar="<Threshold>", dest = "threshold", type = positive_int, required = False, help = "Number active threads to trigger stack trace. Default = total no. of threads/2" ) parser.add_argument("-f", metavar="<Sampling Frequency>", dest = "sample_freq", type = positive_int, required = False, help = "Sampling frequency in Hz. Default = 333Hz (equivalent to 3 ms)" ) parser.add_argument("-d", metavar="<Stack Depth>", dest = "stack_depth", type = positive_int, required = False, help = "Maximum Stack depth for stack unwinding. Default = 10" ) parser.add_argument("-b", metavar="<Ring buffer Size>", dest = "buffer", type = positive_int, required = False, help = "Number of pages to be allocated for the ring buffer, Default = 64" ) parser.add_argument("--threads_only", help = "Trace threads alone", action = "store_true") parser.add_argument("--process_only", help = "Trace processes alone", action = "store_true") parser.add_argument("--trace_lib", help = "Include library paths in tracing", action = "store_true") parser.add_argument("--kernel_stack", help = "Get kernel stack traces", action = "store_true") args = parser.parse_args() # define BPF program bpf_text = """ #include <uapi/linux/ptrace.h> #include <uapi/linux/bpf_perf_event.h> #include <linux/sched.h> #include <linux/types.h> //Structure to pass information from the kernel probe to the user probe struct key_t { u32 tid; //Thread ID u32 tgid; // Parent thread ID u64 cm; //CMetric int source; // 0 - sampling, 1 - critical time slice, 2 - non-critical time slice int user_stackid; int kernel_stackid; u64 inst_ptr; int store_stackTop; }; BPF_HASH(threadList, u32, u32); //Stores threadIds of participating threads - Global BPF_HASH(threadCount, u32, u32, 1); //Stores number of active threads - Global BPF_HASH(tsp, u32, u64, 1); //Stores timestamp of previous event BPF_ARRAY(count, u32, 1); //Stores the total thread count (parent not included) BPF_HASH(global_CM, u32, u64, 1); //Keeps track of cumulative sum of CMetric - Global BPF_PERCPU_ARRAY(local_CM, u64, 1); // To store the snapshot of global_CM when a thread is switched in BPF_HASH(CM_hash, u32, u64); // Criticality Metric hash map for each thread BPF_HASH(GLOBAL_WT_TC, u32, u64,1); //Stores the cumulative sum of weighted thread Count - Global BPF_PERCPU_ARRAY(LOCAL_WT_TC, u64,1); //Stores the snapshot of GLOBAL_WT_TC - CPU Local BPF_PERCPU_ARRAY(inTS, u64, 1); //Store the time at which a thread was switched in - CPU Local BPF_PERF_OUTPUT(events); //Buffer to write event details BPF_STACK_TRACE(user_stacktraces, 4086); BPF_STACK_TRACE(kernel_stacktraces, 4086); /*sched_switch_args { // from /sys/kernel/debug/tracing/events/sched/sched_switch/format u64 __unused__; char prev_comm[16]; pid_t prev_pid; int prev_prio; long prev_state; char next_comm[16]; pid_t next_pid; int next_prio; }; */ TRACEPOINT_PROBE(task, task_rename){ u32 threadId, totalCount; char comm[16]; u32 zero32 = 0, one = 1; int len = bpf_probe_read_str(&comm, sizeof(args->newcomm), args->newcomm); if(!len) return 0; //Compare the command argument with traced command if(PGM_FILTER){ bpf_probe_read(&threadId, sizeof(threadId), &args->pid); threadList.insert(&threadId, &zero32); //Store the thread ID in the hash startTracing.lookup_or_init(&threadId, &zero32); u32 *countVal = count.lookup_or_init(&zero32, &zero32); lock_xadd(countVal,1); } return 0; } TASK_NEWTASK int do_perf_event(struct bpf_perf_event_data *ctx){ u32 zero32 = 0; u32 threadId = bpf_get_current_pid_tgid(); u32 *val = threadList.lookup(&threadId); if(!val) return 0; u32 *activeCount = threadCount.lookup(&zero32); if(!activeCount) {return 0;} u32 tempCount; bpf_probe_read(&tempCount, sizeof(tempCount), activeCount); u32 *totalThreadCount = count.lookup(&zero32); if(!totalThreadCount) return 0; u32 totalCount; bpf_probe_read(&totalCount, sizeof(totalCount), totalThreadCount); if( (tempCount <= STACK_FILTER) || tempCount ==1 ){ struct key_t key = {}; key.tid = bpf_get_current_pid_tgid(); key.tgid = bpf_get_current_pid_tgid()>>32; key.cm = 0; key.source = 0; if(TRACE_THREADS_ONLY){ key.inst_ptr = PT_REGS_IP(&ctx->regs); //Get the instruction pointer events.perf_submit(ctx, &key, sizeof(key)); //Write details to the ring buffer } } return 0; } TRACEPOINT_PROBE(sched, sched_process_exit){ u32 zero32 = 0; //Get the current tid u32 threadId; bpf_probe_read(&threadId, sizeof(threadId), &args->pid); //Check if the thread ID belongs to the application u32 *val = threadList.lookup(&threadId); if(!val) return 0; //Decrement the number of threads u32 *countVal = count.lookup(&zero32); if(!countVal) return 0; //lock_xadd(countVal, -1); countVal -= 1; return 0; } TRACEPOINT_PROBE(sched, sched_wakeup){ u32 targetID, zero32 = 0, status, one32 = 1; //Check if thread being woken up belongs to the application bpf_probe_read(&targetID, sizeof(targetID), &args->pid); u32 *list = threadList.lookup(&targetID); if (!list) return 0; ///////////////////////////////////////////////////////////////////// if(args->success){ //If waking was successful u32 *activeCount = threadCount.lookup(&zero32); if(!activeCount) {return 0;} u32 prev_tCount; //Local variable to store thread count bpf_probe_read(&prev_tCount, sizeof(prev_tCount), activeCount); //Increment thread count if thread was inactive bpf_probe_read(&status, sizeof(status), list); if(status == 0) lock_xadd(activeCount,1); //Set thread as active threadList.update(&targetID,&one32); } return 0; } //Tracepoint probe for the Sched_Switch tracepoint TRACEPOINT_PROBE(sched, sched_switch){ u32 one32=1, arrayKey=0, zero32=0; u32 *listVal, *listVal1; //Pointers to entries in threadList map u32 next_pid, prev_pid; u64 zero64 = 0; //Copy data to BPF stack bpf_probe_read(&next_pid, sizeof(next_pid), &args->next_pid); bpf_probe_read(&prev_pid, sizeof(prev_pid), &args->prev_pid); //Look up thread ids in the list created by sys_clone() listVal1 = threadList.lookup(&next_pid); listVal = threadList.lookup(&prev_pid); u32 prev=0, next=0; if(listVal){ bpf_probe_read(&prev, sizeof(prev),listVal); prev = 1; } if(listVal1){ bpf_probe_read(&next, sizeof(next),listVal1); next = 1; } //Return if the switching threads do not belong to the application if( !prev && !next) return 0; ////////////////////////////////////////////////////////////////////// //Calculate values common for all switching events u64 interval, intervalCM; u64 *oldTS = tsp.lookup_or_init(&arrayKey, &zero64); if(!oldTS) {return 0;} u64 tempTS; bpf_probe_read(&tempTS, sizeof(tempTS), oldTS); //Copy Old time from bpf map to local variable u64 newTS = bpf_ktime_get_ns(); tsp.update(&arrayKey, &newTS); //Update time stamp //The thread count is initialized to one as the first switch in event is always missed. u32 *ptr_threadCount = threadCount.lookup_or_init(&arrayKey, &one32); if(!ptr_threadCount) {return 0;} int prev_tc; //Temporary variable to store thread count for the previous switching interval bpf_probe_read(&prev_tc, sizeof(prev_tc),ptr_threadCount); if(newTS < tempTS)//Very rarely, event probes are triggered out of order, which are ignored return 0; if(tempTS==0 || prev_tc==0){ //If first event or no active threads in during the previous interval, prev interval = 0 interval = 0; } else interval = (newTS - tempTS); //Switching interval u64 *ptr_globalCM = global_CM.lookup_or_init(&arrayKey, &zero64); if(!ptr_globalCM) return 0; //Calculate the CMetric for previous interval and add it to global_CM if (interval != 0){ intervalCM = interval/prev_tc; lock_xadd(ptr_globalCM, intervalCM); } //Calculate weighted thread count for previous interval u64 wt_threadCount = (interval) * prev_tc; u64 *g_wt_threadCount = GLOBAL_WT_TC.lookup_or_init(&arrayKey, &zero64); if(!g_wt_threadCount) return 0; lock_xadd(g_wt_threadCount, wt_threadCount); //Add to global weighted thread count ////////////////////////////////////////////////////////////////////// //If previous thread was a peer thread if(prev){ //Decrement active thread count only if thread switched out is not in RUNNING (0) state if(args->prev_state != TASK_RUNNING){ if(prev_tc > 0 ){ lock_xadd(ptr_threadCount, -1); } //Mark the thread as inactive in the threadList hash map threadList.update(&prev_pid,&zero32); } else //Mark the thread as active as thread is switched out to TASK_RUNNING state threadList.update(&prev_pid,&one32); u64 temp; //Get updated CM bpf_probe_read(&temp, sizeof(temp),ptr_globalCM); //Get snapshot of global_CM which was stored in local_CM when prev_pid was switched in u64 *cpuCM = local_CM.lookup_or_init(&arrayKey, &zero64); if(!cpuCM) {return 0;} //Update the CM of the thread by adding the CM for the time slice u64 updateCM = temp - (*cpuCM); u64 *tCM = CM_hash.lookup_or_init(&prev_pid, &zero64); if(!tCM) {return 0;} *tCM = *tCM + updateCM; //Get LOCAL_WT_TC, the thread's weighted threadCount at the time it was switched in. u64 *t_wt_threadCount; t_wt_threadCount = LOCAL_WT_TC.lookup_or_init(&arrayKey, &zero64); if(!t_wt_threadCount) {return 0;} u64 temp_g_wt_threadCount, temp_t_wt_threadCount; bpf_probe_read(&temp_g_wt_threadCount, sizeof(temp_g_wt_threadCount), g_wt_threadCount); bpf_probe_read(&temp_t_wt_threadCount, sizeof(temp_t_wt_threadCount), t_wt_threadCount); //Reset the per-CPU CMetric counter local_CM.update(&arrayKey, &zero64); //Reset local weighted ThreadCount counter LOCAL_WT_TC.update(&arrayKey, &zero64); //Get time when this thread was switched in oldTS = inTS.lookup_or_init(&arrayKey, &zero64); if(!oldTS) return 0; u64 switch_in_time, timeSlice; bpf_probe_read(&switch_in_time, sizeof(switch_in_time), oldTS); timeSlice = (newTS - switch_in_time); //Reset switch in time inTS.update(&arrayKey, &zero64); u32 *totalThreadCount = count.lookup(&zero32); if(!totalThreadCount) return 0; u32 totalCount; bpf_probe_read(&totalCount, sizeof(totalCount), totalThreadCount); //Calculate the average number of threads u32 ratio = (temp_g_wt_threadCount - temp_t_wt_threadCount) / timeSlice; struct key_t key = {}; key.tid = prev_pid; key.tgid = bpf_get_current_pid_tgid()>>32; key.cm = updateCM; if( (ratio <= STACK_FILTER || ratio == 1) && TRACE_THREADS_ONLY){ //If thread_avg < threshold and not parent thread key.user_stackid = user_stacktraces.get_stackid(args, BPF_F_USER_STACK); if (GET_KERNEL_STACK && args->prev_state != TASK_RUNNING) key.kernel_stackid= kernel_stacktraces.get_stackid(args, 0); else key.kernel_stackid = -1; key.source = 1; } else{ key.user_stackid = 0; key.source = 2; } key.store_stackTop = ((prev_tc <= STACK_FILTER) || prev_tc == 1)? 1:0; if(TRACE_THREADS_ONLY) events.perf_submit(args, &key, sizeof(key)); } //Next thread is a peer thread if(next){ //Get the previous state of this thread from the THREADLIST u32 tempNext; bpf_probe_read(&tempNext, sizeof(tempNext), listVal1); //If the thread was not in TASK_RUNNING state if(tempNext == 0){ lock_xadd(ptr_threadCount, 1); //Increment the number of active threads } threadList.update(&next_pid, &one32); //Set the thread status to RUNNING state u64 temp; //Get updated CM and store it to the CPU counter bpf_probe_read(&temp, sizeof(temp),ptr_globalCM); local_CM.update(&arrayKey,&temp); //Store switch in time inTS.update(&arrayKey, &newTS); //Store the local cumulative weighted thread count u64 temp_g_wt_threadCount; bpf_probe_read(&temp_g_wt_threadCount, sizeof(temp_g_wt_threadCount), g_wt_threadCount); LOCAL_WT_TC.update(&arrayKey, &temp_g_wt_threadCount); } return 0; } """ task_newtask_pgm = """TRACEPOINT_PROBE(task, task_newtask){ u32 zero32=0; char comm[TASK_COMM_LEN]; bpf_get_current_comm(&comm, sizeof(comm)); //We can also check for the parent id in the threadlist //But if the parent was created before starting tracing this can fail //So we check the command line instead //If application is being traced if(PGM_FILTER){ u32 threadId; bpf_probe_read(&threadId, sizeof(threadId), &args->pid); u32 *val = threadList.lookup_or_init(&threadId, &zero32); //Store the thread ID in the hash u32 *countVal = count.lookup_or_init(&zero32, &zero32); lock_xadd(countVal,1); } return 0; }""" #Path to executable targetPath = "" #Executable name pgmName = "" #Segments for customizing the filters task_newtask_probe = task_newtask_pgm trace_threads_only = '1' get_kernel_stack = '0' if args.threads_only: trace_threads_only = 'key.tgid != key.tid' if args.process_only: task_newtask_probe = '' if args.kernel_stack: get_kernel_stack = '1' #Get the path to target if args.targetPath is not None: targetPath = args.targetPath.rstrip(os.sep) pgmName = os.path.basename(targetPath) if pgmName is not None: pgm_filter = 'comm[0]==\'%c\' && comm[1]==\'%c\' && comm[2]==\'%c\' && comm[3]==\'%c\'' % (pgmName[0],pgmName[1], pgmName[2], pgmName[3]) if args.threshold is not None: stack_filter = '%d' % ( (args.threshold) ) else: stack_filter = 'totalCount/2' if args.sample_freq is not None: freq = args.sample_freq else: freq = 333 if args.stack_depth is not None: depth = args.stack_depth else: depth = 10 if args.buffer is not None: buffer_size = args.buffer else: buffer_size = 64 bpf_text = bpf_text.replace('TASK_NEWTASK', task_newtask_probe) bpf_text = bpf_text.replace('PGM_FILTER', pgm_filter) bpf_text = bpf_text.replace('STACK_FILTER', stack_filter) bpf_text = bpf_text.replace('TRACE_THREADS_ONLY', trace_threads_only) bpf_text = bpf_text.replace('GET_KERNEL_STACK', get_kernel_stack) #Print the customized program #print(bpf_text) print ("\n\n---Press Ctrl-C to start post processing---") # load BPF program b = BPF(text=bpf_text) b.attach_perf_event(ev_type=PerfType.SOFTWARE, ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event", sample_freq=freq) user_stack_traces = b["user_stacktraces"] kernel_stack_traces = b["kernel_stacktraces"] sampleAddr = dict() #Stores addresses corresponding to samples CMetric = dict() #Dictionary to store CMetric CM_Entry = 1 #Number of CMetric entry CMetric_sampleAddr = dict() # Stores the sample address for each Cmetric - to get line of code CMetric_callPath = dict() # Stores the call path for each CMetric user_symbolMap = dict() #Store symbols corresponding addresses kernel_symbolMap = dict() total_switch = 0 noSample = 0 ############################################### #Function to trim the symbols of arguments ################################################ ################################################ #Function to execute for each event written to the ring buffer b["events"].open_perf_buffer(print_event, page_cnt=buffer_size) #To print criticality metric of each thread threadCM = b.get_table("CM_hash") sum = 0; criticalSwitch = dict() criticalSwitch_allCM= dict() criticalLine = dict() critLineSamples = dict() critLineSamples_all = dict() critKernelPaths = dict() allFunction = dict() allLines = dict() addrMap_fun = dict() addrMap_line= dict() try: while 1: b.kprobe_poll() finally: #Post Processing the stack traces start = datetime.datetime.now() print("Criticality Metric for each thread"); for k, v in sorted(threadCM.items(), key=lambda x:x[1].value): print("%10u %u " % ((k.value), (v.value))) sum += v.value print ("Sum = %d" % sum) print ("***************************************************") #for key, value in sorted(CMetric.items(), key=lambda x:x[1], reverse= True): # key is CM_Entry, value is CMetric for key, value in CMetric.items(): # key is CM_Entry, value is CMetric user_callPath = CMetric_callPath[key][0] kernel_callPath = CMetric_callPath[key][1] #Combine all call paths irrespective of CMetric value and then sort as per CMetric value if user_callPath in criticalSwitch_allCM: criticalSwitch_allCM[user_callPath][0] += value criticalSwitch_allCM[user_callPath][1] += 1 else: criticalSwitch_allCM[user_callPath] = [value,1] #Combine the sample addresses if user_callPath not in critLineSamples_all: critLineSamples_all[user_callPath] = dict() lineDict = critLineSamples_all[user_callPath] addrList = CMetric_sampleAddr[key] for element in addrList: if element in lineDict: lineDict[element] += 1 else: lineDict[element] = 1 #Combine kernel call paths if user_callPath not in critKernelPaths: critKernelPaths[user_callPath] = dict() allKernelPaths = critKernelPaths[user_callPath] if kernel_callPath in allKernelPaths: allKernelPaths[kernel_callPath] += 1 else: allKernelPaths[kernel_callPath] = 1 user_callPath = "" kernel_callPath = "" print ("Critical Call Paths, functions and Lines of Code:") choose_path(criticalSwitch_allCM, 1) end = datetime.datetime.now() post_time = end - start print ("Post Processing time in milli seconds: %u" % int(post_time.total_seconds() * 1000)) print ("Total switches: %u Critical switches: %u" % (total_switch, CM_Entry )) print ("Stack trace with no samples: %u" % noSample) print ("***************************************************") sys.exit()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 50, 2096, 1912, 319, 1353, 2026, 327, 9171, 1173, 11, 477, 869, 15235, 82, 532, 327, 9171, 1173, 198, 2, 11, 477, 869, 13532, 532, 869, 3108, 954, 290, 477, 8405, 198, 198, 6738, ...
2.579957
7,454
# -*- coding: utf-8 -*- import random import numpy as np import scipy import pandas as pd import pandas import numpy import json videoDict=getDatasetDict() videoNameList=videoDict.keys() random.shuffle(videoNameList) col_names=[] for i in range(400): col_names.append("f"+str(i)) for videoName in videoNameList: videoAnno=videoDict[videoName] data=readData(videoName) numFrame=videoAnno['duration_frame'] featureFrame=len(data)*16 videoAnno["feature_frame"]=featureFrame videoDict[videoName]=videoAnno print(numFrame,featureFrame) videoFeature_mean=poolData(data,videoAnno,num_prop=100,num_bin=1,num_sample_bin=3,pool_type="mean") outDf=pd.DataFrame(videoFeature_mean,columns=col_names) outDf.to_csv("./csv_mean_100/"+videoName+".csv",index=False) outfile=open("./anet_anno_anet.json","w") json.dump(videoDict,outfile) outfile.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 19798, 292, 198, 11748, 299, 32152, 198...
2.442623
366
from cloudevents.sdk.event import v03 import json from ferris_cli.ferris_cli import CloudEventsAPI import uuid import os import consul from ferris_cli.ferris_cli import ApplicationConfigurator from datetime import datetime platform_environment = ApplicationConfigurator().get('ferris.env') broker = f"kafka://{platform_environment['KAFKA_BOOTSTRAP_SERVER']}:{platform_environment['KAFKA_PORT']}" dateTimeObj = datetime.now() timestampStr = dateTimeObj.strftime("%Y-%m-%dT%H:%M:%SZ") print(timestampStr) send_direct_loading_event('/landing/zone/abc') send_confirmation_event('/landing/zone/abc')
[ 6738, 6279, 31534, 13, 21282, 74, 13, 15596, 1330, 410, 3070, 198, 11748, 33918, 198, 6738, 11354, 2442, 62, 44506, 13, 2232, 2442, 62, 44506, 1330, 10130, 37103, 17614, 198, 11748, 334, 27112, 198, 11748, 28686, 198, 11748, 762, 377, 1...
2.912621
206
''' GERADOR DE RELATRIO DOS SERVIDORES (DASHBOARD SERVIDORES) ''' from SQL import sqlpandas from MENSAGEM import mensagemInformacao, mensagemErro from AUXILIAR import salvarPandas def dashboardServidores(): ''' FUNO PARA CRIAR OS DASHDOARD ENTRA ENTRA NULL SAI PLANILHA COM OS DADOS PARA DASHBOARD ''' sql = '''SELECT GR_MATRICULA AS SIAPE, IT_NO_SERVIDOR AS SERVIDOR, IDADE, IT_CO_SEXO AS SEXO, DES_TITULACAO AS TITULAO, DES_ETNIA AS ETNIA, DES_REGIME_JURIDICO AS 'REG JUR', IT_CO_JORNADA_TRABALHO as 'CARGA HORRIA', DES_CARREIRA AS CARREIRA, DES_CARGO AS CARGO, DES_GRUPO AS GRUPO, DES_UPAG AS UPAG FROM tb_ser_rel where IT_DA_OCOR_EXCLUSAO_SERV is null and IT_DA_OCOR_INATIVIDADE_SERV is null and DES_CARREIRA in ('TCN', 'PROF 2', 'PROF 3');''' dados = sqlpandas(sql) if len(dados) > 0: dados['IDADE'] = dados['IDADE'].apply(faixa) dados['TITULAO'] = dados['TITULAO'].replace(['10 DOUTORADO', '08 ESPECIALIZAO', '09 MESTRADO', '06 MEDIO', '04 FUNDAMENTAL I', '05 FUNDAMENTAL', '07 SUPERIOR', '07 ENSINO SUPERIOR', '10 PHD', '07 SUPERIOR-INCOMPLETO'], ['DOUTORADO', 'ESPECIALIZAO', 'MESTRADO', 'ENSINO MDIO', 'ENSINO FUNDAMENTAL', 'ENSINO FUNDAMENTAL', 'ENSINO SUPERIOR', 'ENSINO SUPERIOR', 'DOUTORADO', 'ENSINO MDIO']) dados['TOTAL'] = 1 if len(dados) > 0: salvarPandas(dados, 'DAHSBOARD - SERVIDORES') mensagemInformacao('Relatrio DAHSBOARD - SERVIDORES criado com sucesso.') else: mensagemErro('Relatrio DAHSBOARD - SERVIDORES no foi criado.')
[ 7061, 6, 198, 30373, 2885, 1581, 5550, 29749, 1404, 7112, 46, 43036, 18871, 11008, 1581, 1546, 357, 35, 11211, 8202, 9795, 18871, 11008, 1581, 1546, 8, 198, 7061, 6, 198, 198, 6738, 16363, 1330, 44161, 79, 392, 292, 198, 6738, 41597, ...
1.680637
1,193
from pyroombaadapter.pyroombaadapter import PyRoombaAdapter
[ 6738, 12972, 305, 2381, 64, 324, 3429, 13, 9078, 305, 2381, 64, 324, 3429, 1330, 9485, 15450, 2381, 64, 47307, 198 ]
2.857143
21
from __future__ import print_function from __future__ import division import torch import torch.nn as nn from torch.nn import Parameter import math from torchkit.util.utils import l2_norm from torchkit.head.localfc.common import calc_logits
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 25139, 2357, 198, 11748, 10688, 198, 6738, 28034, ...
3.558824
68
from core.views import BaseViewSet from .models import Cash from .serializers import CashSerializer
[ 6738, 4755, 13, 33571, 1330, 7308, 7680, 7248, 198, 6738, 764, 27530, 1330, 16210, 198, 6738, 764, 46911, 11341, 1330, 16210, 32634, 7509, 628 ]
4.208333
24
import atexit import sqlite3 import traceback ################# import sys sys.path.append('/app') from helper import * settings_dict = load_yaml_dict(read_file("/Settings.yaml")) conn = sqlite3.connect(f"/database/{settings_dict['db_name']}", isolation_level=None, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("PRAGMA foreign_keys=ON") atexit.register(conn.close) atexit.register(cursor.close) version = read_file("/VERSION").rstrip() # This tells us whether the migration has already happened. check_sql = '''SELECT COUNT(*) AS count FROM pragma_table_info("problems") WHERE name = "expected_text_output"''' cursor.execute(check_sql) check_result = cursor.fetchone()["count"] if check_result > 0: print("NotNeeded") else: alter_sql_list = ['ALTER TABLE problems RENAME COLUMN expected_output TO expected_text_output', 'ALTER TABLE problems ADD COLUMN expected_image_output text NOT NULL DEFAULT ""', '''UPDATE problems SET expected_image_output = expected_text_output WHERE output_type = "jpg"''', '''UPDATE problems SET expected_text_output = "" WHERE output_type = "jpg"''', 'ALTER TABLE submissions RENAME COLUMN code_output TO text_output', 'ALTER TABLE submissions ADD COLUMN image_output text NOT NULL DEFAULT ""', '''UPDATE submissions SET image_output = text_output WHERE problem_id IN (SELECT problem_id FROM problems WHERE output_type = "jpg")''', '''UPDATE submissions SET text_output = "" WHERE problem_id IN (SELECT problem_id FROM problems WHERE output_type = "jpg")''', '''CREATE TABLE IF NOT EXISTS submissions2 ( course_id integer NOT NULL, assignment_id integer NOT NULL, problem_id integer NOT NULL, user_id text NOT NULL, submission_id integer NOT NULL, code text NOT NULL, text_output text NOT NULL, image_output text NOT NULL, passed integer NOT NULL, date timestamp NOT NULL, FOREIGN KEY (course_id) REFERENCES courses (course_id) ON DELETE CASCADE, FOREIGN KEY (assignment_id) REFERENCES assignments (assignment_id) ON DELETE CASCADE, FOREIGN KEY (problem_id) REFERENCES problems (problem_id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, PRIMARY KEY (course_id, assignment_id, problem_id, user_id, submission_id))''', '''INSERT INTO submissions2 SELECT course_id, assignment_id, problem_id, user_id, submission_id, code, text_output, image_output, passed, date FROM submissions''', 'DROP TABLE IF EXISTS submissions', 'ALTER TABLE submissions2 RENAME TO submissions' ] error_occurred = False for sql in alter_sql_list: try: cursor.execute(sql) except: print(sql) print(traceback.format_exc()) error_occurred = True if not error_occurred: print("Success")
[ 11748, 379, 37023, 198, 11748, 44161, 578, 18, 198, 11748, 12854, 1891, 198, 14468, 2, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 14, 1324, 11537, 198, 6738, 31904, 1330, 1635, 198, 198, 33692, 62, 11600, 796, 3440, 62, ...
2.040481
1,828
#!/usr/bin/env python3 """ example.py Example of using pypahdb to decompose an astronomical PAH spectrum. """ import pkg_resources from pypahdb.decomposer import Decomposer from pypahdb.observation import Observation if __name__ == '__main__': # The sample data (IPAC table). file_path = 'resources/sample_data_NGC7023.tbl' data_file = pkg_resources.resource_filename('pypahdb', file_path) # Construct an Observation object. obs = Observation(data_file) # Pass the Observation's spectrum to Decomposer, which performs the fit. pahdb_fit = Decomposer(obs.spectrum) # Save the fit to disk, both as a PDF and FITS file. pahdb_fit.save_pdf('NGC7023_pypahdb_tbl_example.pdf', domaps=False) pahdb_fit.save_fits('NGC7023_pypahdb_tbl_example.fits', header=obs.header)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 20688, 13, 9078, 198, 198, 16281, 286, 1262, 279, 4464, 993, 9945, 284, 26969, 3455, 281, 37209, 8147, 39, 10958, 13, 198, 37811, 198, 198, 11748, 279, 10025, 62, 37540...
2.643791
306
""" Mapping registries for Zigbee Home Automation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zha/ """ from .const import ( DEVICE_CLASS, SINGLE_INPUT_CLUSTER_DEVICE_CLASS, SINGLE_OUTPUT_CLUSTER_DEVICE_CLASS, COMPONENT_CLUSTERS, HUMIDITY, TEMPERATURE, ILLUMINANCE, PRESSURE, METERING, ELECTRICAL_MEASUREMENT, EVENT_RELAY_CLUSTERS, OPENING, ZONE, OCCUPANCY, CLUSTER_REPORT_CONFIGS, REPORT_CONFIG_IMMEDIATE, REPORT_CONFIG_ASAP, REPORT_CONFIG_DEFAULT, REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, REPORT_CONFIG_OP, NO_SENSOR_CLUSTERS, BINDABLE_CLUSTERS, ACCELERATION, SENSOR_TYPES, BINARY_SENSOR_TYPES, RADIO_TYPES, RadioType, RADIO, RADIO_DESCRIPTION, CONTROLLER ) SMARTTHINGS_HUMIDITY_CLUSTER = 64581 SMARTTHINGS_ACCELERATION_CLUSTER = 64514 def establish_device_mappings(): """Establish mappings between ZCL objects and HA ZHA objects. These cannot be module level, as importing bellows must be done in a in a function. """ from zigpy import zcl from zigpy.profiles import PROFILES, zha, zll if zha.PROFILE_ID not in DEVICE_CLASS: DEVICE_CLASS[zha.PROFILE_ID] = {} if zll.PROFILE_ID not in DEVICE_CLASS: DEVICE_CLASS[zll.PROFILE_ID] = {} RADIO_TYPES[RadioType.ezsp.name] = { RADIO: get_ezsp_radio, RADIO_DESCRIPTION: 'EZSP' } RADIO_TYPES[RadioType.xbee.name] = { RADIO: get_xbee_radio, RADIO_DESCRIPTION: 'XBee' } RADIO_TYPES[RadioType.deconz.name] = { RADIO: get_deconz_radio, RADIO_DESCRIPTION: 'Deconz' } EVENT_RELAY_CLUSTERS.append(zcl.clusters.general.LevelControl.cluster_id) EVENT_RELAY_CLUSTERS.append(zcl.clusters.general.OnOff.cluster_id) NO_SENSOR_CLUSTERS.append(zcl.clusters.general.Basic.cluster_id) NO_SENSOR_CLUSTERS.append( zcl.clusters.general.PowerConfiguration.cluster_id) NO_SENSOR_CLUSTERS.append(zcl.clusters.lightlink.LightLink.cluster_id) BINDABLE_CLUSTERS.append(zcl.clusters.general.LevelControl.cluster_id) BINDABLE_CLUSTERS.append(zcl.clusters.general.OnOff.cluster_id) BINDABLE_CLUSTERS.append(zcl.clusters.lighting.Color.cluster_id) DEVICE_CLASS[zha.PROFILE_ID].update({ zha.DeviceType.ON_OFF_SWITCH: 'binary_sensor', zha.DeviceType.LEVEL_CONTROL_SWITCH: 'binary_sensor', zha.DeviceType.REMOTE_CONTROL: 'binary_sensor', zha.DeviceType.SMART_PLUG: 'switch', zha.DeviceType.LEVEL_CONTROLLABLE_OUTPUT: 'light', zha.DeviceType.ON_OFF_LIGHT: 'light', zha.DeviceType.DIMMABLE_LIGHT: 'light', zha.DeviceType.COLOR_DIMMABLE_LIGHT: 'light', zha.DeviceType.ON_OFF_LIGHT_SWITCH: 'binary_sensor', zha.DeviceType.DIMMER_SWITCH: 'binary_sensor', zha.DeviceType.COLOR_DIMMER_SWITCH: 'binary_sensor', }) DEVICE_CLASS[zll.PROFILE_ID].update({ zll.DeviceType.ON_OFF_LIGHT: 'light', zll.DeviceType.ON_OFF_PLUGIN_UNIT: 'switch', zll.DeviceType.DIMMABLE_LIGHT: 'light', zll.DeviceType.DIMMABLE_PLUGIN_UNIT: 'light', zll.DeviceType.COLOR_LIGHT: 'light', zll.DeviceType.EXTENDED_COLOR_LIGHT: 'light', zll.DeviceType.COLOR_TEMPERATURE_LIGHT: 'light', zll.DeviceType.COLOR_CONTROLLER: 'binary_sensor', zll.DeviceType.COLOR_SCENE_CONTROLLER: 'binary_sensor', zll.DeviceType.CONTROLLER: 'binary_sensor', zll.DeviceType.SCENE_CONTROLLER: 'binary_sensor', zll.DeviceType.ON_OFF_SENSOR: 'binary_sensor', }) SINGLE_INPUT_CLUSTER_DEVICE_CLASS.update({ zcl.clusters.general.OnOff: 'switch', zcl.clusters.measurement.RelativeHumidity: 'sensor', # this works for now but if we hit conflicts we can break it out to # a different dict that is keyed by manufacturer SMARTTHINGS_HUMIDITY_CLUSTER: 'sensor', zcl.clusters.measurement.TemperatureMeasurement: 'sensor', zcl.clusters.measurement.PressureMeasurement: 'sensor', zcl.clusters.measurement.IlluminanceMeasurement: 'sensor', zcl.clusters.smartenergy.Metering: 'sensor', zcl.clusters.homeautomation.ElectricalMeasurement: 'sensor', zcl.clusters.security.IasZone: 'binary_sensor', zcl.clusters.measurement.OccupancySensing: 'binary_sensor', zcl.clusters.hvac.Fan: 'fan', SMARTTHINGS_ACCELERATION_CLUSTER: 'binary_sensor', }) SINGLE_OUTPUT_CLUSTER_DEVICE_CLASS.update({ zcl.clusters.general.OnOff: 'binary_sensor', }) SENSOR_TYPES.update({ zcl.clusters.measurement.RelativeHumidity.cluster_id: HUMIDITY, SMARTTHINGS_HUMIDITY_CLUSTER: HUMIDITY, zcl.clusters.measurement.TemperatureMeasurement.cluster_id: TEMPERATURE, zcl.clusters.measurement.PressureMeasurement.cluster_id: PRESSURE, zcl.clusters.measurement.IlluminanceMeasurement.cluster_id: ILLUMINANCE, zcl.clusters.smartenergy.Metering.cluster_id: METERING, zcl.clusters.homeautomation.ElectricalMeasurement.cluster_id: ELECTRICAL_MEASUREMENT, }) BINARY_SENSOR_TYPES.update({ zcl.clusters.measurement.OccupancySensing.cluster_id: OCCUPANCY, zcl.clusters.security.IasZone.cluster_id: ZONE, zcl.clusters.general.OnOff.cluster_id: OPENING, SMARTTHINGS_ACCELERATION_CLUSTER: ACCELERATION, }) CLUSTER_REPORT_CONFIGS.update({ zcl.clusters.general.Alarms.cluster_id: [], zcl.clusters.general.Basic.cluster_id: [], zcl.clusters.general.Commissioning.cluster_id: [], zcl.clusters.general.Identify.cluster_id: [], zcl.clusters.general.Groups.cluster_id: [], zcl.clusters.general.Scenes.cluster_id: [], zcl.clusters.general.Partition.cluster_id: [], zcl.clusters.general.Ota.cluster_id: [], zcl.clusters.general.PowerProfile.cluster_id: [], zcl.clusters.general.ApplianceControl.cluster_id: [], zcl.clusters.general.PollControl.cluster_id: [], zcl.clusters.general.GreenPowerProxy.cluster_id: [], zcl.clusters.general.OnOffConfiguration.cluster_id: [], zcl.clusters.lightlink.LightLink.cluster_id: [], zcl.clusters.general.OnOff.cluster_id: [{ 'attr': 'on_off', 'config': REPORT_CONFIG_IMMEDIATE }], zcl.clusters.general.LevelControl.cluster_id: [{ 'attr': 'current_level', 'config': REPORT_CONFIG_ASAP }], zcl.clusters.lighting.Color.cluster_id: [{ 'attr': 'current_x', 'config': REPORT_CONFIG_DEFAULT }, { 'attr': 'current_y', 'config': REPORT_CONFIG_DEFAULT }, { 'attr': 'color_temperature', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.measurement.RelativeHumidity.cluster_id: [{ 'attr': 'measured_value', 'config': ( REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 50 ) }], zcl.clusters.measurement.TemperatureMeasurement.cluster_id: [{ 'attr': 'measured_value', 'config': ( REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 50 ) }], SMARTTHINGS_ACCELERATION_CLUSTER: [{ 'attr': 'acceleration', 'config': REPORT_CONFIG_ASAP }, { 'attr': 'x_axis', 'config': REPORT_CONFIG_ASAP }, { 'attr': 'y_axis', 'config': REPORT_CONFIG_ASAP }, { 'attr': 'z_axis', 'config': REPORT_CONFIG_ASAP }], SMARTTHINGS_HUMIDITY_CLUSTER: [{ 'attr': 'measured_value', 'config': ( REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 50 ) }], zcl.clusters.measurement.PressureMeasurement.cluster_id: [{ 'attr': 'measured_value', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.measurement.IlluminanceMeasurement.cluster_id: [{ 'attr': 'measured_value', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.smartenergy.Metering.cluster_id: [{ 'attr': 'instantaneous_demand', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.homeautomation.ElectricalMeasurement.cluster_id: [{ 'attr': 'active_power', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.general.PowerConfiguration.cluster_id: [{ 'attr': 'battery_voltage', 'config': REPORT_CONFIG_DEFAULT }, { 'attr': 'battery_percentage_remaining', 'config': REPORT_CONFIG_DEFAULT }], zcl.clusters.measurement.OccupancySensing.cluster_id: [{ 'attr': 'occupancy', 'config': REPORT_CONFIG_IMMEDIATE }], zcl.clusters.hvac.Fan.cluster_id: [{ 'attr': 'fan_mode', 'config': REPORT_CONFIG_OP }], }) # A map of hass components to all Zigbee clusters it could use for profile_id, classes in DEVICE_CLASS.items(): profile = PROFILES[profile_id] for device_type, component in classes.items(): if component not in COMPONENT_CLUSTERS: COMPONENT_CLUSTERS[component] = (set(), set()) clusters = profile.CLUSTERS[device_type] COMPONENT_CLUSTERS[component][0].update(clusters[0]) COMPONENT_CLUSTERS[component][1].update(clusters[1])
[ 37811, 198, 44, 5912, 4214, 1678, 329, 24992, 20963, 5995, 17406, 341, 13, 198, 198, 1890, 517, 3307, 546, 428, 7515, 11, 3387, 3522, 284, 262, 10314, 379, 198, 5450, 1378, 11195, 12, 562, 10167, 13, 952, 14, 5589, 3906, 14, 89, 309...
2.038405
4,765
import random import pickle import cv2 import numpy as np import paddle import paddleseg.transforms as T from .points_sampler import MultiPointSampler
[ 11748, 4738, 198, 11748, 2298, 293, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 39517, 198, 198, 11748, 14098, 829, 1533, 13, 7645, 23914, 355, 309, 198, 6738, 764, 13033, 62, 37687, 20053, 1330, 15237,...
3.422222
45
#!/usr/bin/env python3 """ Created on Wed Feb 17 08:32:55 2021 Deface anatomical image(s) @author: dlevitas """ import os, sys import nibabel as nib import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('dark_background') from math import floor os.environ[ 'MPLCONFIGDIR' ] = '/tmp/' print("loading image to create thumbnail "+sys.argv[1]) image = nib.load(sys.argv[1]) output_image = sys.argv[2] object_img_array = image.dataobj[:] slice_x = object_img_array[floor(object_img_array.shape[0]/2), :, :] slice_y = object_img_array[:, floor(object_img_array.shape[1]/2), :] slice_z = object_img_array[:, :, floor(object_img_array.shape[2]/2)] fig, axes = plt.subplots(1,3, figsize=(9,3)) for i, slice in enumerate([slice_x, slice_y, slice_z]): print("creating thumbnail "+str(i)) axes[i].imshow(slice.T, cmap="gray", origin="lower", aspect='auto') axes[i].axis('off') plt.subplots_adjust(wspace=0, hspace=0) plt.savefig(output_image, bbox_inches='tight')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 41972, 319, 3300, 3158, 1596, 8487, 25, 2624, 25, 2816, 33448, 198, 198, 7469, 558, 48631, 2939, 7, 82, 8, 198, 198, 31, 9800, 25, 288, 2768, 21416, 198, 37811, 198, ...
2.49505
404
"""Infrastructure for registering and firing callbacks on application events. Unlike :mod:`IPython.core.hooks`, which lets end users set single functions to be called at specific times, or a collection of alternative methods to try, callbacks are designed to be used by extension authors. A number of callbacks can be registered for the same event without needing to be aware of one another. The functions defined in this module are no-ops indicating the names of available events and the arguments which will be passed to them. .. note:: This API is experimental in IPython 2.0, and may be revised in future versions. """ from __future__ import print_function # event_name -> prototype mapping available_events = {} # ------------------------------------------------------------------------ # Callback prototypes # # No-op functions which describe the names of available events and the # signatures of callbacks for those events. # ------------------------------------------------------------------------
[ 37811, 18943, 6410, 329, 28336, 290, 9645, 869, 10146, 319, 3586, 2995, 13, 198, 198, 18521, 1058, 4666, 25, 63, 4061, 7535, 13, 7295, 13, 25480, 82, 47671, 543, 8781, 886, 2985, 900, 2060, 5499, 284, 198, 1350, 1444, 379, 2176, 1661,...
4.820755
212
from app import app from services import TopicServices from flask import jsonify, request
[ 6738, 598, 1330, 598, 198, 6738, 2594, 1330, 47373, 31007, 198, 6738, 42903, 1330, 33918, 1958, 11, 2581 ]
4.944444
18
#!/usr/bin/env python3 # Copyright (c) 2021 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -uaclientname and -uaclientversion option.""" import re from test_framework.test_framework import BitcoinTestFramework from test_framework.test_node import ErrorMatch from test_framework.util import assert_equal if __name__ == '__main__': UseragentTest().main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 33448, 383, 6185, 6505, 198, 2, 4307, 6169, 739, 262, 17168, 3788, 5964, 11, 766, 262, 19249, 198, 2, 2393, 27975, 45761, 393, 2638, 1378, 2503, 13, 44813, ...
3.478571
140
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import annotations import unittest import numpy as np import numpy.testing as npt import pandas as pd from riip.material import RiiMaterial if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 117...
2.712766
94
# Copyright (c) 2017 Fujitsu Limited # 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 mock from oslo_config import cfg import oslo_messaging from neutron.api.rpc.callbacks import events from neutron.api.rpc.handlers import resources_rpc from neutron.services.logapi.common import constants as log_const from neutron.services.logapi.rpc import server as server_rpc from neutron.tests import base
[ 2, 15069, 357, 66, 8, 2177, 32671, 19831, 15302, 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, ...
3.431655
278