text
stringlengths
8
6.05M
import numpy as np import os iteration=0 Y=0.99 delta=1e-3 stepcost=-5 stepcost_shoot=-5 finalreward=10 action="-1" recharge_prob=0.8 attack_prob=0.5 dodge_prob=0.8 arrow_prob=0.8 def recharge(i, j, k, utility): return (recharge_prob)*(stepcost+Y*utility[i][j][min(utility.shape[2]-1, k+1)])+ (1-recharge_prob)*(stepco...
#-*-coding:utf-8 -*- import csv import random import json txt_file = "/Users/withheart/Desktop/32-did-odin.token" csv_file = "/Users/withheart/Desktop/did_odin_tt.csv" stress_did = '/Users/withheart/Documents/stress_million_du/stress_user.tsv' with open(csv_file, 'w') as csvfile: spam_writer = csv.writer(csvfile, ...
import os import sys import csv if len(sys.argv) != 2: print("Please provide the overall directory name as an argument") sys.exit(0) else: directory = sys.argv[1] fileCount = 0 errorRates = [] problemRates = [] accuracies = [] for filename in os.listdir(directory): currentLastRow = '' if filenam...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-25 00:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('MenuApp', '0002_menuitem_full_uri'), ] operations = [ migrations.AddField( ...
def run(): """ for contador in range(1000): if contador % 2 != 0: continue #!Lo que está después de continue no se va a ejecutar print(contador) """ """ for i in range(400): print(i) if i == 140: break #!Aquí le digo detente y termina todo """ texto ...
fin1 = open("CommitNomber", "r") n = int(fin1.readline()) n += 1 fin1.close() fout1 = open("CommitNomber", "w") fout1.write(str(n)) fout1.close() fin2 = open("Makefile", "r") S = fin2.read() fin2.close() S = S.replace('auto ' + str(n - 1), 'auto ' + str(n)) print(S)
#-- GAUDI jobOptions generated on Tue Nov 11 13:24:45 2014 #-- Contains event types : #-- 15264011 - 33 files - 504749 events - 114.19 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-124834 #-- StepId : 124834 #-- StepName : Reco14a for MC #-- ApplicationName : Br...
# for random distributions, random number generators, statistics import random import numpy as np import scipy.stats as stats # for simulation import simulus def exp_generator(mean, seed): rv = stats.expon(scale=mean) rv.random_state = np.random.RandomState(seed) while True: # 100 random numbers a...
# This script will upload the HP WebInspect port from XML # format to the Internal Ensighten Threadfix server from threadfix_api import threadfix import glob import json # Open JSON File for conf data with open('../threadfix_local.json') as json_data: config = json.load(json_data) # Setup threadfix connection in...
# Linear regression with TF # from '10_introduction_to_artificial_neural_networks # # MNIST data set import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # %matplotlib in ipython mnist = input_data.read_data_sets("/tmp/data/") X_t...
from flask import Blueprint,request,jsonify from .forms import Verify_sendcode,Verify_SendLoginCode from utils.miaodi import sendIndustrySms from utils.memcached import mc import random bp=Blueprint('common',__name__,url_prefix='/common') @bp.route('/sendcode/',methods=['POST']) #发送短信验证码,注册短信api def...
############################################################################### # # opticalflow3.py # # Python OpenCV test program to study optical flow. # Source: http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_video/py_lucas_kanade/py_lucas_kanade.html#goal # and https://docs.opencv....
class Node: def __init__(self, data): self.data = data self.right = None self.down = None class LinkedList: def __init__(self): self.head = None def push(self, head_ref, new_data): new_node = Node(new_data) ...
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 max_vol = 0 while left < right: max_vol = min(height[left], height[right]) * (right - left) if height[left] >= height[right]: right ...
import os import day23_part1, day23_part2 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() assert day23_part1.solve(inp) == 3025 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_inpu...
import cv2 import os import numpy as np #Computeimage is a generic class that allows us easily change the algorithm within the testing environment #you can load the properties you want placing a file .csv #csv format : type,value. Type can either be INT or STR #class variables will be initiated from the csv in their d...
import conexao_banco as sql def todos(): stmt = 'select "id_funcionario","CPF_CNPJ", "email", "telefone","especialidade","nome" from "Usuarios" inner join "Funcionarios" on "Usuarios"."id_usuario" = "Funcionarios"."id_usuario" ' result = sql.query(stmt) return(result) def inclusao(cpf_cnpj,senha,login,nom...
import matplotlib.pyplot as plt import pandas as pd from tf_utils.caliHousingData import CALIHOUSING if __name__ == "__main__": cali_data = CALIHOUSING() print(cali_data.x_train.shape, cali_data.y_train.shape) print(cali_data.x_test.shape, cali_data.y_test.shape) df = pd.DataFrame(data=cali_data.x, ...
from datetime import date, datetime, timedelta import random import string from django.core.mail import send_mail from django.core.cache import cache from django.db import DatabaseError from explorer import app_settings from explorer.exporters import get_exporter_class from explorer.models import Query, QueryLog if ...
import redis from django.http import HttpResponse from ..Utils.utils import Util from datetime import datetime from ..Model.models import Stocks class Redis: host = '127.0.0.1' port = 6379 r = redis.Redis(host=host, port=port) util = Util() #add interested symbol to watch-list d...
from model.contact import Contact import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["contact count", "output file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 3 f = "data/contacts.json" for o...
# This is a script that helps you create h5 files to store the sift features of images read from # json files based on Rhoana's rh_aligner[https://github.com/Rhoana/rh_aligner]. # We modified it to support single-beam file structure and updated syntax to python3. # You have to run this script in terminal(or the termin...
def ssort(l): size = len(l) for i in range(0,size-1): pos = i smallest = l[i] for j in range(i+1,size): if l[j]<smallest: smallest = l[j] pos = j r1 = l[i] r2 = smallest l[pos] = r1 l[i] = r2 return l def bsort(l): size = len(l) ...
#Write your code here # Calculator class with returns n raised to the power of p. # If either value is negative, throw an exception to be caught by the provided # code class Calculator: def power(self, n, p): if n < 0 or p < 0: raise Exception("n and p should be non-negative") else: ...
from tkinter import * import numpy as np import matplotlib.pyplot as plt import math from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg q1_st = 0.0 q2_st = 0.0 q3_st = 0.0 q1_end = 0.0 q2_end = 0.0 q3_end = 0.0 l1 = 0.0 l2 = 0.0 l3 = 0.0 x = []...
#-*- encoding=utf8 -*- #!/usr/bin/env python import sys,string,re,operator # ''' 读取文件,并以字符串形式返回 ''' def readfile(path_to_file): with open(path_to_file) as f: data = f.read() return data ''' 将字符串数据清洗,用空白字符代替所有非字母字符 ''' def filter_chars_normalize(str_data): pattern = re.compile('[\W]+') return...
from redis import StrictRedis from multiprocessing.dummy import Pool from config import BaseConfig from ip_check import is_valid_proxy class RedisHelper(): def __init__(self): self.ip_key = 'proxy_ip' self.movie_key = 'movie_id' self.con = StrictRedis.from_url(BaseConfig.redis_cfg, decod...
a = int(input("What is the value of A: ")) b = int(input("What is the value of B: ")) c = int(input("What is the value of C: ")) x = int(input("What is the value of X: ")) quad = ((a*(x*x))+(b*x)+(c)) print("The value of the quadratic is", quad)
# # 1.Criando um programa que imprima o nome do seu time # #print(input('Qual é o seu time:')) # # 2. Faça um progrma que peça um número e imprima esse número # # N1 = input('Digite um número:') # # print(N1) # # 3. Faça um programa que receba 'F' ou 'M' e mostre Feminino ou Masculino. # # sexo = str(input('Qual...
import cv2 import os import shutil import numpy as np pic_train_path = '/home/liuwr/liuwenran/competition/officialData/dataset/formalCompetition4/pic_resize_train' pic_validate_path = '/home/liuwr/liuwenran/competition/officialData/dataset/formalCompetition4/pic_resize_val' vec_train_path = '/home/liuwr/liuwenran/com...
# XML 처리 # Q1 print('\nXML처리\nQ1') from xml.etree.ElementTree import ElementTree, Element, SubElement, dump, parse blog = Element('blog') blog.attrib['date'] = '20151231' SubElement(blog, 'subject').text = 'Why python?' SubElement(blog, 'author').text = 'Eric' SubElement(blog, 'content').text = 'You need ...
from flask import Flask from flask_pymongo import PyMongo from bson.objectid import ObjectId from datetime import datetime from flask_bcrypt import Bcrypt from flask_jwt_extended import JWTManager import app_setting app = Flask(__name__) app.config['MONGO_DBNAME'] = app_setting.dbname app.config['MONGO_URI'] = app_s...
""" Virtual Machine Class """ ### INCLUDES ### import os import sys import commands import glob import filecmp from py_knife import file_system from py_knife.decorators import multiple_attempts from default_settings import LOG_TS_FORMAT, MUTLIPLE_TAPE_SYSTEM ### FUNCTIONS ### def execute_backup(settings): """...
class Luhn(object): def __init__(self, number): super(Luhn, self).__init__() self.number = number def is_valid(self): return self.checksum() == 0 def addends(self): return_value = [] number = str(self.number) odder = len(number) % 2 for i in xran...
# Generated by Django 3.0.7 on 2020-10-13 15:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cl_table', '0052_auto_20201013_1505'), ] operations = [ migrations.RemoveField( model_name='stock', name='Itm_Statusid', ...
# pip3 install pywin32 # pip3 install pyautogui # pip install keyboard import win32gui,win32api, win32con import pyautogui as pag import keyboard # hwnd = win32gui.FindWindow(None,'live-Bigdata-jumpbox') hwnd = win32gui.FindWindow(None,'安全整改') def get_screen_resolution(): x = win32api.GetSystemMetrics(win32con.S...
import json import argparse parser = argparse.ArgumentParser() parser.add_argument("-f","--fileLocation", help="path to the monLogger file") args = parser.parse_args() f = open(args.fileLocation,"r") f.seek(0) header = f.readline() configDict = {} colToShow = [] for colname in header.split(): colToShow.append(co...
def ctf(celsius): F=(celsius*9/5)+32 return F temperatures = [10, -20, 100] for i in temperatures : print(ctf(i))
import attr import pytest from simulation.validation import context, ValidationError def test_validate_initial_state(config, state): attr.validate(state) def test_validation_context(config): with pytest.raises(ValidationError) as excinfo, context('test context'): raise ValidationError('') erro...
from user import User from privileges import Privileges class Administrator(User): def __init__(self, first_name, last_name, username, date_of_birth): super(Administrator, self).__init__(first_name, last_name, username, date_of_birth) self.privileges = Privileges()
import logging from typing import Optional import hydra import mlflow import numpy as np from omegaconf import DictConfig, OmegaConf from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score from sklearn.model_selection import GridSearchCV fr...
import math '''1 - Faça um Programa que peça dois números e imprima o maior deles.''' #n1 = int(input('Numero 1: ')) #n2 = int(input('Numero 2: ')) #if n1>n2: # print('Numero maior', n1) #else: # print('Numero maior', n2) '''2 - Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou ...
def authent(uname,pword): if uname == "Emeral" and pword == "Dagon": return True else: return False
from torch.utils.data import Dataset import math import numpy as np import random import matplotlib.pyplot as plt from parameters_habitat import ParametersMapNet_Habitat, ParametersIL_Habitat from PIL import Image import data_helper_habitat as dhh import torch import gzip import json import habitat from habitat.confi...
class RpcRequest: def __init__(self, params, id, method=''): self._jsonrpc = '2.0' self._params = params self._id = id self._method = method @property def jsonrpc(self): return self._jsonrpc @property def params(self): return self._params @prop...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from filmmap.models import Film, FilmLocation, FilmActor class FilmAdmin(admin.ModelAdmin): list_display = ('title','release_year','production_company','director','distributor','writer') admin.site.register(Film, Fi...
import random import numpy as np import matplotlib.pyplot as plt # Environment size width = 5 height = 16 # Actions num_actions = 4 actions_list = {"UP": 0, "RIGHT": 1, "DOWN": 2, "LEFT": 3 } actions_vectors = {"UP": (-1, 0), "RIGHT...
from django.contrib import admin from shop.models import Product from eav.forms import BaseDynamicEntityForm from eav.admin import BaseEntityAdmin class ProductAdminForm(BaseDynamicEntityForm): model = Product class ProductAdmin(BaseEntityAdmin): form = ProductAdminForm admin.site.register(Product,ProductAdm...
""" Funciones auxiliares para resolver los problemas. Algunas variables en este modulo pueden carecer de expresividad. He tratado de ser expresivo cuando pude, sin embargo creo que en algunos algoritmos es mejor utilizar las mismas letras que utiliza la wikipedia (o la fuente original, en caso de que la aclare) para d...
from PIL import Image, ImageDraw, ImageFont import torch import torch.nn as nn from net.alexNET import AlexNet from utils import transform from config import * import time import matplotlib.pyplot as plt from torchsummary import summary if __name__ == '__main__': input_image = Image.open(IMG_PATH) input_tenso...
import json import pkg_resources from rest_framework.settings import api_settings from rest_framework import exceptions from rest_framework import request from rest_framework import pagination from rest_framework import test from django_rest_json_api import serializers from django_rest_json_api import renderers from...
"""Advent of Code 2019 Day 11 - Space Police.""" from collections import defaultdict class EHPR: """Class for the Emergency Hull Painting Robot.""" def __init__(self, code, inputs): """Initialises the EHPR with code (dict) and inputs (list).""" self.code = code self.inputs = inputs ...
import argparse from collections import deque from functools import reduce from enum import Enum # Opcode structure: # *** Warning: Apparently, C has this reversed... *** # [--------] ([-][--][-][---][#] arg) # 1 2 3 4 5 # 1) type: float/intergal # 2) type: size (2**0, 2**1, 2**2, 2**3) # 3) type:...
# https://www.hackerrank.com/challenges/the-hurdle-race/problem # Complete the hurdleRace function below. def hurdleRace(k, height): max_height = max(height) jump = k-max_height if jump < 0: return abs(jump) else: return 0
from flask_restful import Resource from flask_restful import abort from flask_restful import marshal_with from flask_restful import fields from flask_restful import reqparse from app.db import dbs from auth import validate_login_jwt from flask import request from app.uploadsets import entityphotos from flask_uploads im...
from turtle import Turtle, Screen screen = Screen() screen.bgcolor("black") screen.setup(width=600, height=600) screen.title("My snake game") start_position = [(0,0), (-20,0), (-40,0)] for position in start_position: snakes = Turtle(shape="square") snakes.color("white") snakes.goto(position) screen.exit...
from datetime import datetime from django.core.cache import cache from django.test import TestCase from data.data_controller import get_neo_estimated_diameter class TestDataController(TestCase): @classmethod def setUpTestData(cls): cls.data = { "2019-01-01": [ { ...
import graphene from graphql import GraphQLError from models import db, User as UserModel, Field as FieldModel, Role as RoleModel from utils.authentication import is_fieldadmin from utils.db import get_or_create ROLES = ('admin', 'fieldadmin', 'creator', 'reader') def validate_role_assignment(role, field): if n...
import os import boto3 import pandas as pd bucket_name = os.getenv("S3_BUCKET_NAME") s3 = boto3.resource("s3") s3_alec = s3.Bucket(bucket_name) simulation_ids_list = [] scenario_ids_list = [] # Fetch simulation data for i in ["applications", "outcomes", "portfolios", "scenarios"]: file_paths_tmp = [f.key for f...
import sys def ASMQ(dna_strings): total_len = sum([len(x) for x in dna_strings]) dna_strings.sort(key=len) curr_len = 0 n50 = total_len n75 = total_len for i in range(len(dna_strings) - 1, -1, -1): curr_len += len(dna_strings[i]) if n50 == total_len and curr_len > total_len * ...
from django.shortcuts import render, redirect # from django.http import HttpResponse from peoplelist.models import Patient, List def home_page(request): return render(request, "peoplelist/home.html") def view_list(request, list_id): list_ = List.objects.get(id=list_id) return render(request, "peoplelist/...
# -*- coding: utf-8 -*- import time from Utils import * from config.settings import symbol_list from common.enums import HUOBI_PERIOD_LIST from common.enums import Symbol, Platform from config.settings import sdb, mdb def trigger(): for sy in symbol_list: try: CandleApp().run(sy, HUOBI_PERIOD...
''' Created on 31 Mar 2015 @author: WMOORHOU ''' from pypomvisualiser.ProjectScraper import ProjectScraper from pypomvisualiser.pom.PomParser import PomParser from pypomvisualiser.pom.TreeCreation import TreeCreation from pypomvisualiser.display.Visualiser import Visualiser class ProjectActions(object): ...
import json import os from unipath import Path from .base import * DEV_SECRETS_PATH = SETTINGS_PATH.child("staging_secrets.json") with open(os.path.join(DEV_SECRETS_PATH)) as f: secrets = json.loads(f.read()) INSTALLED_APPS = INSTALLED_APPS + ('mod_wsgi.server', ) PROPAGATE_EXCEPTIONS = True DEBUG = True # Celery S...
#!/bin/env python from distutils.core import setup setup(name='hts_scripts', version='0.7.0', description='Scripts for processing NGS data', author='Rob Carter', author_email='robert.carter@stjude.org', #packages=['hlatyp'], #package_data={'hlatyper': ['data/*']}, scripts=['s...
from ED6ScenarioHelper import * def main(): # 蔡斯 CreateScenaFile( FileName = 'R3403 ._SN', MapName = 'Zeiss', Location = 'R3403.x', MapIndex = 1, MapDefaultBGM = "ed60030", Flags = 0, En...
# http://pise.info/algo/enonces5.htm # Exercice 5.4 """ Réécrire l'algorithme précédent, en utilisant cette fois l'instruction Pour """ """ Corection en psedo-code Variables N, i en Entier Debut Ecrire "Entrez un nombre : " Lire N Ecrire "Les 10 nombres suivants sont : " Pour i ← 1 à 10 Ecrire N + i i Suivant Fin...
# %% from scipy import stats import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import os # %% MPL SETTINGS mpl.rcdefaults() # sns.set(font_scale=0.8) sns.set_style("white") # sns.set_palette("deep") # sns.set_palette(['w', 'gray']) mpl.rcParams['text....
from functools import reduce import math c1 = [(1, 2), (3, 4), (5, 6)] c2 = [(6, 2), (2, 4), (8, 6)] a = [c1, c2] cols = max(map(lambda x: x[0], reduce(lambda x, y: x + y, a))) + 1 a1 = [] for t in a: dest = [0] * cols a1.append(dest) for e in t: dest[e[0]] = e[1] for l in a1: print(l) a = ...
# Generated by Django 3.2.5 on 2021-08-06 16:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0018_alter_perfil_options'), ] operations = [ migrations.AlterField( model_name='perfil', name='id_perfil', ...
from flask import request, Response, jsonify, g from . import api, auth from .exception import ServerException from ..models.strategy import Strategy from ..schemas.strategy import strategy_schema, strategies_schema from ..common.device_model import DeviceModel from ..common.geo_location import GeoLocation @api.rout...
while(True): x=[] a=input() b=a.split(' ') if(len(b)>10): print("超出范围,请重试!") continue else: for i in range(len(b)): x.append(int(b[i].strip())) x=list(set(x)) x.sort() for j in range(len(x)): print(x[j]) break
# https://pypi.python.org/pypi/changepoint/0.1.1 import numpy as np from changepoint.mean_shift_model import MeanShiftModel data = np.array([12, 14, 20, 31, 16, 17, 21, 174, 180, 131, 140, 113, 100, 106, 91]) model = MeanShiftModel() stats, pvals, nums = model.detect_mean_shift(data) #ind = np.argmax(stats) # ind is...
from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Auth,Complaint,Crime from django.contrib.auth import authenticate,login,logout import random # Create your views here. def homepage(request): return render(request,"crimemanagement/homepage.html") def police(requ...
#import sys #input = sys.stdin.readline def main(): n, d = map( int, input().split()) print( (n+d*2)//(d*2+1)) if __name__ == '__main__': main()
{ "targets": [ { "target_name": "entangled", "sources": [ "src/interface.cpp", "entangled/common/model/bundle.c", "entangled/common/model/transaction.c", "entangled/common/helpers/pow.c", "entangled/common/helpers/sign.c", "entangled/common/helpers...
d = {} doc = [] with open("neko.txt.mecab") as f: lines = f.readlines() sentense = [] for line in lines: line = line[:-1] if line == "EOS": if len(sentense) > 0: doc.append(sentense) sentense = [] continue surface, rest = line.sp...
from datetime import datetime from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from starlette.responses import Response from starlette.responses import JSONResponse from starlette.requests import Request from inspect import currentframe as frame from Scripts.fastapp.database.conn import db ...
import sublime from .view_stream import ViewStream from .view_utils import set_view_options, validate_view_options from ._util.guard import define_guard from ._compat.typing import Any __all__ = ['Panel', 'OutputPanel'] class Panel(): """An abstraction of a panel, such as the console or an output panel. :...
from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from django.utils import timezone from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Project, ProjectCategory, Skill # Create your views here. # TODO: Find o...
import logging import json import os import six import hmac import hashlib import binascii import pkg_resources from datetime import datetime from collections import defaultdict from django.db import models from django.contrib.postgres import fields from django.conf import settings from django.core.serializers.json i...
f = open('/home/hrezaei/codes/python/quran/Quran-en.maududi.txt') c = f.read() l = c.split('\n') lp = [k.split('|') for k in l] v = [b[2] for b in lp if len(b)>2] dic = {} for aye in lp: sura = aye[0] if len(aye)<3: print(aye) continue sura = int(sura) if sura in dic: dic[sura...
# -*- coding:utf-8 -*- from gensim import corpora,models,similarities from pprint import pprint if __name__ == "__main__": f = open("Data/LDA.txt") stop_list = set('for a of the and to in'.split()) print("After") texts = [[word for word in line.strip().lower().split() if word not in stop_list]for line...
import os, re import fsutils from char_utils import is_kanji from pprint import pprint INPUT_FILEPATH = '../data/input/official/joyokanjihyo.txt' OUTPUT_FILE = '../data/output/kanji_joyo.json' def _is_title(line): if (not line.startswith('\t') and not line.startswith('03初_改定常用漢字表')): line = line....
from django.shortcuts import render from django.http import HttpResponse from django.template import loader def home(request): # return render(request, 'ecom/home.html') return HttpResponse('<h1>This is the home page of this awesome website</h1> <a href="/">Back</a>') def index(request): # return HttpRe...
n=int(input("Enter current age")) n=2117-n print("User will be of 100 year in ",n)
def login(): import smtplib smtp = smtplib.SMTP() smtp.connect('10.11.158.13', '25') smtp.starttls() smtp.login('lixf311@chinaunicom.cn', password) return smtp def jd_message(): import smtplib from email.mime.text import MIMEText # 测试发送简单message邮件,可带中文 smtp = smtplib.SMTP() ...
import numpy as np import perturbations as PB import math G = 4.32275e-3 # (km/s)^2 pc/Msun G_pc = G * 1.05026504e-27 # (pc/s)^2 pc/Msun kmtopc = 1.0 / (3.086 * 10 ** 13) MNS = 1.4 # Msun RNS = 10 * kmtopc # pc from scipy.interpolate import interp1d from scipy.integrate import quad, cumtrapz from scipy.special imp...
# Python ≥3.5 is required import os import numpy as np import pandas as pd import sklearn import warnings import urllib.request import itertools import cv2 import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as mpimg import datetime from IPython.core.interactiveshell import InteractiveShell...
from rest_framework import routers from social_network.post import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet, basename='user') router.register(r'posts', views.PostViewSet, basename='post')
from shapely.geometry import LineString, Point import geopandas as gpd import pandas as pd import numpy as np import pathlib import os import json import time from geopy import distance # INPUT # List of NP.ARRAYs with data class LinestringSelector(object): def __init__(self, Istops, Fstops, type_of_dataset="BU...
#========================================================================= # pisa_xori_test.py #========================================================================= import pytest import random import pisa_encoding from pymtl import Bits, sext, zext from PisaSim import PisaSim from pisa_inst_test_utils import ...
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class Motor(): def __init__(self,Ena,In1,In2): self.Ena= Ena self.In1= In1 self.In2= In2 GPIO.setup(self.Ena,GPIO.OUT) GPIO.setup(self.In1,GPIO.OUT) ...
import numpy as np x = 4 y = 5 print(x+y) print(x-y)
#!/usr/bin/python import os.path import struct import subprocess import re import urlparse from objc import YES, NO, nil, signature from AppKit import * from Foundation import * from PyObjCTools import AppHelper import ConfigParser class RuleEvaluator: TTL_DEFAULT = 10 BROWSER_MAP = { 'safari': '/A...
from app.api.db_model import Admin from app.api.config.config import Config TIME = Config.time() print(Admin) class AdminProcess: def login(self, payload, admin_key): responses = {} new_admin = Admin.query.filter_by(name=payload['name']).first() if new_admin.admin_key != admin_key: return "can not ...
''' Demonstrates types in Python by example lists, dictionaries, and tuples ''' # demonstrates a Tuple # can hold multiple types # - used for multiple return values sometimes # - can also contain other tuples # immutable # accessible by index months = ('January', 'February', 'March', 'April', 'etc', 5, 10, True) # D...
# coding: utf-8 class Solution: # @param s, a string # @return an integer def titleToNumber(self, s): n = [ord(x)-64 for x in list(s)][::-1] l = len(n) num = 0 for x in range(l): num += n[x]*(26**x) return num a = Solution() print a.titleToNumber('AB')
"""Loads the contents from the json file""" import json def json_load_ej(filename): with open(filename) as file: numbers = json.load(file) print numbers
#Edo frikin KUN #1/22/2015 # import agent, room, pygame, random as ra def gatherRooms(screen, width, height, sprites): return [bossland0(screen, width, height, sprites), bossland1(screen, width, height, sprites), bossland2(screen, width, height, sprites), bossland3(screen, width, height, sprites), bossland4(scree...