text
stringlengths
38
1.54M
#!/usr/bin/env python3 import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn from RPLCD import CharLCD import time from RPi import GPIO i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) lightchan = AnalogIn(ads, ADS.P1) rainchan = AnalogIn(ads, AD...
from django.shortcuts import render import requests import datetime from datetime import date def index(request): x = datetime.datetime.now() month = x.strftime('%-m') day = x.strftime('%-d') year = x.strftime('%Y') future_date = date(2019, 6, 4) ## returns the number of day from this date...
"""Core tests.""" import csv import logging import unittest from typing import Iterator, List, Tuple import yaml from oaklib import get_adapter from oaklib.datamodels.vocabulary import IS_A, PART_OF from oaklib.interfaces.obograph_interface import OboGraphInterface from ontogpt.io.yaml_wrapper import dump_minimal_yam...
#TAGS dp, kadane # variant of kadane class Solution: def maxProduct(self, nums: List[int]) -> int: cur_max = 1 cur_min = 1 res = float('-inf') for v in nums: cur_max, cur_min = max(v * cur_max, v * cur_min, v), min(v * cur_max, v * cur_min, v) res = max(cur_m...
# Copyright (c) MONAI Consortium # 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, so...
import arviz as az import pymc3 as pm import random import numpy as np import pandas as pd import logging # removes pymc3 sampling output apart from errors logger = logging.getLogger('pymc3') logger.setLevel(logging.ERROR) def convert_full_model(model, num_samples, InferenceData_dims, InferenceData_coords): """ ...
import math import pandas as pd from uuid import uuid4 from db import select_song, insert_db def extract_log_file(path): df = pd.read_json(str(path), dtype={"userId": object, "sessionId": object}, lines=True) # get rows which have NextSong value df = df[df['page']=='NextSong'] return ( pd.to_datetime(...
from typing import Dict from typing import List from arg.qck.decl import QKUnit, QCKQuery, QCKCandidate from arg.qck.instance_generator.qcknc_datagen import QCKInstanceGenerator, QCKCandidateI from arg.qck.qck_worker import QCKWorker from arg.robust.qc_common import load_candidate_all_passage from cache import load_...
# -*- coding: utf8 -*- import string from django.core.management.base import BaseCommand from strongs.models import BibleBook from progressbar import print_progress class Command(BaseCommand): help = 'Initializes the database with the bible books found in the file bibleBooks_de.txt.' def add_arguments(self, ...
# Help on class TempConstr in module gurobipy: class TempConstr(): """ TempConstr(lhs, sense, rhs) Gurobi temporary constraint object. Objects of this class are created as intermediate results when building constraints using overloaded operators. Methods defined here: __ge__(self, rhs) ...
#========================================================================== # # Copyright Insight Software Consortium # # 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...
weight = int(input("Enter your weight: ")) choice = input("(L)bs or (K)gs ? ") if choice == 'l' or choice == 'L': wei = str((weight*0.45)) print("Your weight in Kilos is: "+wei+" Kgs") elif choice == 'k' or choice == 'K': wei1 = str((weight*2.205)) print("Your weight in Pounds is: "+wei1+" Pounds") else...
""" All code must be within the following functions """ def format_names(name): """ The format names function accepts a list of names. It then modifies each name in that list to ensure that it is in title case. You must return a list of title case names """ def name_swap(passage, word, ...
import json import glob import pickle import sys import os import random import hashlib import uuid import datetime from typing import Dict import numpy as np from PySide2.QtWidgets import QApplication from gui.mainplate import MainPlate import function.const as const if __name__ == '__main__': if not os.path.is...
# -*- coding: UTF-8 -*- from flask import Flask, render_template, request, redirect, abort, url_for, g, session, send_file from flask.ext.mysql import MySQL import os, sys, re, auth, files, filters from decorators import login_required # Encoding Hack try: reload(sys) sys.setdefaultencoding('utf-8') except e...
import numpy as np, scipy, math, itertools import pandas as pd from numpy import matlib from scipy.stats import chi from scipy import integrate from pip.util import Inf from functions import * import numpy as np import itertools import math import scipy from scipy.stats import chi import time from scipy.integrate impor...
import timeit test_hasattr = """ if hasattr(gizmo, 'gadget'): feature = gizmo.gadget else: feature = None """ test_getattr = """ feature = getattr(gizmo, 'gadget', None) """ test_tryget = """ try: feature = getattr(gizmo, 'gadget') except AttributeError: feature = None """ class Gizmo: def __in...
import requests import json import io from PIL import Image import base64 subscription_key = "" #subscription_key = "" ################################################# #face-detect 1 ################################################# face_api_url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect" h...
import string def punc_func(exclude): punc = r'' for char in string.punctuation: if char not in exclude: punc = punc + r'\%s' % char return punc digits = string.digits letters = string.letters literal_punc = punc_func("'") dbl_quoted_punc = punc_func("\"") strongem_punc = punc...
import io import logging import os import time from contextlib import redirect_stderr from unittest.mock import patch import pytest import ray from ray import tune from ray.data.preprocessor import Preprocessor from ray.train.data_parallel_trainer import DataParallelTrainer from ray.train.gbdt_trainer import GBDTTrai...
import sunck """ __name__属性: 模块就是一个可执行的.py文件,一个模块被另一个程序引入,我不让想让模块中的某些代码执行, 可以用__name__属性来是程序仅调用模块中的一部分。 """ sunck.say_good()
#!/usr/bin/python # Start pensando agent and hostsim on all nodes import time import sys import os import argparse import paramiko import threading import json import http import exceptions import traceback # Port numbers - keep in sync with venice/globals/constants.go APIGwRESTPort = "443" CMDClusterMgmtPort = "900...
import numpy as np from RandomWalk import RandomWalk import math import matplotlib.pyplot as plt from datetime import datetime def run_exp3(): # params is lamda and best alpha pair params = [] for i in range(11): if i < 5: params.append([i*0.1, 0.2]) elif i < 8: para...
import os N=[120,300,600,1200,2400,4800,9600,19200] R=[2,3] K=4 os.system("rm result/*.csv") for r in R: os.system("echo N,K,R,tmap,tshuffle,treduce,texecution > result/"+str(r)+"_coded.csv") os.system("echo N,K,R,tmap,tshuffle,treduce,texecution > result/uncoded.csv") for n in N: os.system("rm *.txt") pr...
import os import numpy as np fpath = os.path.join('Resources', 'aoc201805_data.txt') with open(fpath, 'r') as f: data = f.read().strip() def react(data): stack = [] for letter in data: if stack and letter.lower() == stack[-1].lower() and letter != stack[-1]: stack.pop() else: ...
import os, sys import numpy as np import matplotlib.pyplot as plt import pickle def vel_track(x, u): track = np.where(u > 0.50) if len(track[0]) > 0: # field is above half max x_l, x_h = track[0][0], track[0][-1] if x_l < 5 or x_h > N - 5: print("Hit boundary...") end ...
import torch import numpy as np IMG_WIDTH = 448 IMG_HEIGHT = 448 S = 7 # number of grid cell is S*S B = 2 # number of bbox for each grid cell C = 20 # number of classses def read_labels(label_file): with open(label_file, 'r') as f: lines = f.readlines() labels = [] for l in lines: ...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 import jupyxplorer.parser as parser import pytest from . import CONFIG_EXAMPLE def test_load_yaml(mocker): # Given data = CONFIG_EXAMPLE file_path = "/path/tests" expected_result = data mocker.patch.object(parser.yaml, "load",...
from django.conf.urls import url from . import views urlpatterns=[ url(r'^$', views.Lista.as_view(), name='list'), url(r'^(?P<pk>\d+)$', views.Detalle.as_view(), name='detail'), url(r'^nuevo/$', views.Crear.as_view(), name='new'), url(r'^editar/(?P<pk>\d+)$', views.Actualiza.as_view(), name='edi...
from typing import List PMAP = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC"...
import argparse import os,sys import subprocess as sp import shlex import yaml def run_bash_cmd(cmd_str): """ runs command string in a bash shell """ print("%s" %(cmd_str)) sp.call(cmd_str,shell=True,executable="/bin/bash") #This allows for the command to output to console while running but with cer...
__all__ = ['IpoptConfig', 'IpoptSolver', 'SnoptConfig', 'SnoptSolver', 'OptProblem', 'OptResult', 'OptSolver', 'OptConfig'] from .pyoptsolvercpp import __with_snopt__, __with_ipopt__, __version__ if __with_snopt__: from .pyoptsolvercpp import IpoptConfig, IpoptSolver else: print("Cannot import IpoptW...
#!/usr/bin/python # coding: utf-8 import logging import os import re import sys import util from datetime import datetime, timedelta from future.utils import string_types from telegram import MessageEntity from telegram.error import BadRequest, TelegramError from telegram.ext import Updater, CommandHandler, RegexHandl...
'''PROJECT EULER PROBLEMS AUTHOR: VAL MCCULLOCH PROBLEM 2: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed...
from typing import List class Solution: def combine(self, n: int, k: int) -> List[List[int]]: def combinations(nums, combination): if len(combination) == k: result.append(list(combination)) return for i in range(len(nums)): combinati...
from dataclasses import dataclass from typing import Optional from labby.server import ExperimentSequenceStatus, Server, ServerResponse, ServerRequest @dataclass(frozen=True) class ExperimentStatusResponse(ServerResponse): sequence_status: Optional[ExperimentSequenceStatus] @dataclass(frozen=True) class Experi...
"""GRID CLASS.""" import pygame class grid(): def __init__(self, screen, height, width, blockSize): self.height = height self.width = width self.blockSize = blockSize self.row = height // blockSize self.col = width // blockSize self.screen = screen self.p...
from datetime import datetime from unittest import TestCase from apel.parsers import SlurmParser class ParserSlurmTest(TestCase): ''' Test case for SLURM parser ''' def setUp(self): self.parser = SlurmParser('testSite', 'testHost', True) def test_parse_line(self): ...
# Please edit this list and import only required elements import webnotes from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate,...
""" 재무제표 누락데이터 채우기 누락데이터 기준 : total_assets 가 누락된 행 누락데이터 보유 파일 : """ import os import re # import pandas as pd import db_oper import financial_reports as fr def get_rdate_list(): df = db_oper.select_by_query('select distinct rdate from reports order by rdate') rdate_df = df[['rdate']] # print(rdate...
import pandas as pd from tqdm import tqdm req_map = {} with open("data/requests.csv", 'r') as trace: for i, row in tqdm(enumerate(trace), desc="Running trace", total=417882879): row = row.split(',') id_ = int(row[2]) if id_ in req_map: req_map[id_] += 1 else: ...
try: from app import create_app # noqa - running at container root except ImportError: from .app import create_app application = create_app() if __name__ == "__main__": application.run()
import json import re from utils import * class Vers: def __init__(self, character, content): self.character = character self.content = content def __str__(self): return "{} : {}".format(self.character, self.content) class Piece: def __init__(self, title): se...
from django.db import models # Create your models here. class passage(models.Model): source = models.CharField(max_length=120) reference = models.CharField(max_length=120) genres = models.CharField(max_length=20) authors = models.CharField(max_length=50) time_period = models.DateField() locatio...
import pytest import numpy as np import sys import cv2 sys.path.append(".") import ex0 import re epsilon = .0001 def all_similar(t1, t2): """Test the maximum square error is lesser than epsilon.""" delta = (t1 - t2) ** 2 correct = delta > epsilon return correct.reshape(-1).mean() == 0 ...
from sklearn.model_selection import GroupShuffleSplit def find_best_group_split(dataframe, target_feature, group_by_feature, balance_focus="train"): """ :param dataframe: pandas.Dataframe dataframe to split for max balance :param target_feature: string name of the target feature of the data...
import random from abc import ABC, abstractmethod from collections import OrderedDict import numpy as np from mesa import Agent from sklearn.metrics.pairwise import cosine_similarity import copy import sys import re class SnetAgent(Agent, ABC): def __init__(self, unique_id, model, message, parameters): #...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseNotFound from .models import * import requests, json import xml.etree.ElementTree as ET import kookoo from random import random, randint from django.shortcuts import render, render_to_response def call_ivr(request): if request.metho...
from random import randint numero_informado = -1 numero_secreto = randint(0, 8) while numero_informado != numero_secreto: numero_informado = int(input('Informe a senha: ')) print('Numero encontrado')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ UW, CSEP 573, Win19 """ from pomdp import POMDP from onlineSolver import OnlineSolver import numpy as np class AEMS2(OnlineSolver): def __init__(self, pomdp, lb_solver, ub_solver, precision = .001, action_selection_time = .1): super(AEMS2, self).__init__(...
import logging from cookiecutter.main import cookiecutter def run_task(name: str, description: str, parameters: dict, service_metadata: dict): logging.info("Generating project directory using cookiecutter") template_url_field_name = parameters['template_url_field_name'] parameters_field_name = parameters...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root == None: retu...
""" Pytorch Implementation of our GFFnet models based on Deeplabv3+ with WiderResNet-38 as backbone. Author: Xiangtai Li (lxtpku@pku.edu.cn) """ import logging import torch from torch import nn from network.wider_resnet import wider_resnet38_a2 from network.deepv3 import _AtrousSpatialPyramidPoolingModule fro...
#!/usr/bin/env python import sys if len(sys.argv) != 3 : sys.stderr.write('%s flux d_kpc\n' % sys.argv[0]) exit() flux = float(sys.argv[1]) d_kpc = float(sys.argv[2]) luminosity = 1.2e+32 * (flux / 1e-12) * d_kpc**2 dump = "flux: %.3e (erg/s/cm2)\n" % flux dump += "distance : %.3e (kpc)\n" % d_kpc dump += "lu...
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Clothes import json from django.views import View from django.shortcuts import get_object_or_404 from django.core.serializers import serialize class IndexView(View): def get(self, request): clothes = ...
from os import getenv as env class Config: app_address = env('APP_ADDR', '0.0.0.0') app_port = env('APP_PORT', '8080') app_name = env('APP_NAME', 'mortimer') llevel = env('LLEVEL', 'DEBUG') app_salt = env('APP_SALT', 'MXhZifmhG7Zzegk2') # cache settings redis_enabled = bool(env('REDIS_ENA...
import numpy as np import pandas as pd from backtesting.Indicator.Meanvariance import MeanVariance from backtesting.example.measure.annualize_return import getReturn """ expand_dims的应用 预估收益率和协方差矩阵 """ def black_litterman(returns,tau,P,Q): # 先验收益率 expect_returns = returns.mean() # 协方差矩阵 cov_returns = r...
__all__ = ["szt_sys","szt_ceph_type", "szt_load_conf", "szt_log", "szt_sshconnection", \ "szt_net_tool", "szt_remote_base"]
# -*- coding: utf-8 -*- import requests from meya import Component class ChuckNorrisJoke(Component): def start(self): response = requests.get("http://api.icndb.com/jokes/random") text = response.json()['value']['joke'] message = self.create_message(text=text) return self.respond(m...
# Minimum Skew import sys lines = open(sys.argv[1].strip(), 'r').readlines() text = str(lines[0]).strip() gc = 0 # g - c skew = [] for i in range(len(text)): if text[i] == 'C': gc -= 1 if text[i] == 'G': gc += 1 skew.append(gc) m = min(skew) for i in range(len(skew)): if skew[i] ...
from rummy_cubes_game import RummyCubesGame def main(num_players, num_games): while num_games > 0: num_games -= 1 game = RummyCubesGame(num_players) game.run() if __name__ == "__main__": number_of_players = 2 number_of_games = 1 main(number_of_players, number_of_games)
def adder(x, y): """Add two numbers together.""" print("INSIDE ADDER!") return x + y assert adder(2, 5) == 7 assert adder(2, 7) == 10, "expected 2+7 to be 10" assert adder(2, 3) == 5 print("HELLO WORLD!")
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class fc(nn.Module): def __init__(self, cfg, feature_shape, num_classes): super(fc, self).__init__() assert len(feature_shape) == 4, "Expect B*C*H*W" feature_size = np.prod(feature_shape) output_si...
# -*- coding: GBK -*- # --------------------------------------------------------------------------- # PointsClusterDefault.py # Created on: 2015-07-02 11:08:02.00000 # (generated by ArcGIS/ModelBuilder) # Usage: PointsClusterDefault <InputExcel> <ClusterDistance> <OutPolygon> <OutPointsExcel> <OutPolygonsExecl> # De...
""" 计数排序(count sort) 1、找出数组中的最大、最小值 2、设置一个大小 = 最大值-最小值+1 的额外数组counts 3、利用下标统计arr中每个数出现的位置,arr中元素对应counts中下标为 counts[arr]+1 4、释放统计结果 适用于: 待排序列表中元素差值较小,重复元素较多 不足:当元素较多时,需要额外的空间较多 属性: 不稳定 O(n)时间复杂度 O(K)空间复杂度 测试用例: arr = [10,1,3,4,2,8,11,4,67,3] print(count_sort(arr)) """ def count_sort(arr): ...
import os,sys from .ioc import Ioc as Ioc class IocFile: def __init__(self, file): self.file = file self.domains = set() self.ips = set() self.hashes = set() self.emails = set() self._parse_indicator_file(self.file) def all_indicators(self): ...
#!/usr/bin/Python # -*- coding: utf-8 -*- # __author__ = "haibo" import xlrd def test(): data = xlrd.open_workbook('demo.xlsx') # 打开demo.xls sheet_names = data.sheet_names() # 获取xls文件中所有sheet的名称 for name in sheet_names: print name table = data.sheet_by_name(sheet_names[0]) print table.n...
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
from django.db import models # Create your models here. from ckeditor_uploader.fields import RichTextUploadingField class feed(models.Model): id=models.IntegerField(primary_key=True) author=models.CharField(max_length=100) title=models.CharField(max_length=100) description=RichTextUploadingField(blank=...
import numpy import math import cv2 import random import matplotlib from scipy.special import gamma import matplotlib.pyplot as plt from functions import * matplotlib.use("TkAgg") def inverse_gamma(data, alpha=0.1, beta=0.1): """ Inverse gamma distributions :param data: Data value :param alpha: alpha ...
from django.conf import settings from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.conf.urls.static import static # used for static files urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('login/', auth_vie...
tab = ["i", "s", "r", "v", "e", "a", "w", "h", "o", "b", "p", "n", "u", "t", "f", "g"] other_tab = ["a","b", "c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] word = ["g", "i", "a", "n", "t", "s"] for j in word: sol = set() for i in other_tab: a = ord(i) ...
import pathlib import yaml from typing import List class MissingConfigurationError(Exception): def __init__(self, missing: List[str]): self.missing = missing class SettingsConfig: def __init__(self, base_url: str, tags: frozenset, cache_duration: int, cache_file_duration: int, ca...
from math import ceil, floor n = input() a = map(float, raw_input().split()) x = 0 isum = 0 fsum = sum(a) for i in xrange(2*n): if a[i] == int(a[i]): x += 1 isum += floor(a[i]) ans = 10**10 for i in xrange(n-x, n+1): ans = min(ans, abs(fsum - isum - i)) print "%.3f" % ans
from django.core.management.base import BaseCommand, CommandError from app.models import BusinessLicense class Command(BaseCommand): help = 'Lorem ipsum' def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS('Lorem ipsum!'))
import jax.numpy as jnp from jax import vmap, grad, jit from utils import * from jax.scipy.stats import laplace, norm #, logistic from itertools import chain def inner_layerwise(act_prime, y): return jnp.log(vmap(vmap(act_prime))(y)) def loss_layerwise(nonlinearity, ys): sigma_prime = grad(nonlinear...
# -*- coding: utf-8 -*- # # Testing Xor pre-trained model. # @auth whuang022ai # import mlp if __name__ == "__main__": mlp = mlp.MLP(0, 0, 0, 0) mlp.load_model('xor') mlp.test_forward()
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QMainWindow,QFileDialog,QMessageBox,QWidget,QAction from PyQt5.QtCore import pyqtSlot,QFile,QDir,Qt from myEEGLAB import QEEGLAB from ui_MainWindow import Ui_MainWindow ##from PyQt5.QtWidgets import ##from PyQt5.QtGui import ##from PyQ...
from django.http import HttpResponse from django.shortcuts import render # Create your views here. from django.views.decorators.cache import cache_page from core.models import Trailer @cache_page(timeout=10) def index(request): context = { 'random_list': Trailer.objects.all().order_by("?")[:30], ...
# card.py # by Johnathon Beaumier # for use in my program for playing the Guillotine card game from guillotine import events # structure: # method definition for helper function # class definition for card types # lists for card object creation and grouping ### Method Definitions ###################################...
import collections import operator def getDistance(startX, endX, startY, endY): # Get difference of every point with every co-ordinate dist={} for i in range(startX, endX+1): for j in range(startY, endY+1): for index,coord in coords.items(): if (i,j) not in dist.keys(): ...
#!/usr/bin/python3 # all arguments to this script are considered as json files # and attempted to be formatted alphabetically import json import os from sys import argv files = argv[1:] for file in files[:]: if os.path.isdir(file): files.remove(file) for f in os.listdir(file): files.a...
# Upload wav file using ampy or deploy tar # # TAR: # import utils.setup # utils.setup.deploy("http[s]://path/to/file.tar") import os import struct from machine import Timer from machine import DAC, Pin from time import sleep #from utils.pinout import set_pinout #pinout = set_pinout() #out = pinout.PI...
#!python from typing import List def is_sorted(items: List[int]) -> bool: """Return a boolean indicating whether given items are in sorted order. Running time: O(n) we're iterating over all elements Memory usage: O(1) we're not creating new memory""" if len(items) < 2: return True for i in...
import pymysql import pandas as pd class DBModel: def __init__(self): self.db_diet = pymysql.connect( user='root', passwd='111111', host='127.0.0.1', db='db_diet', charset='utf8' ) self.cursor = self.db_diet.cursor(pymysql.cursors...
import FWCore.ParameterSet.Config as cms from RecoBTag.Skimming.btagElecInJet_EventContent_cff import * btagElecInJetOutputModuleAODSIM = cms.OutputModule("PoolOutputModule", btagElecInJetEventSelection, AODSIMbtagElecInJetEventContent, dataset = cms.untracked.PSet( filterName = cms.untracked.strin...
# -*- coding: utf-8 -*- # @Author: fengmingshan # @Date: 2019-09-02 15:15:02 # @Last Modified by: Administrator # @Last Modified time: 2019-09-06 17:12:31 import pandas as pd import numpy as np import os import math data_path = 'd:/2019年工作/2019年9月校园超忙小区分析/' file = '能源学校_曲靖KPI指标_08-29_09.02.csv' df_content = pd.re...
from django.db import models # Create your models here. class User(models.Model): name = models.CharField( max_length=100 ) surname = models.CharField( max_length=100 ) def __str__(self): return self.name + self.surname
# -*- coding: utf-8 -*- # from vaex import dataset import vaex.dataset from optparse import OptionParser from mab.utils.progressbar import ProgressBar import sys import h5py import numpy as np def merge(output_filename, datasets_list, datasets_centering=None, sort_property=None, order_column_name=None, ascending=True...
from colorama import Cursor, init, Fore abc = "abcdefghijklmnopqrstuvwxyz 1234567890 %#@![]{}()?¿+-*/" class UtilCrypto: def __init__(self,key): self.key = key self.limitKey = len(abc) #si la key es mayor a la lontyiud de abc entonces error def containerblock(self): self.FILENAMES ...
import numpy as np import torch from torch import nn from torch.autograd import Variable from torchvision.datasets import CIFAR10 torch.manual_seed(1) def data_tf(x): x = np.array(x, dtype='float32') / 255 x = (x - 0.5) / 0.5 x = x.transpose((2, 0, 1)) x = torch.from_numpy(x) return x train_set ...
from flask import Flask, render_template, url_for, flash, redirect from datetime import datetime from flask_sqlalchemy import SQLAlchemy from forms import LoginForm, RegistrationForm app = Flask(__name__) app.config['SECRET_KEY'] = 'oowewbcdeoproeporpebcoiffoekcjefdcdcndcoidfcbdc' app.config['SQLALCHEMY_DATABASE_URI']...
from __future__ import print_function from stylelens_product.bigquery.amazon_search_keywords import AmazonSearchKeywords from pprint import pprint # create an instance of the API class api_instance = AmazonSearchKeywords() keywords = [] keyword = {} keyword['keywords'] = 'sss2' keyword['search_index'] = 'HC8000' keyw...
import matplotlib.pyplot as plt import numpy as np def generate_toy_data(): mean_a = [0.2, 0.2] cov_a = [[0.01, 0], [0, 0.01]] # diagonal covariance mean_b = [0.8, 0.8] cov_b = [[0.01, 0], [0, 0.01]] # diagonal covariance class_a_x = np.random.multivariate_normal(mean_a, cov_a, 500).T cla...
class Song(object): def __init__(self): self.song = song self.file_path = file_path #Set mutators and accessors for song #Get path of song #Set path of song def set_song_path(self, file_path): file_path = self.file_path
#!/usr/bin/env python from __future__ import print_function import socket import sys if len(sys.argv) >= 3: srv = (str(sys.argv[1]), int(sys.argv[2])) else: srv = ("90.176.152.68", 28015) query = "\xFF\xFF\xFF\xFF\x54Source Engine Query\x00" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: soc...
import geocoder def main(): # Declare destinations list here destinations = ['Space Needle', 'Crater Lake', 'Golden Gate Bridge', 'Yosemite National Park', 'Las Vegas, Nevada', 'Grand Canyon National Park', 'Aspen, Colorado', 'Mount Rushmore', 'Yellowstone National Park', 'Sandpoint, Idaho', 'Banff National Pa...
import modi """ Example script for the usage of ir module Make sure you connect 1 ir module to your network module """ if __name__ == "__main__": bundle = modi.MODI() ir = bundle.irs[0] while True: print("{0:<10}".format(ir.proximity), end='\r')
from PIL import Image from pandas import read_csv import os labels = read_csv('Large Files/test.rotfaces/test.preds.csv').values for item in labels: colorImage = Image.open(os.path.join('Large Files/test.rotfaces/test/', item[0])) if item[1] == 'rotated_right': rotated = colorImage.rotate(90) if ...
# -*- coding: utf-8 -*- from models import Item_types as IT, Items, Prices, Places from sqlalchemy import func from auxiliary_functions import prepare_options DEFAULT_CAT = "предмет роскоши" DEFAULT_ITYPE = "предмет" class Search: @staticmethod def item_result_to_dict(result): result = [ ...