text
stringlengths
38
1.54M
""" This module is reponsible for fetching the status of each tank. """ import json from logs import log_warning def get_tank_status() -> dict: """ This function reads the tank json file, saves and returns its contents to a dictionary. """ with open('tanks.json', 'r') as tanks_file: ...
import tensorflow as tf from models.base_model import Model from core.layers import MLP, GRU, SparseMax from utils.constants import BIG_NUMBER, SMALL_NUMBER, FLOW_THRESHOLD from utils.tf_utils import masked_gather from utils.flow_utils import mcf_solver, dual_flow, destination_attn from cost_functions.cost_functions im...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class MailMessage(models.Model): _inherit = 'mail.message' def portal_message_format(self): return self._portal_message_format([ 'id', 'body', 'date', 'author_id', '...
# coding: utf-8 # In[40]: """ 난이도 : 3 문제 : 1부터 10000사이의 자연수 N이 주어진다. 자연수 중에서 6을 연속으로 3개이상 포함하는 수 중에 N번째 수를 출력. 알고리즘 : 666부터 시작하여 1씩 더해가면서, 수를 문자열로바꾼뒤 '666'을 1개 이상 포함하면 하나씩 카운트한다. 입력받은 N과 카운트수가 일치하는 수를 출력한다. """ def Brute_force(N): cnt=666 s=0 while 1: if str(cnt)...
from django.contrib import admin from rd.models import Detail, Photo, EngineCategory, CarCategory, EngineCategoryPhoto, CarCategoryPhoto, DetailCategory, \ City # Register your models here. from django import forms from tinymce.widgets import TinyMCE class PhotoInline(admin.TabularInline): model = Photo clas...
from django.shortcuts import render, HttpResponseRedirect, reverse # used this https://stackoverflow.com/questions/23557697/django-how-to-let-permissiondenied-exception-display-the-reason #in reference on how to display an error to user if they don't have permission from django.http import HttpResponseForbidden from dj...
from Google import Create_Service from flask import Flask, render_template, request, json import requests app = Flask(__name__) parent_folder = ['Admin', '2020'] sub_folder_admin = ['11. Director Details'] sub_folder_tahun = ['01. Januari'] sub_folder_bulan = ['24. PP23'] parent_id_company = [] parent_id_admin = [] p...
import psycopg2 import traceback def execute_select(query): connection = None cursor = None try: connection = get_connection_object() cursor = connection.cursor() cursor.execute(query) desc = cursor.description column_names = [col[0] for col in desc] data = [dict(zip(column_names, row)) for row in c...
from sys import exit from random import randrange class Scene(object): def enter(self): print('This scene is not yet configured.') print('Subclass it and implement enter().') exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map ...
"""PAWN GOING TO END AND CHECKMATE WILL STAY INCOMPLETE FOR THE NEAR FUTURE.""" # cd C:\Users\nellissery\Desktop\python code\Chess # python main.py # to do # castling (it works, but for some reason you have to double click, and an ineffective error is given) # checkmate condition(not done) from tkinter import * from...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os import re import textwrap import nibabel as nib import numpy as np from dipy.core.gradients import gradient_table from dipy.tracking.streamline import length from learn2track.neurotools import TractographyData, subsample_streamlines from learn2...
import os import sys import numpy import h5py import cupy import utility def calcDistField(point_file, h5name, save_location): data_file = h5py.File(h5name) data = data_file['data'][:] data_dim = data.shape[0] data_file.close() ptfile = h5py.File(point_file) sample_points = ptfile['points'][:]...
from functools import wraps from hashlib import md5 from contextlib import contextmanager import psycopg2 from psycopg2.extras import RealDictCursor from flask import session, request from flask_restful import abort from werkzeug.exceptions import BadRequest def authenticated(method): @wraps(method) def wr...
"""IGCV3 for Semantic Segmentation""" import torch import torch.nn as nn import torch.nn.functional as F from light.model.base import BaseModel from light.nn import _ASPP, _FCNHead class IGCV3Seg(BaseModel): def __init__(self, nclass, aux=False, backbone='mobilenetv2', pretrained_base=False, **kwargs): s...
from django.db import models # Create your models here. from tinymce.models import HTMLField class Category(models.Model): name = models.CharField(max_length=20, verbose_name="分类") def __str__(self): return self.name class Meta: db_table = "Category" verbose_name = "分类" ...
# -*- coding: utf-8 -*- """ Test the readers for which there is test data in this package """ import os from io_utils.data.read.geo_ts_readers import ( GeoCCISMv6Ts, GeoSMOSICTs, SelfMaskingAdapter, GeoCCISMv5Ts, GeoSpl3smpTs, GeoCCISMv3Ts, GeoCCISMv4Ts, GeoEra5Ts, GeoEra5LandTs, GeoC3Sv202012Ts, GeoC3Sv20...
class Loaf: "loaves of bread with names, tastes and weights" ingredients=['yeast', 'flour'] counter=0 def taste(self): return "yeasty" def weight(self): return "3lb 2oz" def __init__(self, name="default loaf"): print 'init' print self.__class__ self.__clas...
import requests, re, os, time, sys, subprocess, datetime, json vlc_path = 'C:\\Software\\VideoLAN\\VLC\\vlc.exe' video_folder = 'camarads' file_len = 5 #minutes, approximately night_mode = False offTime = datetime.time(2,0,0) # (3:00 AM) time when downloading stop printCams = False # cam's IDs. For ex.: ['4_4','2_2...
""" Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com 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, m...
from ScenarioHelper import * def main(): SetCodePage("ms932") CreateScenaFile( "r4090.bin", # FileName "r4090", # MapName "r4090", # Location 0x00A6, # MapIndex "ed7354", 0x00000000, ...
import numpy as np from numpy import linalg as LA import scipy as sc from scipy.interpolate import interp1d import scipy.integrate as integrate import scipy.special as special import random as rd from sympy import besseli, besselk #import matplotlib.pyplot as plt import time start_time = time.time() #import mat...
# -*- coding: cp936 -*- import arcpy # 设置工作空间 workSpace="C:\Users\lenovo\Desktop\PyTest\data\geodb.gdb" arcpy.env.workspace=workSpace def editPipeTableNonGeometricalProperties(): ''' 定义一个将管段表中非空间属性的数据汇总到管线表的函数。 如果存在一条管线中的某个属性中有多个值的情况,函数将其设置为这条管线的这一属性None 在与甲方进行管线确认时,请将管线名称写入管段表中的管线名称字段中 基础地理信息字段请手...
def test_basic_settings(): from orb.settings import Settings # validate the default values settings = Settings() assert settings.default_locale == 'en_US' assert settings.default_page_size == '40' assert settings.max_cache_timeout == '86400000' # 24 hours assert settings.max_connections =...
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved Author: Dejiao Zhang (dejiaoz@amazon.com) Date: 02/26/2021 """ import torch import numpy as np from utils.metric import Confusion from dataloader.dataloader import train_unshuffle_loader from sklearn import cluster def prepare_task_input(model, ba...
# import matplotlib.pyplot as plt import numpy as np import plotly as py import plotly.graph_objs as go import plotly.tools as tls """dictionary = { 'A' : [12, 14.8, 16, 20], 'B' : [1], 'c' : [12, 2, 14, 10], 'd' : [12, 2, 4, 5], '3' : [1, 3, 4, 5] }""" def plottingBox(dictionary): N = len(d...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import collections import logging from odoo.tests import common from odoo.cli.populate import Populate from odoo.tools import mute_logger, populate from unittest.mock import patch _logger = logging.getLogger(__name__) ...
# -*- coding: utf-8 -*- a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(a) print(a[3]) # 크기가 N이고, 모든 값이 0인 1차원 리스트 초기화 n = 10 a = [0] * n print(a) # 인덱싱 a = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 여덟번째 원소만 출력 print(a[7]) # 뒤에서 첫 번째 원소 출력 print(a[-1]) # 뒤에서 세 번째 원소 출력 print(a[-3]) # 네번째 원소 값 변경 a[3] = 7 print(a) # 슬라이싱 a = [1, 2, ...
from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from datetime import datetime from track.models import WeightData from django.db.models import Max, Min, Avg def start(request): latest_measure_list = WeightData.objects.order_by('-check_date')[:1] ...
#!/usr/bin/env python #coding=utf-8 #date : 2015-04-12 from socket import * def create_udp_client(): HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpCliSock = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input('please input msg> ') if not data: ...
# from https://github.com/AtsushiSakai/PythonRobotics/blob/master/AerialNavigation/drone_3d_trajectory_following/TrajectoryGenerator.py from mpl_toolkits import mplot3d import matplotlib.pyplot as plt import numpy as np class TrajectoryGenerator(): def __init__(self, start_pos, des_pos, T, start_vel=[0,0,0], des_v...
import math, Matrix import numpy as np #Вычисления массива функций def DeterminatFunc(baseFunc,baseValue): newValue = np.zeros((baseFunc.shape[0],baseFunc.shape[1])) for i in range(0,newValue.shape[0]): for j in range(0,newValue.shape[1]): newValue[i][j] = baseFunc[i][j](baseValue[0],baseV...
dogname = ['Fido','Sean','Sally','Makr'] # print(dogname) # inserting at 1 position # dogname.insert(1, 'Jane') # print(dogname) print(dogname[2]) # To delete from list del(dogname[2]) print(dogname) # length of list print(len(dogname)) # Updating a list dogname[1] = 'Jane' print(dogname) # List can hvae mi...
from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from .consumers import Chat application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack(URLRouter([ path('', Chat), ])) })
from EngineClass import * from DisplayClass import * import pygame import time Score_Increment = 0.1 Width = 900 Height = 700 Tick_Time = 0.05 class Game: def __init__(self, n): self.paused = False self.ensemble = Ensemble(np.array([[Width], [Height]])) self.ensemble.po...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- if __name__ == "__main__": import sys print "Don't run this file directly. It is used by other scripts." sys.exit(0) # NOTE: i must start at 0. colors = ['b', 'r', 'g', 'm', 'c'] symbols = ['-', '--', '-.', ':'] characters = ['x', 'o', '^', 's', 'p', '*', '...
class Solution: def findElement(self, matrix, element): row = 0 col = len(matrix[0]) - 1 while row <= len(matrix) - 1 and col >= 0: if matrix[row][col] == element: return True elif matrix[row][col] > element: col -= 1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy, itertools from pyquery import PyQuery as pq from bulva.parsers import MTParser class Parser(MTParser): URL = 'http://www.kinosvetozor.cz/cz/program/' URL_BASE = 'http://www.kinosvetozor.cz' def get_items(self): items = [] data = ...
from unittest import mock import pytest from wordguess import wordguess def mock_input(*args): input_values = list(args) def mock_input2(s): print(s, end="") return input_values.pop(0) return mock_input2 def test_load_words(): test_words = ["TESTING", "PYTHON", "FINISH", "YELLOW"...
#Determina si un numero es primo o no def is_primo(num): if num<=1: return False es_primo = True for x in range(2,num): if(num%x==0): es_primo=False return es_primo ## Numeros primos hasta un limite def num_primo(num): for x in range(num+1): if (is_primo(x)): print(x," es un numero primo") num_primo...
""" A basic command-line tool that uses JavaScriptCore See also <http://parmanoir.com/Taming_JavascriptCore_within_and_without_WebView> TODO: This needs to be an example that does something useful """ import JavaScriptCore with JavaScriptCore.autoreleasing(JavaScriptCore.JSGlobalContextCreate(None)) as ctx: scri...
#!/usr/bin/python3 # -*- coding: utf-8 -*- #Author: xiaojian #Time: 2019/3/18 17:28 from Common.basepage import BasePage from PageLocators.indexPage_locator import IndexPageLocator as loc from Common import logger import logging class IndexPage(BasePage): #点击导航栏内容 def click_nav_by_name(self,nav_name): ...
import serial.rs485 import minimalmodbus def leia(reg) : ser=serial.rs485.RS485("/dev/ttyAMA0",19200) ser.rs485_mode = serial.rs485.RS485Settings() ser.rs485_mode.rts_level_for_tx=True # com 4n25 - emisor no resistor -o False # True ser.rs485_mode.rts_level_for_rx=False # True # False ser.timeout=0...
import torch from . import Dataset class SubsetDataset(Dataset): """ Dataset that is a subset from another Dataset """ def __init__(self, dataset, indices): """ Constructor Args: dataset: Original dataset indices: Indices of original dataset for sample """ ...
""" Palindromic Decomposition https://www.codingame.com/ide/puzzle/palindromic-decomposition Version: 0.3 Created: 08/07/2019 Last modified: 08/07/2019 """ import sys import math import time # Main input input_string = input() def asymmetric(x: int, v: int) -> int: """ Asymmetric string """ ...
''' This is a simple module with a few functions ''' author = 'Ted Petrou' favorite_number = 4 def add(a, b): return a + b def sub(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): return a / b def count_vowels(word): count = 0 for letter in word.lower(): count...
import logging from tests.frontend import webdriverUtils from tests.frontend.critical_designs.base_procedure import BaseProcedure class TestFillingsInDefs(BaseProcedure): def setup_method(self, method): # test config self.critical_svg = "Fillings-in-defs.svg" self.doConversion = True ...
## Verify fluctuations in difference records ## ## according to expectation of not exceeding 7 S.D. ## ## from Heinemann and Conti Methods in Enzymology 207 ## ## Python Implementation ## Andrew Plested 2006 ## ## Takes input from tab-delimited Excel file 'file.txt'. ## Columns are current traces ## Mean and vari...
import socket def get_remote_machine_info(): remote_host = 'www.aspira.hr' try: print "IP adress: %s" %socket.gethostbyname(remote_host) except socket.error, err_msg: print "%s: %s" %(remote_host,err_msg) if __name__ == '__main__': get_remote_machine_info()
__author__ = 'Ian' import matplotlib.pyplot as plt import matplotlib.dates as mdates import os import pandas as pd import numpy as np from sklearn.metrics import accuracy_score from Data.scripts.data import data from pandas.tools.plotting import autocorrelation_plot def run_strategy(Y_pred, Returns_df): # normal...
import re noise_words_file = open("Noisewords.txt", "r", encoding='utf8') noise_words = set(line.strip() for line in noise_words_file.readlines()) def re_strip(string): """ Removes all non-alphanumeric characters from the ends of the given string. :param string: a string to clean :return: A...
########################################################################## # # Copyright (c) 2020, Cinesite VFX Ltd. 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 ...
from django.contrib import admin from spreedly.models import Gift, Subscription class SubscriptionAdmin(admin.ModelAdmin): list_display = ('user', 'name', 'lifetime', 'active_until', 'active') admin.site.register(Gift) admin.site.register(Subscription, SubscriptionAdmin)
#!/usr/bin/env python # OOI Data Team Portal # Calculate Quarterly uFrame Data Statistics # Written by Sage 6/19/17 import pandas as pd from dateutil.relativedelta import relativedelta from datetime import datetime import requests startTime = datetime.now() #------------------------- # Load M2M configuration import ...
# Take a TSV file of exit questionnaire data exported from LabKey and convert it to JSON following # the OpenTargets "genetic association" schema https://github.com/opentargets/json_schema import argparse import csv import json import logging import sys import gel_utils SOURCE_ID = "genomics_england_questionnaire" PH...
# bubble sort p = lambda x : print(x) arr = [x for x in range(15,0,-1)] def bubble_sort(arr): if len(arr) <= 1: return arr _bool = True while _bool : _bool = False for idx in range(len(arr)-1): if arr[idx] > arr[idx+1]: temp = arr[idx] ...
from django.urls import path from basic_app import views #TEMPLATE TAGGING app_name = 'basic_app' #this global variable name should be app_name. urlpatterns = [ path('relative/',views.relative,name='relative'), path('other/',views.other, name = 'other'), ]
from ethereum.utils import sha3 from trees_core.constants import NULL_HASH from .exceptions import MemberNotExistException from .node import Node from ethereum.abi import encode_single import rlp class Leaf(object): def __init__(self, offset, anchor, permil): self.permil = permil self.anchor = a...
#!/usr/bin/python import psutil, json, requests, getpass, hashlib memory = psutil.virtual_memory() swap = psutil.swap_memory() disk = {'part': {}, 'usage': {}} noditor_url = 'http://noditor.me' def configure_app(): print "\n\nThe application should be configured." print "Please login in your noditor ac...
# Generated by Django 3.1.3 on 2020-11-09 15:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Medi', '0007_auto_20201109_1634'), ] operations = [ migrations.CreateModel( name='tags', ...
""" PyPI setup file """ from setuptools import setup setup( name='dndbuddy_basic', packages=['dndbuddy_basic'], version='0.0.1', author='Matt Cotton', author_email='matthewcotton.cs@gmail.com', url='https://github.com/MattCCS/DnDBuddy-Basic', description='The Basic (fair use) module for ...
import sqlite3 import pandas as pd import datetime ##estbablish the sqlite3 database connection con = sqlite3.connect("ao3_tags.db") cur = con.cursor() ##data types for reading in the clean data ##these have to be enforced or else pandas starts ##making up animals dtypes_w={"language": 'category', ...
from urllib import parse class QueryHelper(): def queryStringToDict(url=None, query_string=None): # TODO : test url param against URL pattern if not url and not query_string: raise ValueError("You must provide either an URL or a querystring") # pep8 ternary identation https:/...
import chaipy.common as common import chaipy.io as io from chaipy.kaldi import ivector_ark_read, print_vector def main(): desc = 'Convert from speaker i-vectors to utt-ivectors. Output to stdout.' parser = common.init_argparse(desc) parser.add_argument('spk_ivectors', help='File containing spk i-vectors.')...
import time def subsets_recursive(nums): # First solution --- using recursive if len(nums) != 0: L = subsets_recursive(nums[:-1]) return L + [l + [nums[-1]] for l in L] else: return [[]] def subsets_forloop(nums): # Second solution --using for loop L = [[]] for i in r...
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() from blog import urls as blog_urls urlpatterns = patterns('', # Uncomment the admin/doc line below to enable admin documentation: (r'^admin/doc/', include('django.contrib.admindocs.u...
# -*- coding: utf-8 -*- import argparse from route4me import Route4Me def main(api_key): route4me = Route4Me(api_key) telematics = route4me.telematics print('****************************') print('Searching for Global Vendors') print('****************************') vendors = telematics.search...
import copy def hang(a): n=len(a[0]) if n != 1: s=0 for i in range(0,n): t=copy.deepcopy(a) t=t[1:] for j in range(n-1): del t[j][i] s+= (-1)**i*a[0][i]*hang(t) return s else: return a[0][0] try: a=inpu...
""" Brendan Koning 4/16/2015 Model.py This file holds all of the information pertaining to the models used in the program and methods to manipulate those models. """ from collections import deque class stats: def __init__(self): self.proceses = [] def add(self, id): self.proceses.append(id) def count(self):...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # (c) DevOpsHQ, 2016 # Integration YouTrack and Zabbix alerts. import yaml from pyzabbix import ZabbixAPI import sys from six.moves.urllib.parse import quote import logging import time import settings from youtrack.connection import Connection import re import urllib3 u...
import unittest import numpy import chainer import chainer.functions as F from chainer import testing class TestFunction(unittest.TestCase): def test_forward(self): xs = (chainer.Variable(numpy.array([0])), chainer.Variable(numpy.array([0])), chainer.Variable(numpy.array([0]...
#!/usr/bin/python3 import datetime import sys import time from collections import defaultdict from as6libs import get_sun_info import os import requests from urllib.request import urlretrieve import json json_file = open('../conf/as6.json') json_str = json_file.read() json_conf = json.loads(json_str) def set_camera...
#! /usr/bin/env python2.7 #coding=utf-8 #filename: deep_tts.py import sys import time import os import glob import matplotlib.pyplot as plt from os import listdir from os.path import isfile, join import numpy as np from scipy.cluster.vq import whiten from keras.models import Sequential from keras.layers.core import De...
# https://www.practicepython.org/exercise/2014/06/06/17-decode-a-web-page.html import requests from bs4 import BeautifulSoup url = 'http://www.nytimes.com/' r = requests.get(url) html = r.text soup = BeautifulSoup(html, 'html.parser') for story_heading in soup.find_all(class_="story-heading"): # for the story h...
import requests import pandas as pd #Year and game range for scraping NBA Play-by-Play: 82 game seasons (66 games in 2011, 50 games in 1998); 29 teams 1996 - 2003, 30 teams 2004 onward games = range(1,991) years = [2011] for year in years: season = str(year) + '-' + str(year+1) playbyplay_df = pd.DataFrame() ...
import re import urllib.request from urllib.request import Request url = "https://www.google.com/search?q=" try: stockFinder = input("Enter any company (belonging to USA) name to find its stock.\n") url = url + stockFinder print("The url of your preffered site is "+ url) newUrl = Request(url,headers={'User-Agent'...
""" ajax的实战分析 在查看网页的时候,选择检查--network,然后我们清空所有的请求信息,刷新页面, 这时候的第一个请求就是这个页面的骨架,基本的代码都在里面,但是数据可能是Ajax请求之后, 在通过js渲染进去的,这个时候将我们想要的页面上的数据进行复制在network的Preview选项 卡查看Response Body,进行搜索,若结果存在,我们直接请求该网页,就能获取到想要的信息, 要是没有,数据就是通过后请求,在渲染的模式进行加载的,这里需要我们分析请求数据的链接, 首先将all的搜索模式切换成xhr,在刷新请求,这里截取到的都是ajax请求,在其中看是否有需要 的数据,如存在,分析请求方式,获取json数据...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###...
import pyodbc #Variables to connect to DB server = 'localhost,1433' database = 'Northwind' username = 'SA' password = 'Passw0rd2018' docker_northwind = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password) #What is a cursor? cursor = docker_n...
from datetime import datetime, timedelta from pytz import timezone import calendar def get_time(): fmt = '%H:%M:%S' aus = timezone('Australia/Sydney') td = datetime.today() aus_dt = td.astimezone(aus) return aus_dt.strftime(fmt) # print(get_time('%m-%d-%Y')) def get_date(): aus = timezone('Au...
from services.twitter import Twitter import pyfiglet class Browse: # List of Menu menus = [ { 'id' : 0, 'title' : 'Read my home timeline' }, { 'id' : 1, 'title' : 'Stalk someone timeline' }, { 'id' : 2, 'title' : 'Retweet a tweet' }, { 'id' : 3, 'title' : 'Like a tweet' }, ...
#!/usr/local/bin/python3 import pysig as ps from pysig import DB #import matplotlib.pyplot as pt #import numpy env = ps.Log(ps.Linear([0,2],[1,100])) ps.plotsig(env)
import sys from torch.utils.data import Dataset, DataLoader import os import os.path as osp import glob import numpy as np import random import cv2 import pickle as pkl import json import h5py import torch import matplotlib.pyplot as plt from lib.utils.misc import process_dataset_for_video class MPIINFD...
#_*_ coding:utf-8 _*_ from log import Log from traceback import format_exc from bs4 import BeautifulSoup import requests from config import PER_REQUESTS_DELAY,PROXIES,IS_CHANGE_HOST,HOST_INDEX,WEBHOSTS from lxml import etree import time,re from faker import Faker ''' 本模块依赖python第三库faker,安装方法 pip install faker 教程详解:ht...
import sys from os.path import expanduser home = expanduser("~") sys.path.append('{}/ProjectDoBrain/codes/Modules'.format(home)) from rest_handler import RestHandler from json_handler import JsonHandler from csv_handler import CsvHandler def parse_commands(argv): from optparse import OptionParser parser = Opt...
import torch import torch.nn as nn import torch.nn.functional as F from .transformer import build_transformer class TrackingModel(nn.Module): def __init__(self, transformer, num_classes, num_queries=None): super().__init__() self.transformer = transformer self.num_classes = num_classes #...
#!/usr/bin/env python # -*- coding: utf-8 -*- import hashlib import datetime import random from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, render, get_object_or_404 from django.template import RequestContext from django.contrib.auth import * from django.core.urlresolvers im...
import random from django.shortcuts import render # Create your views here. from rest_framework.generics import GenericAPIView from rest_framework.mixins import RetrieveModelMixin from rest_framework.response import Response from rest_framework.views import APIView from django_redis import get_redis_connection from r...
# -*- coding:utf-8 -*- from util.operatedb import * from util.logger import Logger logger = Logger(logger="db").getlog() #用户成为会员 class becomeMember(): #1.删除用户 def del_user(self): sql = 'delete c,w from customer_user c ,customer_user_wechat w where c.id = w.user_id AND w.nick_name like "鱼小七%"' ...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from .items import SpidersProxyItem class SpidersProxyPipeline(object): def __init__(self): super(SpidersProxyPi...
# -*- coding: UTF-8 -*- from league.league import League from script.zhongchao_guess import ZhongchaoGuess import csv import sys reload(sys) sys.setdefaultencoding('utf-8') def fajia_guess(round_num): fajia = League(5, 'fajia', 'input/fajia_games.csv', 'input/fajia_ranking.csv') fajia.parse() season...
import os import pickle import shutil import zipfile from functools import partial import numpy as np import pandas as pd import scanpy as sc from scipy import sparse from six import string_types from odin.utils import MPI, one_hot from sisua.data.const import MARKER_GENES from sisua.data.path import DATA_DIR, DOWNLO...
import pymongo, os import json def seedUserData(user_collection): with open('backend/users-api/data.json') as user_data: data = json.load(user_data) response = user_collection.insert_many(data) return response if __name__ == "__main__": db_uri = os.getenv('DB_URI') or 'localhost' db_user...
# -*- coding: utf-8 -*- """ Utility functions, just doing simple tasks. """ __author__ = 'aildyakov' def get_input_function(): """ This function returns right `input` function for python2 and python3. :return: function `input` in python3 or `raw_input` in python2. """ try: input_functio...
""" Program Name: field_util.py Contact(s): George McCabe <mccabe@ucar.edu> Description: METplus utility to handle MET config dictionaries with field info """ from . import get_threshold_via_regex, is_python_script, remove_quotes def field_read_prob_info(config, c_dict, data_types, app_name): """! Read probabili...
# Problem [1074] : Z import sys n = 0 def recursion_Z(x, y, size): global n # 종료조건 if x == r and y == c: print(n) return # 재귀 if x <= r < x + size and y <= c < y + size: recursion_Z(x,y,size//2) recursion_Z(x,y+size//2,size//2) recursion_Z(x+size//2,y,size//...
import glob import os import argparse import csv import cv2 parser = argparse.ArgumentParser(description="Generate a video annotation file.") parser.add_argument("-d", "--data-dir", type=str) parser.add_argument("-o", "--video-annotations", type=str) parser.add_argument("-o", "--output-file", type=str, default="hype...
# coding:utf-8 # 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"...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField,\ FileField,DateField, FormField from wtforms.validators import DataRequired, NoneOf, AnyOf from app import db def pick_option(form, field): print(field.data) ...
#!/usr/bin/python ''' creates bundle graph from filtered multigraph ''' ### imports ### import sys import os import logging import networkx as nx import numpy as np import scipy.stats as stats import cPickle import helpers.io as io import helpers.misc as misc ### definitions ### ### functions ### def compress_edg...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-22 00:57 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Producto', '0003_auto_20170821_1059'), ] operations = [ migrations.RemoveField( ...