content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python # # Creates resources # This script creates VPC/security group/keypair if not already present import logging import os import sys import time from . import aws_util as u from . import util DRYRUN = False DEBUG = True # Names of Amazon resources that are created. These settings are fixed across # all runs, and correspond to resources created once per user per region. PUBLIC_TCP_RANGES = [ 22, # ssh (8888, 8899), # ipython notebook ports 6379, # redis port (6006, 6016) # tensorboard ports ] PUBLIC_UDP_RANGES = [(60000, 61000)] # mosh ports logger = logging.getLogger(__name__) def network_setup(): """Creates VPC if it doesn't already exists, configures it for public internet access, returns vpc, subnet, security_group""" ec2 = u.get_ec2_resource() client = u.get_ec2_client() existing_vpcs = u.get_vpc_dict() zones = u.get_zones() # create VPC from scratch. Remove this if default VPC works well enough. vpc_name = u.get_vpc_name() if u.get_vpc_name() in existing_vpcs: logger.info("Reusing VPC " + vpc_name) vpc = existing_vpcs[vpc_name] else: logger.info("Creating VPC " + vpc_name) vpc = ec2.create_vpc(CidrBlock='192.168.0.0/16') # enable DNS on the VPC local_response = vpc.modify_attribute(EnableDnsHostnames={"Value": True}) assert u.is_good_response(local_response) local_response = vpc.modify_attribute(EnableDnsSupport={"Value": True}) assert u.is_good_response(local_response) vpc.create_tags(Tags=u.create_name_tags(vpc_name)) vpc.wait_until_available() gateways = u.get_gateway_dict(vpc) gateway_name = u.get_gateway_name() if gateway_name in gateways: logger.info("Reusing gateways " + gateway_name) else: logger.info("Creating internet gateway " + gateway_name) ig = ec2.create_internet_gateway() ig.attach_to_vpc(VpcId=vpc.id) ig.create_tags(Tags=u.create_name_tags(gateway_name)) # check that attachment succeeded attach_state = u.extract_attr_for_match(ig.attachments, State=-1, VpcId=vpc.id) assert attach_state == 'available', "vpc %s is in state %s" % (vpc.id, attach_state) route_table = vpc.create_route_table() route_table_name = u.get_route_table_name() route_table.create_tags(Tags=u.create_name_tags(route_table_name)) dest_cidr = '0.0.0.0/0' route_table.create_route(DestinationCidrBlock=dest_cidr, GatewayId=ig.id) assert len(zones) <= 16 # for cidr/20 to fit into cidr/16 ip = 0 for zone in zones: cidr_block = '192.168.%d.0/20' % (ip,) ip += 16 logging.info("Creating subnet %s in zone %s" % (cidr_block, zone)) subnet = vpc.create_subnet(CidrBlock=cidr_block, AvailabilityZone=zone) subnet.create_tags(Tags=[{'Key': 'Name', 'Value': f'{vpc_name}-subnet'}, {'Key': 'Region', 'Value': zone}]) local_response = client.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet.id) assert u.is_good_response(local_response) u.wait_until_available(subnet) assert subnet.map_public_ip_on_launch, "Subnet doesn't enable public IP by default, why?" route_table.associate_with_subnet(SubnetId=subnet.id) existing_security_groups = u.get_security_group_dict(vpc.id) security_group_name = u.get_security_group_name() if security_group_name in existing_security_groups: logger.info("Reusing security group " + security_group_name) security_group = existing_security_groups[security_group_name] assert security_group.vpc_id == vpc.id, f"Found security group {security_group} " \ f"attached to {security_group.vpc_id} but expected {vpc.id}" else: logging.info("Creating security group " + security_group_name) security_group = ec2.create_security_group( GroupName=security_group_name, Description=security_group_name, VpcId=vpc.id) cidr_ip = os.environ.get('SCLUSTER_SECURITY_GROUP_CidrIp', '0.0.0.0/0') security_group.create_tags(Tags=u.create_name_tags(security_group_name)) # allow ICMP access for public ping security_group.authorize_ingress( CidrIp='0.0.0.0/0', IpProtocol='icmp', FromPort=-1, ToPort=-1 ) # open public ports # always include SSH port which is required for basic functionality assert 22 in PUBLIC_TCP_RANGES, "Must enable SSH access" for port in PUBLIC_TCP_RANGES: if util.is_iterable(port): assert len(port) == 2 from_port, to_port = port else: from_port, to_port = port, port response = security_group.authorize_ingress( IpProtocol="tcp", CidrIp=cidr_ip, FromPort=from_port, ToPort=to_port ) assert u.is_good_response(response) for port in PUBLIC_UDP_RANGES: if util.is_iterable(port): assert len(port) == 2 from_port, to_port = port else: from_port, to_port = port, port response = security_group.authorize_ingress(IpProtocol="udp", CidrIp=cidr_ip, FromPort=from_port, ToPort=to_port) assert u.is_good_response(response) return vpc, security_group def keypair_setup(): """Creates keypair if necessary, saves private key locally, returns contents of private key file.""" os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair: print("Reusing keypair " + keypair_name) # check that local pem file exists and is readable assert os.path.exists( keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through " \ "console and run again to recreate keypair/.pem together" % ( keypair_name, keypair_fn, keypair_name) keypair_contents = open(keypair_fn).read() assert len(keypair_contents) > 0 else: print("Creating keypair " + keypair_name) ec2 = u.get_ec2_resource() assert not os.path.exists( keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding " \ "keypair through console" % (keypair_fn) keypair = ec2.create_key_pair(KeyName=keypair_name) open(keypair_fn, 'w').write(keypair.key_material) os.system('chmod 400 ' + keypair_fn) return keypair def placement_group_setup(group_name): """Creates placement_group group if necessary. Returns True if new placement_group group was created, False otherwise.""" existing_placement_groups = u.get_placement_group_dict() group = existing_placement_groups.get(group_name, None) if group: assert group.state == 'available' assert group.strategy == 'cluster' print("Reusing group ", group.name) return group print("Creating group " + group_name) ec2 = u.get_ec2_resource() group = ec2.create_placement_group(GroupName=group_name, Strategy='cluster') return group if __name__ == '__main__': create_resources()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 7921, 274, 4133, 198, 2, 770, 4226, 8075, 569, 5662, 14, 12961, 1448, 14, 2539, 24874, 611, 407, 1541, 1944, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, ...
2.215367
3,501
num = int(input('Digite um nmero inteiro: ')) print(f'O nmero: {num}' f'\nO antecessor: {num - 1}' f'\nO sucessor: {num + 1}')
[ 22510, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 299, 647, 78, 493, 68, 7058, 25, 705, 4008, 198, 198, 4798, 7, 69, 6, 46, 299, 647, 78, 25, 1391, 22510, 92, 6, 198, 220, 220, 220, 220, 220, 277, 6, 59, 77, 46, 29692, 919,...
1.842105
76
"""Support for IHC binary sensors.""" from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.const import CONF_TYPE from . import IHC_CONTROLLER, IHC_INFO from .const import CONF_INVERTING from .ihcdevice import IHCDevice def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the IHC binary sensor platform.""" if discovery_info is None: return devices = [] for name, device in discovery_info.items(): ihc_id = device["ihc_id"] product_cfg = device["product_cfg"] product = device["product"] # Find controller that corresponds with device id ctrl_id = device["ctrl_id"] ihc_key = f"ihc{ctrl_id}" info = hass.data[ihc_key][IHC_INFO] ihc_controller = hass.data[ihc_key][IHC_CONTROLLER] sensor = IHCBinarySensor( ihc_controller, name, ihc_id, info, product_cfg.get(CONF_TYPE), product_cfg[CONF_INVERTING], product, ) devices.append(sensor) add_entities(devices)
[ 37811, 15514, 329, 314, 16045, 13934, 15736, 526, 15931, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, 39491, 62, 82, 22854, 1330, 45755, 47864, 24728, 198, 6738, 1363, 562, 10167, 13, 9979, 1330, 7102, 37, 62, 25216, 198, 198, 6738,...
2.228175
504
#!/usr/bin/env python import os.path as path import sys tmpDir = '../config/tmp/' logDir = '../config/tmp/log/' conffile = sys.argv[1] runfile=sys.argv[2] lr = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] fout = open(runfile, 'w') fout.write("#!/bin/bash\n\n\n") fws = {} confname = path.splitext(path.basename(conffile))[0] loglist = confname+'.meta.log' fl = open(loglist, 'w') for i in range(0, len(lr)): filename = confname+'_'+str(lr[i]) tmpfile = path.join(tmpDir, filename+'.conf') logfile = path.join(logDir, filename + '.txt') fws[i] = open(tmpfile, 'w') fout.write("echo \""+"./local.sh 1 4 "+tmpfile + " 2>"+logfile+'\"\n\n') fout.write("./local.sh 1 4 "+tmpfile + " 2>"+logfile+'\n\n\n') fl.write(logfile+'\n') fout.close() fl.close() for line in open(conffile): if line.find("eta")==0: for i in range(0, len(lr)): output = "eta: "+str(lr[i]) + '\n' fws[i].write(output) else: for i in range(0, len(lr)): fws[i].write(line) for i in range(0, len(lr)): fws[i].close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 13, 6978, 355, 3108, 198, 11748, 25064, 198, 198, 22065, 35277, 796, 705, 40720, 11250, 14, 22065, 14, 6, 198, 6404, 35277, 796, 705, 40720, 11250, 14, 22065, 14, 64...
2.034274
496
# Tic Tac Toe Game # Original repository: (https://github.com/Omar8345/tic-tac-toe) # Author: Omar Mostafa # Date: 08/02/2022 # Version: 1.0 # Description: Tic Tac Toe Game made using Python Tkitner (Open Source) # This game is a simple game that can be played with two players # and can be played with a computer. ##### CODING STARTS HERE ##### # Importing the necessary libraries from itertools import tee import tkinter import random import time from tkinter import messagebox from numpy import empty from time import sleep as sleep try: # Tkinter window = tkinter.Tk() window.title("Tic Tac Toe") window.resizable(0, 0) # It makes everything needed to fit the window! WoW! # Window icon window.iconbitmap("img\XO.ico") # Tkinter game buttons # create 9 tkinter buttons b1 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b1)) b1.grid(row=1, column=0) b2 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b2)) b2.grid(row=1, column=1) b3 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b3)) b3.grid(row=1, column=2) b4 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b4)) b4.grid(row=2, column=0) b5 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b5)) b5.grid(row=2, column=1) b6 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b6)) b6.grid(row=2, column=2) b7 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b7)) b7.grid(row=3, column=0) b8 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b8)) b8.grid(row=3, column=1) b9 = tkinter.Button(window, text=" ", font=('Times 26 bold'), height=4, width=8, command=lambda: btn_click(b9)) b9.grid(row=3, column=2) # create a list to store the buttons buttons = [b1, b2, b3, b4, b5, b6, b7, b8, b9] # create a list to store the values of the buttons values = [] # when button clicked, it puts X in the button except: None if __name__ == "__main__": run_game() else: print("If you run the game using the launcher.py or launcher.exe.") sleep(1) print('Ignore this message, thank you.') print('------------------------------------------------------') print("Error: This is a module and not a script.") sleep(2) print("Please run this module as a script.") sleep(2) print("If you actually did run it as a script, please report this bug.") sleep(2) print("Raise an issue on GitHub. More details:") sleep(2) print("__name__ != __main__") sleep(2) print(" __name__ does not equal __main__ and this was made to prevent errors.") sleep(2) print("If you are a developer and you are seeing this message, please report this bug and (if possible, more details).") sleep(2) print("If you are not a developer and you are seeing this message, please report the details gaven above.") sleep(2) print("Thank you.") sleep(2) print("Omar Mostafa") sleep(2) print("Hope you in good health. Stay safe.") sleep(1)
[ 2, 309, 291, 26075, 1675, 68, 3776, 201, 198, 2, 13745, 16099, 25, 357, 5450, 1378, 12567, 13, 785, 14, 46, 3876, 5999, 2231, 14, 13370, 12, 83, 330, 12, 44579, 8, 201, 198, 2, 6434, 25, 24980, 4042, 28485, 201, 198, 2, 7536, 25...
2.524217
1,404
# # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings try: from numba import cuda except ImportError: cuda = None try: import psutil except ImportError: psutil = None
[ 2, 198, 2, 15069, 357, 66, 8, 12131, 11, 15127, 23929, 44680, 6234, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
3.46729
214
import unittest from maskgen import image_wrap import numpy from maskgen.segmentation.segmanage import select_region,segmentation_classification,convert_color from tests.test_support import TestSupport if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 9335, 5235, 1330, 220, 2939, 62, 37150, 198, 11748, 299, 32152, 198, 6738, 9335, 5235, 13, 325, 5154, 341, 13, 325, 70, 805, 496, 1330, 2922, 62, 36996, 11, 325, 5154, 341, 62, 4871, 2649, 11, 1102, ...
3.189873
79
import pytest import os import random from text import * # noqa from utils import isclose, DataFile # TODO: for .ipynb """ >>> P1.samples(20) 'you thought known but were insides of see in depend by us dodecahedrons just but i words are instead degrees' >>> P2.samples(20) 'flatland well then can anything else more into the total destruction and circles teach others confine women must be added' >>> P3.samples(20) 'flatland by edwin a abbott 1884 to the wake of a certificate from nature herself proving the equal sided triangle' """ if __name__ == '__main__': pytest.main()
[ 11748, 12972, 9288, 201, 198, 11748, 28686, 201, 198, 11748, 4738, 201, 198, 201, 198, 6738, 2420, 1330, 1635, 220, 1303, 645, 20402, 201, 198, 6738, 3384, 4487, 1330, 318, 19836, 11, 6060, 8979, 201, 198, 201, 198, 201, 198, 201, 198...
2.809735
226
import re import argparse import os import sys import logging import traceback import pysatl if __name__ == "__main__": ApduTool(sys.argv)
[ 11748, 302, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 12854, 1891, 198, 11748, 279, 893, 25864, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 5...
2.88
50
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017 jem@seethis.link # Licensed under the MIT license (http://opensource.org/licenses/MIT) import cffi import ctypes.util import platform ffi = cffi.FFI() ffi.cdef(""" struct hid_device_info { char *path; unsigned short vendor_id; unsigned short product_id; wchar_t *serial_number; unsigned short release_number; wchar_t *manufacturer_string; wchar_t *product_string; unsigned short usage_page; unsigned short usage; int interface_number; struct hid_device_info *next; }; typedef struct hid_device_ hid_device; int hid_init(void); int hid_exit(void); struct hid_device_info* hid_enumerate(unsigned short, unsigned short); void hid_free_enumeration (struct hid_device_info *devs); hid_device* hid_open (unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); hid_device* hid_open_path (const char *path); int hid_write (hid_device *device, const unsigned char *data, size_t length); int hid_read_timeout (hid_device *dev, unsigned char *data, size_t length, int milliseconds); int hid_read (hid_device *device, unsigned char *data, size_t length); int hid_set_nonblocking (hid_device *device, int nonblock); int hid_send_feature_report (hid_device *device, const unsigned char *data, size_t length); int hid_get_feature_report (hid_device *device, unsigned char *data, size_t length); void hid_close (hid_device *device); int hid_get_manufacturer_string (hid_device *device, wchar_t *string, size_t maxlen); int hid_get_product_string (hid_device *device, wchar_t *string, size_t maxlen); int hid_get_serial_number_string (hid_device *device, wchar_t *string, size_t maxlen); int hid_get_indexed_string (hid_device *device, int string_index, wchar_t *string, size_t maxlen); const wchar_t* hid_error (hid_device *device); """) if "Windows" in platform.platform(): try: hidapi = ffi.dlopen('hidapi.dll') except: hidapi = ffi.dlopen(ctypes.util.find_library('hidapi.dll')) else: try: hidapi = ffi.dlopen('hidapi-libusb') except: hidapi = ffi.dlopen(ctypes.util.find_library('hidapi-libusb')) def _hid_enumerate(vendor_id=0, product_id=0): """ Enumerates all the hid devices for VID:PID. Returns a list of `DeviceInfo`. If vid is 0, then match any vendor id. Similarly, if pid is 0, match any product id. If both are zero, enumerate all HID devices. """ start = hidapi.hid_enumerate(vendor_id, product_id) result = [] cur = ffi.new("struct hid_device_info*"); cur = start # Copy everything into python list while cur != ffi.NULL: result.append(Device(cur)) cur = cur.next # Free the C memory hidapi.hid_free_enumeration(start) return result # def hid_open(vendor_id, product_id, serial=None): # """ # """ # if serial == None: # serial = ffi.NULL # else: # if type(serial) == bytes or type(serial) == bytearray: # serial = serial.decode('utf-8') # serial = ffi.new("wchar_t[]", serial) # dev = hidapi.hid_open(vendor_id, product_id, serial) # if dev: # return Device(dev) # else: # None if __name__ == "__main__": # Examples from easyhid import Enumeration # Stores an enumertion of all the connected USB HID devices en = Enumeration() # return a list of devices based on the search parameters devices = en.find(manufacturer="Company", product="Widget", interface=3) # print a description of the devices found for dev in devices: print(dev.description()) # open a device dev.open() # write some bytes to the device dev.write(bytearray([0, 1, 2, 3])) # read some bytes print(dev.read()) # close a device dev.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 2177, 474, 368, 31, 325, 2788, 271, 13, 8726, 198, 2, 49962, 739, 262, 17168, 5964, 357, 4023, 1378, 44813,...
2.631181
1,456
""" Align imported dlls/functions to executable functionality. """ import sys # import all supported ordinal decodings from rules.ordinal_mappings import advapi32 from rules.ordinal_mappings import cabinet from rules.ordinal_mappings import comctl32 from rules.ordinal_mappings import mfc42 from rules.ordinal_mappings import msvbvm60 from rules.ordinal_mappings import ntdll from rules.ordinal_mappings import odbc32 from rules.ordinal_mappings import oleaut32 from rules.ordinal_mappings import oledlg from rules.ordinal_mappings import propsys from rules.ordinal_mappings import shell32 from rules.ordinal_mappings import shlwapi from rules.ordinal_mappings import ws2_32 from rules.ordinal_mappings import wsock32 # create ordinal mappings dictionary ords2names = {} ords2names['advapi32.dll'] = advapi32.mapping ords2names['cabinet.dll'] = cabinet.mapping ords2names['comctl32.dll'] = comctl32.mapping ords2names['mfc42.dll'] = mfc42.mapping ords2names['msvbvm60.dll'] = msvbvm60.mapping ords2names['ntdll.dll'] = ntdll.mapping ords2names['odbc32.dll'] = odbc32.mapping ords2names['oleaut32.dll'] = oleaut32.mapping ords2names['oledlg.dll'] = oledlg.mapping ords2names['propsys.dll'] = propsys.mapping ords2names['shell32.dll'] = shell32.mapping ords2names['shlwapi.dll'] = shlwapi.mapping ords2names['ws2_32.dll'] = ws2_32.mapping ords2names['wsock32.dll'] = wsock32.mapping # list of targeted functions and their descriptions targets = { 'accept': 'This function is used to listen for incoming connections. This function indicates that the program will listen for incoming connections on a socket. It is mostly used by malware to communicate with their Command and Communication server.', 'AdjustTokenPrivileges': 'This function is used to enable or disable specific access privileges. In a process injection attack, this function is used by malware to gain additional permissions.', 'AttachThreadInput': 'This function attaches the input processing from one thread to another so that the second thread receives input events such as keyboard and mouse events. Keyloggers and other spyware use this function.', 'bind': 'This function is used to associate a local address to a socket in order to listen for incoming connections.', 'BitBlt': 'This function is used to copy graphic data from one device to another. Spyware sometimes uses this function to capture screenshots.', 'CertOpenSystemStore': 'This function is used to access the certificates stored on the local system.', 'CheckRemoteDebuggerPresent': 'Determines whether the specified process is being debugged. Used by malware to detect and evade reversing.', 'connect': 'This function is used to connect to a remote socket. Malware often uses low-level functionality to connect to a command-and-control server. It is mostly used by malware to communicate with their Command and Communication server.', 'ConnectNamedPipe': 'This function is used to create a server pipe for interprocess communication that will wait for a client pipe to connect. Backdoors and reverse shells sometimes use ConnectNamedPipe to simplify connectivity to a command-and-control server.', 'ControlService': 'This function is used to start, stop, modify, or send a signal to a running service. If malware is using its own malicious service, code needs to be analyzed that implements the service in order to determine the purpose of the call.', 'CreateFile': 'Creates a new file or opens an existing file.', 'CreateFileMapping': 'This function is used to create a handle to a file mapping that loads a file into memory and makes it accessible via memory addresses. Launchers, loaders, and injectors use this function to read and modify PE files.', 'CreateMutex': 'This function creates a mutual exclusion object that can be used by malware to ensure that only a single instance of the malware is running on a system at any given time. Malware often uses fixed names for mutexes, which can be good host-based indicators to detect additional installations of the malware.', 'CreateProcess': 'This function creates and launches a new process. If malware creates a new process, new process needs to be analyzed as well.', 'CreateRemoteThread': 'This function is used to start a thread in a remote process. Launchers and stealth malware use CreateRemoteThread to inject code into a different process.', 'CreateService': 'This function is used to create a service that can be started at boot time. Malware uses CreateService for persistence, stealth, or to load kernel drivers.', 'CreateToolhelp32Snapshot': 'This function is used to create a snapshot of processes, heaps, threads, and modules. Malware often uses this function as part of code that iterates through processes or threads.', 'CryptAcquireContext': 'This function is often the first function used by malware to initialize the use of Windows encryption.', 'DeviceIoControl': 'This function sends a control message from user space to a device driver. Kernel malware that needs to pass information between user space and kernel space often use this function.', 'DllFunctionCall': 'THis function is used to import a DLL within a visual basic executable. This indicates malware with visual basic functionality.', 'EnableExecuteProtectionSupport': 'This function is used to modify the Data Execution Protection (DEP) settings of the host, making it more susceptible to attack.', 'EnumProcesses': 'This function is used to enumerate through running processes on the system. Malware often enumerates through processes to find a process into which to inject.', 'EnumProcessModules': 'This function is used to enumerate the loaded modules (executables and DLLs) for a given process. Malware enumerates through modules when doing an injection.', 'FindFirstFile': 'This function is used to search through a directory and enumerate the file system.', 'FindNextFile': 'This function is used to search through a directory and enumerate the file system.', 'FindResource': 'This function is used to find a resource in an executable or loaded DLL. Malware sometimes uses resources to store strings, configuration information, or other malicious files. If this function is used, then check for an .rsrc section in the malware`s PE header.', 'FindWindow': 'This function is used to search for an open window on the desktop. Sometimes this function is used as an anti-debugging technique to search for OllyDbg windows.', 'FtpOpenFile': 'This function is used to open a file on a remote FTP server.', 'FtpPutFile': 'This function is used to upload a file to remote FTP server.', 'GetAdaptersInfo': 'This function is used to obtain information about the network adapters on the system. Backdoors sometimes call GetAdaptersInfo in the information-gathering phase to gather information about infected machines. In some cases, it`s used to gather MAC addresses to check for VMware as part of anti-virtual machine techniques.', 'GetAsyncKeyState': 'This function is used to determine whether a particular key is being pressed. Malware sometimes uses this function to implement a keylogger.', 'GetClipboardData': 'This function is used to read user clipboard data and is sometimes used in keyloggers.', 'GetDC': 'This function returns a handle to a device context for a window or the whole screen. Spyware that takes screen captures often uses this function.', 'GetForegroundWindow': 'This function returns a handle to the window currently in the foreground of the desktop. Keyloggers commonly use this function to determine in which window the user is entering his keystrokes.', 'gethostbyname': 'This function is used to perform a DNS lookup on a particular hostname prior to making an IP connection to a remote host. Hostnames that serve as command-and-control servers often make good network-based signatures.', 'gethostname': 'This function is used to retrieve the hostname of the computer. Backdoors sometimes use gethostname in information gathering phase of the victim machine.', 'GetKeyState': 'This function is used by keyloggers to obtain the status of a particular key on the keyboard.', 'GetModuleFilename': 'This function returns the filename of a module that is loaded in the current process. Malware can use this function to modify or copy files in the currently running process.', 'GetModuleHandle': 'This function is used to obtain a handle to an already loaded module. Malware may use GetModuleHandle to locate and modify code in a loaded module or to search for a good location to inject code.', 'GetProcAddress': 'This function is used to retrieve the address of a function in a DLL loaded into memory. This is used to import functions from other DLLs in addition to the functions imported in the PE file header.', 'GetStartupInfo': 'This function is used to retrieve a structure containing details about how the current process was configured to run, such as where the standard handles are directed.', 'GetSystemDefaultLangId': 'This function returns the default language settings for the system. These are used by malwares by specifically designed for region-based attacks.', 'GetTempPath': 'This function returns the temporary file path. If malware call this function, check whether it reads or writes any files in the temporary file path.', 'GetThreadContext': 'This function returns the context structure of a given thread. The context for a thread stores all the thread information, such as the register values and current state.', 'GetVersionEx': 'This function returns information about which version of Windows is currently running. This can be used as part of a victim survey, or to select between different offsets for undocumented structures that have changed between different versions of Windows.', 'GetWindowDC': 'This function retrieves the device context (DC) for the entire window, including title bar, menus, and scroll bars. Used to take a screenshot of a particular GUI window (like a browser).', 'GetWindowsDirectory': 'This function returns the file path to the Windows directory (usually C:\\Windows). Malware sometimes uses this call to determine into which directory to install additional malicious programs.', 'GetWindowText': 'This function gets the title of all program windows for the current user. Used to enumerate processes that have a GUI interface.', 'HttpOpenRequest': 'This function sets up the OS resources for an HTTP request.', 'HttpSendRequest': 'This function actually makes an outgoing HTTP connection.', 'inet_addr': 'This function converts an IP address string like 127.0.0.1 so that it can be used by functions such as connect. The string specified can sometimes be used as a network-based signature.', 'InternetOpen': 'This function initializes the high-level Internet access functions from WinINet, such as InternetOpenUrl and InternetReadFile. Searching for InternetOpen is a good way to find the start of Internet access functionality. One of the parameters to InternetOpen is the User-Agent, which can sometimes make a good network-based signature.', 'InternetOpenUrl': 'This function opens a specific URL for a connection using FTP, HTTP, or HTTPS.URLs, if fixed, can often be good network-based signatures.', 'InternetReadFile': 'This function reads data from a previously opened URL.', 'InternetWriteFile': 'This function writes data to a previously opened URL.', 'IsDebuggerPresent': 'Determines whether the calling process is being debugged by a user-mode debugger. Used by malware to detect and evade reversing.', 'IsNTAdmin': 'This function checks if the user has administrator privileges.', 'IsUserAnAdmin': 'This function checks if the user has administrator privileges.', 'IsWoW64Process': 'This function is used by a 32-bit process to determine if it is running on a 64-bit operating system.', 'LdrLoadDll': 'This is a low-level function to load a DLL into a process, just like LoadLibrary. Normal programs use LoadLibrary, and the presence of this import may indicate a program that is attempting to be stealthy.', 'LoadLibrary': 'This is the standard fucntion to load a DLL into a process at runtime.', 'LoadResource': 'This function loads a resource from a PE file into memory. Malware sometimes uses resources to store strings, configuration information, or other malicious files.', 'LsaEnumerateLogonSessions': 'This function is used to enumerate through logon sessions on the current system, which can be used as part of a credential stealer.', 'MapViewOfFile': 'This function is used to map a file into memory and makes the contents of the file accessible via memory addresses. Launchers, loaders, and injectors use this function to read and modify PE files. By using MapViewOfFile, the malware can avoid using WriteFile to modify the contents of a file.', 'MapVirtualKey': 'This function is used to translate a virtual-key code into a character value. It is often used by keylogging malware.', 'Module32First/Module32Next': 'This function is used to enumerate through modules loaded into a process. Injectors use this function to determine where to inject code.', 'NetScheduleJobAdd': 'This function submits a request for a program to be run at a specified date and time. Malware can use NetScheduleJobAdd to run a different program. This is an important indicator to see the program that is scheduled to run at future time.', 'NetShareEnum': 'This function is used to enumerate network shares.', 'NtQueryDirectoryFile': 'This function returns information about files in a directory. Rootkits commonly hook this function in order to hide files.', 'NtQueryInformationProcess': 'This function is used to return various information about a specified process. This function is sometimes used as an anti-debugging technique because it can return the same information as CheckRemoteDebuggerPresent.', 'NtSetInformationProcess': 'This function is used to change the privilege level of a program or to bypass Data Execution Prevention (DEP).', 'OpenMutex': 'This function opens a handle to a mutual exclusion object that can be used by malware to ensure that only a single instance of malware is running on a system at any given time. Malware often uses fixed names for mutexes, which can be good host-based indicators.', 'OpenProcess': 'This function is used to open a handle to another process running on the system. This handle can be used to read and write to the other process memory or to inject code into the other process.', 'OutputDebugString': 'This function is used to output a string to a debugger if one is attached. This can be used as an anti-debugging technique.', 'PeekNamedPipe': 'This function is used to copy data from a named pipe without removing data from the pipe. This function is popular with reverse shells.', 'Process32First': 'This function is used to begin enumerating processes from a previous call to CreateToolhelp32Snapshot. Malware often enumerates through processes to find a process into which to inject.', 'Process32Next': 'This function is used to begin enumerating processes from a previous call to CreateToolhelp32Snapshot. Malware often enumerates through processes to find a process into which to inject.', 'QueueUserAPC': 'This function is used to execute code for a different thread. Malware sometimes uses QueueUserAPC to inject code into another process.', 'ReadProcessMemory': 'This function is used to read the memory of a remote process.', 'recv': 'This function is used to receive data from a remote machine. Malware often uses this function to receive data from a remote command-and-control server.', 'RegCreateKey': 'This function is used to create a handle to a new registry key for reading and editing. Registry keys are sometimes written as a way for software to achieve persistence on a host. The registry also contains a whole host of operating system and application setting information.', 'RegisterHotKey': 'This function is used to register a handler to be notified anytime a user enters a particular key combination (like CTRL-ALT-J), regardless of which window is active when the user presses the key combination. This function is sometimes used by spyware that remains hidden from the user until the key combination is pressed.', 'RegOpenKey': 'This function is used to open a handle to a registry key for reading and editing. Registry keys are sometimes written as a way for software to achieve persistence on a host. The registry also contains a whole host of operating system and application setting information.', 'ResumeThread': 'This function is used to resume a previously suspended thread. ResumeThread is used as part of several injection techniques.', 'RtlCreateRegistryKey': 'This function is used to create a registry from kernel-mode code.', 'RtlWriteRegistryValue': 'This function is used to write a value to the registry from kernel-mode code.', 'SamIConnect': 'This function is used to connect to the Security Account Manager (SAM) in order to make future calls that access credential information. Hash-dumping programs access the SAM database in order to retrieve the hash of users` login passwords.', 'SamIGetPrivateData': 'This function is used to query the private information about a specific user from the Security Account Manager (SAM) database. Hash-dumping programs access the SAM database in order to retrieve the hash of users` login passwords.', 'SamQueryInformationUse': 'This function is used to query information about a specific user in the Security Account Manager (SAM) database. Hash-dumping programs access the SAM database in order to retrieve the hash of users` login passwords.', 'send': 'This function is used to send data to a remote machine. It is often used by malwares to send data to a remote command-and-control server.', 'SetFileTime': 'This function is used to modify the creation, access, or last modified time of a file. Malware often uses this function to conceal malicious activity.', 'SetThreadContext': 'This function is used to modify the context of a given thread. Some injection techniques use SetThreadContext.', 'SetWindowsHookEx': 'This function is used to set a hook function to be called whenever a certain event is called. Commonly used with keyloggers and spyware, this function also provides an easy way to load a DLL into all GUI processes on the system. This function is sometimes added by the compiler.', 'SfcTerminateWatcherThread': 'This function is used to disable Windows file protection and modify files that otherwise would be protected.', 'ShellExecute': 'This function is used to execute another program.', 'StartServiceCtrlDispatcher': 'This function is used by a service to connect the main thread of the process to the service control manager. Any process that runs as a service must call this function within 30 seconds of startup. Locating this function in malware will tell that the function should be run as a service.', 'SQLConnect': 'This function establishes a connection with a driver and data source to allow for data to be shared with the driver/data source.', 'SuspendThread': 'This function is used to suspend a thread so that it stops running. Malware will sometimes suspend a thread in order to modify it by performing code injection.', 'System': 'This function is used to run another program provided by some C runtime libraries. On Windows, this function serves as a wrapper function to CreateProcess.', 'Thread32First/Thread32Next': 'This function is used to iterate through the threads of a process. Injectors use these functions to find an appropriate thread into which to inject.', 'ThunRTMain': 'Thsi function is used as the entry point to a visual basic executable. This indicates malware with visual basic functionality.', 'Toolhelp32ReadProcessMemory': 'This function is used to read the memory of a remote process.', 'URLDownloadToFile': 'This function is used to download a file from a web server and save it to disk. This function is popular with downloaders because it implements all the functionality of a downloader in one function call.', 'VirtualAllocEx': 'This function is a memory-allocation routine that can allocate memory in a remote process. Malware sometimes uses VirtualAllocEx as part of process injection.', 'VirtualProtectEx': 'This function is used to change the protection on a region of memory. Malware may use this function to change a read-only section of memory to an executable.', 'WideCharToMultiByte': 'This function is used to convert a Unicode string into an ASCII string.', 'WinExec': 'This function is used to execute another program.', 'WriteProcessMemory': 'This function is used to write data to a remote process. Malware uses WriteProcessMemory as part of process injection.', 'WSAStartup': 'This function is used to initialize low-level network functionality. Finding calls to WSAStartup can often be an easy way to locate the start of network related functionality.', 'Zombie_AddRef': 'This function is used to make a call to a visual basic subroutine. This indicates malware with visual basic functionality.' } # constant for an unknown import by ordinal ORDINAL_DESC = 'Ordinal is decoded at runtime. To see ordinal mapping, Download the DLL and use the parse_exports() method of the PE class.'
[ 37811, 198, 2348, 570, 17392, 288, 297, 82, 14, 12543, 2733, 284, 28883, 11244, 13, 198, 37811, 198, 11748, 25064, 198, 198, 2, 1330, 477, 4855, 2760, 1292, 875, 375, 654, 198, 6738, 3173, 13, 585, 1292, 62, 76, 39242, 1330, 1354, 1...
4.271728
5,005
#!/usr/bin/env python3 import anki_vector import paho.mqtt.client as mqtt import time ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 281, 4106, 62, 31364, 198, 11748, 279, 17108, 13, 76, 80, 926, 13, 16366, 355, 285, 80, 926, 198, 11748, 640, 198, 198, 29113, 29113, 7804, 4242, 21017, 198, 198, 291...
6.186047
86
import time from beacontools import BeaconScanner, IBeaconFilter # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid="e2c56db5-dffb-48d2-b060-d0f5a71096e0") ) scanner.start() time.sleep(10) scanner.stop()
[ 11748, 640, 198, 6738, 307, 330, 756, 10141, 1330, 29729, 33351, 1008, 11, 314, 3856, 7807, 22417, 198, 198, 2, 9367, 329, 477, 1312, 3856, 7807, 25210, 422, 307, 37256, 351, 262, 7368, 334, 27112, 220, 198, 35836, 1008, 796, 29729, 3...
2.672566
113
# Desafio 61 Curso em Video Python # By Rafabr from estrutura_modelo import cabecalho, rodape cabecalho(61, "Termos de uma Progresso Aritmtica - II") while True: try: p0 = float(input('Digite o Termo inicial da PA: ')) r = float(input('Digite a razo da PA: ')) except ValueError: print('Voe digitou um valor indevido!\n') continue break n = 1 print() while (n <= 10): print(f'Termo {n}:'.ljust(10) + f'{p0 + (n-1)*r}') n += 1 rodape()
[ 2, 2935, 1878, 952, 8454, 4424, 568, 795, 7623, 11361, 198, 2, 2750, 20824, 397, 81, 198, 198, 6738, 1556, 81, 315, 5330, 62, 19849, 78, 1330, 16212, 721, 282, 8873, 11, 15299, 1758, 198, 198, 66, 397, 721, 282, 8873, 7, 5333, 11,...
2.133621
232
from setuptools import setup tests_require = [ 'cov-core', 'mock', 'nose2', ] setup(name='steinlib', version='0.1', description='Python bindings for Steinlib format.', url='http://github.com/leandron/steinlib', author='Leandro Nunes', author_email='leandron85@gmail.com', license='MIT', packages=['steinlib'], tests_require=tests_require, test_suite='nose2.collector.collector', zip_safe=False)
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 41989, 62, 46115, 796, 685, 198, 220, 220, 220, 220, 220, 220, 220, 705, 66, 709, 12, 7295, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 705, 76, 735, 3256, 198, 220, 220, 220, 220, ...
2.235023
217
from pxr import * import os, os.path import numpy import re import usdUtils import math import imp usdStageWithFbxLoaded = True try: imp.find_module('fbx') import fbx except ImportError: usdUtils.printError("Failed to import fbx module. Please install FBX Python bindings from http://www.autodesk.com/fbx and add path to FBX Python SDK to your PYTHONPATH") usdStageWithFbxLoaded = False def usdStageWithFbx(fbxPath, usdPath, legacyModifier, copyTextures, searchPaths, verbose): if usdStageWithFbxLoaded == False: return None try: fbxConverter = FbxConverter(fbxPath, usdPath, legacyModifier, copyTextures, searchPaths, verbose) return fbxConverter.makeUsdStage() except ConvertError: return None except: raise return None
[ 6738, 279, 87, 81, 1330, 1635, 198, 11748, 28686, 11, 28686, 13, 6978, 198, 11748, 299, 32152, 198, 11748, 302, 198, 11748, 514, 67, 18274, 4487, 198, 11748, 10688, 628, 198, 11748, 848, 198, 198, 385, 67, 29391, 3152, 37, 65, 87, 8...
2.532508
323
# PYTHON STANDARD LIBRARY IMPORTS ---------------------------------------------- from __future__ import absolute_import from __future__ import division # LOCAL MODULE IMPORTS --------------------------------------------------------- from ghautoknit.StoredConstraint import StoredConstraint # ALL LIST --------------------------------------------------------------------- __all__ = [ "EmbeddedConstraint" ] # ACTUAL CLASS ----------------------------------------------------------------- # MAIN ------------------------------------------------------------------------- if __name__ == '__main__': pass
[ 2, 350, 56, 4221, 1340, 49053, 9795, 45651, 49, 13153, 30023, 33002, 20368, 26171, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 2, 37347, 1847, 33893, 30023, 33002, 20368, 22369,...
5.230769
117
import tempfile import pytest from dateutil.relativedelta import relativedelta from django.utils import timezone from django.core.files import File from vr.server import models from vr.server.tests import randurl from vr.common.utils import randchars pytestmark = pytest.mark.usefixtures('postgresql') pytestmark = pytest.mark.usefixtures('gridfs')
[ 11748, 20218, 7753, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 3128, 22602, 13, 2411, 265, 1572, 12514, 1330, 48993, 1572, 12514, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 42625, 14208, 13, 7295, 13, 16624, 1330,...
3.216216
111
from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination
[ 6738, 1334, 62, 30604, 13, 79, 363, 1883, 1330, 27272, 34519, 47, 363, 1883, 11, 7873, 15057, 47, 363, 1883, 628, 628, 198 ]
3.73913
23
import time import json import traceback import numpy as np from statistics import mean from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report # Automatic cleanup of the created graph of this class. def __exit__(self, exc_type, exc_value, tb): if exc_type is not None: traceback.print_exception(exc_type, exc_value, tb)
[ 11748, 640, 201, 198, 11748, 33918, 201, 198, 11748, 12854, 1891, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 7869, 1330, 1612, 201, 198, 6738, 1341, 35720, 1330, 662, 36948, 201, 198, 6738, 1341, 35720, 13, 19849...
2.988024
167
# regression tests with gridders taking w-term into account # some fixed parameters are given in wtermtest_template.in from synthprogrunner import * def analyseResult(spr, checkWeights=True): ''' spr - synthesis program runner (to run imageStats) throws exceptions if something is wrong, otherwise just returns ''' src_offset = 0.006/math.pi*180. psf_peak=[-172.5,-45] true_peak=sinProjection(psf_peak,src_offset,src_offset) stats = spr.imageStats('image.field1.restored') print "Statistics for restored image: ",stats disterr = getDistance(stats,true_peak[0],true_peak[1])*3600. if disterr > 8: raise RuntimeError, "Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak) if abs(stats['peak']-1.)>0.1: raise RuntimeError, "Peak flux in the image is notably different from 1 Jy, F=%f" % stats['peak'] stats = spr.imageStats('image.field1') print "Statistics for modelimage: ",stats disterr = getDistance(stats,true_peak[0],true_peak[1])*3600. if disterr > 8: raise RuntimeError, "Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak) stats = spr.imageStats('psf.field1') print "Statistics for psf image: ",stats disterr = getDistance(stats,psf_peak[0],psf_peak[1])*3600. if disterr > 8: raise RuntimeError, "Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak) stats = spr.imageStats('psf.image.field1') print "Statistics for preconditioned psf image: ",stats disterr = getDistance(stats,psf_peak[0],psf_peak[1])*3600. if disterr > 8: raise RuntimeError, "Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak) if abs(stats['peak']-1.)>0.01: raise RuntimeError, "Peak flux in the preconditioned psf image is notably different from 1.0, F=%f" % stats['peak'] if checkWeights: stats = spr.imageStats('weights.field1') print "Statistics for weight image: ",stats if abs(stats['rms']-stats['peak'])>0.1 or abs(stats['rms']-stats['median'])>0.1 or abs(stats['peak']-stats['median'])>0.1: raise RuntimeError, "Weight image is expected to be constant for WProject and WStack gridders" stats = spr.imageStats('residual.field1') print "Statistics for residual image: ",stats if stats['rms']>0.01 or abs(stats['median'])>0.0001: raise RuntimeError, "Residual image has too high rms or median. Please verify" spr = SynthesisProgramRunner(template_parset = 'wtermtest_template.in') spr.runSimulator() spr.addToParset("Cimager.gridder = WProject") spr.runImager() analyseResult(spr) spr.initParset() spr.addToParset("Cimager.gridder = WStack") spr.runImager() analyseResult(spr) spr.initParset() spr.addToParset("Cimager.gridder = WProject") spr.addToParset("Cimager.gridder.snapshotimaging = true") spr.addToParset("Cimager.gridder.snapshotimaging.wtolerance = 500") spr.runImager() analyseResult(spr,False)
[ 2, 20683, 5254, 351, 1036, 1638, 364, 2263, 266, 12, 4354, 656, 1848, 198, 2, 617, 5969, 10007, 389, 1813, 287, 266, 4354, 9288, 62, 28243, 13, 259, 198, 198, 6738, 33549, 1676, 2164, 403, 1008, 1330, 1635, 198, 198, 4299, 39552, 23...
2.702422
1,156
# -*- coding: utf-8 -*- """ Created on Sun Jun 12 14:21:31 2016 @author: TH """ #%% import polib #%% #old (translated) string #new renamed string pairs=""" An initiative by web designers to inform users about browser-updates An initiative by websites to inform users to update their web browser If you are on a computer that is maintained by an admin and you cannot install a new browser, ask your admin about it. Ask your admin to update your browser if you cannot install updates yourself. blaasdasdfsdaf faselsdfsadf"""; pairs=pairs.replace("\r","")[1:-1].split("\n\n") mappings={s.split("\n")[0]:s.split("\n")[1] for s in pairs} #%% po = polib.pofile('lang/de_DE/LC_MESSAGES/update.po') valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: #print(entry.msgid) if entry.msgid in mappings: print("replacing", entry.msgid[:10], "with",mappings[entry.msgid][:10]) entry.msgid=mappings[entry.msgid] po.save() po.save_as_mofile('lang/de_DE/LC_MESSAGES/update.mo') #%% pairs="""aaa bbb Subtle Unobtrusive bla fasel""" pairs=pairs.replace("\r","")[1:-1].split("\n\n") mappings={s.split("\n")[0]:s.split("\n")[1] for s in pairs} #%% po = polib.pofile('lang/de_DE/LC_MESSAGES/site.po') valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: #print(entry.msgid) if entry.msgid in mappings: print("replacing", entry.msgid[:10], "with",mappings[entry.msgid][:10]) entry.msgid=mappings[entry.msgid] po.save() po.save_as_mofile('lang/de_DE/LC_MESSAGES/site.mo') #%% pot = polib.pofile('lang/update.pot') for entry in pot: print (entry.msgid, entry.msgstr) #%% #%% display old translations po = polib.pofile('lang/de_DE/LC_MESSAGES/update.po') valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: print(entry.msgid) #%% #%% getting files from glob import glob paths = glob('lang/*/LC_MESSAGES/') paths=[p[5:10] for p in paths] paths #%% updating all site.po for p in paths: print("updating %s"%p) try: po = polib.pofile('lang/%s/LC_MESSAGES/site.po'%p) except OSError: print("no file found") continue valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: #print(entry.msgid) if entry.msgid in mappings: print(" ", entry.msgid[:10], "-->",mappings[entry.msgid][:10]) entry.msgid=mappings[entry.msgid] po.save() po.save_as_mofile('lang/%s/LC_MESSAGES/site.mo'%p) #%% updating all update.po for p in paths: print("updating %s"%p) try: po = polib.pofile('lang/%s/LC_MESSAGES/update.po'%p) except OSError: print("no file found") continue valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: #print(entry.msgid) if entry.msgid in mappings: print(" ", entry.msgid[:10], "-->",mappings[entry.msgid][:10]) entry.msgid=mappings[entry.msgid] po.save() po.save_as_mofile('lang/%s/LC_MESSAGES/update.mo'%p) #%% pairs="""aaa bbb Optionally include up to two placeholders "%s" which will be replaced with the browser version and contents of the link tag. Example: "Your browser (%s) is old. Please &lt;a%s&gtupdate&lt;/a&gt;" Optionally include up to two placeholders "%s" which will be replaced with the browser version and contents of the link tag. Example: "Your browser (%s) is old. Please &lt;a%s&gt;update&lt;/a&gt;" bla fasel""" pairs=pairs.replace("\r","")[1:-1].split("\n\n") mappings={s.split("\n")[0]:s.split("\n")[1] for s in pairs} #%% from glob import glob paths = glob('lang/*/LC_MESSAGES/') paths=[p[5:10] for p in paths] paths #%% updating all site.po for p in paths: print("customize %s"%p) try: po = polib.pofile('lang/%s/LC_MESSAGES/customize.po'%p) except OSError: print("no file found") continue valid_entries = [e for e in po if not e.obsolete] for entry in valid_entries: #print(entry.msgid) if entry.msgid in mappings: print(" ", entry.msgid[:10], "-->",mappings[entry.msgid][:10]) entry.msgid=mappings[entry.msgid] po.save() po.save_as_mofile('lang/%s/LC_MESSAGES/customize.mo'%p) #%% extract strings import subprocess subprocess.call(['xgettext', "header.php", "footer.php", "update-browser.php", "--keyword=T_gettext", "--keyword=T_", "--keyword=T_ngettext:1,2", "--from-code=utf-8", "--package-name=browser-update-update", "--language=PHP", "--output=lang/update.pot"]) #%% extract site strings import subprocess subprocess.call(['xgettext', "blog.php", "stat.php", "index.php", "contact.php", "update.testing.php", "--keyword=T_gettext", "--keyword=T_", "--keyword=T_ngettext:1,2", "--from-code=utf-8", "--package-name=browser-update-site", "--language=PHP", "--output=lang/site.pot"]) #%% extract customize strings import subprocess subprocess.call(['xgettext', "customize.php", "--keyword=T_gettext", "--keyword=T_", "--keyword=T_ngettext:1,2", "--from-code=utf-8", "--package-name=browser-update-customize", "--language=PHP", "--output=lang/customize.pot"]) #%% upload new sources for translations import subprocess subprocess.call(['crowdin-cli-py', 'upload', 'sources']) #subprocess.call(['java', '-jar', 'manage\crowdin-cli.jar', 'upload', 'sources','--config','manage\crowdin.yaml']) #subprocess.call(['java', '-jar', 'manage\crowdin-cli.jar', 'upload', 'sources'])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3825, 7653, 1105, 1478, 25, 2481, 25, 3132, 1584, 198, 198, 31, 9800, 25, 2320, 198, 37811, 198, 2, 16626, 198, 11748, 755, 571, 198, 2, 16626,...
2.080867
2,906
# -*- coding:utf-8 -*- """ @File : test_template @Author : Chen @Contact : nonevxx@gmail.com @Date : 2021/1/20 20:09 @Desc : """ # import pytest import requests from time import sleep from api.template_api import TemplateAPI from tools.get_log import GetLog from tools.read_file import read_json import allure # log = GetLog.get_log()
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 31, 8979, 1058, 1332, 62, 28243, 198, 31, 13838, 1058, 12555, 198, 31, 17829, 1058, 4844, 85, 5324, 31, 14816, 13, 785, 198, 31, 10430, 1058, 33448, 14, ...
2.780488
123
# -*- coding: utf-8 -*- import botocore.exceptions import logging import dockerfilegenerator.lib.constants as constants import dockerfilegenerator.lib.exceptions as exceptions import dockerfilegenerator.lib.versions as versions import dockerfilegenerator.lib.jsonstore as jsonstore import dockerfilegenerator.lib.s3store as s3store import dockerfilegenerator.lib.github as github logger = logging.getLogger() TRACKED_TOOLS = { "terraform": versions.get_latest_hashicorp_terraform_version, "packer": versions.get_latest_hashicorp_packer_version, "go": versions.get_latest_golango_go_version } class DockerfileGeneratorLambda(UtilsMixin):
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 10214, 420, 382, 13, 1069, 11755, 198, 11748, 18931, 198, 198, 11748, 36253, 7753, 8612, 1352, 13, 8019, 13, 9979, 1187, 355, 38491, 198, 11748, 36253, 7753, ...
3.041667
216
from django.conf.urls import patterns, url from main import views urlpatterns = patterns('', url(r'^$', views.inicio, name='inicio'), url(r'^acerca/', views.acerca, name='acerca'), url(r'^contacto/', views.contacto, name='contacto'), url(r'^autenticar/', views.autenticar, name='autenticar'), url(r'^cerrar_sesion/', views.cerrar_sesion, name='cerrar_sesion'), url(r'^tiempo/', views.tiempo, name='tiempo'), url(r'^perfil/(?P<usuario>\d+)/$', views.perfil, name='perfil'), url(r'^imprimir_ajuste/', views.imprimir_ajuste, name='imprimir_ajuste'), url(r'^imprimir_ajusteId/(?P<ajusteEstudianteId>\d+)/$', views.imprimir_ajusteId, name='imprimir_ajusteId'), url(r'^imprimir_expediente/', views.imprimir_expediente, name='imprimir_expediente'), url(r'^imprimir_expedienteId/(?P<expedienteEstudianteId>\d+)/$', views.imprimir_expedienteId, name='imprimir_expedienteId'), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 19016, 198, 198, 6738, 1388, 1330, 5009, 628, 198, 6371, 33279, 82, 796, 7572, 10786, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
1.723684
684
# -*- coding: utf-8 -*- """ Simblin Test Views ~~~~~~~~~~~~~~~~~~ Test the different views of the blogging application. :copyright: (c) 2010 by Eugen Kiss. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import datetime import flask from simblin.extensions import db from simblin.models import Post, Tag, Category, post_tags, post_categories, Admin from nose.tools import assert_equal, assert_true, assert_false from test import TestCase
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 3184, 2436, 259, 6208, 29978, 198, 220, 220, 220, 220, 27156, 4907, 628, 220, 220, 220, 6208, 262, 1180, 5009, 286, 262, 38310, 3586, 13, 62...
2.726368
201
# coding: utf-8 """ FreeClimb API FreeClimb is a cloud-based application programming interface (API) that puts the power of the Vail platform in your hands. FreeClimb simplifies the process of creating applications that can use a full range of telephony features without requiring specialized or on-site telephony equipment. Using the FreeClimb REST API to write applications is easy! You have the option to use the language of your choice or hit the API directly. Your application can execute a command by issuing a RESTful request to the FreeClimb API. The base URL to send HTTP requests to the FreeClimb REST API is: /apiserver. FreeClimb authenticates and processes your request. # noqa: E501 The version of the OpenAPI document: 1.0.0 Contact: support@freeclimb.com Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from freeclimb.configuration import Configuration def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, MessageResult): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, MessageResult): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 3232, 34, 2475, 65, 7824, 628, 220, 220, 220, 3232, 34, 2475, 65, 318, 257, 6279, 12, 3106, 3586, 8300, 7071, 357, 17614, 8, 326, 7584, 262, 1176, 286, 262, 56...
3.05973
519
from django.shortcuts import render from .models import Post
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 764, 27530, 1330, 2947, 628, 198 ]
3.9375
16
utils = struct( resolve_stamp = _resolve_stamp, check_stamping_format = _check_stamping_format, )
[ 198, 26791, 796, 2878, 7, 198, 220, 220, 220, 10568, 62, 301, 696, 796, 4808, 411, 6442, 62, 301, 696, 11, 198, 220, 220, 220, 2198, 62, 301, 37843, 62, 18982, 796, 4808, 9122, 62, 301, 37843, 62, 18982, 11, 198, 8, 198 ]
2.488372
43
from config import Config import flask import json import os from ssdp import SSDP from threading import Thread import urllib3 config = None config_file_paths = [ os.path.dirname(os.path.realpath(__file__)) + "/config/default.cfg.local", "/etc/hue-adapter/default.cfg.local", ] for config_file_path in config_file_paths: if os.path.isfile(config_file_path): config = Config(file(config_file_path)) if not config: print "Cannot find configuration file" exit(1) app = flask.Flask(__name__) if __name__ == "__main__": ssdp = SSDP(config.web.addr, config.web.port) ssdp_thread = Thread(target=ssdp.run) ssdp_thread.setDaemon(True) ssdp_thread.start() app.run(host=config.web.addr, port=config.web.port)
[ 6738, 4566, 1330, 17056, 198, 11748, 42903, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 264, 21282, 79, 1330, 6723, 6322, 198, 6738, 4704, 278, 1330, 14122, 198, 11748, 2956, 297, 571, 18, 198, 198, 11250, 796, 6045, 198, 198, 1125...
2.504983
301
from kdbush import KDBush # test data points = [ [54,1],[97,21],[65,35],[33,54],[95,39],[54,3],[53,54],[84,72],[33,34],[43,15],[52,83],[81,23],[1,61],[38,74], [11,91],[24,56],[90,31],[25,57],[46,61],[29,69],[49,60],[4,98],[71,15],[60,25],[38,84],[52,38],[94,51],[13,25], [77,73],[88,87],[6,27],[58,22],[53,28],[27,91],[96,98],[93,14],[22,93],[45,94],[18,28],[35,15],[19,81],[20,81], [67,53],[43,3],[47,66],[48,34],[46,12],[32,38],[43,12],[39,94],[88,62],[66,14],[84,30],[72,81],[41,92],[26,4], [6,76],[47,21],[57,70],[71,82],[50,68],[96,18],[40,31],[78,53],[71,90],[32,14],[55,6],[32,88],[62,32],[21,67], [73,81],[44,64],[29,50],[70,5],[6,22],[68,3],[11,23],[20,42],[21,73],[63,86],[9,40],[99,2],[99,76],[56,77], [83,6],[21,72],[78,30],[75,53],[41,11],[95,20],[30,38],[96,82],[65,48],[33,18],[87,28],[10,10],[40,34], [10,20],[47,29],[46,78]] ids = [ 97, 74, 95, 30, 77, 38, 76, 27, 80, 55, 72, 90, 88, 48, 43, 46, 65, 39, 62, 93, 9, 96, 47, 8, 3, 12, 15, 14, 21, 41, 36, 40, 69, 56, 85, 78, 17, 71, 44, 19, 18, 13, 99, 24, 67, 33, 37, 49, 54, 57, 98, 45, 23, 31, 66, 68, 0, 32, 5, 51, 75, 73, 84, 35, 81, 22, 61, 89, 1, 11, 86, 52, 94, 16, 2, 6, 25, 92, 42, 20, 60, 58, 83, 79, 64, 10, 59, 53, 26, 87, 4, 63, 50, 7, 28, 82, 70, 29, 34, 91] coords = [ 10,20,6,22,10,10,6,27,20,42,18,28,11,23,13,25,9,40,26,4,29,50,30,38,41,11,43,12,43,3,46,12,32,14,35,15,40,31,33,18, 43,15,40,34,32,38,33,34,33,54,1,61,24,56,11,91,4,98,20,81,22,93,19,81,21,67,6,76,21,72,21,73,25,57,44,64,47,66,29, 69,46,61,38,74,46,78,38,84,32,88,27,91,45,94,39,94,41,92,47,21,47,29,48,34,60,25,58,22,55,6,62,32,54,1,53,28,54,3, 66,14,68,3,70,5,83,6,93,14,99,2,71,15,96,18,95,20,97,21,81,23,78,30,84,30,87,28,90,31,65,35,53,54,52,38,65,48,67, 53,49,60,50,68,57,70,56,77,63,86,71,90,52,83,71,82,72,81,94,51,75,53,95,39,78,53,88,62,84,72,77,73,99,76,73,81,88, 87,96,98,96,82] index = KDBush(points) result = index.range(20, 30, 50, 70) print(result) # [60, 20, 45, 3, 17, 71, 44, 19, 18, 15, 69, 90, 62, 96, 47, 8, 77, 72] for id in result: p = points[id] if p[0] < 20 or p[0] > 50 or p[1] < 30 or p[1] > 70: print("FAIL") for id in result: p = points[id] if id not in result and p[0] >= 20 and p[0] <= 50 and p[1] >= 30 and p[1] <= 70: print("FAIL: outside point not in range") index2 = KDBush(points) qp = [50, 50] r = 20 r2 = 20 * 20 result = index.within(qp[0], qp[1], r) print(result) # [60, 6, 25, 92, 42, 20, 45, 3, 71, 44, 18, 96] for id in result: p = points[id] if (sqDist2(p, qp) > r2): print('FAIL: result point in range') for id in result: p = points[id] if (id not in result and sqDist2(p, qp) <= r2): print('FAIL: result point not in range')
[ 6738, 479, 9945, 1530, 1330, 509, 11012, 1530, 198, 2, 1332, 1366, 198, 13033, 796, 685, 198, 220, 220, 220, 685, 4051, 11, 16, 38430, 5607, 11, 2481, 38430, 2996, 11, 2327, 38430, 2091, 11, 4051, 38430, 3865, 11, 2670, 38430, 4051, ...
1.855397
1,473
#!/usr/bin/env python3 # Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import logging import os import subprocess import platform from constants import BUCKCONFIG_LOCAL from configure_buck import update_config def configure_compiler(project_root): """ Sets up .buckconfig.local in the root project with basic c++/c compiler settings. More advanced probing will probably be done in the future """ buckconfig_local = os.path.join(project_root, BUCKCONFIG_LOCAL) logging.info("{bold}Detecting compiler{clear}") current_platform = get_current_platform_flavor() cc = detect_cc() cxx = detect_cxx() if not cc or not cxx: logging.warn("Could not find clang or g++ in PATH") return 0 c_standard = detect_c_standard(cc) if c_standard: cflags = [c_standard] else: cflags = [] cxx_standard = detect_cxx_standard(cxx) if cxx_standard: cxxflags = [cxx_standard] else: cxxflags = [] py2 = detect_py2() py3 = detect_py3() py2_include = detect_python_include(py2) py2_libs = detect_python_libs(py2) py3_include = detect_python_include(py3) py3_libs = detect_python_libs(py3) to_set = { 'cxx': { 'cflags': cflags + ['-pthread', '-g'], 'cxxflags': cxxflags + ['-pthread', '-g'], 'ldflags': ['-pthread'], 'cxx': [cxx], 'cc': [cc], }, } to_set['cxx#' + current_platform] = to_set['cxx'].copy() to_set['cxx']['default_platform'] = current_platform py2_settings = { 'interpreter': py2, 'includes': py2_include, 'libs': py2_libs, } py3_settings = { 'interpreter': py3, 'includes': py3_include, 'libs': py3_libs, } if py2: to_set['python#py2'] = py2_settings to_set['python#py2-%s' % current_platform] = py2_settings if py3: to_set['python#py3'] = py3_settings to_set['python#py3-%s' % current_platform] = py3_settings to_set['buckit'] = {'system_lib_paths': ','.join(get_system_lib_paths())} update_config(project_root, buckconfig_local, to_set) return 0
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 1584, 12, 25579, 11, 3203, 11, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 12, 7635, 5964, 1043, ...
2.314448
1,059
#!/usr/bin/env python3 """ Contains testcases for the individual examination. """ import unittest from io import StringIO import os import sys from unittest.mock import patch from examiner import ExamTestCase, ExamTestResult, tags from examiner import import_module, find_path_to_assignment FILE_DIR = os.path.dirname(os.path.realpath(__file__)) REPO_PATH = find_path_to_assignment(FILE_DIR) if REPO_PATH not in sys.path: sys.path.insert(0, REPO_PATH) # Path to file and basename of the file to import main = import_module(REPO_PATH, "main") if __name__ == '__main__': runner = unittest.TextTestRunner(resultclass=ExamTestResult, verbosity=2) unittest.main(testRunner=runner, exit=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 4264, 1299, 1332, 33964, 329, 262, 1981, 12452, 13, 198, 37811, 198, 11748, 555, 715, 395, 198, 6738, 33245, 1330, 10903, 9399, 198, 11748, 28686, 198, 11748, 25064, 198,...
2.910931
247
from django.contrib import admin from olha_boca.infratores.models import Infratores # Register your models here. admin.site.register(Infratores, InfratoresAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 25776, 3099, 62, 65, 11216, 13, 259, 8310, 265, 2850, 13, 27530, 1330, 4806, 10366, 2850, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 198, 28482, 13, 15654, 13, 30238, 7, 8...
3.134615
52
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import functools import torch.nn as nn from torch.nn import init import torch.functional as F from torch.autograd import Variable print('ok') print ('kkk') # class te(nn.Module): # def __init__(self): # super(te,self).__init__() # norm_layer=nn.InstanceNorm2d # kw = 4 # padw = 1 # input_nc=3 # n_layers=3 # ndf=64 # use_bias = False # sequence = [ # nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), # nn.LeakyReLU(0.2, True) # ] # # nf_mult = 1 # nf_mult_prev = 1 # for n in range(1, n_layers): # nf_mult_prev = nf_mult # nf_mult = min(2**n, 8) # sequence += [ # nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, # kernel_size=kw, stride=2, padding=padw, bias=use_bias), # norm_layer(ndf * nf_mult), # nn.LeakyReLU(0.2, True) # ] # # nf_mult_prev = nf_mult # nf_mult = min(2**n_layers, 8) # sequence += [ # nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, # kernel_size=kw, stride=1, padding=padw, bias=use_bias), # norm_layer(ndf * nf_mult), # nn.LeakyReLU(0.2, True) # ] # # sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # # self.model1 = nn.Sequential(*sequence) # def forward(self,x): # return self.model1(x)
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 28034, 198, 11748, 1257, 310, 10141, 198, 11748, 28034, 13, 20471, 355, 299, 77, 1...
1.766206
941
# Generated by Django 2.0.13 on 2019-06-27 17:04 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 1485, 319, 13130, 12, 3312, 12, 1983, 1596, 25, 3023, 198, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 7353, 34239, 13, 25747, 13, 17752, 65, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720...
2.864407
59
__author__ = "Rob MacKinnon <rome@villagertech.com>" __package__ = "DOMObjects" __name__ = "DOMObjects.schema" __license__ = "MIT"
[ 834, 9800, 834, 796, 366, 14350, 4100, 42, 45067, 1279, 5998, 31, 41082, 3536, 13670, 13, 785, 24618, 198, 834, 26495, 834, 796, 366, 39170, 10267, 82, 1, 198, 834, 3672, 834, 796, 366, 39170, 10267, 82, 13, 15952, 2611, 1, 198, 834...
2.64
50
# https://www.codewars.com/kata/detect-pangram/train/python # My solution import string # ... import string # ... import string
[ 2, 3740, 1378, 2503, 13, 19815, 413, 945, 13, 785, 14, 74, 1045, 14, 15255, 478, 12, 79, 648, 859, 14, 27432, 14, 29412, 201, 198, 2, 2011, 4610, 201, 198, 11748, 4731, 201, 198, 201, 198, 2, 2644, 201, 198, 11748, 4731, 201, 19...
2.473684
57
import FWCore.ParameterSet.Config as cms
[ 198, 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 628, 628 ]
3.214286
14
""" 1375. Substring With At Least K Distinct Characters """
[ 37811, 198, 1485, 2425, 13, 3834, 8841, 2080, 1629, 1004, 459, 509, 4307, 4612, 26813, 198, 37811, 198 ]
3.333333
18
people = 20 cats = 30 dogs = 15 if people < cats: print(" ! !") if people > cats: print(" ! !") if people < dogs: print(" !") if people > dogs: print(" !") dogs += 5 if people >= dogs: print(" ") if people <= dogs: print(" .") if people == dogs: print(" .")
[ 15332, 796, 1160, 198, 24619, 796, 1542, 198, 22242, 796, 1315, 628, 198, 361, 661, 1279, 11875, 25, 198, 220, 220, 220, 3601, 7203, 220, 5145, 220, 220, 2474, 8, 198, 198, 361, 661, 1875, 11875, 25, 198, 220, 220, 220, 3601, 7203, ...
2.233577
137
""" Tests for the import manager. """ from traits.util.api import import_symbol from traits.testing.unittest_tools import unittest if __name__ == "__main__": unittest.main() #### EOF ######################################################################
[ 37811, 30307, 329, 262, 1330, 4706, 13, 37227, 628, 198, 6738, 12796, 13, 22602, 13, 15042, 1330, 1330, 62, 1837, 23650, 198, 6738, 12796, 13, 33407, 13, 403, 715, 395, 62, 31391, 1330, 555, 715, 395, 628, 198, 198, 361, 11593, 3672, ...
3.771429
70
# ################ A simple graphical interface which communicates with the server ##################################### from tkinter import * import socket import face import cubie # ################################## some global variables and constants ############################################### DEFAULT_HOST = 'localhost' DEFAULT_PORT = '8080' width = 60 # width of a facelet in pixels facelet_id = [[[0 for col in range(3)] for row in range(3)] for face in range(6)] colorpick_id = [0 for i in range(6)] curcol = None t = ("U", "R", "F", "D", "L", "B") cols = ("yellow", "green", "red", "white", "blue", "orange") ######################################################################################################################## # ################################################ Diverse functions ################################################### def show_text(txt): """Displays messages.""" print(txt) display.insert(INSERT, txt) root.update_idletasks() def create_facelet_rects(a): """Initializes the facelet grid on the canvas.""" offset = ((1, 0), (2, 1), (1, 1), (1, 2), (0, 1), (3, 1)) for f in range(6): for row in range(3): y = 10 + offset[f][1] * 3 * a + row * a for col in range(3): x = 10 + offset[f][0] * 3 * a + col * a facelet_id[f][row][col] = canvas.create_rectangle(x, y, x + a, y + a, fill="grey") if row == 1 and col == 1: canvas.create_text(x + width // 2, y + width // 2, font=("", 14), text=t[f], state=DISABLED) for f in range(6): canvas.itemconfig(facelet_id[f][1][1], fill=cols[f]) def create_colorpick_rects(a): """Initializes the "paintbox" on the canvas""" global curcol global cols for i in range(6): x = (i % 3)*(a+5) + 7*a y = (i // 3)*(a+5) + 7*a colorpick_id[i] = canvas.create_rectangle(x, y, x + a, y + a, fill=cols[i]) canvas.itemconfig(colorpick_id[0], width=4) curcol = cols[0] def get_definition_string(): """Generates the cube definition string from the facelet colors.""" color_to_facelet = {} for i in range(6): color_to_facelet.update({canvas.itemcget(facelet_id[i][1][1], "fill"): t[i]}) s = '' for f in range(6): for row in range(3): for col in range(3): s += color_to_facelet[canvas.itemcget(facelet_id[f][row][col], "fill")] return s ######################################################################################################################## # ############################### Solve the displayed cube with a local or remote server ############################### def solve(): """Connects to the server and returns the solving maneuver.""" display.delete(1.0, END) # clear output window try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: show_text('Failed to create socket') return # host = 'f9f0b2jt6zmzyo6b.myfritz.net' # my RaspberryPi, if online host = txt_host.get(1.0, END).rstrip() # default is localhost port = int(txt_port.get(1.0, END)) # default is port 8080 try: remote_ip = socket.gethostbyname(host) except socket.gaierror: show_text('Hostname could not be resolved.') return try: s.connect((remote_ip, port)) except: show_text('Cannot connect to server!') return show_text('Connected with ' + remote_ip + '\n') try: defstr = get_definition_string()+'\n' except: show_text('Invalid facelet configuration.\nWrong or missing colors.') return show_text(defstr) try: s.sendall((defstr+'\n').encode()) except: show_text('Cannot send cube configuration to server.') return show_text(s.recv(2048).decode()) ######################################################################################################################## # ################################# Functions to change the facelet colors ############################################# def clean(): """Restores the cube to a clean cube.""" for f in range(6): for row in range(3): for col in range(3): canvas.itemconfig(facelet_id[f][row][col], fill=canvas.itemcget(facelet_id[f][1][1], "fill")) def empty(): """Removes the facelet colors except the center facelets colors.""" for f in range(6): for row in range(3): for col in range(3): if row != 1 or col != 1: canvas.itemconfig(facelet_id[f][row][col], fill="grey") def random(): """Generates a random cube and sets the corresponding facelet colors.""" cc = cubie.CubieCube() cc.randomize() fc = cc.to_facelet_cube() idx = 0 for f in range(6): for row in range(3): for col in range(3): canvas.itemconfig(facelet_id[f][row][col], fill=cols[fc.f[idx]] ) idx += 1 ######################################################################################################################## # ################################### Edit the facelet colors ########################################################## def click(event): """Defines how to react on left mouse clicks""" global curcol idlist = canvas.find_withtag("current") if len(idlist) > 0: if idlist[0] in colorpick_id: curcol = canvas.itemcget("current", "fill") for i in range(6): canvas.itemconfig(colorpick_id[i], width=1) canvas.itemconfig("current", width=5) else: canvas.itemconfig("current", fill=curcol) ######################################################################################################################## # ###################################### Generate and display the TK_widgets ########################################## root = Tk() root.wm_title("Solver Client") canvas = Canvas(root, width=12 * width + 20, height=9 * width + 20) canvas.pack() bsolve = Button(text="Solve", height=2, width=10, relief=RAISED, command=solve) bsolve_window = canvas.create_window(10 + 10.5 * width, 10 + 6.5 * width, anchor=NW, window=bsolve) bclean = Button(text="Clean", height=1, width=10, relief=RAISED, command=clean) bclean_window = canvas.create_window(10 + 10.5 * width, 10 + 7.5 * width, anchor=NW, window=bclean) bempty = Button(text="Empty", height=1, width=10, relief=RAISED, command=empty) bempty_window = canvas.create_window(10 + 10.5 * width, 10 + 8 * width, anchor=NW, window=bempty) brandom = Button(text="Random", height=1, width=10, relief=RAISED, command=random) brandom_window = canvas.create_window(10 + 10.5 * width, 10 + 8.5 * width, anchor=NW, window=brandom) display = Text(height=7, width=39) text_window = canvas.create_window(10 + 6.5 * width, 10 + .5 * width, anchor=NW, window=display) hp = Label(text=' Hostname and Port') hp_window = canvas.create_window(10 + 0 * width, 10 + 0.6 * width, anchor=NW, window=hp) txt_host = Text(height=1, width=20) txt_host_window = canvas.create_window(10 + 0 * width, 10 + 1 * width, anchor=NW, window=txt_host) txt_host.insert(INSERT, DEFAULT_HOST) txt_port = Text(height=1, width=20) txt_port_window = canvas.create_window(10 + 0 * width, 10 + 1.5 * width, anchor=NW, window=txt_port) txt_port.insert(INSERT, DEFAULT_PORT) canvas.bind("<Button-1>", click) create_facelet_rects(width) create_colorpick_rects(width) root.mainloop() ########################################################################################################################
[ 2, 1303, 7804, 4242, 21017, 317, 2829, 27831, 7071, 543, 48556, 351, 262, 4382, 1303, 29113, 4242, 198, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 11748, 17802, 198, 11748, 1986, 198, 11748, 13617, 494, 628, 198, 2, 1303, 29113, 2, 61...
2.716102
2,832
"""Abstraction layer to deal with Django related changes in order to keep compatibility with several Django versions simultaneously.""" from __future__ import unicode_literals from django.conf import settings as django_settings USER_MODEL = getattr(django_settings, 'AUTH_USER_MODEL', 'auth.User') # Django 1.11 Widget.build_attrs has a different signature, designed for the new # template based rendering. The previous version was more useful for our needs, # so we restore that version. # When support for Django < 1.11 is dropped, we should look at using the # new template based rendering, at which point this probably won't be needed at all. try: # Python 3 from urllib.parse import urljoin # noqa except ImportError: # Python 2 from urlparse import urljoin # noqa @UnusedImport
[ 37811, 4826, 301, 7861, 7679, 284, 1730, 351, 37770, 3519, 2458, 287, 1502, 284, 1394, 198, 5589, 25901, 351, 1811, 37770, 6300, 11640, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, ...
3.623318
223
""" ethereum.py ethereum.py contains an EthereumClient class that provides functions for interacting with the Coverage.sol solidity contract on an Ethereum blockchain network. """ import asyncio import datetime import json import logging import os from ethereum.clients.nats import get_nats_client from ethereum.config import get_settings, nats_eligibility_subject from ethereum.exceptions import EthereumNetworkConnectionError from hexbytes import HexBytes from typing import Optional, Any, List from web3 import Web3 logger = logging.getLogger(__name__) # client instance eth_client = None def get_ethereum_client() -> Optional[EthereumClient]: """ :return: a connected EthereumClient instance """ global eth_client if not eth_client: settings = get_settings() # load ABI file abi_file: str = os.path.join(settings.ethereum_config_directory, settings.ethereum_contract_abi) contract_info = json.load(open(abi_file)) eth_client = EthereumClient( eth_network_uri=settings.ethereum_network_uri, contract_address=settings.ethereum_contract_address, contract_abi=contract_info["abi"], event_poll_interval=settings.ethereum_event_poll_seconds ) return eth_client
[ 37811, 198, 316, 1456, 388, 13, 9078, 198, 198, 316, 1456, 388, 13, 9078, 4909, 281, 20313, 11792, 1398, 326, 3769, 5499, 329, 24986, 198, 4480, 262, 33998, 13, 34453, 4735, 414, 2775, 319, 281, 20313, 11779, 3127, 13, 198, 37811, 198...
2.909707
443
from argparse import Namespace from .action import Action from symengine.lib.symengine_wrapper import sympify from termcolor import colored from program.mc_comb_finder import MCCombFinder from cli.common import prepare_program
[ 6738, 1822, 29572, 1330, 28531, 10223, 198, 6738, 764, 2673, 1330, 7561, 198, 6738, 5659, 18392, 13, 8019, 13, 37047, 18392, 62, 48553, 1330, 10558, 1958, 198, 6738, 3381, 8043, 1330, 16396, 198, 6738, 1430, 13, 23209, 62, 24011, 62, 22...
3.931034
58
import gunicorn accesslog = "-" errorlog = "-" access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Forwarded-For}i)s"' capture_output = True forwarded_allow_ips = "*" secure_scheme_headers = {"X-CLOUDFRONT": "yes"} workers = 2 worker_class = "gthread" worker_connections = 5 bind = ":8000" keep_alive = 75 chdir = "/madewithwagtail" # Obfuscate the Server header (to the md5sum of "Springload") gunicorn.SERVER_SOFTWARE = "04e96149a2f64d6135c82d199ab62122"
[ 11748, 2485, 291, 1211, 198, 198, 15526, 6404, 796, 366, 21215, 198, 18224, 6404, 796, 366, 21215, 198, 15526, 62, 6404, 62, 18982, 796, 705, 4, 7, 71, 8, 82, 4064, 7, 75, 8, 82, 4064, 7, 84, 8, 82, 4064, 7, 83, 8, 82, 36521, ...
2.225225
222
# -- encoding:utf-8 -- # ''' Crie uma varivel com a string instituto de cincias matemticas e de computao e faa: a. Concatene (adicione) uma outra string chamada usp b. Concatene (adicione) uma outra informao: 2021 c. Verifique o tamanho da nova string (com as informaes adicionadas das questes a e b), com referncia a caracteres e espaos d. Transforme a string inteiramente em maisculo e. Transforme a string inteiramente em minsculo f. Retire o espao que est no incio da string e imprima a string g. Substitua todas as letras a por x h. Separe a string em palavras nicas i. Verifique quantas palavras existem na string j. Separe a string por meio da palavra de k. Verifique agora quantas palavras/frases foram formadas quando houve a separao pela palavra de l. Junte as palavras que foram separadas (pode usar a separao resultante da questo h ou j) m. Junte as palavras que foram separadas, mas agora separadas por uma barra invertida, no por espaos (pode usar a separao resultante da questo h ou j) ''' texto = " instituto de cincias matemticas e de computao" #a) texto = texto + " usp" print(texto) #b) texto = texto + " 2021" print(texto) #c) tamanho = len(texto) print(tamanho) #d) print(texto.upper()) #e) print(texto.lower()) #f) print(texto[1:]) print(texto.strip()) #g) print(texto.replace('a', 'x')) #h separar = texto.split() print(separar) #i) print(separar) #j) separar2 = texto.split('de') print(separar2) #k) print(len(separar2)) #l) juntar = " ".join(separar) print(juntar) #m) juntar2 = "/".join(separar) print(juntar2)
[ 2, 1377, 21004, 25, 40477, 12, 23, 1377, 1303, 198, 7061, 6, 198, 34, 5034, 334, 2611, 1401, 425, 75, 401, 257, 4731, 220, 6113, 9390, 390, 269, 259, 979, 292, 2603, 368, 13370, 292, 304, 390, 2653, 5488, 304, 277, 7252, 25, 198, ...
2.473684
627
# -*- coding: utf-8 -*- from django.shortcuts import resolve_url from django.template.loader import render_to_string from django_jinja import library from jinja2 import contextfunction
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 10568, 62, 6371, 198, 6738, 42625, 14208, 13, 28243, 13, 29356, 1330, 8543, 62, 1462, 62, 8841, 198, 6738, 42625, 14208, 62, ...
3.224138
58
import platform import requests
[ 11748, 3859, 198, 198, 11748, 7007, 628 ]
4.857143
7
from typing import List
[ 6738, 19720, 1330, 7343, 628 ]
5
5
import torchvision import torch import torch.nn as nn import torch.nn.functional as F if __name__ == "__main__": net = Vgg_Deeplab(3, 10) in_ten = torch.randn(1, 3, 224, 224) out = net(in_ten) print(net) print(out.size()) in_ten = torch.randn(1, 3, 64, 64) mod = nn.Conv2d(3, 512, kernel_size=3, stride=1, padding=2, dilation=2) out = mod(in_ten) print(out.shape)
[ 11748, 28034, 10178, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 2010, 7...
1.762238
286
# -*- coding: utf-8 -*- """ This module defines a connexion app object and configures the API endpoints based the swagger.yml configuration file. copyright: 2019 by Erik R Berlin. license: MIT, see LICENSE for more details. """ import connexion app = connexion.App(__name__, specification_dir="./") app.app.url_map.strict_slashes = False app.add_api("swagger.yml") if __name__ == "__main__": # FLASK_ENV=development & FLASK_DEBUG=1 w/ Docker don't seem to enable debug mode. app.run(debug=True)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 8265, 15738, 257, 369, 12413, 295, 598, 2134, 290, 4566, 942, 262, 7824, 198, 437, 13033, 1912, 262, 1509, 7928, 13, 88, 4029, 8398, 2393, 13, 198, 1...
2.781421
183
# -*- coding: utf-8 -*- """ 17 June 2020 Author: Xiandi Ooi Visualizing the types of pollutants. """ import pandas as pd from plotly.offline import plot import plotly.graph_objects as go # Get the file from us df = pd.read_csv(https://www.dropbox.com/s/u0ymg0ufne0an60/api-20200713.csv?dl=1", sep = ";") # Make the selection selected_area = "Sandakan" df_select = df.loc[(df.Area == selected_area), ["Area", "Dominant", "Datetime"]] # Data wrangling for this particular visual df_update = df_select.set_index(pd.DatetimeIndex(df_select["Datetime"])) df_update.drop(df_update.columns[2], axis = 1, inplace = True) # Wrangling df_group_time = df_update.groupby(pd.Grouper(freq = "Q")).size().reset_index(name = "Total") df_group = df_update.groupby([pd.Grouper(freq = "Q"), pd.Grouper("Dominant")]).size().reset_index(name = "Count") df_output = df_group.set_index("Datetime").join(df_group_time.set_index("Datetime")) df_output["Frequency"] = df_output["Count"] / df_output["Total"] # Creating df subset for the stacked bars, here we are only dealing with the main dominant pollutants df_pm2_5 = df_output.loc[(df_output.Dominant == "**")] df_pm10 = df_output.loc[(df_output.Dominant == "*")] df_so2 = df_output.loc[(df_output.Dominant == "a")] df_no2 = df_output.loc[(df_output.Dominant == "b")] df_o3 = df_output.loc[(df_output.Dominant == "c")] df_co = df_output.loc[(df_output.Dominant == "d")] # Now comes the bar chart fig = go.Figure() fig.add_trace(go.Bar(x = df_pm2_5.index, y = df_pm2_5["Frequency"], name = "PM 2.5")) fig.add_trace(go.Bar(x = df_pm10.index, y = df_pm10["Frequency"], name = "PM 10")) fig.add_trace(go.Bar(x = df_so2.index, y = df_so2["Frequency"], name = "SO2")) fig.add_trace(go.Bar(x = df_no2.index, y = df_no2["Frequency"], name = "NO2")) fig.add_trace(go.Bar(x = df_o3.index, y = df_o3["Frequency"], name = "O3")) fig.add_trace(go.Bar(x = df_co.index, y = df_co["Frequency"], name = "CO")) fig.update_layout(barmode = "stack", title_text="Frequency of Detected Pollutants") plot(fig)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1558, 2795, 12131, 198, 13838, 25, 21313, 26800, 440, 23013, 198, 36259, 2890, 262, 3858, 286, 41824, 13, 198, 220, 198, 37811, 198, 198, 11748, 19798, 292, ...
2.088314
1,121
from django import forms from django.test import TestCase from template_forms import bs3
[ 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 11055, 62, 23914, 1330, 275, 82, 18, 628, 628, 198 ]
3.392857
28
""" Copyright 2017 BlazeMeter Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import json import os import shutil import subprocess import time from os import listdir from os.path import join from bzt import ToolError, TaurusConfigError from bzt.engine import HavingInstallableTools, Scenario from bzt.modules import SubprocessedExecutor from bzt.utils import get_full_path, shell_exec, TclLibrary, JavaVM, RequiredTool, MirrorsManager SELENIUM_DOWNLOAD_LINK = "http://selenium-release.storage.googleapis.com/3.6/" \ "selenium-server-standalone-3.6.0.jar" SELENIUM_VERSION = "3.6" # FIXME: unused, remove it JUNIT_DOWNLOAD_LINK = "http://search.maven.org/remotecontent?filepath=junit/junit/" \ "{version}/junit-{version}.jar" JUNIT_VERSION = "4.12" JUNIT_MIRRORS_SOURCE = "http://search.maven.org/solrsearch/select?q=g%3A%22junit%22%20AND%20a%3A%22" \ "junit%22%20AND%20v%3A%22{version}%22&rows=20&wt=json".format(version=JUNIT_VERSION) TESTNG_VERSION = "6.8.5" TESTNG_DOWNLOAD_LINK = "http://search.maven.org/remotecontent?filepath=org/testng/testng/" \ "{version}/testng-{version}.jar".format(version=TESTNG_VERSION) HAMCREST_DOWNLOAD_LINK = "http://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core" \ "/1.3/hamcrest-core-1.3.jar" JSON_JAR_DOWNLOAD_LINK = "http://search.maven.org/remotecontent?filepath=org/json/json/20160810/json-20160810.jar"
[ 37811, 198, 15269, 2177, 33965, 44, 2357, 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, 11846, 351, 262, 13789, 13, 198,...
2.542199
782
""" Maybe not so relevant in Python due to the possibility to use multiple inheritance... """ from abc import ABC, abstractmethod if __name__ == "__main__": amazon = Amazon() dropbox = Dropbox() amazon.get_file("Baba") dropbox.store_file("Baba")
[ 37811, 198, 13300, 407, 523, 5981, 287, 11361, 2233, 284, 262, 5885, 284, 779, 3294, 24155, 986, 198, 37811, 198, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 628, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417,...
2.967033
91
# MIT License # # Copyright The SCons Foundation # # 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. """Variable type for package Variables. To be used whenever a 'package' may be enabled/disabled and the package path may be specified. Given these options :: x11=no (disables X11 support) x11=yes (will search for the package installation dir) x11=/usr/local/X11 (will check this path for existence) Can be used as a replacement for autoconf's ``--with-xxx=yyy`` :: opts = Variables() opts.Add( PackageVariable( key='x11', help='use X11 installed here (yes = search some places)', default='yes' ) ) ... if env['x11'] == True: dir = ... # search X11 in some standard places ... env['x11'] = dir if env['x11']: ... # build with x11 ... """ from typing import Tuple, Callable import SCons.Errors __all__ = ['PackageVariable',] ENABLE_STRINGS = ('1', 'yes', 'true', 'on', 'enable', 'search') DISABLE_STRINGS = ('0', 'no', 'false', 'off', 'disable') def _converter(val): """ """ lval = val.lower() if lval in ENABLE_STRINGS: return True if lval in DISABLE_STRINGS: return False return val def _validator(key, val, env, searchfunc) -> None: """ """ # NB: searchfunc is currently undocumented and unsupported # TODO write validator, check for path import os if env[key] is True: if searchfunc: env[key] = searchfunc(key, val) elif env[key] and not os.path.exists(val): raise SCons.Errors.UserError( 'Path does not exist for option %s: %s' % (key, val)) def PackageVariable(key, help, default, searchfunc=None) -> Tuple[str, str, str, Callable, Callable]: """Return a tuple describing a package list SCons Variable. The input parameters describe a 'package list' option. Returns a tuple including the correct converter and validator appended. The result is usable as input to :meth:`Add` . A 'package list' option may either be 'all', 'none' or a pathname string. This information is appended to *help*. """ # NB: searchfunc is currently undocumented and unsupported help = '\n '.join( (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, lambda k, v, e: _validator(k, v, e, searchfunc), _converter) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 383, 6374, 684, 5693, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 198, 2, 257, 4866, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 198,...
2.867802
1,233
# # This source file is part of the EdgeDB open source project. # # Copyright 2020-present MagicStack Inc. and the EdgeDB authors. # # 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 asyncio import edgedb from edb.server import compiler from edb import protocol from edb.testbase.protocol.test import ProtocolTestCase
[ 2, 198, 2, 770, 2723, 2393, 318, 636, 286, 262, 13113, 11012, 1280, 2723, 1628, 13, 198, 2, 198, 2, 15069, 12131, 12, 25579, 6139, 25896, 3457, 13, 290, 262, 13113, 11012, 7035, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 1...
3.767123
219
import re RE_NUMBER_VALIDATOR = re.compile(r'^\d+[.,]\d+$') assert number_is_valid('1.32') assert number_is_valid('1,32') assert not number_is_valid('asdasd1234') assert not number_is_valid('22,a44')
[ 11748, 302, 198, 198, 2200, 62, 41359, 13246, 62, 23428, 2389, 25633, 796, 302, 13, 5589, 576, 7, 81, 6, 61, 59, 67, 10, 58, 1539, 60, 59, 67, 10, 3, 11537, 628, 198, 198, 30493, 1271, 62, 271, 62, 12102, 10786, 16, 13, 2624, ...
2.306818
88
""" prec_reformat.py Taking state data and having each line be a precinct's voting results and candidate cf-scores (rather than each line be each candidate per precinct. | prec_id | cf_score_0 | num_votes_0 | cf_score_1 | num_votes_1 | """ import math import numpy as np import pandas as pd from prec_cd import prec_cd_main from check_data import check_main """ data_clean() Function to parse out certain types of data that are not useful in our results. # NOTE: overwrites the old file, since it is unnecessary """ """ prec_reformat_main() Function that does the bulk of the original main function and can be called by the commandline. @param: state, year @return: location of new precline file """ if __name__ == "__main__": main()
[ 37811, 198, 3866, 66, 62, 260, 18982, 13, 9078, 198, 198, 26556, 1181, 1366, 290, 1719, 1123, 1627, 307, 257, 28802, 338, 6709, 2482, 290, 4540, 198, 12993, 12, 1416, 2850, 357, 34330, 621, 1123, 1627, 307, 1123, 4540, 583, 28802, 13,...
3.124
250
from snakemake import shell input, output, params, threads, w, config = snakemake.input, snakemake.output, snakemake.params, snakemake.threads, snakemake.wildcards, snakemake.config genome = w.genome params.hybrid = config['x'][genome]['hybrid'] opt = params.opt shell(""" rm -rf {output.fna}* {output.fai}* rm -rf {output.chrom_bed} {output.chrom_size} {output.gap} mkdir -p {params.wdir}/{params.odir} cd {params.wdir}/{params.odir} rm -rf raw.fna.* renamed* map* raw.sizes """) merge_tag = '--merge_short' if w.genome != 'Mt_R108' else '' if params.hybrid: shell(""" cat {input} > {params.wdir}/{params.odir}/renamed.fna cd {params.wdir}/{params.odir} fasta.py size renamed.fna > renamed.sizes touch mapf.chain mapb.chain """) else: params.gap = int(config['x'][genome]['gap']) params.prefix = config['x'][genome]['prefix'] shell(""" cd {params.wdir}/{params.odir} ln -sf ../download/raw.fna raw.fna fasta.py size raw.fna > raw.sizes fasta.py rename raw.fna renamed.fna mapf.bed mapb.bed \ --opt {params.opt} {merge_tag} \ --gap {params.gap} --prefix_chr {params.prefix} fasta.py size renamed.fna > renamed.sizes chain.py fromBed mapf.bed raw.sizes renamed.sizes > mapf.chain chainSwap mapf.chain mapb.chain """) shell(""" cd {params.wdir} ln -sf {params.odir}/renamed.fna 10_genome.fna cd .. samtools faidx {output.fna} fasta.py size --bed {output.fna} > {output.chrom_bed} cut -f1,3 {output.chrom_bed} > {output.chrom_size} fasta.py gaps {output.fna} > {output.gap} """)
[ 6738, 17522, 15883, 1330, 7582, 198, 15414, 11, 5072, 11, 42287, 11, 14390, 11, 266, 11, 4566, 796, 17522, 15883, 13, 15414, 11, 17522, 15883, 13, 22915, 11, 17522, 15883, 13, 37266, 11, 17522, 15883, 13, 16663, 82, 11, 17522, 15883, ...
2.200528
758
# -*- coding: utf-8 -*- import time import xlrd import Register_aidaiwangApp import LogOut_aidiawangApp
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 640, 198, 11748, 2124, 75, 4372, 198, 11748, 17296, 62, 1698, 1872, 47562, 4677, 198, 11748, 5972, 7975, 62, 1698, 544, 47562, 4677, 198 ]
2.625
40
from sys import argv script, user_name = argv prompt = '>' print(user_name, script) print("Do you like me " + user_name + "?") likes = input(prompt) print("Where do you live " + user_name + "?") lives = input(prompt) print(""" So you said {:s} about liking me. You live in {:s}. """.format(likes, lives)) print("Script: ", script) age = int(input("Age? ")) print("Age*2: ", age*2)
[ 6738, 25064, 1330, 1822, 85, 198, 198, 12048, 11, 2836, 62, 3672, 796, 1822, 85, 198, 16963, 457, 796, 705, 29, 6, 198, 198, 4798, 7, 7220, 62, 3672, 11, 4226, 8, 198, 4798, 7203, 5211, 345, 588, 502, 366, 1343, 2836, 62, 3672, ...
2.576159
151
import io import pytest from requests import get from urllib.parse import urljoin def test_my_uploads_page(wait_for_api, login_user): """ GIVEN a user has logged in (login_user) WHEN the '/my/uploads' page is navigated to (GET) THEN check the response is valid and page title is correct """ request_session, api_url = wait_for_api response = request_session.get(urljoin(api_url, '/my/uploads')) assert response.status_code == 200 assert '<h1>My uploads</h1>' in response.text def test_valid_new_upload_page(wait_for_api, login_user): """ GIVEN a user has logged in (login_user) WHEN the '/media/newupload' page is navigated to (GET) THEN check the response is valid and page title is correct """ request_session, api_url = wait_for_api response = request_session.get(urljoin(api_url, '/media/newupload')) assert response.status_code == 200 assert '<h1>New upload</h1>' in response.text def test_invalid_new_upload_page(wait_for_api): """ GIVEN a user has not logged in WHEN the '/media/newupload' page is navigated to (GET) THEN check the response is valid and page title is correct """ request_session, api_url = wait_for_api response = request_session.get(urljoin(api_url, '/media/newupload')) assert response.status_code == 200 assert '<div class="flash">Please login first</div>' in response.text def test_new_upload(wait_for_api, login_user): """ GIVEN a user has logged in (login_user) WHEN the '/media/newupload' page is posted an example image (POST) THEN check the response is valid and the page title is correct """ example_file=open("./app/static/gfx/example.png","rb") files = { 'file': example_file } request_session, api_url = wait_for_api response = request_session.post(urljoin(api_url, '/media/newupload'), files=files, allow_redirects=True) assert response.status_code == 200 assert '<h1>My uploads</h1>' in response.text #def test_remove_upload(wait_for_api, login_user): # """ # GIVEN a user has logged in (login_user) # WHEN the '/blob/delete' page is posted (POST) # THEN check the response is valid and the user is logged in # """ # valid_blob = dict(blob_path='images/*example.png', upload_id=2) # request_session, api_url = wait_for_api # response = request_session.post(urljoin(api_url, '/blob/delete'), data=valid_blob, allow_redirects=True) # assert response.status_code == 200 # assert 'example.png was deleted successfully' in response.text
[ 11748, 33245, 198, 11748, 12972, 9288, 198, 6738, 7007, 1330, 651, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 22179, 198, 198, 4299, 1332, 62, 1820, 62, 39920, 62, 7700, 7, 17077, 62, 1640, 62, 15042, 11, 17594, 62, 7220, 2599...
2.794118
918
#!/usr/bin/env python import sys from shotgun import * try: if len(sys.argv) > 1: sg = Shotgun(sys.argv[1]) else: sg = Shotgun() ################################################################# # Find CustomEntity01 entities ################################################################# print "*" * 40, "findEntities - CustomEntity01", "*" * 40 for entity in sg.findEntities("CustomEntity01", FilterBy(), 5): #print entity #print "-" * 40 print "%s : %s" % (entity.sgProjectCode(), entity.getAttrValue("code")) ################################################################# # Find CustomEntity02 entities ################################################################# print "*" * 40, "findEntities - CustomEntity02", "*" * 40 for entity in sg.findEntities("CustomEntity02", FilterBy(), 5): #print entity #print "-" * 40 print "%s : %s" % (entity.sgProjectCode(), entity.getAttrValue("code")) except SgError, e: print "SgError:", e except Exception, e: print "Error:", e
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25064, 198, 6738, 18607, 1330, 1635, 198, 198, 28311, 25, 198, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 1875, 352, 25, 198, 220, 220, 220, 220, 220, 220, 22...
2.983827
371
import word2vec_np.utils.checks as checks import collections import numpy as np import math import time import logging def get_sentences_from_file(train_file): """ Returns a list of sentences from an input file. Args: train_file: A path to a file Returns: A list of sentences as they appear in the input. """ # Read the sentences from the input file (assumed to be a sentence per line) sentences = [line.rstrip('\n') for line in open(train_file)] return sentences def get_words_from_file(train_file): """ Returns a list of words from input sentences. Args: train_file: A path to a file Returns: A list of words as they appear in the input. """ words = [] sentences = get_sentences_from_file(train_file) for sentence in sentences: sentence_words = sentence.split() words.extend(sentence_words) return words def get_words_from_sentences(sentences): """ Returns a list of words from a list of sentences. Args: sentences: A list of sentences Returns: A list of words as they appear in the input. """ words = [] for sentence in sentences: sentence_words = sentence.split() words.extend(sentence_words) return words def save_word_counts(word_count, dict_file): """ Saves the dictionary into a file. The word_count and dictionary have the same ordering except that dictionary has extra 'PAD' symbol at index 0 Args: word_count: List of (word, count) tuples dict_file: Path to the output file. """ dict_file = open(dict_file, 'w+') for word, count in word_count: dict_file.write(word + ' ' + str(count) + '\n') dict_file.close() def save_dictionary(word_count, dict_file): """Saves the dictionary into a file. The word_count and dictionary have the same ordering except that dictionary has extra 'PAD' symbol at index 0 Args: word_count: List of (word, count) tuples dict_file: Path to the output file. """ # dict_file = open(dict_file, 'w+') for word, _ in word_count: dict_file.write(word + '\n') dict_file.close() def get_data(sentences, num_total_words, dictionaries, args): """ Gets data ready for training. Args: sentences: list of training sentences num_total_words: Total number of words in training corpus. dictionaries: Dictionary of dictionary (urgh) and word counts. args: Args passed to the script. """ logger = logging.getLogger('main') logger.info('Building train data...') # Get the relevant dictionaries dictionary = dictionaries['dictionary'] word_count = dictionaries['word_count'] # If we want to use word2vec's dictionary swap here. # This is for debugging only, to compare with embeddings # generated from original word2vec. if args.use_w2v_weights: dictionary_w2v, word_count_w2v = get_w2v_dictionaries(num_total_words, args) # Do some sanity checks checks.check_word_counts(word_count, word_count_w2v) checks.check_dictionaries(dictionary, dictionary_w2v) # Swap the dictionaries dictionary = dictionary_w2v reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) word_count = word_count_w2v # See if we want to load pre-generated data instead of building it. if args.load_data: return np.load(args.x_file + '.npy'), np.load(args.y_file + '.npy'), np.load(args.yneg_file + '.npy') # Get the probabilities of keeping the words during downsampling keep_prob = get_keep_probs(word_count, num_total_words, args.ds_param) # Dump the dictionary into a file. save_word_counts(word_count, args.dict_file) # Get the training data. This returns a list of ([context], target, [negative samples]) tuples. train_data = get_train_data_with_sentence_downsampling(sentences, dictionaries, args) # Break training data into arrays of context words, targets and negative samples. x_train, y_train, y_neg = process_data(train_data, word_count, args) logger.info('Finished building train data...') # Dump the files to a file np.save(args.x_file, x_train) np.save(args.y_file, y_train) np.save(args.yneg_file, y_neg) return x_train, y_train, y_neg def get_dictionaries(words, args): """ Returns a dictionary of dictionaries used in training. Args: words: A list of words from the training file. args: The arguments passed on to the script. Returns: A dictionary of consisting of dictionary -- dictionary mapping words to indices. reversed_dictionary -- dictionary indices to words. word_count -- dictionary mapping words to the number of times they occur in the corpus keep_prob -- a list of probabilities of keeping them during down-sampling. ns_prob -- a list of probabilities of getting sampled during NS """ logger = logging.getLogger('main') logger.info('Building dictionaries...') start_time = time.time() # List of (word, word_count) tuples word_count = [('UNK', 0)] # Total number of the words in the corpus num_total_words = len(words) # Sort the list of words by frequency and pick the top vocab_size ones if args.vocab_size == 0: # noinspection PyArgumentList # vocab_size = 0 implies we take the entire vocabulary available from the corpus word_count.extend(collections.Counter(words).most_common()) else: # noinspection PyArgumentList word_count.extend(collections.Counter(words).most_common(args.vocab_size - 1)) # Build the dictionary dictionary = dict() dictionary['PAD'] = 0 # num_vocab_words stores the number of words in the corpus that exist in our dictionary. num_vocab_words = 0 for word, count in word_count: num_vocab_words += count dictionary[word] = len(dictionary) # Update word count list word_count[0] = ('UNK', num_total_words - num_vocab_words) # Get the reversed dictionary. reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) # Get the negative sampling probabilities ns_probs = get_ns_probs(word_count, args.ns_param) # Get the probabilities of keeping the words during downsampling keep_probs = get_keep_probs(word_count, num_total_words, args.ds_param) dictionaries = {'dictionary': dictionary, 'reversed_dictionary': reversed_dictionary, 'word_count': word_count, 'ns_probs': ns_probs, 'keep_probs': keep_probs} elapsed_time = time.time() - start_time logger.info('Finished building dictionaries in %d seconds' % elapsed_time) return dictionaries def downsample_sentence(sentence_in, dictionaries): """ Downsamples the training sentences exactly as in word2vec. * Words not in the vocabulary are omitted. * EOS symbols are also omitted. Args: sentence_in: The input sentence that will be downsampled dictionaries: List of dictionaries Returns: The downsampled sentence """ dictionary = dictionaries['dictionary'] keep_probs = dictionaries['keep_probs'] sentence_out = [] sentence_words = sentence_in.split() for ind, word in enumerate(sentence_words): # Ignore the UNK words if dictionary.get(word, 1) == 1: continue # Ignore the EOS word if word == 'EOS': continue # Sub-sample the frequent words. random_number = np.random.rand() if keep_probs.get(word) < random_number: continue sentence_out.append(word) return ' '.join(sentence_out) def get_train_data_with_sentence_downsampling(sentences, dictionaries, args): """ This is the new implementation of get_train_data where the downsampling is done before building the context on each sentence. The main differences with get_train_data_with_context_downsampling implementation are * Downsampling is done before building context on each sentence. * Context window size is downsized randomly for each sentence. Args: sentences: list of sentences in the training data dictionaries: a list of dictionaries including dictionary: dictionary of the vocabulary words mapping words to indices reversed_dictionary: dictionary mapping indices to their corresponding words word_count: a list of (word, word_count) tuples ns_probs: dictionary of negative sampling probabilities keep_prob: a dictionary mapping words to their probability of staying during downsampling args: input args Returns: train_data: A list of (context, target, neg_samples) tuples """ logger = logging.getLogger('main') train_data = [] # Get the required dictionaries ns_probs = dictionaries['ns_probs'] dictionary = dictionaries['dictionary'] reversed_dictionary = dictionaries['reversed_dictionary'] num_processed_sentences = 0 num_total_sentences = len(sentences) logger.info('Number of sentences: %d' % num_total_sentences) for sentence in sentences: # Note that the downsampled sentence will not contain 'UNK' or 'EOS' symbols. sentence = downsample_sentence(sentence, dictionaries) sentence_words = sentence.split() num_processed_words = 0 num_total_words = len(sentence_words) for ind, word in enumerate(sentence_words): # Get the dictionary index for the given word. This is our target # W2 matrix does not contain 'PAD' or 'UNK', so we shift the target index by two target_ind = dictionary.get(word) - 2 # Build context for the current word in the sentence. # Shrink context window by a random number context_window = np.random.randint(1, args.context_window + 1) context = [] for cont_ind in range(ind - context_window, ind + context_window + 1): if cont_ind < 0: continue if cont_ind == ind: continue if cont_ind >= len(sentence_words): continue if dictionary.get(sentence_words[cont_ind], 1) == 1: continue context.append(dictionary.get(sentence_words[cont_ind])) if len(context) != 0: # If we are doing negative sampling, build a set of negative samples neg_samples = [] if args.ns_param != 0: # Pick neg_samples of negative samples. while len(neg_samples) < args.num_neg_samples: # Pick a random word from the dictionary (ignoring 'PAD', 'UNK' and 'EOS') # according to probabilities stored in ns_prob table. neg_ind = np.random.choice(np.arange(2, len(dictionary)), p=ns_probs) # Ignore if the random pick is the EOS symbol, or the target index if reversed_dictionary.get(neg_ind) == 'EOS' \ or neg_ind == target_ind \ or neg_ind in neg_samples: continue # W2 matrix does not contain 'PAD' or 'UNK', so we shift the dictionary by two neg_samples.append(neg_ind - 2) train_data.append((context, target_ind, neg_samples)) num_processed_words += 1 if num_processed_words % 1000 == 0: logger.info('Processed words for sentence: %.3f%%' % (float(num_processed_words * 100) / num_total_words)) num_processed_sentences += 1 if num_processed_sentences % 1000 == 0: logger.info('Processed sentences: %.3f%%' % (float(num_processed_sentences * 100) / num_total_sentences)) return train_data def get_ns_probs(word_count, ns_param): """ Returns a list of the probabilities of picking each word as a negative sample. List is ordered as word_count without the 'UNK' (this is not considered in any of these calculations). :param word_count: The dictionary containing mappings from words to their count in the corpus. :param ns_param: The negative sampling parameter used when building the probability distribution. :return: A list of probabilities for each word. """ ns_probs = [] # Compute normalization constant so that probabilities add up to 1. norm_const = 0 for word, count in word_count[1:]: # TODO: Think about this norm_const += np.power(count, ns_param) # Compute the probabilities for each word. for word, count in word_count[1:]: # <- Skip 'UNK' word_prob = np.power(count, ns_param) / norm_const ns_probs.append(word_prob) return ns_probs def get_keep_probs(word_count, num_total_words, ds_param): """ Returns a list of probabilities of keeping the corresponding words during downsampling :param word_count: A list containing tuples of (word, word_count) :param num_total_words: Total number of words in the corpus :param ds_param: The downsampling parameter, used in the distribution :return: A dictionary mapping words to their probabilities """ # Build the probabilities of keeping the words when downsampling keep_prob = [] for word, count in word_count[1:]: # <- Ignore 'UNK' # Compute the fraction of the words in the vocabulary that are the current word. word_frac = float(count) / num_total_words # Compute the probability of keeping the current word. word_prob = (np.sqrt(word_frac / ds_param) + 1) * ds_param / word_frac keep_prob.append(word_prob) return keep_prob def get_mini_batches(X, Y, YNEG, batch_size=64, shuffled=True): """Split the data into minibatches of batch_size :param X: array containing the context words at each row :param Y: array containing the target word at each row :param YNEG: array containing the negative samples at each row :param batch_size: size of the mini-batch :param shuffled: If true, training examples will be shuffled before building mini-batches :return: a list of mini-batches. """ logger = logging.getLogger('main') logger.info('Processing into mini-batches...') mini_batches = [] # Get the total number of training examples n_training_examples = X.shape[0] # If shuffled=True, shuffle X and Y if shuffled: permutation = list(np.random.permutation(n_training_examples)) X = X[permutation, :] Y = Y[permutation, :] YNEG = YNEG[permutation, :] num_full_batches = int(math.floor(n_training_examples / batch_size)) for k in range(0, num_full_batches): mini_batch_X = X[k * batch_size: (k + 1) * batch_size, :] mini_batch_Y = Y[k * batch_size: (k + 1) * batch_size, :] mini_batch_YNEG = YNEG[k * batch_size: (k + 1) * batch_size, :] mini_batch = (mini_batch_X, mini_batch_Y, mini_batch_YNEG) mini_batches.append(mini_batch) if n_training_examples % batch_size != 0: mini_batch_X = X[num_full_batches * batch_size:, :] mini_batch_Y = Y[num_full_batches * batch_size:, :] mini_batch_YNEG = YNEG[num_full_batches * batch_size:, :] mini_batch = (mini_batch_X, mini_batch_Y, mini_batch_YNEG) mini_batches.append(mini_batch) logger.info('Finished processing mini-batches.') return mini_batches sentence_index = 0 word_index = 0 def get_training_example(sentences, dictionaries, args): """ Generates a single training example from the input sentences sequentially (a.k.a. we keep track of positioning on the sentence and the target word) :param sentences: A list of sentences, where each sentence is a list of word indices :param dictionaries: The dictionaries built from corpus :param args: Scripts arguments :return: A tuple of ([context], target, [negative samples]) """ logger = logging.getLogger('main') global sentence_index global word_index current_sentence = sentences[sentence_index] target = current_sentence[word_index] - 2 # Shrink context window by random amount context_window = np.random.randint(1, args.context_window + 1) context = [] low = max(word_index - context_window, 0) high = min(word_index + context_window + 1, len(current_sentence)) for cont_ind in range(low, high): # Target word cannot be part of context if cont_ind == word_index: continue # Do not use 'UNK' words as context # TODO: Remove this check if downsampling is applied # if current_sentence[cont_ind] == 1: # continue context.append(current_sentence[cont_ind]) # Pad context with zeros while len(context) < 2 * args.context_window: context.append(0) neg_samples = get_negative_samples(target, args.num_neg_samples, dictionaries) # Advance the word_index to the next word word_index += 1 # If we reached the end of the sentence, advance to next sentence and reset word index if word_index >= len(current_sentence): sentence_index += 1 word_index = 0 # If we reached the end of the sentences, reset sentence_index back to the first one if sentence_index >= len(sentences): sentence_index = 0 logger.info('Epoch completed.') return context, target, neg_samples
[ 11748, 1573, 17, 35138, 62, 37659, 13, 26791, 13, 42116, 355, 8794, 201, 198, 11748, 17268, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 10688, 201, 198, 11748, 640, 201, 198, 11748, 18931, 201, 198, 201, 198, 201, 198, 4...
2.416028
7,699
import justpy as jp from .group import Group
[ 11748, 655, 9078, 355, 474, 79, 198, 6738, 764, 8094, 1330, 4912, 198 ]
3.461538
13
# -*- coding: utf-8 -*- import pkg_resources __version__ = pkg_resources.require("mtvs")[0].version
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 279, 10025, 62, 37540, 198, 198, 834, 9641, 834, 796, 279, 10025, 62, 37540, 13, 46115, 7203, 16762, 14259, 4943, 58, 15, 4083, 9641, 628 ]
2.55
40
# coding=utf-8 import sys from teamcity.unittestpy import TeamcityTestRunner if sys.version_info < (2, 7): from unittest2 import main, TestCase, expectedFailure else: from unittest import main, TestCase, expectedFailure main(testRunner=TeamcityTestRunner)
[ 2, 19617, 28, 40477, 12, 23, 198, 11748, 25064, 198, 6738, 1074, 19205, 13, 403, 715, 395, 9078, 1330, 4816, 19205, 14402, 49493, 198, 198, 361, 25064, 13, 9641, 62, 10951, 1279, 357, 17, 11, 767, 2599, 198, 220, 220, 220, 422, 555,...
3.104651
86
import uvicorn from fastapi import FastAPI from database import Base, engine from routers.user import router as router_user from routers.product import router as router_product from routers.authentication import router as router_auth app = FastAPI( title="Wish List", description="Permita que seus clientes acompanhem seus produtos favoritos, adicionando-os a uma lista de desejos.", version="1.0.0", ) Base.metadata.create_all(engine) app.include_router(router_auth) app.include_router(router_product) app.include_router(router_user) if __name__ == "__main__": uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
[ 198, 11748, 334, 25531, 1211, 198, 6738, 3049, 15042, 1330, 12549, 17614, 198, 198, 6738, 6831, 1330, 7308, 11, 3113, 198, 6738, 41144, 13, 7220, 1330, 20264, 355, 20264, 62, 7220, 198, 6738, 41144, 13, 11167, 1330, 20264, 355, 20264, 6...
2.958525
217
# encoding: utf-8 import torch import cv2 import numpy as np import pdb def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (tensor) [batch, num_gt, 5] batch of annotations stacked on their 0 dim annotations for a given image are stacked on 1 dim """ targets = [] imgs = [] # numpy array num_gts = [sample[1].shape[0] for sample in batch] max_num_gt = max(num_gts) for sample in batch: imgs.append(sample[0]) size_gt = sample[1].shape num_gt = size_gt[0] aug_size = list(size_gt[:]) aug_size[0] = max_num_gt aug_gt = np.zeros(aug_size, dtype=sample[1].dtype) aug_gt[:num_gt] = sample[1] targets.append(torch.FloatTensor(aug_gt)) return torch.stack(imgs, 0), torch.stack(targets, 0)
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 11748, 28034, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 279, 9945, 198, 198, 4299, 13326, 62, 26000, 378, 7, 43501, 2599, 198, 220, 220, 220, 37227, 15022, 2927, 37...
2.349896
483
# Copyright (c) 2018 Copyright holder of the paper Generative Adversarial Model Learning # submitted to NeurIPS 2019 for review # All rights reserved. import numpy as np import torch
[ 2, 15069, 357, 66, 8, 2864, 15069, 15762, 286, 262, 3348, 2980, 876, 1215, 690, 36098, 9104, 18252, 198, 2, 8948, 284, 3169, 333, 47643, 13130, 329, 2423, 198, 2, 1439, 2489, 10395, 13, 198, 198, 11748, 299, 32152, 355, 45941, 198, ...
4.021277
47
#!/usr/bin/python3 import boto3 source_ddb = boto3.resource('dynamodb', 'us-east-1') dest_ddb = boto3.client('dynamodb', 'us-west-2') sync(source_ddb, dest_ddb)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 275, 2069, 18, 198, 10459, 62, 1860, 65, 796, 275, 2069, 18, 13, 31092, 10786, 67, 4989, 375, 65, 3256, 705, 385, 12, 23316, 12, 16, 11537, 198, 16520, 62, 1860, 65, 796, 275, ...
2.16
75
""" """ import json from django.views.decorators.cache import never_cache from django.http import HttpResponse from django.shortcuts import render_to_response from core.views import initRequest, DateEncoder from core.reports import MC16aCPReport, ObsoletedTasksReport, TitanProgressReport
[ 37811, 198, 198, 37811, 198, 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 33571, 13, 12501, 273, 2024, 13, 23870, 1330, 1239, 62, 23870, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 19509, ...
3.447059
85
from typing import Dict, List, Tuple import numpy as np import tensorflow as tf from absl import logging from xain.datasets import prep from xain.types import History, Metrics, Partition, Theta, VolumeByClass from .model_provider import ModelProvider
[ 6738, 19720, 1330, 360, 713, 11, 7343, 11, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 2352, 75, 1330, 18931, 198, 198, 6738, 2124, 391, 13, 19608, 292, 1039, 1330, 3143, ...
3.407895
76
#!/usr/bin/env python3 """! QR code generator animation script.""" import numpy as np import qrcode from src.animate import Animate
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 0, 42137, 2438, 17301, 11034, 4226, 526, 15931, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10662, 6015, 1098, 198, 6738, 12351, 13, 45685, 1330, 1052, 1920, 628 ]
3.410256
39
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # sys.path.append(BASE_DIR) import datetime from yxf_yixue.xiaochengtu import XiaochengtuApi if __name__ == '__main__': string = '1996/02/29 23:16' obj = datetime.datetime(2012, 3, 7, 17, 40) a = XiaochengtuApi() res1 = a.paipan(obj) print(res1) a.print_pan() res2 = a.get_chuantongfenxi() print(res2)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 25064, 198, 33, 11159, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13,...
2.121076
223
import numpy as np from sklearn.preprocessing import OneHotEncoder
[ 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 1881, 21352, 27195, 12342, 628 ]
3.777778
18
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/graph_debug_info.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow/core/protobuf/graph_debug_info.proto', package='tensorflow', syntax='proto3', serialized_options=_b('\n\030org.tensorflow.frameworkB\024GraphDebugInfoProtosP\001ZUgithub.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto\370\001\001'), serialized_pb=_b('\n/tensorflow/core/protobuf/graph_debug_info.proto\x12\ntensorflow\"\xd5\x02\n\x0eGraphDebugInfo\x12\r\n\x05\x66iles\x18\x01 \x03(\t\x12\x36\n\x06traces\x18\x02 \x03(\x0b\x32&.tensorflow.GraphDebugInfo.TracesEntry\x1aX\n\x0b\x46ileLineCol\x12\x12\n\nfile_index\x18\x01 \x01(\x05\x12\x0c\n\x04line\x18\x02 \x01(\x05\x12\x0b\n\x03\x63ol\x18\x03 \x01(\x05\x12\x0c\n\x04\x66unc\x18\x04 \x01(\t\x12\x0c\n\x04\x63ode\x18\x05 \x01(\t\x1aL\n\nStackTrace\x12>\n\x0e\x66ile_line_cols\x18\x01 \x03(\x0b\x32&.tensorflow.GraphDebugInfo.FileLineCol\x1aT\n\x0bTracesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x34\n\x05value\x18\x02 \x01(\x0b\x32%.tensorflow.GraphDebugInfo.StackTrace:\x02\x38\x01\x42\x8c\x01\n\x18org.tensorflow.frameworkB\x14GraphDebugInfoProtosP\x01ZUgithub.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto\xf8\x01\x01\x62\x06proto3') ) _GRAPHDEBUGINFO_FILELINECOL = _descriptor.Descriptor( name='FileLineCol', full_name='tensorflow.GraphDebugInfo.FileLineCol', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='file_index', full_name='tensorflow.GraphDebugInfo.FileLineCol.file_index', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='line', full_name='tensorflow.GraphDebugInfo.FileLineCol.line', index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='col', full_name='tensorflow.GraphDebugInfo.FileLineCol.col', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='func', full_name='tensorflow.GraphDebugInfo.FileLineCol.func', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='code', full_name='tensorflow.GraphDebugInfo.FileLineCol.code', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=153, serialized_end=241, ) _GRAPHDEBUGINFO_STACKTRACE = _descriptor.Descriptor( name='StackTrace', full_name='tensorflow.GraphDebugInfo.StackTrace', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='file_line_cols', full_name='tensorflow.GraphDebugInfo.StackTrace.file_line_cols', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=243, serialized_end=319, ) _GRAPHDEBUGINFO_TRACESENTRY = _descriptor.Descriptor( name='TracesEntry', full_name='tensorflow.GraphDebugInfo.TracesEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='tensorflow.GraphDebugInfo.TracesEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='tensorflow.GraphDebugInfo.TracesEntry.value', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=321, serialized_end=405, ) _GRAPHDEBUGINFO = _descriptor.Descriptor( name='GraphDebugInfo', full_name='tensorflow.GraphDebugInfo', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='files', full_name='tensorflow.GraphDebugInfo.files', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='traces', full_name='tensorflow.GraphDebugInfo.traces', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GRAPHDEBUGINFO_FILELINECOL, _GRAPHDEBUGINFO_STACKTRACE, _GRAPHDEBUGINFO_TRACESENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=64, serialized_end=405, ) _GRAPHDEBUGINFO_FILELINECOL.containing_type = _GRAPHDEBUGINFO _GRAPHDEBUGINFO_STACKTRACE.fields_by_name['file_line_cols'].message_type = _GRAPHDEBUGINFO_FILELINECOL _GRAPHDEBUGINFO_STACKTRACE.containing_type = _GRAPHDEBUGINFO _GRAPHDEBUGINFO_TRACESENTRY.fields_by_name['value'].message_type = _GRAPHDEBUGINFO_STACKTRACE _GRAPHDEBUGINFO_TRACESENTRY.containing_type = _GRAPHDEBUGINFO _GRAPHDEBUGINFO.fields_by_name['traces'].message_type = _GRAPHDEBUGINFO_TRACESENTRY DESCRIPTOR.message_types_by_name['GraphDebugInfo'] = _GRAPHDEBUGINFO _sym_db.RegisterFileDescriptor(DESCRIPTOR) GraphDebugInfo = _reflection.GeneratedProtocolMessageType('GraphDebugInfo', (_message.Message,), { 'FileLineCol' : _reflection.GeneratedProtocolMessageType('FileLineCol', (_message.Message,), { 'DESCRIPTOR' : _GRAPHDEBUGINFO_FILELINECOL, '__module__' : 'tensorflow.core.protobuf.graph_debug_info_pb2' # @@protoc_insertion_point(class_scope:tensorflow.GraphDebugInfo.FileLineCol) }) , 'StackTrace' : _reflection.GeneratedProtocolMessageType('StackTrace', (_message.Message,), { 'DESCRIPTOR' : _GRAPHDEBUGINFO_STACKTRACE, '__module__' : 'tensorflow.core.protobuf.graph_debug_info_pb2' # @@protoc_insertion_point(class_scope:tensorflow.GraphDebugInfo.StackTrace) }) , 'TracesEntry' : _reflection.GeneratedProtocolMessageType('TracesEntry', (_message.Message,), { 'DESCRIPTOR' : _GRAPHDEBUGINFO_TRACESENTRY, '__module__' : 'tensorflow.core.protobuf.graph_debug_info_pb2' # @@protoc_insertion_point(class_scope:tensorflow.GraphDebugInfo.TracesEntry) }) , 'DESCRIPTOR' : _GRAPHDEBUGINFO, '__module__' : 'tensorflow.core.protobuf.graph_debug_info_pb2' # @@protoc_insertion_point(class_scope:tensorflow.GraphDebugInfo) }) _sym_db.RegisterMessage(GraphDebugInfo) _sym_db.RegisterMessage(GraphDebugInfo.FileLineCol) _sym_db.RegisterMessage(GraphDebugInfo.StackTrace) _sym_db.RegisterMessage(GraphDebugInfo.TracesEntry) DESCRIPTOR._options = None _GRAPHDEBUGINFO_TRACESENTRY._options = None # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 11192, 273, 11125, 14, 7295, 14, 11235, 672, 3046, 14, 34960, 62, 24442, ...
2.438656
3,839
import pytest from tests.test_data.lists import LIST from tests.test_data.people import MOVIE_CREDITS, PERSON, SHOW_CREDITS from tests.utils import mk_mock_client from trakt.core.exceptions import ArgumentError from trakt.core.json_parser import parse_tree from trakt.core.models import Person
[ 11748, 12972, 9288, 198, 6738, 5254, 13, 9288, 62, 7890, 13, 20713, 1330, 39498, 198, 6738, 5254, 13, 9288, 62, 7890, 13, 15332, 1330, 28184, 10008, 62, 9419, 24706, 50, 11, 46740, 11, 37041, 62, 9419, 24706, 50, 198, 6738, 5254, 13, ...
3.348315
89
#!/usr/bin/env python3 import argparse import os import sys import traceback from lib import core, utilities, run from lib.attributes import Attributes from lib.database import Database def process_arguments(): """ Uses the argparse module to parse commandline arguments. Returns: Dictionary of parsed commandline arguments. """ parser = argparse.ArgumentParser( description='Calculate the scores of a set of repositories.' ) parser.add_argument( '--cleanup', action='store_true', dest='cleanup', help='Delete cloned repositories from the disk when done.' ) parser.add_argument( '-c', '--config', type=argparse.FileType('r'), default='config.json', dest='config_file', help='Path to the configuration file.' ) parser.add_argument( '-m', '--manifest', type=argparse.FileType('r'), default='manifest.json', dest='manifest_file', help='Path to the manifest file.' ) parser.add_argument( '-r', '--repositories-root', dest='repositories_root', help='Path to the root of downloaded repositories.' ) parser.add_argument( '-s', '--repositories-sample', type=argparse.FileType('r'), dest='repositories_sample', help='A file containing newline-separated GHTorrent project ids' ) parser.add_argument( '-k', '--key-string', type=str, dest='key_string', default=None, required=False, help='String of attribute initials. Uppercase to persist data' ) parser.add_argument( '-n', '--num-processes', type=int, dest='num_processes', default=1, required=False, help=( 'Number of processes to spawn when processing repositories' ' from the samples file.' ) ) parser.add_argument( '--goldenset', action='store_true', dest='goldenset', help=( 'Indicate that the repositories sample file contains projects' ' from the Golden Set.' ) ) if len(sys.argv) < 2: parser.print_help() sys.exit(1) return parser.parse_args() def main(): """ Main execution flow. """ try: args = process_arguments() config = utilities.read(args.config_file) manifest = utilities.read(args.manifest_file) # TODO: Refactor core.config = config utilities.TOKENIZER = core.Tokenizer() database = Database(config['options']['datasource']) globaloptions = { 'today': config['options']['today'], 'timeout': config['options']['timeout'] } attributes = Attributes( manifest['attributes'], database, args.cleanup, args.key_string, **globaloptions ) if not os.path.exists(args.repositories_root): os.makedirs(args.repositories_root, exist_ok=True) table = 'reaper_results' if args.goldenset: table = 'reaper_goldenset' _run = run.Run( args.repositories_root, attributes, database, config['options']['threshold'], args.num_processes ) _run.run([int(line) for line in args.repositories_sample], table) except Exception as e: extype, exvalue, extrace = sys.exc_info() traceback.print_exception(extype, exvalue, extrace) if __name__ == '__main__': try: main() except KeyboardInterrupt: print('\rCaught interrupt, killing all children...')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 12854, 1891, 198, 198, 6738, 9195, 1330, 4755, 11, 20081, 11, 1057, 198, 6738, 9195, 13, 1078, 7657, 1330, ...
2.228417
1,668
# -*- coding: UTF-8 -*- """ Provides a summary after each test run. """ from __future__ import absolute_import, division, print_function import sys from time import time as time_now from behave.model import Rule, ScenarioOutline # MAYBE: Scenario from behave.model_core import Status from behave.reporter.base import Reporter from behave.formatter.base import StreamOpener # --------------------------------------------------------------------------- # CONSTANTS: # --------------------------------------------------------------------------- # -- DISABLED: OPTIONAL_STEPS = ('untested', 'undefined') OPTIONAL_STEPS = (Status.untested,) # MAYBE: Status.undefined STATUS_ORDER = (Status.passed, Status.failed, Status.skipped, Status.undefined, Status.untested) # --------------------------------------------------------------------------- # UTILITY FUNCTIONS: # --------------------------------------------------------------------------- def compute_summary_sum(summary): """Compute sum of all summary counts (except: all) :param summary: Summary counts (as dict). :return: Sum of all counts (as integer). """ counts_sum = 0 for name, count in summary.items(): if name == "all": continue # IGNORE IT. counts_sum += count return counts_sum # -- PREPARED: def format_summary2(statement_type, summary, end="\n"): """Format the summary line for one statement type. .. code-block:: 6 scenarios (passed: 5, failed: 1, skipped: 0, untested: 0) :param statement_type: :param summary: :return: """ parts = [] for status in STATUS_ORDER: if status.name not in summary: continue counts = summary[status.name] if status in OPTIONAL_STEPS and counts == 0: # -- SHOW-ONLY: For relevant counts, suppress: untested items, etc. continue parts.append((status.name, counts)) counts_sum = summary["all"] statement = pluralize(statement_type, sum) parts_text = ", ".join(["{0}: {1}".format(name, value) for name, value in parts]) return "{count:4} {statement:<9} ({parts}){end}".format( count=counts_sum, statement=statement, parts=parts_text, end=end) # --------------------------------------------------------------------------- # REPORTERS: # ---------------------------------------------------------------------------
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 198, 15946, 1460, 257, 10638, 706, 1123, 1332, 1057, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 117...
3.120865
786
from typing import Dict, Any import pytest from checkov.common.bridgecrew.bc_source import SourceType from checkov.common.bridgecrew.platform_integration import BcPlatformIntegration, bc_integration
[ 6738, 19720, 1330, 360, 713, 11, 4377, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 2198, 709, 13, 11321, 13, 9458, 42276, 13, 15630, 62, 10459, 1330, 8090, 6030, 198, 6738, 2198, 709, 13, 11321, 13, 9458, 42276, 13, 24254, 62, 18908...
3.625
56
import argparse from pathlib import Path from cv2 import cv2 from trimap import generate_trimap from trimap_output_utils import save_trimap_output if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 269, 85, 17, 1330, 269, 85, 17, 198, 198, 6738, 15797, 499, 1330, 7716, 62, 2213, 320, 499, 198, 6738, 15797, 499, 62, 22915, 62, 26791, 1330, 3613, 62, 2213, 3...
2.893939
66
#!/usr/bin/env python # -*- coding: utf-8 -*- from http.client import OK from unittest.mock import MagicMock, patch from urllib.parse import urlencode import graphene_django.views as views from django.urls import reverse from graphql import GraphQLError from graphql.error import GraphQLLocatedError
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 2638, 13, 16366, 1330, 7477, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 11, 8529, 198, ...
3.07
100
# coding: utf8 from __future__ import unicode_literals # The original stop words list (added in f46ffe3) was taken from # http://www.damienvanholten.com/downloads/dutch-stop-words.txt # and consisted of about 100 tokens. # In order to achieve parity with some of the better-supported # languages, e.g., English, French, and German, this original list has been # extended with 200 additional tokens. The main source of inspiration was # https://raw.githubusercontent.com/stopwords-iso/stopwords-nl/master/stopwords-nl.txt. # However, quite a bit of manual editing has taken place as well. # Tokens whose status as a stop word is not entirely clear were admitted or # rejected by deferring to their counterparts in the stop words lists for English # and French. Similarly, those lists were used to identify and fill in gaps so # that -- in principle -- each token contained in the English stop words list # should have a Dutch counterpart here. STOP_WORDS = set(""" aan af al alle alles allebei alleen allen als altijd ander anders andere anderen aangaangde aangezien achter achterna afgelopen aldus alhoewel anderzijds ben bij bijna bijvoorbeeld behalve beide beiden beneden bent bepaald beter betere betreffende binnen binnenin boven bovenal bovendien bovenstaand buiten daar dan dat de der den deze die dit doch doen door dus daarheen daarin daarna daarnet daarom daarop des dezelfde dezen dien dikwijls doet doorgaand doorgaans een eens en er echter enige eerder eerst eerste eersten effe eigen elk elke enkel enkele enz erdoor etc even eveneens evenwel ff ge geen geweest gauw gedurende gegeven gehad geheel gekund geleden gelijk gemogen geven geweest gewoon gewoonweg geworden gij haar had heb hebben heeft hem het hier hij hoe hun hadden hare hebt hele hen hierbeneden hierboven hierin hoewel hun iemand iets ik in is idd ieder ikke ikzelf indien inmiddels inz inzake ja je jou jouw jullie jezelf jij jijzelf jouwe juist kan kon kunnen klaar konden krachtens kunnen kunt lang later liet liever maar me meer men met mij mijn moet mag mede meer meesten mezelf mijzelf min minder misschien mocht mochten moest moesten moet moeten mogelijk mogen na naar niet niets nog nu nabij nadat net nogal nooit nr nu of om omdat ons ook op over omhoog omlaag omstreeks omtrent omver onder ondertussen ongeveer onszelf onze ooit opdat opnieuw opzij over overigens pas pp precies prof publ reeds rond rondom sedert sinds sindsdien slechts sommige spoedig steeds t 't te tegen toch toen tot tamelijk ten tenzij ter terwijl thans tijdens toe totdat tussen u uit uw uitgezonderd uwe uwen van veel voor vaak vanaf vandaan vanuit vanwege veeleer verder verre vervolgens vgl volgens vooraf vooral vooralsnog voorbij voordat voordien voorheen voorop voort voorts vooruit vrij vroeg want waren was wat we wel werd wezen wie wij wil worden waar waarom wanneer want weer weg wegens weinig weinige weldra welk welke welken werd werden wiens wier wilde wordt zal ze zei zelf zich zij zijn zo zonder zou zeer zeker zekere zelfde zelfs zichzelf zijnde zijne zon zoals zodra zouden zoveel zowat zulk zulke zulks zullen zult """.split())
[ 2, 19617, 25, 3384, 69, 23, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 2, 383, 2656, 2245, 2456, 1351, 357, 29373, 287, 277, 3510, 16658, 18, 8, 373, 2077, 422, 198, 2, 2638, 1378, 2503, 13, 11043, ...
2.779255
1,128
''' (c) University of Liverpool 2020 Licensed under the MIT License. To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.. @author: neilswainston ''' # pylint: disable=broad-except import os.path import tempfile from liv_covid19.web.artic import opentrons from liv_covid19.web.job import JobThread, save_export
[ 7061, 6, 198, 7, 66, 8, 2059, 286, 11761, 12131, 198, 198, 26656, 15385, 739, 262, 17168, 13789, 13, 198, 198, 2514, 1570, 257, 4866, 286, 428, 5964, 11, 3187, 1279, 4023, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 36393, 15913...
2.956522
115
import logging from datetime import datetime import os logger = logging.getLogger('FT') log_level = logging.INFO is_file_log = True # loggerlevelDEBUG logger.setLevel(log_level) # StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s [%(filename)s] %(funcName)s:%(lineno)d: %(message)s') hdr.setFormatter(formatter) # loggerhandler logger.addHandler(hdr) # handle if is_file_log: filename = 'ft_' + datetime.now().strftime('%Y%m%d') + '.log' tempPath = os.path.join(os.getcwd(), 'log') if not os.path.exists(tempPath): os.makedirs(tempPath) filepath = os.path.join(tempPath, filename) fileHandler = logging.FileHandler(filepath) fileHandler.setLevel(log_level) fileHandler.setFormatter(formatter) logger.addHandler(fileHandler)
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 28686, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 10786, 9792, 11537, 198, 6404, 62, 5715, 796, 18931, 13, 10778, 198, 271, 62, 7753, 62, 6404, 796, 6407, ...
2.556604
318
# Copyright 2018 Esteban Collado. # # Licensed under the MIT License import tensorflow as tf DEFAULT_VARIABLE_NAMES = ['conv1', 'conv2', 'conv3', 'conv4', 'fc1', 'fc2', 'softmax_linear'] BATCH_SIZE = 200 IMAGE_WIDTH = 32 IMAGE_HEIGHT = 32 IMAGE_DEPTH = 3 NUM_CLASSES = 10 INPUT_PLACEHOLDER = 'X_INPUT' LABELS_PLACEHOLDER = 'Y_LABELS'
[ 2, 15069, 2864, 10062, 1765, 272, 7778, 4533, 13, 198, 2, 198, 2, 49962, 739, 262, 17168, 13789, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 7206, 38865, 62, 53, 1503, 3539, 19146, 62, 45, 29559, 796, 37250, 42946, 16, ...
2.363014
146
""" The LibRoadRunner SBML Simulation Engine, (c) 2009-2014 Andy Somogyi and Herbert Sauro LibRoadRunner is an SBML JIT compiler and simulation engine with a variety of analysis functions. LibRoadRunner is a self contained library which is designed to be integrated into existing simulation platforms or may be used a stand alone simulation and analysis package. """ from sbmlsolver import * __version__ = getVersionStr()
[ 37811, 198, 464, 7980, 29197, 49493, 18056, 5805, 41798, 7117, 11, 357, 66, 8, 3717, 12, 4967, 12382, 9995, 9868, 72, 290, 28648, 23167, 305, 198, 198, 25835, 29197, 49493, 318, 281, 18056, 5805, 449, 2043, 17050, 290, 18640, 3113, 351,...
4.086538
104
from classification.models import EvidenceMixin from classification.models.evidence_mixin import VCStore # doesn't work without Transcripts loaded now # class EvidenceMixinTest(TestCase): # # @override_settings(VARIANT_ANNOTATION_TRANSCRIPT_PREFERENCES=['refseq_transcript_accession']) # def test_get_transcript(self): # # if transcript version is in c.hgvs use it # be = BasicEvidence({ # SpecialEKeys.C_HGVS: "NM_020975.5(RET):c.867+48A>G", # SpecialEKeys.REFSEQ_TRANSCRIPT_ID: "NM_020975", # SpecialEKeys.GENOME_BUILD: "GRCh37" # }) # self.assertEqual(be.transcript, "NM_020975.5") # # # if transcript version is in c.hgvs but transcript doesn't match # # value in transcript field, use the raw transcript value # be = BasicEvidence({ # SpecialEKeys.C_HGVS: "NM_020975.5(RET):c.867+48A>G", # SpecialEKeys.REFSEQ_TRANSCRIPT_ID: "NM_033333", # SpecialEKeys.GENOME_BUILD: "GRCh37" # }) # self.assertEqual(be.transcript, "NM_033333") # # # if there is no transcript field, use the contents of c.hgvs # be = BasicEvidence({ # SpecialEKeys.C_HGVS: "NM_020975.5(RET):c.867+48A>G", # SpecialEKeys.GENOME_BUILD: "GRCh37" # }) # self.assertEqual(be.transcript, "NM_020975.5")
[ 6738, 17923, 13, 27530, 1330, 21259, 35608, 259, 198, 6738, 17923, 13, 27530, 13, 46817, 62, 19816, 259, 1330, 26706, 22658, 628, 198, 2, 1595, 470, 670, 1231, 42978, 82, 9639, 783, 198, 2, 1398, 21259, 35608, 259, 14402, 7, 14402, 20...
2.083082
662
import urwid from scronsole.config_manager import ConfigManager from scronsole.plugin_manager import PluginManager from scronsole.widgets.main_menu import MainMenu from scronsole.widgets.server_screen import ServerScreen
[ 11748, 2956, 28029, 198, 198, 6738, 629, 1313, 6753, 13, 11250, 62, 37153, 1330, 17056, 13511, 198, 6738, 629, 1313, 6753, 13, 33803, 62, 37153, 1330, 42636, 13511, 198, 6738, 629, 1313, 6753, 13, 28029, 11407, 13, 12417, 62, 26272, 133...
3.779661
59
import re from csv import reader
[ 11748, 302, 198, 6738, 269, 21370, 1330, 9173, 198 ]
3.666667
9
import itertools ################################################# # This function will see if there is any # # possible combination of the numbers in # # the array that will give the largest number # ################################################# print ArrayAdditionI(raw_input())
[ 11748, 340, 861, 10141, 198, 198, 29113, 14468, 2, 198, 2, 770, 2163, 481, 766, 611, 612, 318, 597, 220, 220, 220, 220, 220, 220, 220, 1303, 198, 2, 1744, 6087, 286, 262, 3146, 287, 220, 220, 220, 220, 220, 220, 220, 1303, 198, ...
3.771084
83
import numpy as np import quadprog def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): """ Solve a QP of the form min 1/2xTPx + qTx st Gx < h st Ax=b""" #qp_G = .5 * (P + P.T) # make sure P is symmetric qp_G = P qp_a = -q if A is not None: qp_C = -np.vstack([A, G]).T qp_b = -np.hstack([b, h]) meq = A.shape[0] else: # no equality constraint qp_C = -G.T qp_b = -h meq = 0 return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] def evaluate_alpha(alpha, K, label): """ Return success percent """ result = K.dot(alpha) success = [float(result[i,0]*label[i] > 0) for i in range(len(label))] return np.mean(success)*100 def svm_compute_label(data_in_kernel, alpha): """ Compute the label for the data given (in the form data[i,j] = K(x, xj) with x a new data, xj in the data set""" result = data_in_kernel.dot(alpha) return [int(result[i,0] > 0.) for i in range(data_in_kernel.shape[0])] """ Just an example of how quadprog works : M = np.array([[1., 2., 0.], [-8., 3., 2.], [0., 1., 1.]]) P = np.dot(M.T, M) q = np.dot(np.array([3., 2., 3.]), M).reshape((3,)) G = np.array([[1., 2., 1.], [2., 0., 1.], [-1., 2., -1.]]) h = np.array([3., 2., -2.]).reshape((3,)) al = quadprog_solve_qp(P, q, G, h) print(al)"""
[ 11748, 299, 32152, 355, 45941, 198, 11748, 15094, 1676, 70, 628, 198, 4299, 15094, 1676, 70, 62, 82, 6442, 62, 80, 79, 7, 47, 11, 10662, 11, 402, 28, 14202, 11, 289, 28, 14202, 11, 317, 28, 14202, 11, 275, 28, 14202, 2599, 198, ...
2.050847
649
#!/usr/bin/python from ConfigUtils import getBaseConfig from LogUtils import getModuleLogger from StringUtils import isValidUrl, randomString from urlparse import urlparse import json import os import requests import sys cDir = os.path.dirname(os.path.realpath(__file__)) rootDir = os.path.abspath(os.path.join(cDir, os.pardir)) baseConfig = getBaseConfig(rootDir) logging = getModuleLogger(__name__)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 6738, 17056, 18274, 4487, 1330, 651, 14881, 16934, 198, 6738, 5972, 18274, 4487, 1330, 651, 26796, 11187, 1362, 198, 6738, 10903, 18274, 4487, 1330, 318, 47139, 28165, 11, 4738, 10100, 198, 6738,...
3.075758
132
from attempt.ddpg import HERDDPG, DDPG import gym import os import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm if __name__ == "__main__": os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' env = gym.make('FetchReach-v1') agent = HERDDPG(env) for epoch in range(2): for cycle in tqdm(range(10)): agent.gather_cycle() # target_agent.train() agent.test_env(10) env.close() plt.plot(np.vstack(agent.rewards)) plt.title('Rewards') plt.show() plt.plot(np.vstack(agent.policy_losses)) plt.title('Policy Losses') plt.show() plt.plot(np.vstack(agent.value_losses)) plt.title('Value Losses') plt.show()
[ 198, 6738, 2230, 13, 1860, 6024, 1330, 24906, 35, 6322, 38, 11, 360, 6322, 38, 198, 11748, 11550, 198, 11748, 28686, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80,...
2.136364
330
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # Written (W) 2008-2009 Soeren Sonnenburg # Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max Planck Society class_str='class' types=["BOOL", "CHAR", "INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32", "INT64", "UINT64", "FLOAT32", "FLOAT64", "FLOATMAX", "COMPLEX128"] config_tests=["HAVE_HDF5", "HAVE_JSON", "HAVE_XML", "HAVE_LAPACK", "USE_CPLEX", "USE_SVMLIGHT", "USE_GLPK", "USE_LZO", "USE_GZIP", "USE_BZIP2", "USE_LZMA", "USE_MOSEK", "HAVE_EIGEN3", "HAVE_COLPACK", "HAVE_NLOPT", "HAVE_PROTOBUF", "HAVE_VIENNACL"] SHOGUN_TEMPLATE_CLASS = "SHOGUN_TEMPLATE_CLASS" SHOGUN_BASIC_CLASS = "SHOGUN_BASIC_CLASS" def extract_classes(HEADERS, template, blacklist, supports_complex): """ Search in headers for non-template/non-abstract class-names starting with `C'. Does not support local nor multiple classes and drops classes with pure virtual functions """ classes=list() for fname in HEADERS: try: lines=open(fname).readlines() except: # python3 workaround lines=open(fname, encoding='utf-8', errors='ignore').readlines() line_nr=0 while line_nr<len(lines): line=lines[line_nr] if line.find('IGNORE_IN_CLASSLIST')!=-1: line_nr+=1 continue c=None if template: tp=line.find('template') if tp!=-1: line=line[tp:] cp=line.find('>') line=line[cp+1:] cp=line.find(class_str) if cp!=-1: c=extract_class_name(lines, line_nr, line, blacklist) else: if line.find(class_str)!=-1: c=extract_class_name(lines, line_nr, None, blacklist) if c: ok, line_nr=test_candidate(c, lines, line_nr, supports_complex) if ok: classes.append((c,template)) continue line_nr+=1 return classes if __name__=='__main__': import sys TEMPL_FILE=sys.argv[1] HEADERS=None if (sys.argv[2] == "-in"): # read header file list from file with open(sys.argv[3]) as f: content = f.readlines() HEADERS = [x.strip() for x in content] else: HEADERS=sys.argv[2:] blacklist = get_blacklist() classes = extract_classes(HEADERS, False, blacklist, False) template_classes = extract_classes(HEADERS, True, blacklist, False) complex_template_classes = extract_classes(HEADERS, True, blacklist, True) includes = get_includes(classes+template_classes+complex_template_classes) definitions = get_definitions(classes) template_definitions = get_template_definitions(template_classes, False) complex_template_definitions = get_template_definitions(complex_template_classes, True) struct = get_struct(classes+template_classes+complex_template_classes) substitutes = {'includes': includes, 'definitions' :definitions, 'template_definitions' : template_definitions, 'complex_template_definitions' : complex_template_definitions, 'struct' : struct } write_templated_file(TEMPL_FILE, substitutes)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 2, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094, 13789, 355, 3199, 416, 198, 2, 26...
2.555004
1,209
#!/usr/bin/env python # -*- coding: utf-8 -*- # project = https://github.com/Xyntax/POC-T # author = i@cdxy.me """ Apache Solr PoC (iterate_path) Usage python POC-T.py -s solr-unauth -iF target.txt python POC-T.py -s solr-unauth -aZ "solr country:cn" """ from lib.verify import verify from lib.random_header import get_ua import requests vuln = ['solr']
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 1628, 796, 3740, 1378, 12567, 13, 785, 14, 55, 33567, 897, 14, 47, 4503, 12, 51, 198, 2, 1772, 796, 1312, 31, ...
2.354839
155