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 import matplotlib.pyplot as plt import numpy as np import time import cv2 from real.camera import Camera from robot import Robot from subprocess import Popen, PIPE # User options (change me) # --------------- Setup options --------------- tcp_host_ip = '100.127.7.223' # IP and port to robot arm as TCP client (UR5) tcp_host_ip = "172.19.97.157" tcp_port = 30002 rtc_host_ip = '100.127.7.223' # IP and port to robot arm as real-time client (UR5) rtc_host_ip = "172.19.97.157" rtc_port = 30003 # Cols: min max, Rows: x y z (define workspace limits in robot coordinates) workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) workspace_limits = np.asarray([[-0.237, 0.211], [-0.683, -0.235], [0.18, 0.4]]) # workspace_limits = np.asarray([[-0.224, 0.224], [-0.674, -0.226], [0.18, 0.4]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates) tool_orientation = [2.22, -2.22, 0] tool_orientation = [0, -3.14, 0] # --------------------------------------------- # Move robot to home pose robot = Robot(False, None, None, workspace_limits, tcp_host_ip, tcp_port, rtc_host_ip, rtc_port, False, None, None) robot.open_gripper() transformation_matrix = get_camera_to_robot_transformation(robot.camera) # Slow down robot robot.joint_acc = 1.4 robot.joint_vel = 1.05 # Callback function for clicking on OpenCV window click_point_pix = () camera_color_img, camera_depth_img = robot.get_camera_data() # Show color and depth frames cv2.namedWindow('color') cv2.setMouseCallback('color', mouseclick_callback) cv2.namedWindow('depth') while True: camera_color_img, camera_depth_img = robot.get_camera_data() bgr_data = cv2.cvtColor(camera_color_img, cv2.COLOR_RGB2BGR) if len(click_point_pix) != 0: bgr_data = cv2.circle(bgr_data, click_point_pix, 7, (0, 0, 255), 2) cv2.imshow('color', bgr_data) camera_depth_img[camera_depth_img < 0.19] = 0 cv2.imshow('depth', camera_depth_img) if cv2.waitKey(1) == ord('c'): break cv2.destroyAllWindows()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 640, 198, 11748, 269, 85, 17, 198, 6738, 1103, 13, 25695, 1330, 20432, 198...
2.468009
844
# Header starts here. from sympy.physics.units import * from sympy import * # Rounding: import decimal from decimal import Decimal as DX from copy import deepcopy # LateX: kwargs = {} kwargs["mat_str"] = "bmatrix" kwargs["mat_delim"] = "" # kwargs["symbol_names"] = {FB: "F^{\mathsf B}", } # Units: (k, M, G ) = ( 10**3, 10**6, 10**9 ) (mm, cm) = ( m/1000, m/100 ) Newton = kg*m/s**2 Pa = Newton/m**2 MPa = M*Pa GPa = G*Pa kN = k*Newton deg = pi/180 half = S(1)/2 # Header ends here. # EA, l, F1, F2 = var("EA, l, F1, F2") sub_list = [ ( EA, 2 *Pa*m**2 ), ( l, 1 *m ), ( F1, 1 *Newton /2 ), # due to symmetry ( F2, 2 *Newton /2 ), # due to symmetry ] def k(phi): """ element stiffness matrix """ # phi is angle between: # 1. vector along global x axis # 2. vector along 1-2-axis of truss # phi is counted positively about z. # pprint("phi / deg:") # pprint(N(deg(phi),3)) (c, s) = ( cos(phi), sin(phi) ) (cc, ss, sc) = ( c*c, s*s, s*c) return Matrix( [ [ cc, sc, -cc, -sc], [ sc, ss, -sc, -ss], [-cc, -sc, cc, sc], [-sc, -ss, sc, ss], ]) (p1, p2, p3) = (315*pi/180, 0 *pi/180, 45 *pi/180) # k2 uses only 1/2 A due to symmetry: (k1, k2, k3) = (EA/l*k(p1), EA/2/l*k(p2), EA/l*k(p3)) pprint("\nk1 / (EA / l): ") pprint(k1 / (EA/l) ) pprint("\nk2 / (EA / l): ") pprint(k2 / (EA/l) ) pprint("\nk3 / (EA / l): ") pprint(k3 / (EA/l) ) K = EA/l*Matrix([ [ 1 , -S(1)/2 ], [ -S(1)/2, 1 ] ]) u2x, u3x = var("u2x, u3x") u = Matrix([u2x , u3x ]) f = Matrix([F1 , F2 ]) u2x, u3x = var("u2x, u3x") eq = Eq(K*u , f) sol = solve(eq, [u2x, u3x]) pprint("\nSolution:") pprint(sol) u2x, u3x = sol[u2x], sol[u3x] pprint("\nu2x / m:") tmp = u2x.subs(sub_list) tmp /= m pprint(tmp) pprint("\nu3x / m:") tmp = u3x.subs(sub_list) tmp /= m pprint(tmp) pprint("\nF1x / N:") tmp = - EA/l * u2x/2 tmp = tmp.subs(sub_list) tmp /= Newton pprint(tmp) # k1 / (EA / l): # 1/2 -1/2 -1/2 1/2 # # -1/2 1/2 1/2 -1/2 # # -1/2 1/2 1/2 -1/2 # # 1/2 -1/2 -1/2 1/2 # # k2 / (EA / l): # 1/2 0 -1/2 0 # # 0 0 0 0 # # -1/2 0 1/2 0 # # 0 0 0 0 # # k3 / (EA / l): # 1/2 1/2 -1/2 -1/2 # # 1/2 1/2 -1/2 -1/2 # # -1/2 -1/2 1/2 1/2 # # -1/2 -1/2 1/2 1/2 # # Solution: # 2l(2F + F) 2l(F + 2F) # u2x: , u3x: # 3EA 3EA # # u2x / m: # 2/3 # # u3x / m: # 5/6 # # F1x / N: # -2/3
[ 2, 48900, 4940, 994, 13, 198, 6738, 10558, 88, 13, 746, 23154, 13, 41667, 1330, 1635, 198, 6738, 10558, 88, 1330, 1635, 198, 198, 2, 371, 9969, 25, 198, 11748, 32465, 198, 6738, 32465, 1330, 4280, 4402, 355, 19393, 198, 6738, 4866, ...
1.611045
1,684
#!/usr/bin/python3 import csv ucc_dictionary_file_list = [ './downloads/diary08/diary08/uccd08.txt', './downloads/diary09/diary09/uccd09.txt', './downloads/diary11/diary11/uccd11.txt', './downloads/diary10/diary10/uccd10.txt', ] cleaned_ucc_dictionary = dict() for dictionary in ucc_dictionary_file_list: with open(dictionary) as file: line_list = file.read().splitlines() for line in line_list: ucc_tuple = tuple(line.split(" ", 1)) cleaned_ucc_dictionary[int(ucc_tuple[0])] = ucc_tuple[1] with open('cleaned_ucc_dictionary.csv', 'w', newline='') as csvfile: ucc_writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) for key, value in cleaned_ucc_dictionary.items(): ucc_writer.writerow([key, value]) # print(len(cleaned_ucc_dictionary.keys())) # print(line_list)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 269, 21370, 198, 198, 18863, 62, 67, 14188, 62, 7753, 62, 4868, 796, 685, 198, 220, 220, 220, 705, 19571, 15002, 82, 14, 67, 8042, 2919, 14, 67, 8042, 2919, 14, 18863, 67,...
2.236504
389
import datetime import os import traceback from inspect import ismethod from queue import Empty, Queue from threading import Event, Lock, Thread from time import sleep from typing import Dict, Optional, Tuple, Type import ray from eventsourcing.application.process import ProcessApplication from eventsourcing.application.simple import ( ApplicationWithConcreteInfrastructure, Prompt, PromptToPull, is_prompt_to_pull, ) from eventsourcing.domain.model.decorators import retry from eventsourcing.domain.model.events import subscribe, unsubscribe from eventsourcing.exceptions import ( EventSourcingError, ExceptionWrapper, OperationalError, ProgrammingError, RecordConflictError, ) from eventsourcing.infrastructure.base import ( DEFAULT_PIPELINE_ID, RecordManagerWithNotifications, ) from eventsourcing.system.definition import ( AbstractSystemRunner, System, TProcessApplication, ) from eventsourcing.system.rayhelpers import RayDbJob, RayPrompt from eventsourcing.system.raysettings import ray_init_kwargs from eventsourcing.system.runner import DEFAULT_POLL_INTERVAL ray.init(**ray_init_kwargs) MAX_QUEUE_SIZE = 1 PAGE_SIZE = 20 MICROSLEEP = 0.000 PROMPT_WITH_NOTIFICATION_IDS = False PROMPT_WITH_NOTIFICATION_OBJS = False GREEDY_PULL_NOTIFICATIONS = True
[ 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 12854, 1891, 198, 6738, 10104, 1330, 318, 24396, 198, 6738, 16834, 1330, 33523, 11, 4670, 518, 198, 6738, 4704, 278, 1330, 8558, 11, 13656, 11, 14122, 198, 6738, 640, 1330, 3993, 198, 67...
3.218978
411
# Generated by Django 3.2.6 on 2021-08-23 14:34 import django.contrib.postgres.fields from django.apps.registry import Apps from django.db import migrations, models from django.db.backends.base.schema import BaseDatabaseSchemaEditor from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 21, 319, 33448, 12, 2919, 12, 1954, 1478, 25, 2682, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 7353, 34239, 13, 25747, 198, 6738, 42625, 14208, 13, 18211, 13, 2301, 4592, 1330, 27710, 198...
3.058824
102
from django.test import TestCase from django.contrib.auth.models import User from article.models import Article, Category
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 2708, 13, 27530, 1330, 10172, 11, 21743, 628 ]
3.875
32
import os , sys sys.path.append(os.getcwd()) import pytest from typehints_checker import *
[ 11748, 28686, 837, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 1136, 66, 16993, 28955, 198, 11748, 12972, 9288, 198, 6738, 2099, 71, 29503, 62, 9122, 263, 1330, 1635 ]
2.903226
31
# -*- coding: utf-8 -*- """ Created on Nov 24, 2014 @author: moloch Copyright 2014 Root the Box 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 os from uuid import uuid4 from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Unicode, String, Integer from models.BaseModels import DatabaseObject from libs.StringCoding import encode, decode from builtins import str from tornado.options import options
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 5267, 1987, 11, 1946, 198, 198, 31, 9800, 25, 18605, 5374, 628, 220, 220, 220, 15069, 1946, 20410, 262, 8315, 628, 220, 220, 220, 49962, 739, 2...
3.571429
266
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') detector.run = run
[ 11748, 1278, 571, 198, 11748, 288, 10885, 198, 6738, 288, 10885, 13, 12417, 26268, 13, 4743, 571, 1330, 360, 16286, 38, 13383, 39516, 198, 6738, 12972, 1453, 1330, 8558, 10161, 1967, 198, 11748, 2604, 2070, 198, 6404, 1362, 796, 2604, 2...
2.843023
172
#!/usr/bin/env python3 # # Copyright (c) 2015 - 2022, Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # """ Runs an application with a large number of short regions and checks that the controller successfully runs. """ import sys import unittest import os import subprocess import glob import geopmpy.io import geopmpy.agent import geopmdpy.error import geopmdpy.topo from integration.test import geopm_test_launcher from integration.test import check_trace def test_short_region_count(self): ''' Test that the count for MPI_Barrier is as expected. ''' report = geopmpy.io.RawReport(self._report_path) hosts = report.host_names() for hh in hosts: region_data = report.raw_region(hh, 'MPI_Barrier') count = region_data['count'] self.assertEqual(count, 10000000) def test_sample_rate(self): ''' Test that the sample rate is regular. ''' traces = glob.glob(self._trace_path + "*") if len(traces) == 0: raise RuntimeError("No traces found with prefix: {}".format(self._trace_path_prefix)) for tt in traces: check_trace.check_sample_rate(tt, 0.005) if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 1853, 532, 33160, 11, 8180, 10501, 198, 2, 220, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 198, ...
2.468085
517
# Description: OptiAlign.py by Jason Vertree modified for aligning multiple RNA structures. # Source: Generated while helping Miranda Adams at U of Saint Louis. """ cmd.do('python') cmd.do(' ##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py. A python implementation of the optimal superposition') cmd.do('# of two sets of vectors as proposed by Kabsch 1976 & 1978.') cmd.do('#') cmd.do('# @AUTHOR: Jason Vertrees') cmd.do('# @COPYRIGHT: Jason Vertrees (C), 2005-2007') cmd.do('# @LICENSE: Released under GPL:') cmd.do('# This program is free software; you can redistribute it and/or modify') cmd.do('# it under the terms of the GNU General Public License as published by') cmd.do('# the Free Software Foundation; either version 2 of the License, or') cmd.do('# (at your option) any later version.') cmd.do('# This program is distributed in the hope that it will be useful, but WITHOUT') cmd.do('# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS') cmd.do('# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.') cmd.do('#') cmd.do('# You should have received a copy of the GNU General Public License along with') cmd.do('# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin') cmd.do('# Street, Fifth Floor, Boston, MA 02110-1301, USA ') cmd.do('#') cmd.do('# DATE : 2007-01-01') cmd.do('# REV : 2') cmd.do('# REQUIREMENTS: numpy') cmd.do('#') cmd.do('#') cmd.do('# Modified optAlign.py to use C1' carbon atoms of RNA for alignment.') cmd.do('# Jan. 29, 2020 ') cmd.do('# Blaine Mooers, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#############################################################################') cmd.do('from array import *') cmd.do(' ') cmd.do('# system stuff') cmd.do('import os') cmd.do('import copy') cmd.do(' ') cmd.do('# pretty printing') cmd.do('import pprint') cmd.do(' ') cmd.do('# for importing as a plugin into PyMol') cmd.do('from pymol import cmd') cmd.do('from pymol import stored') cmd.do('from pymol import selector') cmd.do(' ') cmd.do('# using numpy for linear algebra') cmd.do('import numpy') cmd.do(' ') cmd.do('def optAlignRNA( sel1, sel2 ):') cmd.do(' """') cmd.do(' optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections.') cmd.do(' Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1'') cmd.do(' ') cmd.do(' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from') cmd.do(' PyMOL based upon your selections.') cmd.do(' ') cmd.do(' This function can be run in a for loop to fit multiple structures with a common prefix name:') cmd.do(' ') cmd.do(' for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001")') cmd.do(' ') cmd.do(' or get the rmsds for all combinations, do the following:') cmd.do(' ') cmd.do(' [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do(' """') cmd.do(' cmd.reset()') cmd.do(' ') cmd.do(' # make the lists for holding coordinates') cmd.do(' # partial lists') cmd.do(' stored.sel1 = []') cmd.do(' stored.sel2 = []') cmd.do(' # full lists') cmd.do(' stored.mol1 = []') cmd.do(' stored.mol2 = []') cmd.do(' ') cmd.do(' # -- CUT HERE') cmd.do(' sel1 += " and N. C1'"') cmd.do(' sel2 += " and N. C1'"') cmd.do(' # -- CUT HERE') cmd.do(' ') cmd.do(' # Get the selected coordinates. We') cmd.do(' # align these coords.') cmd.do(' cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")') cmd.do(' ') cmd.do(' # get molecule name') cmd.do(' mol1 = cmd.identify(sel1,1)[0][0]') cmd.do(' mol2 = cmd.identify(sel2,1)[0][0]') cmd.do(' ') cmd.do(' # Get all molecule coords. We do this because') cmd.do(' # we have to rotate the whole molcule, not just') cmd.do(' # the aligned selection') cmd.do(' cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")') cmd.do(' ') cmd.do(' # check for consistency') cmd.do(' assert len(stored.sel1) == len(stored.sel2)') cmd.do(' L = len(stored.sel1)') cmd.do(' assert L > 0') cmd.do(' ') cmd.do(' # must alway center the two proteins to avoid') cmd.do(' # affine transformations. Center the two proteins') cmd.do(' # to their selections.') cmd.do(' COM1 = numpy.sum(stored.sel1,axis=0) / float(L)') cmd.do(' COM2 = numpy.sum(stored.sel2,axis=0) / float(L)') cmd.do(' stored.sel1 -= COM1') cmd.do(' stored.sel2 -= COM2') cmd.do(' ') cmd.do(' # Initial residual, see Kabsch.') cmd.do(' E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)') cmd.do(' ') cmd.do(' #') cmd.do(' # This beautiful step provides the answer. V and Wt are the orthonormal') cmd.do(' # bases that when multiplied by each other give us the rotation matrix, U.') cmd.do(' # S, (Sigma, from SVD) provides us with the error! Isn't SVD great!') cmd.do(' V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))') cmd.do(' ') cmd.do(' # we already have our solution, in the results from SVD.') cmd.do(' # we just need to check for reflections and then produce') cmd.do(' # the rotation. V and Wt are orthonormal, so their det's') cmd.do(' # are +/-1.') cmd.do(' reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))') cmd.do(' ') cmd.do(' if reflect == -1.0:') cmd.do(' S[-1] = -S[-1]') cmd.do(' V[:,-1] = -V[:,-1]') cmd.do(' ') cmd.do(' RMSD = E0 - (2.0 * sum(S))') cmd.do(' RMSD = numpy.sqrt(abs(RMSD / L))') cmd.do(' ') cmd.do(' #U is simply V*Wt') cmd.do(' U = numpy.dot(V, Wt)') cmd.do(' ') cmd.do(' # rotate and translate the molecule') cmd.do(' stored.sel2 = numpy.dot((stored.mol2 - COM2), U)') cmd.do(' stored.sel2 = stored.sel2.tolist()') cmd.do(' # center the molecule') cmd.do(' stored.sel1 = stored.mol1 - COM1') cmd.do(' stored.sel1 = stored.sel1.tolist()') cmd.do(' ') cmd.do(' # let PyMol know about the changes to the coordinates') cmd.do(' cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")') cmd.do(' cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")') cmd.do(' ') cmd.do(' #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD)') cmd.do(' print("% s, % s,% 5.3f" % (mol1, mol2, RMSD))') cmd.do(' ') cmd.do(' # make the alignment OBVIOUS') cmd.do(' cmd.hide("everything")') cmd.do(' cmd.show("ribbon", sel1 + " or " + sel2)') cmd.do(' cmd.color("gray70", mol1 )') cmd.do(' cmd.color("magenta", mol2 )') cmd.do(' cmd.color("red", "visible")') cmd.do(' cmd.show("ribbon", "not visible")') cmd.do(' cmd.center("visible")') cmd.do(' cmd.orient()') cmd.do(' cmd.zoom("visible")') cmd.do(' ') cmd.do('cmd.extend("optAlignRNA", optAlignRNA)') cmd.do('python end') """ cmd.do('python') cmd.do(' ##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py. A python implementation of the optimal superposition') cmd.do('# of two sets of vectors as proposed by Kabsch 1976 & 1978.') cmd.do('#') cmd.do('# @AUTHOR: Jason Vertrees') cmd.do('# @COPYRIGHT: Jason Vertrees (C), 2005-2007') cmd.do('# @LICENSE: Released under GPL:') cmd.do('# This program is free software; you can redistribute it and/or modify') cmd.do('# it under the terms of the GNU General Public License as published by') cmd.do('# the Free Software Foundation; either version 2 of the License, or') cmd.do('# (at your option) any later version.') cmd.do('# This program is distributed in the hope that it will be useful, but WITHOUT') cmd.do('# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS') cmd.do('# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.') cmd.do('#') cmd.do('# You should have received a copy of the GNU General Public License along with') cmd.do('# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin') cmd.do('# Street, Fifth Floor, Boston, MA 02110-1301, USA ') cmd.do('#') cmd.do('# DATE : 2007-01-01') cmd.do('# REV : 2') cmd.do('# REQUIREMENTS: numpy') cmd.do('#') cmd.do('#') cmd.do('# Modified optAlign.py to use C1' carbon atoms of RNA for alignment.') cmd.do('# Jan. 29, 2020 ') cmd.do('# Blaine Mooers, PhD') cmd.do('# Univ. of Oklahoma Health Sciences Center') cmd.do('#') cmd.do('#############################################################################') cmd.do('from array import *') cmd.do(' ') cmd.do('# system stuff') cmd.do('import os') cmd.do('import copy') cmd.do(' ') cmd.do('# pretty printing') cmd.do('import pprint') cmd.do(' ') cmd.do('# for importing as a plugin into PyMol') cmd.do('from pymol import cmd') cmd.do('from pymol import stored') cmd.do('from pymol import selector') cmd.do(' ') cmd.do('# using numpy for linear algebra') cmd.do('import numpy') cmd.do(' ') cmd.do('def optAlignRNA( sel1, sel2 ):') cmd.do(' """') cmd.do(' optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections.') cmd.do(' Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1'') cmd.do(' ') cmd.do(' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from') cmd.do(' PyMOL based upon your selections.') cmd.do(' ') cmd.do(' This function can be run in a for loop to fit multiple structures with a common prefix name:') cmd.do(' ') cmd.do(' for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001")') cmd.do(' ') cmd.do(' or get the rmsds for all combinations, do the following:') cmd.do(' ') cmd.do(' [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()]') cmd.do('') cmd.do(' """') cmd.do(' cmd.reset()') cmd.do(' ') cmd.do(' # make the lists for holding coordinates') cmd.do(' # partial lists') cmd.do(' stored.sel1 = []') cmd.do(' stored.sel2 = []') cmd.do(' # full lists') cmd.do(' stored.mol1 = []') cmd.do(' stored.mol2 = []') cmd.do(' ') cmd.do(' # -- CUT HERE') cmd.do(' sel1 += " and N. C1'"') cmd.do(' sel2 += " and N. C1'"') cmd.do(' # -- CUT HERE') cmd.do(' ') cmd.do(' # Get the selected coordinates. We') cmd.do(' # align these coords.') cmd.do(' cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")') cmd.do(' ') cmd.do(' # get molecule name') cmd.do(' mol1 = cmd.identify(sel1,1)[0][0]') cmd.do(' mol2 = cmd.identify(sel2,1)[0][0]') cmd.do(' ') cmd.do(' # Get all molecule coords. We do this because') cmd.do(' # we have to rotate the whole molcule, not just') cmd.do(' # the aligned selection') cmd.do(' cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")') cmd.do(' cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")') cmd.do(' ') cmd.do(' # check for consistency') cmd.do(' assert len(stored.sel1) == len(stored.sel2)') cmd.do(' L = len(stored.sel1)') cmd.do(' assert L > 0') cmd.do(' ') cmd.do(' # must alway center the two proteins to avoid') cmd.do(' # affine transformations. Center the two proteins') cmd.do(' # to their selections.') cmd.do(' COM1 = numpy.sum(stored.sel1,axis=0) / float(L)') cmd.do(' COM2 = numpy.sum(stored.sel2,axis=0) / float(L)') cmd.do(' stored.sel1 -= COM1') cmd.do(' stored.sel2 -= COM2') cmd.do(' ') cmd.do(' # Initial residual, see Kabsch.') cmd.do(' E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)') cmd.do(' ') cmd.do(' #') cmd.do(' # This beautiful step provides the answer. V and Wt are the orthonormal') cmd.do(' # bases that when multiplied by each other give us the rotation matrix, U.') cmd.do(' # S, (Sigma, from SVD) provides us with the error! Isn't SVD great!') cmd.do(' V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))') cmd.do(' ') cmd.do(' # we already have our solution, in the results from SVD.') cmd.do(' # we just need to check for reflections and then produce') cmd.do(' # the rotation. V and Wt are orthonormal, so their det's') cmd.do(' # are +/-1.') cmd.do(' reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))') cmd.do(' ') cmd.do(' if reflect == -1.0:') cmd.do(' S[-1] = -S[-1]') cmd.do(' V[:,-1] = -V[:,-1]') cmd.do(' ') cmd.do(' RMSD = E0 - (2.0 * sum(S))') cmd.do(' RMSD = numpy.sqrt(abs(RMSD / L))') cmd.do(' ') cmd.do(' #U is simply V*Wt') cmd.do(' U = numpy.dot(V, Wt)') cmd.do(' ') cmd.do(' # rotate and translate the molecule') cmd.do(' stored.sel2 = numpy.dot((stored.mol2 - COM2), U)') cmd.do(' stored.sel2 = stored.sel2.tolist()') cmd.do(' # center the molecule') cmd.do(' stored.sel1 = stored.mol1 - COM1') cmd.do(' stored.sel1 = stored.sel1.tolist()') cmd.do(' ') cmd.do(' # let PyMol know about the changes to the coordinates') cmd.do(' cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")') cmd.do(' cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")') cmd.do(' ') cmd.do(' #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD)') cmd.do(' print("% s, % s,% 5.3f" % (mol1, mol2, RMSD))') cmd.do(' ') cmd.do(' # make the alignment OBVIOUS') cmd.do(' cmd.hide("everything")') cmd.do(' cmd.show("ribbon", sel1 + " or " + sel2)') cmd.do(' cmd.color("gray70", mol1 )') cmd.do(' cmd.color("magenta", mol2 )') cmd.do(' cmd.color("red", "visible")') cmd.do(' cmd.show("ribbon", "not visible")') cmd.do(' cmd.center("visible")') cmd.do(' cmd.orient()') cmd.do(' cmd.zoom("visible")') cmd.do(' ') cmd.do('cmd.extend("optAlignRNA", optAlignRNA)') cmd.do('python end')
[ 2, 12489, 25, 220, 13123, 72, 2348, 570, 13, 9078, 416, 8982, 24417, 631, 9518, 329, 10548, 278, 3294, 25897, 8573, 13, 198, 2, 8090, 25, 220, 2980, 515, 981, 5742, 29575, 12620, 379, 471, 286, 9281, 5593, 13, 198, 198, 37811, 198, ...
2.498533
5,454
test_input = """ L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL """ test_input2 = """ .......#. ...#..... .#....... ......... ..#L....# ....#.... ......... #........ ...#..... """ test_input3 = """ ............. .L.L.#.#.#.#. ............. """ test_input4 = """ .##.##. #.#.#.# ##...## ...L... ##...## #.#.#.# .##.##. """ input = """ LL.LL.LLLLLL.LLLLLLLLLLLLLLLLLL.LLLLL..LLLLLLL.LLLLLLLLLLLL.LLLL.LLLLL.LL.LLLLLL.LLLL.LLLLL LLLLL.LLLLLL.LLLLLLLLLLLLL.LLLL.LL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL LLLLL.LLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLL.LLLL.LLLLL LLLLL.LLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLLL LLLLL.LLLLLL.LLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLL.LLLLL.LLLLLL.LLLL.LLLLLLLL.LLLLLLLLLLLLLLLLL .LL...LL.L.L....LL..LL..L.L.L..L.....L...LL.....LLL..L..L..L.....L.L..LLLL...LL.LL.L....... LLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL..LLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLL.LLLLL LLLLL.LLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLL.LLLLL.LLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLL.LLLLL LLLLLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLL.LLLLL LLLLL.LLLLLL.LLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLL.LL.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLL LLLLL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LLLLL.LLLLL LLLLL.LLLLLL.LLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLL.LLLLLLLL.LLLLLLLLLLL.LLLLL LLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLLL LLLLL.LLLLLLLLLLLLLL..LLLLLLLLL.LLLLLL.LLLLLLL.LLLLL.LLLLL..LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLL.LLLLL.LLLLLL.LLLL.LLLLLLLL.LLLLLL.LLLL.LLLLL """ import numpy as np val = {'L': -1, '#': 1, '.': 0} rval = {v: k for k, v in val.items()} print("Day 11") print("Part 1") print("Test input") testa = strtoarray(test_input) print(test_input) print(testa) print(arraytostr(testa)) print("Adjacent to 0, 0", arraytostr(adjacent(testa, 0, 0))) print("Adjacent to 2, 2", arraytostr(adjacent(testa, 2, 2))) test_finala = generations(testa) print(np.sum(test_finala == 1)) print("Puzzle input") a = strtoarray(input) finala = generations(a) print(np.sum(finala == 1)) print("Part 2") print("Test input") testa2 = strtoarray(test_input2) assert testa2[4, 3] == -1 print(adjacent2(testa2, 4, 3)) testa3 = strtoarray(test_input3) assert testa3[1, 3] == -1 print(adjacent2(testa3, 1, 3)) testa4 = strtoarray(test_input4) assert testa4[3, 3] == -1 print(adjacent2(testa4, 3, 3)) test_finala = generations2(testa) print(np.sum(test_finala==1)) print("Puzzle input") finala = generations2(a) print(np.sum(finala == 1))
[ 9288, 62, 15414, 796, 37227, 198, 43, 13, 3069, 13, 3069, 13, 3069, 198, 3069, 3069, 3069, 43, 13, 3069, 198, 43, 13, 43, 13, 43, 492, 43, 492, 198, 3069, 3069, 13, 3069, 13, 3069, 198, 43, 13, 3069, 13, 3069, 13, 3069, 198, 4...
1.812786
5,678
from SMA2CAgent import SMA2CAgent from A2CAgent import A2CAgent from RandomAgent import RandomAgent # from .SMA2CAgent import SMA2CAgent import gym import numpy as np from IPD_fixed import IPDEnv import axelrod import time import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--rounds", help='number of rounds to play per episode', type=int, default=20) parser.add_argument("--episodes", help='number of episodes to play', type=int, default=1000) parser.add_argument("--seed", help='random seed, -1 if random', type=int, default=-1) parser.add_argument("--output", help="output folder", default=f'output-{time.time():.0f}') parser.add_argument("--pure-a2c", help="Don't use an encoder", action='store_true') parser.add_argument("--alpha", help='LR of encoder', type=float) parser.add_argument("--beta", help = 'LR of A2C agent', type=float) parser.add_argument("--lstm-dims", help='LSTM dimensions', type=int) parser.add_argument("--encoder-fc", help='dimensions of encoder dense layers',type=int, action='append') parser.add_argument("--a2c-fc", help='dimensions of a2c hidden layers', type=int, action='append') parser.add_argument("--latent-dims", help='dimensions of code', type=int) parser.add_argument("opponents", help='opponents that the bot should face', nargs="*") parser.add_argument("--random", help="Don't use an agent, just random", action='store_true') # parser.add_argument("") args = parser.parse_args() opponents = [] strats = dict([(s.name.lower(), s) for s in axelrod.all_strategies]) for opp in args.opponents: if opp not in strats: print(f'{opp} not found in strats') s = strats[opp] opponents.append(s) env = IPDEnv({'rounds': args.rounds, 'opponents' : opponents}) seed = args.seed if args.seed != -1 else None env.seed(seed=seed) # remove empty values config = {k: v for k, v in vars(args).items() if v is not None} if config['pure_a2c']: print("____USING PURE A2C_____") agent= A2CAgent(env, config) elif config['random']: print("__RANDOM AGENT___") agent = RandomAgent(env, config) else: print("____USING SMA2C______") agent = SMA2CAgent(env, config) # obs = env.reset() # action = agent.act(obs, 0, 0, 1) # print(f'resulting action: {action}') # encodings_before = np.array(agent.encode_run(axelrod.Cooperator())) # print(f'encodings before: {encodings_before}') agent.run(episodes=args.episodes) # encodings_after_c = np.array(agent.encode_run(axelrod.Cooperator())) # encodings_after_d = np.array(agent.encode_run(axelrod.Defector())) # print(f'encodings after: {encodings_after_c}') # print(encodings_after_d) agent.save()
[ 6738, 311, 5673, 17, 8141, 6783, 1330, 311, 5673, 17, 8141, 6783, 198, 6738, 317, 17, 8141, 6783, 1330, 317, 17, 8141, 6783, 198, 6738, 14534, 36772, 1330, 14534, 36772, 198, 2, 422, 764, 50, 5673, 17, 8141, 6783, 1330, 311, 5673, 1...
2.555157
1,115
import heapq as h # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
[ 11748, 24575, 80, 355, 289, 628, 198, 2, 3406, 26178, 37, 5540, 2134, 481, 307, 9113, 12931, 290, 1444, 355, 884, 25, 198, 2, 26181, 796, 26178, 37, 5540, 3419, 198, 2, 26181, 13, 2860, 33111, 7, 22510, 8, 198, 2, 5772, 62, 17, ...
3.078431
51
import pytest from app.domain.models.Metadatafil import Metadatafil, MetadataType from app.exceptions import InvalidContentType from app.routers.mappers.metadafil import _get_file_content, metadatafil_mapper, _content_type2metadata_type def test__content_type2metadata_type__success(): """ GIVEN the string 'text/xml' as content_type WHEN calling the method _content_type2metadata_type THEN check that return value is MetadataType.XML_METS """ expected = MetadataType.XML_METS actual = _content_type2metadata_type('text/xml') assert actual == expected def test__content_type2metadata_type__failure(): """ GIVEN the string 'text' as content_type WHEN calling the method _content_type2metadata_type THEN check that a InvalidContentType Exception has been raised """ with pytest.raises(InvalidContentType): _content_type2metadata_type('text') def test__get_file_content(testfile, testfile_content): """ GIVEN a file with testdata where the content is an METS/XML file WHEN calling the method _get_file_content THEN check that the returned string is correct """ expected = testfile_content actual = _get_file_content(testfile) assert actual == expected def test_metadatafil_mapper(testfile, testfile_content): """ GIVEN a file with testdata where the content is an METS/XML file WHEN calling the method metadatafil_mapper THEN check that the returned Metadatafil object is correct """ expected = Metadatafil( filnavn="df53d1d8-39bf-4fea-a741-58d472664ce2.xml", type_=MetadataType.XML_METS, innhold=testfile_content) actual = metadatafil_mapper(testfile) assert vars(actual) == vars(expected)
[ 11748, 12972, 9288, 198, 198, 6738, 598, 13, 27830, 13, 27530, 13, 9171, 14706, 10379, 1330, 3395, 14706, 10379, 11, 3395, 14706, 6030, 198, 6738, 598, 13, 1069, 11755, 1330, 17665, 19746, 6030, 198, 6738, 598, 13, 472, 1010, 13, 76, ...
2.787167
639
from django import template register = template.Library() RACK_SIZE_PX = 20 MARGIN_HEIGHT = 2
[ 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 198, 49, 8120, 62, 33489, 62, 47, 55, 796, 1160, 198, 40569, 38, 1268, 62, 13909, 9947, 796, 362, 628, 628, 628, 628 ]
2.833333
36
import numpy as np import matplotlib.pyplot as plt from shamir import * from binascii import hexlify # img = plt.imread('cat.png') # plt.imshow(img) # plt.show() s = 'TEST_STRING'.encode() print("Original secret:", hexlify(s)) l = Shamir.split(3, 5, '12345'.encode()) for idx, item in l: print("Share {}: {}".format(str(idx), hexlify(item))) shares = l[1:4] secret = Shamir.combine(shares) print(f'Secret is : {secret.decode()}')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 23565, 343, 1330, 1635, 198, 6738, 9874, 292, 979, 72, 1330, 17910, 75, 1958, 198, 198, 2, 33705, 796, 458, 83, 13, 320, 961, 10...
2.363636
187
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" s = Reverse_Stack() print(s.is_empty()) s.push(4) s.push("Dog") print(s.peek()) s.push("Cat") print(s.size()) print(s.is_empty()) s.pop() print(s.peek()) print(s.size())
[ 37811, 49, 964, 325, 8931, 318, 1262, 257, 1351, 810, 262, 1353, 318, 379, 262, 3726, 2427, 286, 379, 262, 886, 526, 15931, 628, 198, 198, 82, 796, 31849, 62, 25896, 3419, 198, 198, 4798, 7, 82, 13, 271, 62, 28920, 28955, 198, 82,...
2.472222
108
from gerapy.server.manage import manage import sys
[ 6738, 27602, 12826, 13, 15388, 13, 805, 496, 1330, 6687, 198, 11748, 25064, 198 ]
3.642857
14
#!/usr/bin/env python import sys, tty, termios, array, fcntl, curses
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 11, 256, 774, 11, 3381, 4267, 11, 7177, 11, 277, 66, 429, 75, 11, 43878, 198 ]
2.555556
27
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Unit tests for the `ensemble_calibration.CalibratedForecastDistributionParameters` class. """ import unittest import numpy as np from iris.cube import CubeList from iris.tests import IrisTest from numpy.testing import assert_array_almost_equal from improver.calibration.ensemble_calibration import ( CalibratedForecastDistributionParameters as Plugin, ) from improver.calibration.ensemble_calibration import ( EstimateCoefficientsForEnsembleCalibration, ) from improver.metadata.constants.attributes import MANDATORY_ATTRIBUTE_DEFAULTS from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube from improver.utilities.warnings_handler import ManageWarnings from .helper_functions import EnsembleCalibrationAssertions, SetupCubes from .test_EstimateCoefficientsForEnsembleCalibration import SetupExpectedCoefficients if __name__ == "__main__": unittest.main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16529, 32501, 198, 2, 357, 34, 8, 3517, 12223, 15069, 2177, 12, 1238, 2481, 3395, 4452, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 290, ...
3.476319
739
"Test handling/parsing of various DAZ Studio files" from pathlib import Path from tempfile import NamedTemporaryFile from django.apps import apps from rendaz.daztools import ( DSONFile, ProductMeta, manifest_files, supplement_product_name, ) TEST_DIR = Path(__file__).parent def test_read_dson_compressed(): "Test reading compressed DSON files" fname = TEST_DIR / "Sphere-compressed.duf" duf = DSONFile(path=str(fname)) assert duf.path.name == "Sphere-compressed.duf" assert duf.is_compressed assert "asset_info" in duf.dson def test_read_dson_uncompressed(): "Test reading uncompressed DSON files" fname = TEST_DIR / "Sphere-uncompressed.duf" duf = DSONFile(path=str(fname)) assert duf.path.name == "Sphere-uncompressed.duf" assert duf.is_compressed is False assert "asset_info" in duf.dson def test_save_dson_compressed(): "Test write round trip, read uncompressed, write compressed, read back" fname = TEST_DIR / "Sphere-uncompressed.duf" duf = DSONFile(path=str(fname)) out = NamedTemporaryFile(mode="wt", delete=False) tmpname = out.name out.close() try: duf.save(tmpname, compress=True) new = DSONFile(tmpname) assert new.is_compressed assert "asset_info" in new.dson finally: Path(tmpname).unlink() def test_save_dson_uncompressed(): "Test write round trip, read compressed, write uncompressed, read back" fname = TEST_DIR / "Sphere-compressed.duf" duf = DSONFile(path=str(fname)) out = NamedTemporaryFile(mode="wt", delete=False) tmpname = out.name out.close() try: duf.save(tmpname, compress=False) new = DSONFile(tmpname) assert new.is_compressed is False assert "asset_info" in new.dson finally: Path(tmpname).unlink()
[ 1, 14402, 9041, 14, 79, 945, 278, 286, 2972, 17051, 57, 11733, 3696, 1, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 20218, 7753, 1330, 34441, 12966, 5551, 8979, 198, 198, 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 198, 67...
2.464807
753
import random import string from typing import Union, List import torch import torch.nn as nn import torch.nn.functional as F from ..layers.common import EncoderRNN, DecoderRNN, dropout from ..layers.attention import * from ..layers.graphs import GraphNN from ..utils.generic_utils import to_cuda, create_mask from ..utils.constants import VERY_SMALL_NUMBER
[ 11748, 4738, 198, 11748, 4731, 198, 6738, 19720, 1330, 4479, 11, 7343, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 198, 6738, 11485, 75, 6962, 13, 11321, ...
3.351852
108
# Copyright 2021 Zilliz. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from towhee.engine.graph_context import GraphContext from towhee.dag.graph_repr import GraphRepr from towhee.dataframe.dataframe import DFIterator
[ 2, 15069, 33448, 1168, 359, 528, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13...
3.728643
199
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 201, 198, 201, 198, 2, 13610, 534, 4981, 994, 13, 201 ]
3.277778
18
# Copyright 20152020 Kullo GmbH # # This source code is licensed under the 3-clause BSD license. See LICENSE.txt # in the root directory of this source tree for details. from django.test import TestCase # Create your tests here.
[ 2, 15069, 1853, 42334, 509, 724, 78, 402, 2022, 39, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 513, 12, 565, 682, 347, 10305, 5964, 13, 4091, 38559, 24290, 13, 14116, 198, 2, 287, 262, 6808, 8619, 286, 428, 2723, 5509,...
3.538462
65
#!/usr/bin/env python import signal import buttonshim print(""" Button SHIM: rainbow.py Command on button press. Press Ctrl+C to exit. """) import commands signal.pause()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 6737, 198, 11748, 12163, 38400, 198, 198, 4798, 7203, 15931, 198, 21864, 6006, 3955, 25, 27223, 13, 9078, 198, 198, 21575, 319, 4936, 1803, 13, 220, 198, 198, 13800, 19212, ...
2.322222
90
from .cascade_head import CascadeFCBBoxHead from .convfc_bbox_head import SharedFCBBoxHead __all__ = [ 'CascadeFCBBoxHead', 'SharedFCBBoxHead']
[ 6738, 764, 66, 28966, 62, 2256, 1330, 48788, 4851, 33, 14253, 13847, 198, 6738, 764, 42946, 16072, 62, 65, 3524, 62, 2256, 1330, 39403, 4851, 33, 14253, 13847, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 34, 28966, 4...
2.55
60
import datetime from .monzobalance import MonzoBalance from .monzopagination import MonzoPaging from .monzotransaction import MonzoTransaction
[ 11748, 4818, 8079, 198, 6738, 764, 2144, 89, 2572, 590, 1330, 2892, 10872, 45866, 198, 6738, 764, 2144, 89, 404, 363, 1883, 1330, 2892, 10872, 47, 3039, 198, 6738, 764, 2144, 89, 313, 26084, 2673, 1330, 2892, 10872, 48720, 198, 220, 2...
3.06
50
from typing import Dict, Optional from fastapi import status, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from learninghouse.models import LearningHouseErrorMessage MIMETYPE_JSON = 'application/json'
[ 6738, 19720, 1330, 360, 713, 11, 32233, 198, 198, 6738, 3049, 15042, 1330, 3722, 11, 19390, 198, 6738, 3049, 15042, 13, 16733, 274, 1330, 19449, 31077, 198, 6738, 3049, 15042, 13, 1069, 11755, 1330, 19390, 7762, 24765, 12331, 198, 198, ...
3.955882
68
import pandas as pd def get_windowed_ts(ranged_ts, window_size, with_actual=True): """ Creates a data frame where each row is a window of samples from the time series. Each consecutive row is a shift of 1 cell from the previous row. For example: [[1,2,3],[2,3,4],[3,4,5]] :param ranged_ts: a pd.DataFrame containing one column for values and one pd.DatetimeIndex for dates :param window_size: The number of timestamps to be used as features :param with_actual: Whether to increase window size by one, and treat the last column as the ground truth (relevant for forecasting scenarios). Returns the same output just with a window size bigger by 1. :return: """ windowed_ts = ranged_ts windowed_ts_copy = windowed_ts.copy() for i in range(window_size - 1 + int(with_actual)): windowed_ts = pd.concat([windowed_ts, windowed_ts_copy.shift(-(i + 1))], axis=1) windowed_ts = windowed_ts.dropna(axis=0) return windowed_ts def split_history_and_current(windowed_ts): """ Returns the first n-1 columns as X, and the last column as y. Useful mainly for forecasting scenarios :param windowed_ts: a pd.DataFrame with a date index and a column per timestamp. see get_windowed_ts :return: """ X = windowed_ts.iloc[:, :-1].values y = windowed_ts.iloc[:, -1].values return (X, y) if __name__ == "__main__": ranged_ts = pd.DataFrame({"date": range(6), "value": range(6)}) ranged_ts["date"] = pd.to_datetime(ranged_ts["date"]) ranged_ts = ranged_ts.set_index(pd.DatetimeIndex(ranged_ts["date"])) ranged_ts = ranged_ts.drop(columns="date") ranged_ts.head() windowed_df = get_windowed_ts(ranged_ts, window_size=3, with_actual=False)
[ 11748, 19798, 292, 355, 279, 67, 628, 198, 4299, 651, 62, 7972, 6972, 62, 912, 7, 34457, 62, 912, 11, 4324, 62, 7857, 11, 351, 62, 50039, 28, 17821, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 7921, 274, 257, 1366, 5739, ...
2.718944
644
# Copyright (C) 2021 Markus Wallerberger and others # SPDX-License-Identifier: MIT import numpy as np import xprec
[ 2, 15069, 357, 34, 8, 33448, 46013, 5007, 263, 21041, 290, 1854, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 3866, 66, 628, 628, 628, 198 ]
3.184211
38
from .read_hdf5 import * from .hdf5_api import *
[ 6738, 764, 961, 62, 71, 7568, 20, 1330, 1635, 198, 6738, 764, 71, 7568, 20, 62, 15042, 1330, 1635 ]
2.526316
19
from pathlib import Path from toolz import itertoolz, curried import vaex transform_path_to_posix = lambda path: path.as_posix() transform_xlsx_to_vaex = lambda path: vaex.from_ascii(path, seperator="\t") transform_ascii_to_vaex = lambda path: vaex.from_ascii(path, seperator="\t") transform_ascii_to_vaex2 = lambda path: vaex.from_ascii(path) transform_vaex_to_list = lambda df: [itertoolz.second(x) for x in df.iterrows()] transform_vaex_to_dict = lambda df: df.to_dict()
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 2891, 89, 1330, 340, 861, 970, 89, 11, 1090, 2228, 198, 11748, 46935, 1069, 628, 198, 35636, 62, 6978, 62, 1462, 62, 1930, 844, 796, 37456, 3108, 25, 3108, 13, 292, 62, 1930, 844, 3419, 628,...
2.497462
197
import PIL from PIL import Image from io import BytesIO import re
[ 11748, 350, 4146, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 11748, 302 ]
3.421053
19
# Copyright 2018-2021 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from typing import TYPE_CHECKING, List, Optional, Tuple from synapse.api.errors import SynapseError from synapse.handlers.room_member import RoomMemberHandler from synapse.replication.http.membership import ( ReplicationRemoteJoinRestServlet as ReplRemoteJoin, ReplicationRemoteKnockRestServlet as ReplRemoteKnock, ReplicationRemoteRejectInviteRestServlet as ReplRejectInvite, ReplicationRemoteRescindKnockRestServlet as ReplRescindKnock, ReplicationUserJoinedLeftRoomRestServlet as ReplJoinedLeft, ) from synapse.types import JsonDict, Requester, UserID if TYPE_CHECKING: from synapse.server import HomeServer logger = logging.getLogger(__name__)
[ 2, 15069, 2864, 12, 1238, 2481, 383, 24936, 13, 2398, 5693, 327, 13, 40, 13, 34, 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, 284...
3.485175
371
import tempfile import maya.OpenMaya as OpenMaya import maya.OpenMayaRender as OpenMayaRender import maya.OpenMayaMPx as OpenMayaMPx import maya.cmds as cmds import maya import re from maya.app.edl.fcp import * def _setTimeCode(timecode): pass def doExport(fileName, allowPlayblast): """ Exports the Maya sequence using the EDL Exporter class. """ pass def doMel(*args, **kwargs): """ Takes as input a string containing MEL code, evaluates it, and returns the result. This function takes a string which contains MEL code and evaluates it using the MEL interpreter. The result is converted into a Python data type and is returned. If an error occurs during the execution of the MEL script, a Python exception is raised with the appropriate error message. """ pass def audioClipCompare(a, b): pass def _getValidClipObjectName(clipName, isVideo): pass def doImport(fileName, useStartFrameOverride, startFrame): """ Imports the specified file using the EDL Importer class. """ pass def _nameToNode(name): pass def getTimeCode(): pass def videoClipCompare(a, b): pass def getShotsResolution(): """ Returns the video resolution of the sequencer if all the shots have the same resolution Otherwise it returns False, 0, 0 """ pass mayaFrameRates = {}
[ 11748, 20218, 7753, 198, 11748, 743, 64, 13, 11505, 6747, 64, 355, 4946, 6747, 64, 198, 11748, 743, 64, 13, 11505, 6747, 64, 45819, 355, 4946, 6747, 64, 45819, 198, 11748, 743, 64, 13, 11505, 6747, 64, 7378, 87, 355, 4946, 6747, 64,...
2.930962
478
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 2006-2010 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ## Note: ## 1. This package depends on dsm from mcni.neutron_coordinates_transformers import default as default_neutron_coordinates_transformer default_simulator = simulator( default_neutron_coordinates_transformer ) # version __id__ = "$Id$" # End of file
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 198, 2, 220, 220, 27156, 27156, 27156, 27156, 27156, 198, 2, 220, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
2.751037
241
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todolist.settings') application = get_wsgi_application()
[ 11748, 28686, 198, 6738, 42625, 14208, 13, 7295, 13, 18504, 12397, 1330, 651, 62, 18504, 12397, 62, 31438, 628, 198, 418, 13, 268, 2268, 13, 2617, 12286, 10786, 35028, 1565, 11230, 62, 28480, 51, 20754, 62, 33365, 24212, 3256, 705, 83, ...
2.864407
59
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of CERN Search. # Copyright (C) 2018-2021 CERN. # # Citadel Search is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line utilities.""" import json import click from flask.cli import with_appcontext from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_records.models import RecordMetadata from invenio_search import current_search from invenio_search.cli import es_version_check from cern_search_rest_api.modules.cernsearch.indexer import CernSearchRecordIndexer from cern_search_rest_api.modules.cernsearch.indexer_tasks import process_bulk_queue def abort_if_false(ctx, param, value): """Abort command is value is False.""" if not value: ctx.abort()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 327, 28778, 11140, 13, 198, 2, 15069, 357, 34, 8, 2864, 12, 1238, 2481, 327, 28778, ...
3.129964
277
__author__ = 'wektor' from generic import GenericBackend import redis
[ 834, 9800, 834, 796, 705, 732, 74, 13165, 6, 198, 198, 6738, 14276, 1330, 42044, 7282, 437, 198, 11748, 2266, 271, 198 ]
3.227273
22
# Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from collections import namedtuple from time import sleep try: from botocore.exceptions import BotoCoreError, ClientError, WaiterError except ImportError: pass from ansible.module_utils._text import to_text from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict from .ec2 import AWSRetry from .ec2 import ansible_dict_to_boto3_tag_list from .ec2 import boto3_tag_list_to_ansible_dict from .ec2 import compare_aws_tags from .waiters import get_waiter Boto3ClientMethod = namedtuple('Boto3ClientMethod', ['name', 'waiter', 'operation_description', 'cluster', 'instance']) # Whitelist boto3 client methods for cluster and instance resources cluster_method_names = [ 'create_db_cluster', 'restore_db_cluster_from_db_snapshot', 'restore_db_cluster_from_s3', 'restore_db_cluster_to_point_in_time', 'modify_db_cluster', 'delete_db_cluster', 'add_tags_to_resource', 'remove_tags_from_resource', 'list_tags_for_resource', 'promote_read_replica_db_cluster' ] instance_method_names = [ 'create_db_instance', 'restore_db_instance_to_point_in_time', 'restore_db_instance_from_s3', 'restore_db_instance_from_db_snapshot', 'create_db_instance_read_replica', 'modify_db_instance', 'delete_db_instance', 'add_tags_to_resource', 'remove_tags_from_resource', 'list_tags_for_resource', 'promote_read_replica', 'stop_db_instance', 'start_db_instance', 'reboot_db_instance' ]
[ 2, 15069, 25, 357, 66, 8, 2864, 11, 28038, 856, 4935, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 357, 3826, 27975, 45761, 393, 3740, 1378, 2503, 13, 41791, 13, 2398, 14, 677, 4541, 14, 70, 489, 12, 18, 13, 15, 13, ...
2.803723
591
# Uppercases string one character at a time from cs50 import get_string s = get_string("Before: ") print("After: ", end="") for c in s: print(c.upper(), end="") print()
[ 2, 471, 39921, 1386, 4731, 530, 2095, 379, 257, 640, 198, 198, 6738, 50115, 1120, 1330, 651, 62, 8841, 198, 198, 82, 796, 651, 62, 8841, 7203, 8421, 25, 366, 8, 198, 4798, 7203, 3260, 25, 220, 33172, 886, 2625, 4943, 198, 1640, 26...
2.75
64
from datetime import datetime from pathlib import Path import pytz import kobuddy # a bit meh, but ok for now kobuddy.set_databases(get_test_db()) from kobuddy import _iter_events_aux, get_events, get_books_with_highlights, _iter_highlights
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 12972, 22877, 198, 198, 11748, 479, 672, 21584, 198, 198, 2, 257, 1643, 502, 71, 11, 475, 12876, 329, 783, 198, 74, 672, 21584, 13, 2617, 62, 19608, ...
2.929412
85
from django.shortcuts import render from .models import Tank from django.db import models from django.http import HttpResponse from django.views import View # Create your views here. # The view for the created model Tank
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 764, 27530, 1330, 15447, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 33571, 1330, 358...
3.737705
61
import os import numpy as np import torch import torch.nn as nn import torch.optim as optim import argparse from tqdm import tqdm import sys import distributed as dist import utils from models.vqvae import VQVAE, VQVAE_Blob2Full from models.discriminator import discriminator visual_folder = '/home2/bipasha31/python_scripts/CurrentWork/samples/VQVAE' os.makedirs(visual_folder, exist_ok=True) verbose = False save_idx_global = 0 save_at = 100 did = 0 models = { 'gan': 0, 'vae': 1 } model_to_train = models['vae'] results = { 'n_updates': 0, 'recon_errors': [], 'loss_vals': [], 'perplexities': [], 'd_loss': [] } device = 'cuda:0' def main(args): """ Set up VQ-VAE model with components defined in ./models/ folder """ model = VQVAE(args.n_hiddens, args.n_residual_hiddens, args.n_residual_layers, args.n_embeddings, args.embedding_dim, args.beta, device) if args.ckpt: model.load_state_dict(torch.load(args.ckpt)['model']) model = model.to(device) if args.test: loader = utils.load_data_and_data_loaders(args.dataset, args.batch_size, test=True) test(loader, model) return """ Load data and define batch data loaders """ items = utils.load_data_and_data_loaders(args.dataset, args.batch_size) training_loader, validation_loader = items[2], items[3] x_train_var = items[4] """ Set up optimizer and training loop """ optimizer = optim.Adam(model.parameters(), lr=args.learning_rate, amsgrad=True) model.train() if model_to_train == models['gan']: train_vqgan(args, training_loader, validation_loader, x_train_var, model, optimizer) else: train(args, training_loader, validation_loader, x_train_var, model, optimizer) if __name__ == "__main__": # train_vqgan() # train_blob2full() parser = argparse.ArgumentParser() """ Hyperparameters """ timestamp = utils.readable_timestamp() parser.add_argument("--batch_size", type=int, default=64) parser.add_argument("--n_updates", type=int, default=50000) parser.add_argument("--n_hiddens", type=int, default=128) parser.add_argument("--n_residual_hiddens", type=int, default=32) parser.add_argument("--n_residual_layers", type=int, default=2) parser.add_argument("--embedding_dim", type=int, default=64) parser.add_argument("--n_embeddings", type=int, default=512) parser.add_argument("--beta", type=float, default=.25) parser.add_argument("--learning_rate", type=float, default=3e-4) parser.add_argument("--ckpt", type=str) parser.add_argument("--log_interval", type=int, default=3) parser.add_argument("--save_at", type=int, default=100) parser.add_argument("--device_id", type=int, default=0) parser.add_argument("--dataset", type=str, default='HandGestures') parser.add_argument("--test", action='store_true') # whether or not to save model parser.add_argument("-save", action="store_true") parser.add_argument("--filename", type=str, default=timestamp) args = parser.parse_args() args.save = True if args.save and dist.is_primary(): print('Results will be saved in ./results/vqvae_' + args.filename + '.pth') args.n_gpu = torch.cuda.device_count() port = ( 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14 )+1 print(f'port: {port}') print(args) dist.launch(main, args.n_gpu, 1, 0, f"tcp://127.0.0.1:{port}", args=(args,))
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 1822, 29572, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198...
2.430883
1,483
# pylint: disable=unused-variable,unused-argument,expression-not-assigned from django.forms.models import model_to_dict import arrow import pytest from expecter import expect from api.elections.models import Election from .. import models def describe_registration_info(): def describe_voter(): def describe_status():
[ 2, 279, 2645, 600, 25, 15560, 28, 403, 1484, 12, 45286, 11, 403, 1484, 12, 49140, 11, 38011, 12, 1662, 12, 562, 3916, 198, 198, 6738, 42625, 14208, 13, 23914, 13, 27530, 1330, 2746, 62, 1462, 62, 11600, 198, 198, 11748, 15452, 198, ...
3.412371
97
from operator import itemgetter
[ 6738, 10088, 1330, 2378, 1136, 353, 628, 198 ]
4.25
8
from typing import Optional, Dict, Any from fastapi import APIRouter from jina.helper import ArgNamespace from jina.parsers import set_pod_parser from ....excepts import PartialDaemon400Exception from ....models import PodModel from ....models.partial import PartialStoreItem from ....stores import partial_store as store router = APIRouter(prefix='/pod', tags=['pod'])
[ 6738, 19720, 1330, 32233, 11, 360, 713, 11, 4377, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 198, 198, 6738, 474, 1437, 13, 2978, 525, 1330, 20559, 36690, 10223, 198, 6738, 474, 1437, 13, 79, 945, 364, 1330, 900, 62, 33320, 62, ...
3.6
105
import yaml
[ 11748, 331, 43695, 628 ]
3.25
4
#!/usr/bin/env python3 import argparse import csv import logging import os import re import sys DELIMITER = ',' if __name__ == '__main__': sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 1822, 29572, 198, 11748, 269, 21370, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 198, 35, 3698, 3955, 2043, 1137, 796, 705, 4032, 628, 628, ...
2.59375
64
# coding=utf-8 from builtins import str import json from django.contrib.auth.models import Group, Permission from django.urls import reverse from rest_framework import status from bluebottle.impact.models import ImpactGoal from bluebottle.impact.tests.factories import ( ImpactTypeFactory, ImpactGoalFactory ) from bluebottle.time_based.tests.factories import DateActivityFactory from bluebottle.members.models import MemberPlatformSettings from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from bluebottle.test.utils import BluebottleTestCase, JSONAPITestClient
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 3170, 1040, 1330, 965, 198, 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 11, 2448, 3411, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, ...
3.656442
163
from . import ParserV2 import dotmotif import unittest _THREE_CYCLE = """A -> B\nB -> C\nC -> A\n""" _THREE_CYCLE_NEG = """A !> B\nB !> C\nC !> A\n""" _THREE_CYCLE_INH = """A -| B\nB -| C\nC -| A\n""" _THREE_CYCLE_NEG_INH = """A !| B\nB !| C\nC !| A\n""" _ABC_TO_D = """\nA -> D\nB -> D\nC -> D\n""" _THREE_CYCLE_CSV = """\nA,B\nB,C\nC,A\n""" _THREE_CYCLE_NEG_CSV = """\nA,B\nB,C\nC,A\n"""
[ 6738, 764, 1330, 23042, 263, 53, 17, 198, 11748, 16605, 27926, 361, 198, 198, 11748, 555, 715, 395, 198, 198, 62, 4221, 11587, 62, 34, 56, 29931, 796, 37227, 32, 4613, 347, 59, 77, 33, 4613, 327, 59, 77, 34, 4613, 317, 59, 77, 3...
1.658333
240
from typing import List import click import torch from fandak.utils import common_config from fandak.utils import set_seed from fandak.utils.config import update_config from proj.config import get_config_defaults from proj.datasets import MNISTClassification from proj.evaluators import ValidationEvaluator from proj.models import MLPModel from proj.trainers import SimpleTrainer if __name__ == "__main__": main()
[ 6738, 19720, 1330, 7343, 198, 198, 11748, 3904, 198, 11748, 28034, 198, 198, 6738, 277, 392, 461, 13, 26791, 1330, 2219, 62, 11250, 198, 6738, 277, 392, 461, 13, 26791, 1330, 900, 62, 28826, 198, 6738, 277, 392, 461, 13, 26791, 13, ...
3.27907
129
from problem_solving.algorithms.sorting import *
[ 6738, 1917, 62, 82, 10890, 13, 282, 7727, 907, 13, 82, 24707, 1330, 1635, 628, 198 ]
3.1875
16
import sqlite3 from sqlite3 import Error import os import time import datetime import re import random import schedule import cryptography from apscheduler.schedulers.background import BackgroundScheduler from slackclient import SlackClient from cryptography.fernet import Fernet conn = sqlite3.connect('/home/ubuntu/otakuBot/data/anime.db') serverCursor = conn.cursor() keyFile = open('/home/ubuntu/otakuBot/data/otakubot_token.key', 'rb') key = keyFile.read() keyFile.close() f = Fernet(key) encryptedTokenFile = open('/home/ubuntu/otakuBot/data/otakubot_token.encrypted', 'rb') encryptedToken = encryptedTokenFile.read() decryptedToken = f.decrypt(encryptedToken) SLACK_BOT_TOKEN = decryptedToken.decode() # instantiate Slack client slack_client = SlackClient(SLACK_BOT_TOKEN) # starterbot's user ID in Slack: value is assigned after the bot starts up otakuBotID = None # constants RTM_READ_DELAY = 0.5 # 0.5 second delay in reading events schedule.every(15).minutes.do(logIt) def handle_command(command, channel, aUser, tStamp): """ Executes bot command if the command is known """ #command = command.lower() response = None # This is where you start to implement more commands! if command.lower().startswith("!help"): response = """I'm Otaku Bot! I don't do a lot yet. But watch out! I'm just getting started! !addquote[SPACE][A quote of your choice!] - I will remember your quote! !quote - I will reply with a random quote! !addAniMusic[SPACE][Link to a Japanese anime song] - I will remember your music! !addEngMusic[SPACE][Link to an English anime song] - I will remember your music! !addIconic[SPACE][Link to an iconic anime moment] - I will remember your moment! !animusic - I will reply with a Japanese anime song from memory! !engmusic - I will reply with an English anime song from memory! !iconic - I will show you an iconic anime moment! """ inChannelResponse(channel,response) return if command.lower().startswith("!addquote"): newQuote = str(command[10:]) insertQuote(aUser,newQuote) threadedResponse(channel,"I'll try to remember: " + newQuote ,tStamp) stdOut("Quote Added: " + newQuote) return if command.lower().startswith("!quote"): aQuote = getQuote(conn) inChannelResponse(channel,aQuote) return if command.lower().startswith("!animusic"): aQuote = getAniMusic(conn) inChannelResponse(channel,aQuote) return if command.lower().startswith("!engmusic"): aQuote = getEngMusic(conn) inChannelResponse(channel,aQuote) return if command.lower().startswith("!iconic"): aQuote = getIconic(conn) inChannelResponse(channel,aQuote) return if command.lower().startswith("!onepunch"): inChannelResponse(channel,"https://www.youtube.com/watch?v=_TUTJ0klnKk") return if command.lower().startswith("!addanimusic"): newQuote = str(command[13:]) insertAniMusic(aUser,newQuote) threadedResponse(channel,"I'll add this to the Anime music section: " + newQuote ,tStamp) stdOut("Anime Music Added: " + newQuote) return if command.lower().startswith("!addengmusic"): newQuote = str(command[13:]) insertEngMusic(aUser,newQuote) threadedResponse(channel,"I'll add this to the English music section: " + newQuote ,tStamp) stdOut("English Music Added: " + newQuote) return if command.lower().startswith("!addiconic"): newQuote = str(command[11:]) insertIcon(aUser,newQuote) threadedResponse(channel,"I'll add this to the Iconic moments section: " + newQuote ,tStamp) stdOut("Iconic Moment Added: " + newQuote) return if command.lower().startswith("!delquote"): if aUser == "UC176R92M": num = command[10:] deleteQuote(num) inChannelResponse(channel,"You have removed a quote.") else: inChannelResponse(channel,"You don't have permission to do that!") return if command.lower().startswith("!getquotes"): if aUser == "UC176R92M": inChannelResponse(channel,getAllQuotes(conn)) else: inChannelResponse(channel,"You don't have permission to do that!") return if command.startswith("!test"): return response = (("""Text:{0} Channel:{1} TS:{2} User:{3} """).format(command,channel,tStamp,aUser)) inChannelResponse(channel,response) return return # Sends the response back to the channel if __name__ == "__main__": if slack_client.rtm_connect(with_team_state=False): stdOut("Otaku Bot connected and running!") # Read bot's user ID by calling Web API method `auth.test` otakuBotID = slack_client.api_call("auth.test")["user_id"] while True: try: command, channel,usr,stp = parseSlackInput(slack_client.rtm_read()) if command: handle_command(command, channel,usr,stp) except: pass schedule.run_pending() time.sleep(RTM_READ_DELAY) else: stdOut("Connection failed. Exception traceback printed above.")
[ 11748, 44161, 578, 18, 201, 198, 6738, 44161, 578, 18, 1330, 13047, 201, 198, 11748, 28686, 201, 198, 11748, 640, 201, 198, 11748, 4818, 8079, 201, 198, 11748, 302, 201, 198, 11748, 4738, 201, 198, 11748, 7269, 201, 198, 11748, 45898, ...
2.661859
1,872
from PIL import Image import cv2 import pytesseract import tesserocr from pyocr import pyocr from pyocr import builders import sys import os
[ 6738, 350, 4146, 1330, 7412, 198, 11748, 269, 85, 17, 198, 11748, 12972, 83, 408, 263, 529, 198, 11748, 256, 408, 263, 1696, 198, 6738, 12972, 1696, 1330, 12972, 1696, 198, 6738, 12972, 1696, 1330, 31606, 198, 11748, 25064, 198, 11748, ...
3.244444
45
# Copyright (c) 2021 PPViT Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import paddle import paddle.nn as nn from paddle.nn.initializer import Normal, Constant from retinanet_loss import RetinaNetLoss from post_process import RetinaNetPostProcess from det_utils.generator_utils import AnchorGenerator
[ 2, 220, 220, 15069, 357, 66, 8, 33448, 21082, 38432, 51, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393,...
3.704348
230
from django import template from django.forms import widgets register = template.Library()
[ 6738, 42625, 14208, 1330, 11055, 198, 6738, 42625, 14208, 13, 23914, 1330, 40803, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 198 ]
4.181818
22
# CONFIG seeds = [6598903756360202179, 2908409715321502665, 6126375328734039552, 1447957147463681860, 8611858271322161001, 1129180857020570158, 6362222119948958210, 7116573423379052515, 6183551438103583226, 4025455056998962241, 3253052445978017587, 8447055112402476503, 5958072666039141800, 704315598608973559, 1273141716491599966, 8030825590436937002, 6692768176035969914, 8405559442957414941, 5375803109627817298, 1491660193757141856, 3436611086188602011, 3271002097187013328, 4006294871837743001, 7473817498436254932, 7891796310200224764, 3130952787727334893, 697469171142516880, 133987617360269051, 1978176412643604703, 3541943493395593807, 5679145832406031548, 5942005640162452699, 5170695982942106620, 3168218038949114546, 9211443340810713278, 675545486074597116, 3672488441186673791, 6678020899892900267, 2416379871103035344, 8662874560817543122, 2122645477319220395, 2405200782555244715, 6145921643610737337, 5436563232962849112, 8616414727199277108, 3514934091557929937, 6828532625327352397, 4198622582999611227, 1404664771100695607, 2109913995355226572, 7499239331133290294, 1663854912663070382, 8773050872378084951, 847059168652279875, 2080440852605950627, 842456810578794799, 2969610112218411619, 8028963261673713765, 8849431138779094918, 6906452636298562639, 8279891918456160432, 3007521703390185509, 7384090506069372457, 2587992914778556505, 7951640286729988102, 812903075765965116, 4795333953396378316, 1140497104356211676, 8624839892588303806, 5867085452069993348, 8978621560802611959, 8687506047153117100, 1433098622112610322, 2329673189788559167, 1697681906179453583, 1151871187140419944, 7331838985682630168, 2010690807327394179, 8961362099735442061, 3782928183186245068, 8730275423842935904, 2250089307129376711, 6729072114456627667, 6426359511845339057, 1543504526754215874, 6764758859303816569, 438430728757175362, 850249168946095159, 7241624624529922339, 633139235530929889, 8443344843613690342, 5097223086273121, 3838826661110586915, 7425568686759148634, 5814866864074983273, 5375799982976616117, 6540402714944055605, 448708351215739494, 5101380446889426970, 8035666378249198606]
[ 2, 25626, 198, 325, 5379, 796, 685, 2996, 42520, 3070, 2425, 5066, 1899, 19004, 21738, 11, 2808, 2919, 1821, 5607, 21395, 2481, 1120, 2075, 2996, 11, 718, 1065, 5066, 2425, 34256, 4790, 1821, 2670, 40427, 11, 1478, 31714, 3553, 20198, 3...
2.233546
942
import torch import torch.nn as nn import numpy as np
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 299, 32152, 355, 45941, 198 ]
3.176471
17
n = int(input()) % 8 if n == 0: print(2) elif n <= 5: print(n) else: print(10 - n)
[ 77, 796, 493, 7, 15414, 28955, 4064, 807, 198, 361, 299, 6624, 657, 25, 198, 220, 220, 220, 3601, 7, 17, 8, 198, 417, 361, 299, 19841, 642, 25, 220, 198, 220, 220, 220, 3601, 7, 77, 8, 198, 17772, 25, 198, 220, 220, 220, 3601,...
1.846154
52
#!/usr/bin/env python3 # coding:utf-8 import urllib from xml.etree import ElementTree import xml.dom.minidom as md
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 25, 40477, 12, 23, 198, 11748, 2956, 297, 571, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 198, 11748, 35555, 13, 3438, 13, 1084, 312, 296, 355, 45243, 628, 628...
2.704545
44
#!/usr/bin/env python3 import os import shutil from subprocess import Popen, PIPE from datetime import date import yaml os.chdir(os.path.dirname(os.path.realpath(__file__))) CLIMBING_FOLDER = "." CLIMBING_VIDEOS_FOLDER = os.path.join(CLIMBING_FOLDER, "videos") CLIMBING_INFO = os.path.join(CLIMBING_FOLDER, "videos.yaml") config = {} if os.path.exists(CLIMBING_INFO): with open(CLIMBING_INFO, "r") as f: config = yaml.safe_load(f.read()) files = os.listdir(CLIMBING_VIDEOS_FOLDER) for file in files: if file.lower().endswith(".mp4") and file not in config: print(f"adding new file {file}.") config[file] = { "color": "TODO", "date": date.today(), "zone": "TODO", "new": None, "rotate": "left", "encode": None, "trim": "TODO", } with open(CLIMBING_INFO, "w") as f: f.write(yaml.dump(config))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 6738, 4818, 8079, 1330, 3128, 198, 198, 11748, 331, 43695, 628, 198, 418, ...
2.010846
461
from django.db import models from categorias.models import Categoria from django.contrib.auth.models import User from django.utils import timezone # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 17851, 4448, 13, 27530, 1330, 327, 2397, 7661, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 19...
3.666667
48
#!/usr/bin/env python import datetime import logging import os import random import rospy import schedule from interaction_engine.cordial_interface import CordialInterface from interaction_engine.database import Database from interaction_engine.int_engine import InteractionEngine from interaction_engine.message import Message from interaction_engine.state import State from interaction_engine.state_collection import StateCollection from cordial_msgs.msg import AskOnGuiAction, AskOnGuiGoal, MouseEvent from std_msgs.msg import Bool logging.basicConfig(level=logging.INFO) greeting = State( name=Keys.GREETING, message_type=Message.Type.MULTIPLE_CHOICE_ONE_COLUMN, content="Hello!", next_states=[Keys.HOW_ARE_YOU], transitions={"Hello!": Keys.HOW_ARE_YOU, "Hi!": Keys.HOW_ARE_YOU} ) how_are_you = State( name=Keys.HOW_ARE_YOU, message_type=Message.Type.MULTIPLE_CHOICE_ONE_COLUMN, content="How are you doing today?", next_states=[Keys.TAKE_CARE], transitions={ "Pretty good.": Keys.TAKE_CARE, "Great!": Keys.TAKE_CARE, "Not too good.": Keys.TAKE_CARE } ) take_care = State( name=Keys.TAKE_CARE, message_type=Message.Type.MULTIPLE_CHOICE_ONE_COLUMN, content="Don't forget to drink enough water and get enough sleep!", next_states=[Keys.WHEN_TO_TALK], transitions={"Next": Keys.WHEN_TO_TALK} ) when_to_talk = State( name=Keys.WHEN_TO_TALK, message_type=Message.Type.TIME_ENTRY, content="When would you like to talk tomorrow?", next_states=["exit"], args=["15", "15:15"] ) state_collection = StateCollection( name="example interaction", init_state_name=Keys.WHEN_TO_TALK, states=[ greeting, how_are_you, take_care, when_to_talk ] ) cwd = os.getcwd() database_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), "example_interaction_database.json" ) default_database_keys = [ Keys.GREETING, Keys.HOW_ARE_YOU, Keys.TAKE_CARE, Keys.WHEN_TO_TALK ] database_manager = Database( database_file_name=database_file, default_database_keys=default_database_keys ) interface = CordialInterface( action_name="cordial/say_and_ask_on_gui", seconds_until_timeout=None ) interaction_engine = InteractionEngine( state_collection=state_collection, database_manager=database_manager, interface=interface ) if __name__ == "__main__": while not rospy.is_shutdown(): rospy.logdebug("Scheduled interaction running") interaction_engine.run() rospy.sleep(5)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 4818, 8079, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 686, 2777, 88, 198, 11748, 7269, 198, 198, 6738, 10375, 62, 18392, 13, 66, 31223, 62, 39994, ...
2.516252
1,046
# -*- coding: utf-8 -*- """ @author: nicolas.posocco """ from abc import ABC import numpy as np
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 9800, 25, 9200, 12456, 13, 1930, 420, 1073, 198, 37811, 198, 198, 6738, 450, 66, 1330, 9738, 198, 11748, 299, 32152, 355, 45941, 628 ]
2.390244
41
#!/usr/bin/env python """Script used to test the network with batfish""" from pybatfish.client.commands import * from pybatfish.question import load_questions from pybatfish.client.asserts import ( assert_no_duplicate_router_ids, assert_no_incompatible_bgp_sessions, assert_no_incompatible_ospf_sessions, assert_no_unestablished_bgp_sessions, assert_no_undefined_references, ) from rich.console import Console console = Console(color_system="truecolor") def test_duplicate_rtr_ids(snap): """Testing for duplicate router IDs""" console.print( ":white_exclamation_mark: [bold yellow]Testing for duplicate router IDs[/bold yellow] :white_exclamation_mark:" ) assert_no_duplicate_router_ids( snapshot=snap, protocols={"ospf", "bgp"}, ) console.print( ":green_heart: [bold green]No duplicate router IDs found[/bold green] :green_heart:" ) def test_bgp_compatibility(snap): """Testing for incompatible BGP sessions""" console.print( ":white_exclamation_mark: [bold yellow]Testing for incompatible BGP sessions[/bold yellow] :white_exclamation_mark:" ) assert_no_incompatible_bgp_sessions( snapshot=snap, ) console.print( ":green_heart: [bold green]All BGP sessions compatible![/bold green] :green_heart:" ) def test_ospf_compatibility(snap): """Testing for incompatible OSPF sessions""" console.print( ":white_exclamation_mark: [bold yellow]Testing for incompatible OSPF sessions[/bold yellow] :white_exclamation_mark:" ) assert_no_incompatible_ospf_sessions( snapshot=snap, ) console.print( ":green_heart: [bold green]All OSPF sessions compatible![/bold green] :green_heart:" ) def test_bgp_unestablished(snap): """Testing for BGP sessions that are not established""" console.print( ":white_exclamation_mark: [bold yellow]Testing for unestablished BGP sessions[/bold yellow] :white_exclamation_mark:" ) assert_no_unestablished_bgp_sessions( snapshot=snap, ) console.print( ":green_heart: [bold green]All BGP sessions are established![/bold green] :green_heart:" ) def test_undefined_references(snap): """Testing for any undefined references""" console.print( ":white_exclamation_mark: [bold yellow]Testing for undefined references[/bold yellow] :white_exclamation_mark:" ) assert_no_undefined_references( snapshot=snap, ) console.print( ":green_heart: [bold green]No undefined refences found![/bold green] :green_heart:" ) def main(): """init all the things""" NETWORK_NAME = "PDX_NET" SNAPSHOT_NAME = "snapshot00" SNAPSHOT_DIR = "./snapshots" bf_session.host = "192.168.10.193" bf_set_network(NETWORK_NAME) init_snap = bf_init_snapshot(SNAPSHOT_DIR, name=SNAPSHOT_NAME, overwrite=True) load_questions() test_duplicate_rtr_ids(init_snap) test_bgp_compatibility(init_snap) test_ospf_compatibility(init_snap) test_bgp_unestablished(init_snap) test_undefined_references(init_snap) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 7391, 973, 284, 1332, 262, 3127, 351, 7365, 11084, 37811, 198, 198, 6738, 12972, 8664, 11084, 13, 16366, 13, 9503, 1746, 1330, 1635, 198, 6738, 12972, 8664, 11084, 13, 25652,...
2.621175
1,209
""" A fixed-capacity queue implemented as circular queue. Queue can become full. * enqueue is O(1) * dequeue is O(1) """
[ 37811, 198, 32, 5969, 12, 42404, 16834, 9177, 355, 18620, 16834, 13, 198, 34991, 460, 1716, 1336, 13, 198, 9, 551, 36560, 318, 440, 7, 16, 8, 198, 9, 390, 36560, 318, 440, 7, 16, 8, 198, 37811, 628 ]
3.128205
39
""" Create train and dev set from bronze data Example call: $ python3 create_train_dev.py --pos /mounts/work/ayyoob/results/gnn_align/yoruba/pos_tags_tam-x-bible-newworld_posfeatFalse_transformerFalse_trainWEFalse_maskLangTrue.pickle --bible tam-x-bible-newworld.txt --bronze 1 --lang tam $ python3 create_train_dev.py --pos /mounts/work/ayyoob/results/gnn_align/yoruba/pos_tags_fin-x-bible-helfi_posfeatFalse_transformerFalse_trainWEFalse_maskLangTrue.pickle --bible fin-x-bible-helfi.txt --bronze 1 --lang fin """ import torch import random import argparse if __name__ == "__main__": main()
[ 37811, 198, 16447, 4512, 290, 1614, 900, 422, 22101, 1366, 198, 198, 16281, 869, 25, 198, 3, 21015, 18, 2251, 62, 27432, 62, 7959, 13, 9078, 1377, 1930, 1220, 14948, 82, 14, 1818, 14, 323, 8226, 672, 14, 43420, 14, 4593, 77, 62, 3...
2.626087
230
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import pytest import stat from spack.hooks.permissions_setters import ( chmod_real_entries, InvalidPermissionsError ) import llnl.util.filesystem as fs
[ 2, 15069, 2211, 12, 23344, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
3.247788
113
import dask.dataframe as dd
[ 11748, 288, 2093, 13, 7890, 14535, 355, 49427, 201 ]
3.111111
9
#!/usr/bin/python # -*- coding: UTF-8 -*- import numpy as np import pandas as pd ''' sqlpandas ''' from pandas import DataFrame, Series from pandasql import sqldf, load_meat, load_births df1 = DataFrame({'name': ['jack', 'tony', 'pony'], 'data1': range(3)}) print(df1) sql = "select * from df1 where name = 'jack'" pysqldf = lambda sql: sqldf(sql, globals()); print(pysqldf(sql))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 7061, 6, 198, 25410, 79, 392, 292, 198, 706...
2.421384
159
import pytest from mock import patch import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import boto3 from string import ascii_lowercase import random from dfmock import DFMock import s3parq.publish_parq as parq import s3fs from moto import mock_s3
[ 11748, 12972, 9288, 198, 6738, 15290, 1330, 8529, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 12972, 6018, 355, 14187, 198, 11748, 12972, 6018, 13, 1845, 21108, 355, 279, 80, 198, 11748, 275, 2069, 18, 198, 6738, 4731, 1330, 355, ...
3.045455
88
#import sys #sys.path.append("../..") import pyiomica as pio from pyiomica import categorizationFunctions as cf if __name__ == '__main__': # Unzip example data with pio.zipfile.ZipFile(pio.os.path.join(pio.ConstantPyIOmicaExamplesDirectory, 'SLV.zip'), "r") as zipFile: zipFile.extractall(path=pio.ConstantPyIOmicaExamplesDirectory) # Process sample dataset SLV_Hourly1 # Name of the fisrt data set dataName = 'SLV_Hourly1TimeSeries' # Define a directory name where results are be saved saveDir = pio.os.path.join('results', dataName, '') # Directory name where example data is (*.csv files) dataDir = pio.os.path.join(pio.ConstantPyIOmicaExamplesDirectory, 'SLV') # Read the example data into a DataFrame df_data = pio.pd.read_csv(pio.os.path.join(dataDir, dataName + '.csv'), index_col=[0,1,2], header=0) # Calculate time series categorization cf.calculateTimeSeriesCategorization(df_data, dataName, saveDir, NumberOfRandomSamples = 10**5) # Cluster the time series categorization results cf.clusterTimeSeriesCategorization(dataName, saveDir) # Make plots of the clustered time series categorization cf.visualizeTimeSeriesCategorization(dataName, saveDir) # Process sample dataset SLV_Hourly2, in the same way as SLV_Hourly1 above dataName = 'SLV_Hourly2TimeSeries' saveDir = pio.os.path.join('results', dataName, '') dataDir = pio.os.path.join(pio.ConstantPyIOmicaExamplesDirectory, 'SLV') df_data = pio.pd.read_csv(pio.os.path.join(dataDir, dataName + '.csv'), index_col=[0,1,2], header=0) cf.calculateTimeSeriesCategorization(df_data, dataName, saveDir, NumberOfRandomSamples = 10**5) cf.clusterTimeSeriesCategorization(dataName, saveDir) cf.visualizeTimeSeriesCategorization(dataName, saveDir) # Import data storage submodule to read results of processing sample datasets SLV_Hourly1 and SLV_Hourly2 from pyiomica import dataStorage as ds # Use results from processing sample datasets SLV_Hourly1 and SLV_Hourly2 to calculate "Delta" dataName = 'SLV_Hourly1TimeSeries' df_data_processed_H1 = ds.read(dataName+'_df_data_transformed', hdf5fileName=pio.os.path.join('results',dataName,dataName+'.h5')) dataName = 'SLV_Hourly2TimeSeries' df_data_processed_H2 = ds.read(dataName+'_df_data_transformed', hdf5fileName=pio.os.path.join('results',dataName,dataName+'.h5')) dataName = 'SLV_Delta' saveDir = pio.os.path.join('results', dataName, '') df_data = df_data_processed_H2.compareTwoTimeSeries(df_data_processed_H1, compareAllLevelsInIndex=False, mergeFunction=pio.np.median).fillna(0.) cf.calculateTimeSeriesCategorization(df_data, dataName, saveDir, NumberOfRandomSamples = 10**5) cf.clusterTimeSeriesCategorization(dataName, saveDir) cf.visualizeTimeSeriesCategorization(dataName, saveDir)
[ 2, 11748, 25064, 201, 198, 2, 17597, 13, 6978, 13, 33295, 7203, 40720, 492, 4943, 201, 198, 201, 198, 11748, 12972, 29005, 3970, 355, 279, 952, 201, 198, 201, 198, 6738, 12972, 29005, 3970, 1330, 17851, 1634, 24629, 2733, 355, 30218, ...
2.589065
1,134
# returns number of unique records for icews with different filtering: # -by rounded lat/lon (100,000) # -by country, district, province, city (100,000) # -by lat/lon, filtered by 2 or more matches (70,000) from pymongo import MongoClient import os mongo_client = MongoClient(host='localhost', port=27017) # Default port db = mongo_client.event_data # icews_coordinates_rounded() icews_coordinates() # icews_names()
[ 2, 5860, 1271, 286, 3748, 4406, 329, 14158, 15515, 351, 1180, 25431, 25, 198, 2, 532, 1525, 19273, 3042, 14, 14995, 357, 3064, 11, 830, 8, 198, 2, 532, 1525, 1499, 11, 4783, 11, 8473, 11, 1748, 357, 3064, 11, 830, 8, 198, 2, 532...
3.174242
132
# Copyright (c) 2020. Hanchen Wang, hw501@cam.ac.uk # Ref: https://github.com/fxia22/pointnet.pytorch/pointnet/model.py import torch, torch.nn as nn, numpy as np, torch.nn.functional as F from torch.autograd import Variable # STN -> Spatial Transformer Network
[ 2, 220, 15069, 357, 66, 8, 12131, 13, 367, 1192, 831, 15233, 11, 289, 86, 33548, 31, 20991, 13, 330, 13, 2724, 198, 2, 220, 6524, 25, 3740, 1378, 12567, 13, 785, 14, 21373, 544, 1828, 14, 4122, 3262, 13, 9078, 13165, 354, 14, 41...
2.765306
98
import MapReduce import sys """ SQL style Joins in MapReduce """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
[ 11748, 9347, 7738, 7234, 198, 11748, 25064, 198, 198, 37811, 198, 17861, 3918, 5302, 1040, 287, 9347, 7738, 7234, 198, 37811, 198, 198, 43395, 796, 9347, 7738, 7234, 13, 13912, 7738, 7234, 3419, 198, 198, 2, 36658, 25609, 198, 2, 2141, ...
3.22
100
from anonapi.testresources import ( MockAnonClientTool, JobInfoFactory, RemoteAnonServerFactory, JobStatus, )
[ 6738, 281, 261, 15042, 13, 9288, 37540, 1330, 357, 198, 220, 220, 220, 44123, 2025, 261, 11792, 25391, 11, 198, 220, 220, 220, 15768, 12360, 22810, 11, 198, 220, 220, 220, 21520, 2025, 261, 10697, 22810, 11, 198, 220, 220, 220, 15768,...
2.702128
47
"""The Mikrotik router class.""" from datetime import timedelta import logging import socket import ssl import librouteros from librouteros.login import plain as login_plain, token as login_token from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.util import slugify import homeassistant.util.dt as dt_util from .const import ( ARP, ATTR_DEVICE_TRACKER, ATTR_FIRMWARE, ATTR_MODEL, ATTR_SERIAL_NUMBER, CAPSMAN, CONF_ARP_PING, CONF_DETECTION_TIME, CONF_FORCE_DHCP, DEFAULT_DETECTION_TIME, DHCP, IDENTITY, INFO, IS_WIRELESS, MIKROTIK_SERVICES, NAME, WIRELESS, ) from .errors import CannotConnect, LoginError _LOGGER = logging.getLogger(__name__) class MikrotikData: """Handle all communication with the Mikrotik API.""" def __init__(self, hass, config_entry, api): """Initialize the Mikrotik Client.""" self.hass = hass self.config_entry = config_entry self.api = api self._host = self.config_entry.data[CONF_HOST] self.all_devices = {} self.devices = {} self.available = True self.support_wireless = bool(self.command(MIKROTIK_SERVICES[IS_WIRELESS])) self.hostname = None self.model = None self.firmware = None self.serial_number = None def get_info(self, param): """Return device model name.""" cmd = IDENTITY if param == NAME else INFO data = list(self.command(MIKROTIK_SERVICES[cmd])) return data[0].get(param) if data else None def get_hub_details(self): """Get Hub info.""" self.hostname = self.get_info(NAME) self.model = self.get_info(ATTR_MODEL) self.firmware = self.get_info(ATTR_FIRMWARE) self.serial_number = self.get_info(ATTR_SERIAL_NUMBER) def connect_to_hub(self): """Connect to hub.""" try: self.api = get_api(self.hass, self.config_entry.data) self.available = True return True except (LoginError, CannotConnect): self.available = False return False def get_list_from_interface(self, interface): """Get devices from interface.""" result = list(self.command(MIKROTIK_SERVICES[interface])) return self.load_mac(result) if result else {} def restore_device(self, mac): """Restore a missing device after restart.""" self.devices[mac] = Device(mac, self.all_devices[mac]) def update_devices(self): """Get list of devices with latest status.""" arp_devices = {} wireless_devices = {} device_list = {} try: self.all_devices = self.get_list_from_interface(DHCP) if self.support_wireless: _LOGGER.debug("wireless is supported") for interface in [CAPSMAN, WIRELESS]: wireless_devices = self.get_list_from_interface(interface) if wireless_devices: _LOGGER.debug("Scanning wireless devices using %s", interface) break if self.support_wireless and not self.force_dhcp: device_list = wireless_devices else: device_list = self.all_devices _LOGGER.debug("Falling back to DHCP for scanning devices") if self.arp_enabled: arp_devices = self.get_list_from_interface(ARP) # get new hub firmware version if updated self.firmware = self.get_info(ATTR_FIRMWARE) except (CannotConnect, socket.timeout, socket.error): self.available = False return if not device_list: return for mac, params in device_list.items(): if mac not in self.devices: self.devices[mac] = Device(mac, self.all_devices.get(mac, {})) else: self.devices[mac].update(params=self.all_devices.get(mac, {})) if mac in wireless_devices: # if wireless is supported then wireless_params are params self.devices[mac].update( wireless_params=wireless_devices[mac], active=True ) continue # for wired devices or when forcing dhcp check for active-address if not params.get("active-address"): self.devices[mac].update(active=False) continue # ping check the rest of active devices if arp ping is enabled active = True if self.arp_enabled and mac in arp_devices: active = self.do_arp_ping( params.get("active-address"), arp_devices[mac].get("interface") ) self.devices[mac].update(active=active) def do_arp_ping(self, ip_address, interface): """Attempt to arp ping MAC address via interface.""" _LOGGER.debug("pinging - %s", ip_address) params = { "arp-ping": "yes", "interval": "100ms", "count": 3, "interface": interface, "address": ip_address, } cmd = "/ping" data = list(self.command(cmd, params)) if data is not None: status = 0 for result in data: if "status" in result: status += 1 if status == len(data): _LOGGER.debug( "Mikrotik %s - %s arp_ping timed out", ip_address, interface ) return False return True def command(self, cmd, params=None): """Retrieve data from Mikrotik API.""" try: _LOGGER.info("Running command %s", cmd) if params: response = self.api(cmd=cmd, **params) else: response = self.api(cmd=cmd) except ( librouteros.exceptions.ConnectionClosed, socket.error, socket.timeout, ) as api_error: _LOGGER.error("Mikrotik %s connection error %s", self._host, api_error) raise CannotConnect except librouteros.exceptions.ProtocolError as api_error: _LOGGER.warning( "Mikrotik %s failed to retrieve data. cmd=[%s] Error: %s", self._host, cmd, api_error, ) return None return response if response else None def update(self): """Update device_tracker from Mikrotik API.""" if not self.available or not self.api: if not self.connect_to_hub(): return _LOGGER.debug("updating network devices for host: %s", self._host) self.update_devices() class MikrotikHub: """Mikrotik Hub Object.""" def __init__(self, hass, config_entry): """Initialize the Mikrotik Client.""" self.hass = hass self.config_entry = config_entry self._mk_data = None self.progress = None async def async_add_options(self): """Populate default options for Mikrotik.""" if not self.config_entry.options: options = { CONF_ARP_PING: self.config_entry.data.pop(CONF_ARP_PING, False), CONF_FORCE_DHCP: self.config_entry.data.pop(CONF_FORCE_DHCP, False), CONF_DETECTION_TIME: self.config_entry.data.pop( CONF_DETECTION_TIME, DEFAULT_DETECTION_TIME ), } self.hass.config_entries.async_update_entry( self.config_entry, options=options ) def get_api(hass, entry): """Connect to Mikrotik hub.""" _LOGGER.debug("Connecting to Mikrotik hub [%s]", entry[CONF_HOST]) _login_method = (login_plain, login_token) kwargs = {"login_methods": _login_method, "port": entry["port"]} if entry[CONF_VERIFY_SSL]: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE _ssl_wrapper = ssl_context.wrap_socket kwargs["ssl_wrapper"] = _ssl_wrapper try: api = librouteros.connect( entry[CONF_HOST], entry[CONF_USERNAME], entry[CONF_PASSWORD], **kwargs, ) _LOGGER.debug("Connected to %s successfully", entry[CONF_HOST]) return api except ( librouteros.exceptions.LibRouterosError, socket.error, socket.timeout, ) as api_error: _LOGGER.error("Mikrotik %s error: %s", entry[CONF_HOST], api_error) if "invalid user name or password" in str(api_error): raise LoginError raise CannotConnect
[ 37811, 464, 17722, 10599, 1134, 20264, 1398, 526, 15931, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 11748, 18931, 198, 11748, 17802, 198, 11748, 264, 6649, 198, 198, 11748, 9195, 472, 353, 418, 198, 6738, 9195, 472, 353, 418, 13, 3...
2.112423
4,234
from bs4 import BeautifulSoup import requests import re from lxml.html import fromstring from lxml.etree import ParserError from gemlog_from_rss.spip import SinglePost
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 7007, 198, 11748, 302, 198, 6738, 300, 19875, 13, 6494, 1330, 422, 8841, 198, 6738, 300, 19875, 13, 316, 631, 1330, 23042, 263, 12331, 198, 6738, 16840, 6404, 62, 6738, 62, 42216,...
3.42
50
# Copyright (c) 2017 David Sorokin <david.sorokin@gmail.com> # # Licensed under BSD3. See the LICENSE.txt file in the root of this distribution. from simulation.aivika.modeler.model import * from simulation.aivika.modeler.port import * def create_arrival_timer(model, name, descr = None): """Return a new timer that allows measuring the processing time of transacts.""" y = ArrivalTimerPort(model, name = name, descr = descr) code = 'newArrivalTimer' y.write(code) return y def arrival_timer_stream(arrival_timer_port, stream_port): """Measure the processing time of transacts from the specified stream within the resulting stream.""" t = arrival_timer_port s = stream_port expect_arrival_timer(t) expect_stream(s) expect_same_model([t, s]) model = t.get_model() item_data_type = s.get_item_data_type() code = 'return $ runProcessor (arrivalTimerProcessor ' + t.read() + ') ' + s.read() y = StreamPort(model, item_data_type) y.write(code) y.bind_to_input() s.bind_to_output() return y def reset_arrival_timer(arrival_timer_port, reset_time): """Reset the arrival timer statistics at the specified modeling time.""" t = arrival_timer_port expect_arrival_timer(t) model = t.get_model() code = 'runEventInStartTime $ enqueueEvent ' + str(reset_time) code += ' $ resetArrivalTimer ' + t.read() model.add_action(code)
[ 2, 15069, 357, 66, 8, 2177, 3271, 15423, 36749, 1279, 67, 8490, 13, 82, 273, 36749, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 49962, 739, 347, 10305, 18, 13, 4091, 262, 38559, 24290, 13, 14116, 2393, 287, 262, 6808, 286, 428, 6082, ...
2.759223
515
m = float(input('digite o metro ')) print(f'{m} metros e igual {m*100} centimetros e {m*1000} milimetros')
[ 76, 796, 12178, 7, 15414, 10786, 12894, 578, 267, 24536, 705, 4008, 198, 4798, 7, 69, 6, 90, 76, 92, 1138, 4951, 304, 45329, 723, 1391, 76, 9, 3064, 92, 1247, 38813, 4951, 304, 1391, 76, 9, 12825, 92, 1465, 38813, 4951, 11537 ]
2.465116
43
#!/usr/bin/env python import rospy import rosbag import os import sys import textwrap import yaml lidarmsg=None ################# read the lidar msg from yaml file and return ############## if __name__ == '__main__': readlidardummy()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 11748, 686, 82, 21454, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 2420, 37150, 198, 198, 11748, 331, 43695, 198, 75, 312, 8357, 70, 28, 14202, 19...
2.95122
82
from flyteidl.plugins import qubole_pb2 as _qubole from flytekit.models import common as _common
[ 6738, 6129, 660, 312, 75, 13, 37390, 1330, 627, 45693, 62, 40842, 17, 355, 4808, 421, 45693, 198, 198, 6738, 6129, 660, 15813, 13, 27530, 1330, 2219, 355, 4808, 11321, 628, 628 ]
3.15625
32
# -*- coding: utf-8 -*- from dataclasses import asdict from logging import DEBUG import os from flask import Flask, jsonify, request from werkzeug.exceptions import HTTPException from mecab_parser import MecabParserFactory app = Flask(__name__) app.config["JSON_AS_ASCII"] = False if __name__ == "__main__": port = int(os.getenv("PORT", 5000)) app.logger.level = DEBUG app.run(host="0.0.0.0", port=port)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4818, 330, 28958, 1330, 355, 11600, 198, 6738, 18931, 1330, 16959, 198, 11748, 28686, 198, 198, 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 198, 6738, 266, ...
2.729032
155
#!/usr/bin/env python # -*- coding: UTF-8 -*- """Emitters are used to export models to output format. This module contains all classes for emitters: base and actuals. Currently the system has two emitters: :class:`~.CSVEmitter` and :class:`~.MySQLEmitter` implemented, of which the last is the default emitter. An emitter provides the export format for the scanned and cleaned datasets. It also provides preambles and postambles in the output files, for example to clean the target table before loading it. The following classes are defined in this module: * :class:`~.BaseEmitter` * :class:`~.MySQLEmitter` * :class:`~.CSVEmitter` * :class:`~.JSONEmitter` * :class:`~.UpdateEmitter` The basic structure for emitting is a combination between :class:`~.BaseManager` and :class:`~.BaseEmitter`: .. code-block:: python e = Emitter(manager=Model.objects) print e.preamble(header=[..my header lines to add..]) for l in Model.objects.all(): print e.emit(l) # emit is returning a list of strings! .. note:: At this moment *data-migrator* does not an actively take part in schema migrations of any sort. It is purely about cleaning, anonymizing and transforming data (yet!). """ from .update import UpdateEmitter # noqa from .mysql import MySQLEmitter # noqa from .csv import CSVEmitter # noqa from .json_emit import JSONEmitter # noqa from .singer import SingerEmitter # noqa
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 36, 2781, 1010, 389, 973, 284, 10784, 4981, 284, 5072, 5794, 13, 198, 198, 1212, 8265, 4909, 477, 6097, 329, 27588,...
3.171946
442
# Generated by Django 2.0.9 on 2018-12-12 08:18 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 24, 319, 2864, 12, 1065, 12, 1065, 8487, 25, 1507, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import math import numpy as np from scipy import signal #%% M = 16; N = 100; AddImm = 1000; MAT_M = 3; MAT_N = 5; MAT_P = 7; Pm = 5; Pn = 5; Km = 5; Kn = 5; MODE = 1; fpp = open("./npu_verification_para.list", "w") fpp.write("%d\n"%(M)) fpp.write("%d\n"%(N)) fpp.write("%d\n"%(AddImm)) fpp.write("%d\n"%(MAT_M)) fpp.write("%d\n"%(MAT_N)) fpp.write("%d\n"%(MAT_P)) fpp.write("%d\n"%(Km)) fpp.write("%d\n"%(Kn)) fpp.write("%d\n"%(Pm)) fpp.write("%d\n"%(Pn)) fpp.write("%d\n"%(MODE)) fpp.close() #%% fpd = open("./source_sram_dq.list", "w") #%% Dollar1 = np.random.randint(-50,-1, size=(M,N))*2**16 fpd.write("@%X\n"%(2*0x010000)) for i in range(0, M): for j in range(0, N): tmp_v = int(Dollar1[i, j]) if tmp_v<0: tmp_v = tmp_v + 0x100000000 fpd.write("%04X\n"%((tmp_v >> 0)&0xFFFF)) fpd.write("%04X\n"%((tmp_v >> 16)&0xFFFF)) #%% Dollar22 = np.random.randint(-15,-10, size=(M,N))*2**16 fpd.write("@%X\n"%(2*0x020000)) for i in range(0, M): for j in range(0, N): tmp_v = int(Dollar22[i, j]) if tmp_v<0: tmp_v = tmp_v + 0x100000000 fpd.write("%04X\n"%((tmp_v >> 0)&0xFFFF)) fpd.write("%04X\n"%((tmp_v >> 16)&0xFFFF)) #%% fp_add = open("./fp_add_test.txt", "w") fp_addi = open("./fp_addi_test.txt", "w") fp_sub = open("./fp_sub_test.txt", "w") fp_dot = open("./fp_dot_test.txt", "w") # for i in range(0, len(Dollar1)): for j in range(0, len(Dollar1[0])): add_value = int((Dollar1[i, j]+Dollar22[i, j])) addi_value = int((Dollar1[i, j]+AddImm)) sub_value = int((Dollar1[i, j]-Dollar22[i, j])) dot_value = int((Dollar1[i, j]/2**16*Dollar22[i, j])) fp_add.write("%d\n"%(add_value)) fp_sub.write("%d\n"%(sub_value)) fp_dot.write("%d\n"%(dot_value)) fp_addi.write("%d\n"%(addi_value)) fp_add.close() fp_addi.close() fp_sub.close() fp_dot.close() #%% fp_tran = open("./fp_tran_test.txt", "w") # for j in range(0, len(Dollar1[0])): for i in range(0, len(Dollar1)): tran_value = int((Dollar1[i, j])) fp_tran.write("%d\n"%(tran_value)) fp_tran.close() #%% kernel = np.random.randint(-15,10, size=(Km,Kn))*2**16 fpd.write("@%X\n"%(2*0x030000)) for i in range(0, len(kernel)): for j in range(0, len(kernel[0])): tmp_v = int(kernel[i, j]) if tmp_v<0: tmp_v = tmp_v + 0x100000000 fpd.write("%04X\n"%((tmp_v >> 0)&0xFFFF)) fpd.write("%04X\n"%((tmp_v >> 16)&0xFFFF)) d1 = Dollar1 d2 = kernel d1x = d1/2**16; d2x = d2/2**16; dcx = (signal.convolve2d(d1x, d2x, 'valid') * 2**16).astype(np.int) # fp_conv = open("./fp_conv_test.txt", "w") for i in range(0, len(dcx)): for j in range(0, len(dcx[0])): conv_value = int(dcx[i, j]) fp_conv.write("%d\n"%(conv_value)) fp_conv.close() #%% pooling fp_pool = open("./fp_pool_test.txt", "w") dpx = np.zeros((M//Pm, N//Pn)) for i in range(0, M//Pm): for j in range(0, N//Pn): if MODE==0: dpx[i, j] = np.mean(d1x[Pm*i:Pm*i+Pm, Pn*j:Pn*j+Pn]) elif MODE==1: dpx[i, j] = np.max(d1x[Pm*i:Pm*i+Pm, Pn*j:Pn*j+Pn]) pool_value = int(2**16*dpx[i, j]) fp_pool.write("%d\n"%(pool_value)) fp_pool.close() #%% MULT mat1 = np.random.randint(-1,2, size=(MAT_M,MAT_N)) mat2 = np.random.randint(-2,-1, size=(MAT_N,MAT_P)) mat1_216 = 2**16*mat1 mat2_216 = 2**16*mat2 mat3 = np.dot(mat1, mat2) fpd.write("@%X\n"%(2*0x040000)) # for i in range(0, len(mat1)): for j in range(0, len(mat1[0])): mult_value = int(2**16*mat1[i, j]) fpd.write("%04X\n"%((mult_value >> 0)&0xFFFF)) fpd.write("%04X\n"%((mult_value >> 16)&0xFFFF)) fpd.write("@%X\n"%(2*0x050000)) for i in range(0, len(mat2)): for j in range(0, len(mat2[0])): mult_value = int(2**16*mat2[i, j]) fpd.write("%04X\n"%((mult_value >> 0)&0xFFFF)) fpd.write("%04X\n"%((mult_value >> 16)&0xFFFF)) # fp_mult = open("./fp_mult_test.txt", "w") for i in range(0, len(mat3)): for j in range(0, len(mat3[0])): mult_value = int(2**16*mat3[i, j]) fp_mult.write("%d\n"%(mult_value)) fp_mult.close() #%% ###################### fp_tanh = open("./fp_tanh_test.txt", "w") Dollar2 = np.random.randn(M,N)*2**16 fpd.write("@%X\n"%(2*0x060000)) for i in range(0, M): for j in range(0, N): tmp_v = int(Dollar2[i, j]) if tmp_v<0: tmp_v = tmp_v + 0x100000000 fpd.write("%04X\n"%((tmp_v >> 0)&0xFFFF)) fpd.write("%04X\n"%((tmp_v >> 16)&0xFFFF)) tanh_value = int(2**16*math.tanh(Dollar2[i, j]/(2**16))) fp_tanh.write("%d\n"%(tanh_value)) fp_tanh.close() #%% fp_adds = open("./fp_adds_test.txt", "w") Dollar2_ini = Dollar2[0, 0] # for i in range(0, len(Dollar1)): for j in range(0, len(Dollar1[0])): adds_value = int((Dollar1[i, j] + Dollar2_ini)) fp_adds.write("%d\n"%(adds_value)) fp_adds.close() #%% RGB565 fp_gray = open("./fp_gray_test.txt", "w") fpd.write("@%X\n"%(2*0x070000)) red = np.random.randint(0,2**5, size=(M,N)) green = np.random.randint(0,2**6, size=(M,N)) blue = np.random.randint(0,2**5, size=(M,N)) rgb565 = red*2**11 + green*2**5 + blue # for i in range(0, len(rgb565)): for j in range(0, len(rgb565[0])): r = ((rgb565[i][j]>>11) & 0x1F) *8 g = ((rgb565[i][j]>>5) & 0x3F) *4 b = ((rgb565[i][j]>>0) & 0x1F) *8 gray_value = int((r*66 + g*129 + b*25)/256) + 16 if gray_value<16: gray_value = 16 elif gray_value>235: gray_value = 235 # fpd.write("%04X\n"%((rgb565[i][j] >> 0)&0xFFFF)) fpd.write("%04X\n"%((rgb565[i][j] >> 16)&0xFFFF)) fp_gray.write("%d\n"%(gray_value)) fp_gray.close() #%% fpd.close()
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 6737, 198, 2, 16626, 220, 198, 44, 796, 1467, 26, 399, 796, 1802, 26, 220, 198, 4550, 24675, 796, 8576, 26, 198, 41636, 62, 44, 796, 513, 26, 36775, ...
1.810054
2,964
A = 1 B = 2 C = 4
[ 32, 796, 352, 198, 33, 796, 362, 198, 34, 796, 604 ]
1.545455
11
from . import up
[ 6738, 764, 1330, 510, 198 ]
3.4
5
print('Controle de Terrenos') print('--------------------') l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) rea(l, c)
[ 198, 198, 4798, 10786, 4264, 18090, 390, 3813, 918, 418, 11537, 198, 4798, 10786, 19351, 11537, 198, 75, 796, 12178, 7, 15414, 10786, 43, 853, 5330, 357, 76, 2599, 705, 4008, 198, 66, 796, 12178, 7, 15414, 10786, 5377, 1050, 3681, 78,...
2.618182
55
import logging from functools import wraps from django.http import Http404 from readthedocs.projects.models import Project, ProjectRelationship log = logging.getLogger(__name__) # noqa def map_subproject_slug(view_func): """ A decorator that maps a ``subproject_slug`` URL param into a Project. :raises: Http404 if the Project doesn't exist .. warning:: Does not take into account any kind of privacy settings. """ return inner_view def map_project_slug(view_func): """ A decorator that maps a ``project_slug`` URL param into a Project. :raises: Http404 if the Project doesn't exist .. warning:: Does not take into account any kind of privacy settings. """ return inner_view
[ 11748, 18931, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 198, 198, 6738, 1100, 83, 704, 420, 82, 13, 42068, 13, 27530, 1330, 4935, 11, 4935, 47117, 1056, 198, 198, 6404, ...
3.109705
237
import discord import asyncio import re import logging from data.groups_name import free_random_name logging.basicConfig(level=logging.INFO) client = discord.Client()
[ 11748, 36446, 198, 11748, 30351, 952, 198, 11748, 302, 198, 11748, 18931, 198, 6738, 1366, 13, 24432, 62, 3672, 1330, 1479, 62, 25120, 62, 3672, 198, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 8, 198, 16366...
3.469388
49
from flask import request, make_response, jsonify, g from datetime import datetime from functools import wraps import jwt from models import DBContext, User from settings import SECRET_KEY from service import is_token_valid
[ 6738, 42903, 1330, 2581, 11, 787, 62, 26209, 11, 33918, 1958, 11, 308, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 11748, 474, 46569, 198, 198, 6738, 4981, 1330, 360, 2749, 261, 5239, 11, 11...
3.766667
60
""" Utilities --------- The utilities module. """ from collections.abc import Mapping, Sequence from functools import wraps import types def classonce(meth): """Decorator that executes a class method once, stores the results at the class level, and subsequently returns those results for every future method call. """ return decorated def is_sequence(value): """Test if `value` is a sequence but ``str``. This function is mainly used to determine if `value` can be treated like a ``list`` for iteration purposes. """ return (is_generator(value) or (isinstance(value, Sequence) and not isinstance(value, str))) def is_generator(value): """Return whether `value` is a generator or generator-like.""" return (isinstance(value, types.GeneratorType) or (hasattr(value, '__iter__') and hasattr(value, '__next__') and not hasattr(value, '__getitem__')))
[ 37811, 198, 18274, 2410, 198, 45537, 198, 198, 464, 20081, 8265, 13, 198, 37811, 198, 198, 6738, 17268, 13, 39305, 1330, 337, 5912, 11, 45835, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 11748, 3858, 628, 198, 198, 4299, 1398, 27078,...
3
314
try: from . import generic as g except BaseException: import generic as g if __name__ == '__main__': g.trimesh.util.attach_to_log() g.unittest.main()
[ 28311, 25, 198, 220, 220, 220, 422, 764, 1330, 14276, 355, 308, 198, 16341, 7308, 16922, 25, 198, 220, 220, 220, 1330, 14276, 355, 308, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 308...
2.449275
69
# /*********************************************************************** # Copyright 2019 Google 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. # # Note that these code samples being shared are not official Google # products and are not formally supported. # ************************************************************************/ import os from typing import Union import yaml from yaml.parser import ParserError from collections.abc import Iterable from enum import EnumMeta from typing import ClassVar from typing import Dict from typing import Generic from typing import List from typing import TypeVar from absl import flags from prompt_toolkit import ANSI from prompt_toolkit import prompt from prompt_toolkit.shortcuts import CompleteStyle from termcolor import colored from termcolor import cprint from flagmaker.building_blocks import list_to_string_list from flagmaker.exceptions import FlagMakerPromptInterruption from flagmaker.validators import ChoiceValidator from .building_blocks import SettingOptionInterface from .building_blocks import SettingsInterface from .building_blocks import Value from .exceptions import FlagMakerConfigurationError from .exceptions import FlagMakerInputError from .hints import StringKeyDict from .sanity import Validator FLAGS = flags.FLAGS T = TypeVar('T', bound=SettingsInterface) def get_option_prompt(self, k, default, prompt_val): if not isinstance(self._options, EnumMeta): raise FlagMakerConfigurationError('Need to add options for ' + k) options = list_to_string_list(self.options) return ( '{0}\n' '{1}\n' '{2}\n' 'Choices{3}: ' ).format( k, colored('Options:', attrs=['underline']), options, default, prompt_val ) def get_basic_prompt(self, k, default, prompt_val): return '{}{}{}'.format(k, default, prompt_val) def _set_value(self, value): if value is None: self._value.set_val(None) return if self.method == flags.DEFINE_boolean: if value in ['1', 'true', 'True', True]: value = True elif value in ['0', 'false', 'False', False]: value = False elif self.method == flags.DEFINE_integer: value = int(value) elif self.method == flags.DEFINE_enum: options = self.options is_iterable = isinstance(options, Iterable) if not (is_iterable and value in options): raise FlagMakerInputError( 'Need to choose one of [{}]'.format(', '.join(options)) ) self._value.set_val(value) # perform actions if self.after is None: self._error = False return in_called = (self, self.after) not in self.called if in_called: self.called[(self, self.after)] = True self.after(self) class SettingBlock: def __init__(self, block: str, settings: Dict[str, SettingOption], conditional: callable = None): self.name = block self.settings = settings self.conditional = conditional AbstractSettingsClass = ClassVar[T]
[ 2, 1220, 17174, 17174, 2466, 8162, 198, 2, 15069, 13130, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 705, 34156, 24036, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
2.714592
1,398
# coding:utf-8 # # The MIT License (MIT) # # Copyright (c) 2018-2020 azai/Rgveda/GolemQuant base on QUANTAXIS/yutiansut # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import json import sys import websocket from datetime import datetime as dt, timezone, timedelta, date import datetime import time as timer import numba as nb import traceback try: import easyquotation easyquotation_not_install = False except: easyquotation_not_install = True try: import QUANTAXIS as QA from QUANTAXIS.QAUtil.QAParameter import ORDER_DIRECTION from QUANTAXIS.QAUtil.QASql import QA_util_sql_mongo_sort_ASCENDING from QUANTAXIS.QAUtil.QADate_trade import ( QA_util_if_tradetime, QA_util_get_pre_trade_date, QA_util_get_real_date, trade_date_sse ) from QUANTAXIS.QAData.QADataStruct import ( QA_DataStruct_Index_min, QA_DataStruct_Index_day, QA_DataStruct_Stock_day, QA_DataStruct_Stock_min ) from QUANTAXIS.QAIndicator.talib_numpy import * from QUANTAXIS.QAUtil.QADate_Adv import ( QA_util_timestamp_to_str, QA_util_datetime_to_Unix_timestamp, QA_util_print_timestamp ) from QUANTAXIS.QAUtil import ( DATABASE, QASETTING, QA_util_log_info, QA_util_log_debug, QA_util_log_expection, QA_util_to_json_from_pandas ) except: print('PLEASE run "pip install QUANTAXIS" before call GolemQ.cli.sub modules') pass try: from GolemQ.utils.parameter import ( AKA, INDICATOR_FIELD as FLD, TREND_STATUS as ST, ) except: from GolemQ.utils.symbol import ( normalize_code ) def formater_l1_tick(code: str, l1_tick: dict) -> dict: """ Tick tdx l1 tick """ if ((len(code) == 6) and code.startswith('00')): l1_tick['code'] = normalize_code(code, l1_tick['now']) else: l1_tick['code'] = normalize_code(code) l1_tick['servertime'] = l1_tick['time'] l1_tick['datetime'] = '{} {}'.format(l1_tick['date'], l1_tick['time']) l1_tick['price'] = l1_tick['now'] l1_tick['vol'] = l1_tick['volume'] del l1_tick['date'] del l1_tick['time'] del l1_tick['now'] del l1_tick['name'] del l1_tick['volume'] # print(l1_tick) return l1_tick def formater_l1_ticks(l1_ticks: dict, codelist: list = None, stacks=None, symbol_list=None) -> dict: """ l1 ticks """ if (stacks is None): l1_ticks_data = [] symbol_list = [] else: l1_ticks_data = stacks for code, l1_tick_values in l1_ticks.items(): # l1_tick = namedtuple('l1_tick', l1_ticks[code]) # formater_l1_tick_jit(code, l1_tick) if (codelist is None) or \ (code in codelist): l1_tick = formater_l1_tick(code, l1_tick_values) if (l1_tick['code'] not in symbol_list): l1_ticks_data.append(l1_tick) symbol_list.append(l1_tick['code']) return l1_ticks_data, symbol_list def sub_l1_from_sina(): """ L13mongodbSSD Intel DC P3600 800GB SSD 3600tick < 0.6s """ client = QASETTING.client['QAREALTIME'] if (easyquotation_not_install == True): print(u'PLEASE run "pip install easyquotation" before call GolemQ.cli.sub modules') return quotation = easyquotation.use('sina') # ['sina'] ['tencent', 'qq'] sleep_time = 2.0 sleep = int(sleep_time) _time1 = dt.now() database = collections_of_today() get_once = True # / end_time = dt.strptime(str(dt.now().date()) + ' 16:30', '%Y-%m-%d %H:%M') start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M') day_changed_time = dt.strptime(str(dt.now().date()) + ' 01:00', '%Y-%m-%d %H:%M') while (dt.now() < end_time): # / end_time = dt.strptime(str(dt.now().date()) + ' 16:30', '%Y-%m-%d %H:%M') start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M') day_changed_time = dt.strptime(str(dt.now().date()) + ' 01:00', '%Y-%m-%d %H:%M') _time = dt.now() if QA_util_if_tradetime(_time) and \ (dt.now() < day_changed_time): # print(u'~ {} '.format(datetime.date.today())) database = collections_of_today() print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) continue symbol_list = [] l1_ticks_data = [] if QA_util_if_tradetime(_time) or \ (get_once): # l1_ticks = quotation.market_snapshot(prefix=True) l1_ticks_data, symbol_list = formater_l1_ticks(l1_ticks) if (dt.now() < start_time) or \ ((len(l1_ticks_data) > 0) and \ (dt.strptime(l1_ticks_data[-1]['datetime'], '%Y-%m-%d %H:%M:%S') < dt.strptime(str(dt.now().date()) + ' 00:00', '%Y-%m-%d %H:%M'))): print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) continue # l1_ticks = quotation.market_snapshot(prefix=False) l1_ticks_data, symbol_list = formater_l1_ticks(l1_ticks, stacks=l1_ticks_data, symbol_list=symbol_list) # tick query_id = { "code": { '$in': list(set([l1_tick['code'] for l1_tick in l1_ticks_data])) }, "datetime": sorted(list(set([l1_tick['datetime'] for l1_tick in l1_ticks_data])))[-1] } # print(sorted(list(set([l1_tick['datetime'] for l1_tick in # l1_ticks_data])))[-1]) refcount = database.count_documents(query_id) if refcount > 0: if (len(l1_ticks_data) > 1): # # print('Delete', refcount, list(set([l1_tick['datetime'] # for l1_tick in l1_ticks_data]))) database.delete_many(query_id) database.insert_many(l1_ticks_data) else: # database.replace_one(query_id, l1_ticks_data[0]) else: # tick # print('insert_many', refcount) database.insert_many(l1_ticks_data) if (get_once != True): print(u'Trading time now A {}\nProcessing ticks data cost:{:.3f}s'.format(dt.now(), ( dt.now() - _time).total_seconds())) if ((dt.now() - _time).total_seconds() < sleep): timer.sleep(sleep - (dt.now() - _time).total_seconds()) print('Program Last Time {:.3f}s'.format((dt.now() - _time1).total_seconds())) get_once = False else: print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) # 5 QUANTAXIS/save X save_time = dt.strptime(str(dt.now().date()) + ' 17:00', '%Y-%m-%d %H:%M') if (dt.now() > end_time) and \ (dt.now() < save_time): # 16:0017:00 # block # pass # While513 print(u'While513 tick') timer.sleep(40000) def sub_codelist_l1_from_sina(codelist: list = None): """ L13mongodbSSD Intel DC P3600 800GB SSD 3600tick < 0.6s """ quotation = easyquotation.use('sina') # ['sina'] ['tencent', 'qq'] sleep_time = 2.0 sleep = int(sleep_time) _time1 = dt.now() database = collections_of_today() get_once = True # / end_time = dt.strptime(str(dt.now().date()) + ' 16:30', '%Y-%m-%d %H:%M') start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M') day_changed_time = dt.strptime(str(dt.now().date()) + ' 01:00', '%Y-%m-%d %H:%M') while (dt.now() < end_time): # / end_time = dt.strptime(str(dt.now().date()) + ' 16:30', '%Y-%m-%d %H:%M') start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M') day_changed_time = dt.strptime(str(dt.now().date()) + ' 01:00', '%Y-%m-%d %H:%M') _time = dt.now() if QA_util_if_tradetime(_time) and \ (dt.now() < day_changed_time): # print(u'~ {} '.format(datetime.date.today())) database = collections_of_today() print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) continue if QA_util_if_tradetime(_time) or \ (get_once): # l1_ticks = quotation.market_snapshot(prefix=True) l1_ticks_data, symbol_list = formater_l1_ticks(l1_ticks, codelist=codelist) if (dt.now() < start_time) or \ ((len(l1_ticks_data) > 0) and \ (dt.strptime(l1_ticks_data[-1]['datetime'], '%Y-%m-%d %H:%M:%S') < dt.strptime(str(dt.now().date()) + ' 00:00', '%Y-%m-%d %H:%M'))): print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) continue # l1_ticks = quotation.market_snapshot(prefix=False) l1_ticks_data, symbol_list = formater_l1_ticks(l1_ticks, codelist=codelist, stacks=l1_ticks_data, symbol_list=symbol_list) # tick query_id = { "code": { '$in': list(set([l1_tick['code'] for l1_tick in l1_ticks_data])) }, "datetime": sorted(list(set([l1_tick['datetime'] for l1_tick in l1_ticks_data])))[-1] } # print(symbol_list, len(symbol_list)) refcount = database.count_documents(query_id) if refcount > 0: if (len(l1_ticks_data) > 1): # database.delete_many(query_id) database.insert_many(l1_ticks_data) else: # database.replace_one(query_id, l1_ticks_data[0]) else: # tick database.insert_many(l1_ticks_data) if (get_once != True): print(u'Trading time now A {}\nProcessing ticks data cost:{:.3f}s'.format(dt.now(), ( dt.now() - _time).total_seconds())) if ((dt.now() - _time).total_seconds() < sleep): timer.sleep(sleep - (dt.now() - _time).total_seconds()) print('Program Last Time {:.3f}s'.format((dt.now() - _time1).total_seconds())) get_once = False else: print(u'Not Trading time A {}'.format(_time)) timer.sleep(sleep) # 5 QUANTAXIS/save X save_time = dt.strptime(str(dt.now().date()) + ' 17:00', '%Y-%m-%d %H:%M') if (dt.now() > end_time) and \ (dt.now() < save_time): # 16:0017:00 # block # # save_X_func() pass # While513 print(u'While513 tick') timer.sleep(40000) def sub_1min_from_tencent_lru(): """ K """ blockname = ['MSCI', 'MSCI', 'MSCI', '', '180', '380', '300', '380', '300', '50', '', '', '100', '150', '300', '100', '500', '', '', '', '', '1000', '', '', '', '', '', '', '', '', '', '100', '', '', 'A50', '', '', '', '', '', '', '', '', '', '', '', '', '100', '', '', '', '', '4G5G', '5G', '', '', '', '', '', ''] all_stock_blocks = QA.QA_fetch_stock_block_adv() for blockname in blocks: if (blockname in all_stock_blocks.block_name): codelist_300 = all_stock_blocks.get_block(blockname).code print(u'QA{}'.format(blockname)) print(codelist_300) else: print(u'QA{}'.format(blockname)) quotation = easyquotation.use("timekline") data = quotation.real([codelist], prefix=False) while (True): l1_tick = quotation.market_snapshot(prefix=False) print(l1_tick) return True if __name__ == '__main__': # tick # # TCP/IP # 3 """ sub.py D:\\QUANTAXIS\QUANTAXIS\cli __init__.py2__init__.py sub.py PowerShellsub_l1.ps1 D: CD D:\\QUANTAXIS\ $n = 1 while($n -lt 6) { python -m QUANTAXIS.cli.sub Start-Sleep -Seconds 3 } Cmd/Batchsub_l1.cmd D: CD D:\\QUANTAXIS\ :start python -m QUANTAXIS.cli.sub @ping 127.0.0.1 -n 3 >nul goto start pause Linux Bashlinux """ import sys sys.path.append('/root/ipython/') import CommonUtils as cu try: cu.sendDingMsg("Start realtime sub from sina_l1 progress start now.") sub_l1_from_sina() except: traceback.print_exc() cu.sendDingMsg("Realtime sub from sina_l1 progress has stopped. please check it soon.") # sub_l1_from_sina() # sub_1min_from_tencent_lru() pass
[ 2, 19617, 25, 40477, 12, 23, 198, 2, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 2864, 12, 42334, 257, 35142, 14, 49, 70, 1079, 64, 14, 38, 2305, 76, 24915, 2779, 319, 19604, 1565, 5603, 55, 17...
1.796346
8,485
#!/usr/bin/env python """ Installs ETA. Copyright 2017-2021, Voxel51, Inc. voxel51.com """ import os from setuptools import setup, find_packages from wheel.bdist_wheel import bdist_wheel VERSION = "0.6.1" with open("README.md", "r") as fh: long_description = fh.read() setup( name="voxel51-eta", version=get_version(), description="Extensible Toolkit for Analytics", author="Voxel51, Inc.", author_email="info@voxel51.com", url="https://github.com/voxel51/eta", license="Apache", long_description=long_description, long_description_content_type="text/markdown", packages=find_packages(), include_package_data=True, install_requires=[ "argcomplete", "dill", "future", "glob2", "importlib-metadata; python_version<'3.8'", "ndjson", "numpy", "opencv-python-headless<5,>=4.1", "packaging", "patool", "Pillow>=6.2", "python-dateutil", "pytz", "requests", "retrying", "six", "scikit-image", "sortedcontainers", "tabulate", "tzlocal", ], extras_require={ "pipeline": ["blockdiag", "Sphinx", "sphinxcontrib-napoleon"], "storage": [ "boto3>=1.15", "google-api-python-client", "google-cloud-storage>=1.36", "httplib2<=0.15", "pysftp", ], }, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Scientific/Engineering :: Image Processing", "Topic :: Scientific/Engineering :: Image Recognition", "Topic :: Scientific/Engineering :: Information Analysis", "Topic :: Scientific/Engineering :: Visualization", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], entry_points={"console_scripts": ["eta=eta.core.cli:main"]}, python_requires=">=2.7", cmdclass={"bdist_wheel": BdistWheelCustom}, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 6310, 5691, 412, 5603, 13, 198, 198, 15269, 2177, 12, 1238, 2481, 11, 28035, 417, 4349, 11, 3457, 13, 198, 85, 1140, 417, 4349, 13, 785, 198, 37811, 198, 11748, 28686, 19...
2.282801
1,128