text
stringlengths
38
1.54M
from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify import itertools class Holliday(models.Model): name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) ...
__author__ = 'Administrator' import json import urllib.parse import urllib.request from suds.client import Client import configparser class HttpGet: def __init__(self, path): conf = configparser.ConfigParser() conf.read(path) self.url = conf.get("url", "Http_url") key = conf.get("Ht...
# 项目各密码配置文件 # 放置于项目根目录下 ### django APP秘钥 SECRET_KEY = '-qhsgt6r3a4lb1*181+hl141#o@7@am29wa8v$^@dgp(1e)=yj' QQ_SECRET = 'B5T4EEMD2MHnmGyX' ### mysql 配置 MYSQL_HOST = 'cdb-07n3b91f.gz.tencentcdb.com' MYSQL_PORT = 10081 MYSQL_USER = 'root' MYSQL_PASSWORD = '18759799353gjb!' ### 邮件发送配置 # 发件人授权码 EMAIL_HOST_PASSWORD = 'xfY...
#Importing all the important modules that are reuired import pandas as pd import numpy as np import random import string #Dataset is loaded df = pd.read_csv ('C:/Users/Hp 840/Desktop/Shakespeare_data.csv') df.head () #Unnecesary lines are removed df = df.dropna (subset = ['Player', 'ActSceneLine']) df.tail ()...
''' Copyright (c) 2020 Thomas Wilkinson 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, dis...
#not found invalid or unknown data in all row #not found invalid gender data in all row #total data instance is complete #group column data is have many format to tell about this data import csv import sys with open('gender_age_train.csv') as myCSV: csvReader = csv.reader(myCSV) findMaxAge = -sys.maxsize ...
from guizero import App, Text, Box, PushButton, Picture, TextBox, Drawing from lemon_pi.car.display_providers import * from lemon_pi.car.event_defs import ( LeaveTrackEvent, StateChangePittedEvent, StateChangeSettingOffEvent, CompleteLapEvent, OBDConnectedEvent, OBDDisconnectedEvent, GPSConnectedEvent, GPSDis...
# coding: utf-8 """ Xero Finance API The Finance API is a collection of endpoints which customers can use in the course of a loan application, which may assist lenders to gain the confidence they need to provide capital. # noqa: E501 Contact: api@xero.com Generated by: https://openapi-generator.tech...
# -*- coding: utf-8 -*- import scrapy import re try: import urlparse as parse except: from urllib import parse class FishcSpider(scrapy.Spider): name = 'fishc' allowed_domains = ['https://fishc.com.cn/'] start_urls = ['https://fishc.com.cn/thread-51842-1-1.html'] headers = { "HOST": "f...
from .Weapons import Wand class OakWand(Wand): def __init__(self, name="Oak Wand", value=10, weight=0.5, strBuff=0, agiBuff=0, intBuff=5, damage=2, actionCost=3, scaleValue=1.0, tier=1): super().__init__(name, value, weight, strBuff, agiBuff, intBuff, damage, actionCost, scaleValue, t...
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
# coding:utf-8 # 把KNN的结果作为输入 import math original = file('../../../features/3_refine_street/train.csv') knn = file('../../../features/4_points/knn_train.csv') target = file('../../../features/4_points/train.csv', 'w') knn.readline() line_cnt = 0 for line in original: target.write(line[:-1]) if line[0] == '...
# Generated by Django 3.2.7 on 2021-10-27 17:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0001_initial'), ] operations = [ migrations.AddField( model_name='product', name='product_detail', ...
from django.shortcuts import render from django.http import Http404 from .models import Artist, Genre, Album from .filters import ArtistFilter, GenreFilter def artist_list(request): artist_list = Artist.objects.all() artist_filter = ArtistFilter(request.GET, queryset=artist_list) return render(request, ...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def height(self, node, h): if node: d1 = self.height(node.left, h) d2 = self.height(node.right, h) d = max(d1, d2) + 1 ...
import re import os import numpy as np import pandas as pd from pathlib import Path from datetime import datetime import tensorflow as tf from tensorflow.keras.applications import ResNet50, MobileNetV2, InceptionV3 from tensorflow.keras.preprocessing.image import ImageDataGenerator def list_dataset(): for dirnam...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.DiagnosisDisease import DiagnosisDisease class Diagnosis(object): def __init__(self): self._diseases = None @property def diseases(self): return self...
import UdGraph import random import math """ Mathematics of Gerrymandering Washington Experimental Mathematics Lab, 18 Sp Project GitHub: https://github.com/weifanjiang/WXML-18wi-Research This file contains the model to perform Metropolis-Ising algorithm on a graph which represents an actual state """ class Washingt...
import copy def get_num_left_most_pos(number, num): """ :param number: :return: """ # O(n) pos = len(number) -1 for item in number: print(number[pos]) if number[pos] == num: return pos pos = pos -1 return pos def big_number(): """ :return...
import os import pytest from app import create_app, db from users.daos.user_dao import add_user, get_user_by_name @pytest.fixture(scope='module') def client(): # arrange filename = '/tmp/fresh_test.db' db_path = 'sqlite:///' + filename app = create_app({'TESTING': True, 'SQLALCHEMY_DATABASE_URI': db_...
# -*- coding: utf-8 -*- from hearthstone.entities import Entity from entity.spell_entity import SpellEntity class LETL_648(SpellEntity): """ 混乱护符4 眼棱造成的伤害增加6点。 """ def __init__(self, entity: Entity): super().__init__(entity) def equip(self, hero): pass
import pandas as pd import math class WeightCalculationForPyfolio: def __init__(self,wtsDF,returnsDF): self.wtsDF=wtsDF self.returnsDF=returnsDF def returnsCalculation(self,strategyName): returnsDFCopied = self.returnsDF.copy() for idx,i in self.wtsDF.iterrows...
#!/usr/bin/env python import numpy as np import pyopencl as cl ctx = cl.create_some_context() queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE) MAX_GRID = 65535 kernels =""" __kernel void update_h(int nx, int ny, int nz, float cl, __global float *ex, __global float *ey, __glob...
#!/usr/bin/python import math def recipe_batches(recipe, ingredients): count = 0 for name in recipe.keys(): if name not in ingredients: return 0 tempCount = int(ingredients[name] / recipe[name]) if count == 0 or tempCount < count: count = tempCount return count if __name__ == '__main...
from app import db class Environment(db.Model): """ Model inherits db.Model from SQL Alchemy """ id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), index=True, unique=True) env_status = db.Column(db.Integer, index=True, default=1) status_timestamp = db.Column(db....
# -*- coding: utf-8 from django.db import models class VIP(models.Model): id = models.IntegerField(primary_key=True) sycee = models.IntegerField("直接充值元宝", unique=True) levy = models.IntegerField("征收次数") hang_addition = models.IntegerField("挂机收益加成") friends = models.IntegerField("好友数量上限") are...
from django.db import models from django.core.validators import MinValueValidator from User import models as user_models from Client import models as client_models from Restaurant import models as restaurant_models from Orders import models as order_models choices = ( ('Client', 'Client'), ('Invigilator', 'In...
# Get the top n stories by word x import pandas as pd pd.options.display.max_colwidth = 5000 stories = 10 word = 'china' df = pd.read_csv('../data/data/data.csv', sep=',', low_memory=False, encoding = 'ISO-8859-1') df = df.drop(labels=['subreddit', 'over_18', 'time_created', 'down_votes'], axis=1) df = df[df['title'...
''' NOTE: the program using the Psutil library that should be installed first via 'pip' or other source that requering your system. Created on 24 Apr 2018 @authors: Gal , Mark , Noy Process_monitor can scan the system (Process that running in the background) and export two csv files: 1. process_list.csv - History ...
__author__ = 'frankhe' import time import sys import tensorflow as tf import numpy as np from mpi4py import MPI import copy import interaction import neural_networks import agents FLAGS = tf.app.flags.FLAGS # Experiment settings tf.app.flags.DEFINE_integer('epochs', 40, 'Number of training epochs') tf.app.flags.DEFIN...
# -*- coding:utf-8 -*- ''' __author__ = 'XD' __mtime__ = 2021/1/22 __project__ = Pon-Sol2 Fix the Problem, Not the Blame. ''' # 本地 from unittest import TestCase import logging # 第三方 import pandas as pd import numpy as np # 自定义 import feature_extraction as fe import logconfig import model class FeatureTest(TestCase)...
import sprite import struct class Map: g_width = 0 g_height = 0 sprite_bank = [] grid = [] def __init__(self, g_width=0, g_height=0, sprite_bank=None, grid=None): self.g_width = g_width self.g_height = g_height self.sprite_bank = sprite_bank self.grid = grid d...
import unittest import json import sys try: filename = sys.argv[1] with open('tmp/%s' % filename, 'r') as f: pass except FileNotFoundError: print('[X] file not exist. tmp/filename') sys.exit(0) except IndexError: print('[X] please enter filename.') sys.exit(0) class ResultTestCase(uni...
import os,re import numpy as np import gslibUtil as gu import arrayUtil as au prefix = 'Q2' nrow,ncol = 197,116 delc,delr = 2650.,2650. offset = 668350.,288415. #--load hard data harddata_file = 'tbl_29.dat' title,harddata_names,harddata = gu.loadGslibFile(harddata_file) hard_xy = np.zeros((len(harddata),2),dtype='f...
from pysensationcore import * import math # === IntensityModulation Block === # A Block which can be used to modulate the intensity (strength) of a Sensation at a supplied frequency intensityModulationBlock = defineBlock("IntensityModulation") defineInputs(intensityModulationBlock, "t", "point...
# Runtime 48 ms, Memory Usage 14 MB def selfDividingNumbers(left: int, right: int): # declare an empty list self_dividing = [] # iterate through the range of numbers starting with left and ending with right # since range() is not inclusive, we need to set the last end of the range as right+1 fo...
# 주말 과제 # Dence 모델로 구성 input_shape=(28*28, ) import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() print(x_train.shape, y_train.shape) # (60000, 28, 28), (60000,) <- 흑백 print(x_test.shape, y_test.shape) # (10...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator from UM.Signal import Signal, SignalEmitter from UM.Application import Application from copy import deepcopy ## A decorator that can be used to override indiv...
import urllib.request from bs4 import BeautifulSoup as b import json import requests from requests.auth import HTTPBasicAuth, HTTPDigestAuth from urllib import parse import csv import datetime import time import re import uuid import sqlite3 from db_location import dbLoc # this is a scraper for mtg deck lists that us...
sm.lockUI() FANZY = 1500010 sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.sendNext("#bBleh! I almost drowned!#k") sm.setSpeakerID(FANZY) sm.sendSay("There must be some kind of enchantment to keep people from swimming across.") sm.flipDialoguePlayerAsSpeaker() sm.sendSay("#bYou could have told me that ...
import requests from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import View from django.views.generic.edit import CreateView,UpdateView from django.contrib.auth.views import LoginView from .forms import IndexForm,AuthUserForm,CustomUserCreationForm, CustomUserChangeFor...
# this is Bi-Directional Bubble Sort def bdBubbleSort(alist): exchanges = True passnum = len(alist)-1 # the high and low bound of the list that will be bubbled low = 0 high = len(alist)-1 direction = 'r' while passnum > 0 and exchanges: exchanges = False # bubble from left to rig...
from BasePlotter import BasePlotter from MeasurementStatistics import MeasurementStatistics from CSVWriter import CSVWriter import os import matplotlib import matplotlib.pyplot as plt import numpy as np class DiagramPlotter(BasePlotter): def __init__(self, outputDir): BasePlotter.__init__(self, outputDir)...
import httplib import json from hashing import ConsistentHashRing cr = ConsistentHashRing() cr.__setitem__("server1","5001") cr.__setitem__("server2","5002") cr.__setitem__("server3","5003") for i in xrange(1,11): port = cr.__getitem__(str(i)) url = "localhost:" + str(port) print url connection = ht...
import pandas as pd import pdb import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import os def plot_RZ_heatmap(R_data_coords_mesh, Z_data_coords_mesh, R_edges_mesh, Z_edges_mesh, data_grid, file_name, fig_height = 9, fig_w...
filename = input('Enter new filename: ') f = open(filename, 'w') strings = [ 'Hey', 'Men', 'Aye\n', 'Hello\n', ] try: for i in strings: f.write(i) except Exception as e: print('Error caught', e) finally: f.close() print('Closed')
import os import logging class ScraperLogger: """ Class for logging. """ log_file = os.path.join(os.path.dirname(__file__), '../logs/scraping.log') formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s') def __init__(self, name): """ Constructor fo...
import torch from torch.distributions import Normal from torch import nn from torch.nn import functional as F class Encoder(nn.Module): """Maps an (x_i, y_i) pair to a representation r_i. Parameters ---------- x_dim : int Dimension of x values. y_dim : int Dimension of y values. ...
''' 写一个函数get_score()来获取用户输入的学生成绩(0-100的整数),如果输入 出现错误,则此函数返回0,如果用户输入的数是0-100之间的数,返回这个数 ''' def get_score(): score =input("输入学生成绩:") i =int (score) if 0 < i <= 100: return i return 0 try: scors=get_score() except ValueError: scors =0 print('学生成绩:',scors)
"""Models for asteroids app.""" from flask_sqlalchemy import SQLAlchemy from datetime import datetime from flask_login import UserMixin db = SQLAlchemy() class User(UserMixin, db.Model): """A user.""" __tablename__ = 'users' user_id = db.Column(db.Integer, autoincrement=True, ...
def send_email(text): import socket import smtplib import os import sys from secrets import sender_address from secrets import sender_password from secrets import sender_server from secrets import sender_port from secrets import recipient_address try: message = "From: " ...
# Databricks notebook source # Function to call connection config class load_connect_config(): def __init__(self, p_config_id): table_metadata_query = "select \ conn.kv_scope, conn.secret_url \ from de_barney.test_process_metadata_events_v4 pm \ inner join de_barney.conn_config conn\ on \ ...
def bubble_sort(items): is_sorted = False while not is_sorted: is_sorted = True for i in range(len(items) - 1): if items[i] > items[i + 1]: is_sorted = False temp = items[i] items[i] = items[i + 1] items[i + 1] = temp ...
#!/usr/bin/python import socket import time import spidev import array from subprocess import call, PIPE TCP_IP = '192.168.0.116' TCP_PORT = 5044 # Reset Attiny call("gpio -g mode 22 out", shell = True) call("gpio -g write 22 0", shell = True) time.sleep(0.1) call("gpio -g write 22 1", shell = True) #call("sudo raspi...
#! /usr/bin/env python import rospy, tf from math import pi from geometry_msgs.msg import Quaternion from fake_sensor import FakeSensor # Convert from radians to Quaternion def make_quaternion(angle): q = tf.transformations.quaternion_from_euler(0, 0, angle) return Quaternion(*q) def publish_value(value): angle =...
//Use xrange() if you ever have break. range() pre-creates the list and that can be memory inefficieint. //The code below is a bit ugly because I used some measures to optimize it. //Solution by Andrew Xing n = input() breaker = False if n == 1 or n == 2: print 2 elif n == 3: print 3 elif n == 5 or n == 4: prin...
# coding utf-8 # @time :2019/6/12 10:39 # @Author :zjunbin # @Email :648060307@qq.com # @File :OrganizationManagement.py import time from common.basepage import BasePage from PageLocator.OrgManagement import OrgManage as om class OrgManagemnet(BasePage): def loginPage(self): self.wait_...
from dataclasses import dataclass from flask import render_template, Blueprint from flask_login import login_required, current_user from app.permissions.permissions import army_name_required base = Blueprint('base', __name__, template_folder='templates') @dataclass class UserResources: amount: int picture: s...
import sys import pickle import random import numpy as np from difflib import SequenceMatcher as Sqm split_ratio=float(sys.argv[1]) f=open("/home/ubuntu/results/saliency/featured.pkl","rb") featured_list=pickle.load(f) f.close() f=open("/home/ubuntu/results/saliency/distanced.pkl","rb") dis_list=pickle.load(f) f.clo...
#!/usr/bin/env python #-*- coding:utf-8 -*- import numpy as np import cv2, sys, time, os from pantilthat import * from pan_tilt.msg import MsgState # from sensor_msgs.msg import Image #이미지 캡쳐 # from cv_bridge import CvBridge, CvBridgeError class PID: def __init__(self, kP=1, kI=0, kD=0): # initialize gai...
# https://towardsdatascience.com/text-summarization-96079bf23e83 import glob import os import nltk import re import heapq from collections import Counter stop_words = set(nltk.corpus.stopwords.words('english')) stop_words.add('figure') max_sentence_length = 30 max_summary_sentences = 3 os.chdir('data') for text_f...
import pandas as pd import matplotlib.pyplot as plt from os import path from os import makedirs dir_path = 'reports' def list_to_csv(l, name='dataframe.csv'): create_dir(dir_path) df = pd.DataFrame(l[1:], columns=l[:1]) df.to_csv(dir_path + '/' + name, index=False) df = None def create_dir(dir_path):...
''' Created on Jan 22, 2018 @author: PATI ''' from domain.jucator import Jucator class ExceptionR(Exception): """ Clasa de exceptii pentru repo """ def __init__(self,*args,**kwargs): Exception.__init__(self,*args,**kwargs) class RepoJ(): ''' repo pentru jucatori ''' def...
#!/usr/bin/env python import os from flask_mongoengine import MongoEngine from flask_script import Manager from flask_script import Server from flask_script import Shell from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError from application import create_app from application import ...
# Generated by Django 3.1.2 on 2020-10-02 17:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0005_auto_20201002_1710'), ] operations = [ migrations.AlterField( model_name='profile', name='DateOfBirth'...
# https://stackoverflow.com/a/4142178 # This file signals to python that is is okay to import from this directory.
import vim from abstract_formatter import AbstractFormatter class BashFormatter(AbstractFormatter): def __init__(self): super(self.__class__, self).__init__() self._beautysh = self._getAbsPath(self._getRootDir(), "build/venv/bin/beautysh") def _getFo...
import sqlite3 conn = sqlite3.connect("sqlit3_LOCAL.db") Mobile_Number="9986146542" RequirementID="1" Client="2" name="3" skills="4" Yearsofexperience="5" CURRENT_LOCATION="6" lOCATION_OF_INTEREST="7" CTC="8" ECTC="9" Notice_Period="10" Email="12" Source="13" Date_of_birth="14" PANCARD_NO="15" dateOfSub="16" Note="17...
from PyQt5.QtWidgets import QApplication, QLabel def hello_qt(a_message): app = QApplication([]) label = QLabel(a_message) label.show() app.exec_() # Press the green button in the gutter to run the script. if __name__ == '__main__': hello_qt('Hello, Qt') # See PyCharm help at https://www.jetbr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import lib.shortestPaths as sp def generateMetaGraph (mazeMap, playerLocation, coins): """ Generate a metaGraph from mazeMap, containing all coins and the player. This function is built on the shortestPaths lib. """ nodes = [playerLocation] + coins ...
#!/usr/bin/python #-*- coding: utf-8 -*- import commands def system_running_time(): s = commands.getoutput('uptime').split() if len(s) == 10: d = 0 else: d = s[2] if len(s[-8].split(':')) < 2: d = 0 h = 0 m = s[-9] else: h = s[-8].split(':')[0] ...
""" created by Bradley Sheneman modified version of SpockBot physics.py changed the walk, sprint, jump functions to a single move function for code clarity more importantly, it allows for single movements that are composites of different motions (e.g. jump while walking northeast) does not directly impact any data. ...
from __future__ import print_function import airflow import pytz import logging from datetime import datetime, timedelta from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.models import Variable start_date = datetime(2017, 10, 24, 0, 0, 0, tzinfo=pytz.utc) default_args = { ...
import random from copy import copy class Player: def __init__(self, player_id): self.player_id = player_id self.market = {} # {item: price} self.inventory = {} # {item: amount} self.merchant_pos = "Home" self.money = 50 self.victory_points = 0 self.buildings...
import zipfile import json import glob import os def save_json(filename, json_str): with open(filename, "w") as f: new_dict = json.loads(json_str) json.dump(new_dict, f) print("加载入文件完成...") def zip_files(files, zip_name): files = glob.glob(files) f = zipfile.ZipFile(zip_name, 'w'...
import os import sys if __name__ == '__main__': pkgname = sys.argv[1] os.system('pip uninstall -y {0}'.format(pkgname)) os.system('conda install {0}'.format(pkgname)) os.system('conda env export > environment.yml')
LINK = "http://selenium1py.pythonanywhere.com/" LOGIN_LINK = "http://selenium1py.pythonanywhere.com/accounts/login/" CODERS_LINK = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/" STARS_LINK = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
# -*- coding: utf-8 -*- """ Created on Mon May 16 10:44:25 2016 Constants used across modules. @author: lvanhulle """ import logging import importlib ARC_NUMPOINTS = 20 CW = -1 #Circle direction clock wise CCW = 1 #circle direction counter clowise X, Y, Z = 0, 1, 2 START = 0 #start of circle END = 1 #end of circle D...
# cfg # Globalized things needed throughout all modules from datetime import datetime import os from os.path import dirname import sys #Variables modified by JSONReader token = '' adminUsers = [] cmdPrefix = '' soundTime = '' noSoundTimer = [] disabledIntros = [] blockedChannels = [] fileSizeAllowed = '' maxSoundFile...
from tasks.set_tasks.unique_in_list import get_unique_in_list def test_get_unique_in_list(new_set): assert get_unique_in_list([1, 2, 1, 3, 2]) == {1, 2, 3}
#ImportModules import ShareYourSystem as SYS """ Nicolas tests rates 5-15 sigmaext 5-5 taums 20-10 thresholds 20-20 resets 10-10 taurps 0-0 delays 1-1 taur 0.5-0.5 taud 5-5 JEE, JEI, JIE, JII=100,100,100,100: stable, eigenvalue w largest real part = -36,0 100,100,100,0: unstable, 128, 184 (f=29Hz) 0,100,100,100: ...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), # path('monitor/<str:address>', views.monitor, name='monitor'), path('monitor/<str:address>/<int:pool_id>', views.monitor_pool, name='monitor_pool'), path('chart_data_json/<str:addr>/<int:pool_id>', v...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from odoo import api, fields, models class ImportItem(models.Model): _name='account.import.item' name = fields.Char(string="Name") import_entry_id = fields.Many2one('account.import.entry', string="Import journal entry") active = fields...
import requests import json from dotenv import load_dotenv import os load_dotenv() nyt_api_key1 = os.getenv("nyt_api_key") rainforest_api1 = os.getenv("rainforest_api") list_names = f"https://api.nytimes.com/svc/books/v3/lists/names.json?api-key={nyt_api_key1}" api_url = f"https://api.nytimes.com/svc/books/v3/lists/c...
import torch import random import cairo import numpy as np import math import os import torchvision import skimage.draw import skimage.io from models import LocationBasedGenerator from PIL import Image from torchvision.datasets import ImageFolder from torch.utils.data import Dataset, DataLoader from utils import return...
from django.contrib import admin from .models import Departamento admin.site.register(Departamento)
''' Manage everything from the install to the grub-install ''' import os import shutil import subprocess class Grub: ''' Manage preparing the environment for grub ''' def __init__(self, opts, target, nbd): self.opts = opts self.target = target self.nbd = nbd def _grub_conf(...
# -*- coding: utf-8 -*- """ Created on Mon Apr 8 08:59:46 2019 @author: lopez """ ''' while loop, find ma height ''' v0 = 5 # meters per sec g = 9.81 n = 2000 X= 1000 # for github use # time steps # time import numpy as np a_t = np.linspace(0,1,n) # we created an array # computations y = v0*a_...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # __author__ = 'Benjamin' import json import time from osc_sdk_python import Gateway TIMEOUT=60 def create_vm(profile, vmtype, storage, omi): gw = Gateway(**{'profile': profile}) with open('/Users/benjaminlaplane/.oapi_credentials') as creds: credential...
#!/usr/bin/env python import logging import time from collections import Counter import numpy as np import pickle import pysam from util import initialize_iterator, prepare_file_name logger = logging.getLogger(__name__) samples = ['GACCGC', 'AAAACT', 'GGCGTC', 'AAAGTT', 'GTTCGA', 'ATATAG', 'TAAAGT', 'A...
# -*- coding: utf-8 -*- # Created on Sun Dec 17 2017 11:28:47 # Author: WuLC # EMail: liangchaowu5@gmail.com # dp, O(1) space class Solution(object): def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ last1, last2 = cost[0], cost[1] for...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import sys # In[3]: if "__main__": data = pd.read_csv(sys.argv[1]) by_rep = pd.Series("No-repair(Conditon 1 and 2)" if ((i==1) or (i==2)) else "Repair(Condition 3 and 4)" for i in data['Participant study:']) data['r...
from function_base import my_abs from function_base import power from function_base import enroll from function_base import add_end from function_base import calc from function_base import calc_change from function_base import person from function_base import move from function_base import lazy_sum from function_base i...
import requests_mock import requests.exceptions import pytest from .. import weather def test_simple_result(): """Check that the weather info can be parsed.""" sample_good_output = '{"coord":{"lon":0.08,"lat":52.24},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"s...
#!/usr/bin/env python3 import math def solve0(problem): elves = int(problem) names = [i for i in range(1, elves+1)] current = 0 while True: nextto = (current + len(names) // 2) % len(names) names.pop(nextto) if len(names) == 1: return names[0] if curren...
import pandas as pd import numpy as np import re import sys import pyper from time import sleep def cleansing(one_day): half = int(one_day.shape[0]/2) one_day = one_day.iloc[:half] one_day = one_day.drop('Unnamed: 0', axis=1) for i in range(one_day.shape[0]): if one_day.loc[i, 'e_win'] == 1....
#!/usr/bin/env python # coding: utf-8 # Author: SCU Wuyuzhang College, Wei Chengan & Wan Ziyi # Data: 2020/5 import os import h5py import json import datetime import random import numpy as np import tensorflow as tf from tensorflow.keras import callbacks from tensorflow.keras import backend as K from tensorflow.keras...
# 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 u...
import boto3 BUCKET_NAME = "parwizforogh12" s3_client = boto3.client('s3') def upload_files(file_name, bucket, object_name=None, args=None): if object_name is None: object_name = file_name s3_client.upload_file(file_name, bucket, object_name, ExtraArgs=args) print("{} has been uploaded to {...
from flask import Flask, request, render_template, json, Response, make_response import logging from config import server_host, server_port from config import LOGGER, DEBUG_LEVEL from classes import PackageSearch app = Flask(__name__) # Ensure that the required JSON data file are pre-loaded in memory at the time of ...