text
stringlengths
8
6.05M
import numpy as np import soundfile as sf def read_audio(audio_file, config, duration): if duration > config['target_duration']: offset = np.random.choice(duration - config['target_duration']) y, sr = sf.read(audio_file, start=offset, frames=config['t...
from __future__ import absolute_import from __future__ import print_function from __future__ import division import random random.seed(67) import numpy as np np.random.seed(67) import pandas as pd from tpot import TPOTClassifier import os def main(): df_train = pd.read_csv(os.getenv('PREPARED_TRAINING')) ...
#!/usr/bin/python3.4 # -*-coding:Utf-8 prenom = "Anthony" nom = "TASTET" age = 21 print("Je m'appelle {0} {1} et j'ai {2} ans".format(prenom, nom, age))
import json from django.views.generic.simple import direct_to_template from django.shortcuts import get_object_or_404 from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from ...
from rest_framework.serializers import (ModelSerializer, CharField, HyperlinkedIdentityField, SerializerMethodField, ValidationError) from User.models impo...
import mne import numpy as np import scipy.io from sklearn import preprocessing '''author of all functions found in this file : Alina Weinberger''' def printShape(file_name, nb_subjects, ext): files=[] subjects=range(nb_subjects) if ext == '.edf': for i in subjects: files.append(...
# coding:utf-8 import click class State(object): def __init__(self): self.verbosity = 0 self.debug = False pass_state = click.make_pass_decorator(State, ensure=True) def verbosity_option(f): def callback(ctx, param, value): state = ctx.ensure_object(State) state.verbosity ...
from setuptools import setup, find_packages setup (name = 'py-faster-rcnn', version = "0.0.16", package_dir = {'':'.'}, packages = ['','datasets','fast_rcnn','nms','roi_data_layer','rpn','transform', 'utils', 'caffe', 'caffe.proto'], package_data = { 'nms':['cpu_nms.so', 'gpu_nms.so'], ...
import typing as typ from .base import BaseMH class RegexMH(BaseMH): regex: str class Meta: abstract = True @classmethod def _get_regex(cls) -> str: return cls.regex class CommandMH(BaseMH): command: str args: typ.List[str] = [] must_start_with_command: bool = True ...
import airflow from airflow.models import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.python_operator import BranchPythonOperator import pendulum local_tz = pendulum.timezone("America/Los_Angeles") args = { 'own...
import pandas as pd import os DEEPCOM = "/home/qiuyuanchen/Onedrive/EMSE-DeepCom/my_test" CODE2SEQ = "/home/qiuyuanchen/Onedrive/code2seq-master/my_test" NNGEN = "/home/qiuyuanchen/Onedrive/nngen/my_test" MERGE = "/home/qiuyuanchen/Onedrive/my_parser/src/main/resources/merge_result" deepcom_res = os.path.join(DEEPCO...
# Generated by Django 3.0.7 on 2020-06-19 10:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("foodcartapp", "0020_auto_20200619_0959"), ] operations = [ migrations.RenameField( model_name="order", old_name="order_type"...
from flask import Flask from flask_restful import Api from flaskext.mysql import MySQL class ConfigDatabaseA: _mysql = None @staticmethod def getMysql(): return ConfigDatabaseA._mysql def __init__(self, app): """ Virtually private constructor. """ if ConfigDatabaseA._mysql != No...
from django.test import TestCase,Client from .models import Airport ,Flight # Create your tests here. class ModelsTestCase(TestCase): def setUp(self): a1 = Airport.objects.create(code="AAA",city="aaa") a2=Airport.objects.create(code="BBB",city="bbb") Flight.objects.create(origin=a1,destinat...
#!/bin/python3 """Script to retrieve image files from urls listed in a file.""" from urllib import request, error, parse import os # Base directory for the downloaded images IMAGE_DIR = '.' # Suffix for the downloads subdirectory DIR_SUFFIX = '_downloads' # File extensions that are accepted as images IMAGE_EXTS = [...
import os import unittest from abc import abstractmethod from pathlib import Path from typing import TypeVar, Generic, Optional from patchworkdocker.importers import GitImporter, Importer, FileSystemImporter from patchworkdocker.tests._common import TestWithTempFiles, EXAMPLE_GIT_REPOSITORY ImporterType = TypeVar("Im...
# -*- coding: utf-8 -*- # _author_ = "qqx" # date : 4/7/2020 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains #鼠标悬停 from PIL import Image,ImageEnhance import pytesseract from time import sleep option = webdriver.ChromeOptions() option.add_argument('--proxy-server=socks...
from django.utils import timezone def calculate_age(birth_date): today = timezone.now().date() return today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:preprocess.py # @Author: Michael.liu # @Date:2020/5/8 17:31 # @Desc: this code is .... import codecs import os def character_tagging(input_file_, output_file_): input_data = codecs.open(input_file_, 'r', 'utf-8') output_data = codecs.open(output_file_, 'w', 'ut...
#!/usr/bin/env python import sys import ebmlite from .elf import * from .helpers import * def pprint(el, values=True, out=sys.stdout, depth=0): if isinstance(el, ebmlite.core.Document): if el.size and depth < 3: print("[0x%X,0x%X) %s (Document, type %s)\n" % (el.offset, el.offset + el.size, s...
from classes.model.package import Package from classes.util.tree import Tree from pathlib import Path from typing import Any, Dict, IO, List, Optional, Union import yaml class YamlParser: def __init__(self, path: str): self.path: str = path self.data: Optional[Dict[str, Any]] = None def __va...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
import cv2 as cv img = cv.imread("irene.jpg", cv.IMREAD_UNCHANGED) # opencv에서는 BGR 순서로 색을 numpy에 저장 # mac에서는 keyevent로 움직이는게 불가능한가??? # ten keyless도 고려하면 asdw로 ... # asdw로 구현하자... ESC = 27 arrowL = ord('a') arrowR = ord('d') arrowU = ord('w') arrowD = ord('s') delta = 10 row_num, col_num, _ = img.shape x_pos = int...
c = int(input("How much celsuis are you going to convert?")) ce = c * 1.5 print (ce + 32)
import os from pathlib import Path import random import pickle import os import json from .run_cross_val import un_cross_val_training from .train_fetal import main_train ### Training using prediction has several stages: # 1. Cross-training using some non-prediction-using configuration # 2. Run prediction of all the cr...
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-01 17:42 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('jars', '0001_initial'), ...
"""empty message Revision ID: 88bbc83d3dc4 Revises: aab74117e579 Create Date: 2021-02-27 22:40:53.615375 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '88bbc83d3dc4' down_revision = 'aab74117e579' branch_labels = None...
"""Update Packages Classes.""" import logging from .listapplicabledevices import ListApplicableDevices from .listapplicabledevices import ApplicableDevices from .upgradepackages import UpgradePackages from .upgradepackages import UpgradePackage from .upgradepackage import Upgrades logging.debug("In the update_package...
import numpy as np import matplotlib.pyplot as plt import configparser #def phase_filer(): config = configparser.ConfigParser() config.read('snip-config.ini') next_config = configparser.ConfigParser() next_config.read('NeXtRAD.ini') data_file = config.get('Config','data_file') update_rate = config.get('Config','updat...
# -*- coding: utf-8 -*- import math import re import os import pdb file_dir = os.path.dirname(os.path.realpath(__file__)) def tf(text): dict = {} list_word = text.split() for word in list_word: if word in dict: dict[word] += 1.0 else: dict[word] = 1.0 try: ...
import cv2 as cv #读取图片并显示 src = cv.imread('C:/Users/zx/Desktop/jpg1.jpg')#读图片 cv.namedWindow('input image', cv.WINDOW_AUTOSIZE) cv.imshow("input image", src)#通过opcv的GUI显示图像 cv.waitKey(0)#等待一个按键输入后退出 cv.destroyAllWindows()#关闭所有窗口
#!/usr/bin/env python # encoding: utf-8 # @author: Zhipeng Ye # @contact: Zhipeng.ye19@xjtlu.edu.cn # @file: full_chinese.py # @time: 2020-01-17 17:19 # @desc: import os import re if __name__ == "__main__": files_name = sorted(os.listdir('/Data_SSD/zhipengye/zhipengye/LM/processed_data/small_dictory_filtered'))...
amt=int(input("enter amount")) if(amt>=100 and amt<=1000): disc=amt elif(amt>=1001 and amt<=2000): disc=0.1*amt elif(amt>=2001 and amt<=3000): disc=0.2*amt elif(amt>=3001): disc=0.25*amt else: print("invalid amount") print("amount=",amt) print("disount=",disc) print("net pay=",amt+disc)
''' Binary Search ''' class BinarySearch: def __init__(self, arr, val): self.arr = arr self.val = val def bubsortArray(self): for i in range(len(self.arr)): for j in range(len(self.arr)-1): if self.arr[i] < self.arr[j]: self....
filecontent = open("data.in") text = filecontent.readline() for i in text: if i == '(': print("Sumando") else: print("Restando")
from django.db import models class Foo(models.Model): name = models.CharField(max_length=255) content = models.TextField() boolean = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) birthday = models.DateField(auto_now_add=True) decimal = models.DecimalField...
#!/usr/bin/env python3 import sys import re def get_region(info): region_list = re.findall(";Func.refGene=(.+?);", info) if region_list[0] == "splicing": return region_list[0] elif region_list[0] == "exonic": region = re.findall(';ExonicFunc.refGene=(.+?);', info) return region[0] ...
# Find if a given number is a power of 3 test_num = raw_input("Enter number under test: ") test_num = int(test_num) test_num1 = test_num rem=100 if test_num < 0: print "The number is less than 0, so it is not power of 3" elif test_num == 0: print "The given number is 0. Please provide a number other than 0" e...
from collections import defaultdict from functools import partial from pathlib import Path import joblib import numpy as np import pandas as pd import sklearn.metrics from torch.utils.data import DataLoader from tqdm import tqdm from ..datasets import VOCDetection from ..transforms.util import get_transforms from .....
import json def save_response(response, filename,mydir=None): try: if mydir is not None: filename= f"{mydir}/{filename}" file = open(filename, 'w') json.dump(response.json(), file) file.close() except FileNotFoundError: print(filename + " not found. ...
from api.models import * from api.serializers import * from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framew...
from django.conf.urls import url,include from django.conf.urls.static import static from django.conf import settings from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('inicio.urls')), url(r'^selecao/', include('selecao.urls')), url(r'^downlo...
import hashlib import binascii def process_request(request): password = request.GET["password"] # BAD: Inbound authentication made by comparison to string literal if password == "myPa55word": redirect("login") hashed_password = load_from_config('hashed_password', CONFIG_FILE) salt = load_...
# -*- coding: utf-8 -*- """ Created on Sat Sep 2 07:45:53 2017 @author: my7pro """ import redis r = redis.Redis() class RQueue(object): """An abstract FIFO queue""" def __init__(self, local_id=None): if local_id is None: local_id = r.incr("queue_space") id_name = "q:%s" %(local_i...
''' Defines base block of a map. @author: stevenh47 ''' from google.appengine.ext import db from util.type_cast import Cast class MapElement(db.Model): '''Base block of a map. ''' width = db.IntegerProperty() height = db.IntegerProperty() x = db.IntegerProperty() y = db.IntegerProperty() pic = db.BlobP...
from rest_framework import serializers from django.contrib.auth import get_user_model from .models import Product, OrderProduct, Order User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class ProductSerializer(serializers.Model...
''' You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. ''' class Solution(object): def climbStairs(self, n): """ :type n: int :rtyp...
from datetime import timedelta import os import redis REDIS_URL = os.environ.get('REDIS_URL') redis_pool = redis.from_url(url=REDIS_URL, db=0) for key in redis_pool.keys('board*'): print(key) # redis_pool.expire(key, timedelta(minutes=30)) for key in redis_pool.keys('turn*'): print(key) # redis_pool.e...
# Generated by Django 3.0.5 on 2020-05-07 17:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0022_auto_20181028_1731'), ] operations = [ migrations.RemoveField( model_name='bookinstance', name='book...
from django.core.exceptions import ValidationError def validate_non_empty_string(value): try: value += '' if len(value) == 0: raise ValidationError( ('%(value)s must be a non-empty string'), params={'value': value}) except TypeError: raise Va...
import tensorflow as tf def get_product_type(title): # uses model trained by train.py to get the product name return 'RX 480 8GB'
# coding=utf-8 # @Author: wjn import unittest from common import HTMLTestRunnerCN import time # dir = './case/browser/' dir = './case/' # suite = unittest.defaultTestLoader.discover(dir, 'test_*.py') if __name__ == '__main__': runner = unittest.TextTestRunner() # runner.run(suite) """ cur_time = time...
#coding:utf8 from base.IterativeRecommender import IterativeRecommender import numpy as np from random import choice,random from tool import config import tensorflow as tf from collections import defaultdict from tensorflow import set_random_seed set_random_seed(2) class CDAE(IterativeRecommender): de...
# _*_coding:utf-8_*_ __author__ = "Jorden Hai" from modules import models from modules.db_conn import engine, session from modules.utils import print_err, json_parser import json def syncdb(argvs): print("Syncing DB....") models.Base.metadata.create_all(engine) # 创建所有表结构 def create_tables(argvs): if "-...
greet="Hello i am Aziz." a=greet.startswith("Hello") print(a) a=greet.startswith("h") print(a) a=greet.startswith("H") print(a)
from nose.tools import * def test_foo(): return
def sc(strng): seen = set(strng) return ''.join(a for a in strng if a.swapcase() in seen)
""" test_sql_tables.py: unit test file for sql_tables.py """ import sys import datetime import json import flask import flask_sqlalchemy import unittest from unittest.mock import MagicMock, patch sys.path.insert(1, '/home/ec2-user/environment/Distribution-System-CS490/backend') import sql_tables class testcases_s...
# Enter script code keyboard.send_keys("<f6>7")
from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import tkinter import sys client_socket = socket(AF_INET, SOCK_STREAM) # --------------------------------------------------------- # Definindo o endereço de destino - conjunto (ip, porta) # -------------------------------------------------...
import random file = open('dataWithoutTeacher.txt','w') maxValue = 1000000 dataSize = 100000 for i in range(0,dataSize): file.write(str((random.randint(-maxValue,maxValue))/(maxValue/100))+'\n') file.write("EOF") file = open('dataWithTeacher.txt','w') for i in range(0,dataSize): value = (random.randint(-ma...
import marshaltools # test source and some keys to play with name, src_id = 'ZTF18abjyjdz', 3329 keys = [ 'classification', 'redshift', 'uploaded_spectra.observer', 'autoannotations.username', 'redshift' ] prog = marshaltools.ProgramList("AMPEL Test", load_sources=True, load_candidates=True...
#!/usr/bin/env python3 """Model construction functions.""" # Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com # miTorch: Medical Imaging with PyTorch # Deep Learning Package for 3D medical imaging in PyTorch # Implemented by Mahdi Biparva, April 2021 # Brain Imaging Lab, Sunnybrook Research Institute (S...
from django.apps import AppConfig class KrwConfig(AppConfig): name = 'krw'
from licant.modules import module, submodule from licant.scripter import scriptq scriptq.execute("libc/libc.g.py") scriptq.execute("std/std.g.py") scriptq.execute("posix/posix.g.py") scriptq.execute("gxx/debug/debug.g.py") scriptq.execute("gxx/diag/diag.g.py") module("gxx.util.c", srcdir = "gxx", sources = [ "uti...
import cv2 import numpy as np cap = cv2.VideoCapture('./data/vtest.avi') ret, first_frame = cap.read() ret, second_frame = cap.read() while cap.isOpened(): diff = cv2.absdiff(first_frame, second_frame) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = ...
# Generated by Django 3.0.3 on 2020-03-30 04:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('shorten', '0005_auto_202...
#-*- coding: utf-8 -*- ''' Created on Jun 14, 2011 FP-Growth FP means frequent pattern the FP-Growth algorithm needs: 1. FP-tree (class treeNode) 2. header table (use dict) This finds frequent itemsets similar to apriori but does not find association rules. @author: Peter ''' import os # 推文文本处理函数 ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from django.core.checks import Error, register @register() def check_settings(app_configs, **kwargs): from django.conf import settings errors = []...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ 根据二维码位置,计算出目标距离 """ import rospy from math import pow, atan2, sqrt from tf.transformations import * import smach import smach_ros from smach_ros import SimpleActionState from smach_ros import ServiceState import threading import time # Navigation from move_base_msgs...
#! /usr/bin/env python # Uber's original name was "UberCab". Let's say we have a bunch of bumper stickers left over from those days # which say "UBERCAB" and we decide to cut these up into their separate letters to make new words. # So, for example, one sticker would give us the letters "U", "B", "E", "R", "C", "A", "...
from settings import * class CrossHairs(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(os.path.join(img_folder, "crosshairs.png")).convert() self.image = pygame.transform.scale(self.image, (30, 30)) self.image.set_color...
from rest_framework import serializers from .models import Match from teams.serializers import TeamsSerializer class MatchSerializer(serializers.ModelSerializer): team1 = serializers.SerializerMethodField(source="get_team1") team2 = serializers.SerializerMethodField(source="get_team2") winner = seriali...
import boto3 import hashlib import uuid from base64 import b64encode, b64decode from cfn_random_bytes_provider import RandomBytesProvider from secrets import handler kms = boto3.client("kms") default_length = 8 def test_defaults(): request = Request("Create", "abc") r = RandomBytesProvider() r.set_reque...
def sequenze_parametriche(n, m, k): ''' Presi i tre interi n, m e k, stampa tutte le sequenze di n interi positivi con interi di valore al più m e nelle quali nessun intero compare più di k volte. Ad esempio per n = 3, m = 2 e k = 2 le sequenze da stampare sono: [1, 1, 2] [1, 2, 1] [2, 1, 1] [...
import numpy as np import pandas as pd try: from ..dbutil.temptable_template import temptable_template except: from dbutil.temptable_template import temptable_template def order_filter(trips, legs, points, trip_link, point_meta, DB, CONFIG): """ Given the dataframes describing trips, and the associate...
def main(): lst = [] for a in range(2,101): for b in range(2,101): lst.append(a**b) return len(set(lst)) if __name__=='__main__': print(main())
# tg from flask import Blueprint tg = Blueprint('tg', __name__) from . import views
from PIL import Image, ImageDraw, ImageOps, ImageColor # Super sample and then downscale to reduce jaggy edges. multiplier = 2 # Wallpaper Parameters x = 3440 * multiplier y = 1440 * multiplier # Colours colour1 = ImageColor.getrgb("#1047A9") colour2 = ImageColor.getrgb("#E20048") colour3 = ImageColor.getrgb("#DCF90...
import subprocess import shlex import math import os import sys import stat import time import getopt class Line: def __init__(self, num, m, b): self.num = num self.m = m self.b = b self.visible = True def __str__(self): return str(self.num) + ": " + str(self.m) + "x " + "+ " + str(self.b) debug_filename ...
# -*- generated by 1.0.12 -*- import da PatternExpr_424 = da.pat.TuplePattern([da.pat.ConstantPattern('CTL_Ready')]) PatternExpr_429 = da.pat.FreePattern('source') PatternExpr_451 = da.pat.TuplePattern([da.pat.ConstantPattern('CTL_Done'), da.pat.FreePattern('rudata'), da.pat.FreePattern('rugroup_id')]) PatternExpr_460 ...
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.api import deps from app import models, schemas, crud route = APIRouter() @route.post('/', response_model=schemas.User) def create_user(user: schemas.UserCreate, db: Session = Depends(deps.get_db)) -> models.User: ...
# encoding: utf-8 from tastypie.validation import *
# Generated by Django 2.2.12 on 2020-05-06 12:15 from django.db import migrations, models import upload.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ImageBed', fields=[ (...
from collections import defaultdict import sys # arguments should be the length of the mer and hla types mer_len = int(sys.argv[1]) #for example 8 peptide_len = int(sys.argv[2]) #for example 15 # Obtain a dictionary of score score_dict = defaultdict(list) #key is the peptide and values are scores with open(sys.argv[...
#!/usr/bin/env python # # Copyright 2007 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 o...
# from selenium.common.exceptions import TimeoutException # from selenium.webdriver.chrome.webdriver import WebDriver # # from pages.ldma import ParseLinkBudget # from pages.base import BasePage # from rich.traceback import install # from rich.table import Table # from rich.panel import Panel # from rich.align import A...
# Python backend for go-lite-bot, the small Go bot # Should really use the fnctl package with the flock() function # to place locks on the files being read. Setting read/write locks as appropriate # will allow multiple instances to access the same filesystem for reading and # writing files. A really extensible solutio...
''' Desarollado Por: Martin Galvan-201614423 Tomas Kavanagh-201615122 ''' from __future__ import division from pyomo.environ import * from pyomo.opt import SolverFactory from matplotlib import pyplot as plt import sys import os f1=[] f2=[] ##########################################################################...
from datetime import datetime from app import db, login from config import Config from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('follo...
import boto3 region = 'us-west-2' info = [] client = boto3.client('ec2', region_name=region) response = client.describe_network_interfaces() for security_group in response['NetworkInterfaces']: for sg in security_group['Groups']: info.append(sg['GroupId']) for network_interface in response['NetworkInterf...
#!/usr/bin/python import os import re import sys import time import mmap import random import string import argparse import threading from time import sleep from multiprocessing import Pool, Lock # echo 3 > /proc/sys/vm/drop_caches lock = Lock() #####################################################################...
# -^- coding:utf-8 -^- import inspect import re class ValidateException(Exception): pass def validParam(*varargs, **keywords): '''验证参数的装饰器。''' varargs = map(_toStardardCondition, varargs) keywords = dict((k, _toStardardCondition(keywords[k])) for k in keywords) def generator(fu...
#!/usr/bin/env python from setuptools import setup setup(name='floatdict', version='0.1', packages=['floatdict'])
from PIL import Image import os imgwidth={} for img in os.listdir('./myfont/'): if img.endswith('.png'): char,ext=os.path.splitext(img) # print(char) pic=Image.open("./myfont/"+img) imgwidth[char]=pic.width;
# -*- coding: utf-8 -*- import numpy as np def getactions(u1,u2): actions= np.array([ [u2,u2],[u1,u1],[u2,u1], [u1,0], [u2,0],[0,u2],[0,u1],[u1,u2]]) calc=((2*np.pi)/60) actions=actions*calc return actions
# Licensed to Elasticsearch B.V under one or more agreements. # Elasticsearch B.V licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information from .utils import NamespacedClient, SKIP_IN_PATH, query_params, _make_path class EqlClient(NamespacedClient): ...
import os import sublime def truncate(s, l, ellipsis="…"): """Truncates string to length `l` if need be and adds `ellipsis`.""" try: _l = len(s) except: return s if _l > l: try: return s[:l] + ellipsis # in case s is a byte string except: retu...
import tensorflow as tf from matplotlib import pyplot as plt fashion = tf.keras.datasets.fashion_mnist (x_train, y_train),(x_test, y_test) = fashion.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(256, activati...