text
stringlengths
38
1.54M
import csv import statistics #This function iterates over quant_bootstrap.tsv and creates a map for confidence interval for each transcript def evaluateCI(inputDir): trCIMap = dict() with open('input/' + inputDir + '/quant_bootstraps.tsv') as tsv: for column in zip(*[line for line in csv.reader(...
r1=float(input("resistor1: ")) r2=float(input("resistor2: ")) r3=float(input("resistor3: ")) req=(r1*r2*r3)/((r1*r2)+(r2*r3)+(r1*r3)) print(req)
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2020-01-15 07:08 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('award', '0003_auto_20200115_1005'), ] operations = [ migrations.RemoveField( ...
#!/usr/bin/env python # coding: utf8 """ A simple example for training a part-of-speech tagger with a custom tag map. To allow us to update the tag map with our custom one, this example starts off with a blank Language class and modifies its defaults. For more details, see the documentation: * Training: https://spacy.i...
""" RL-Scope: Cross-Stack Profiling for Deep Reinforcement Learning Workloads """ # NOTE: setup.py is based on the one from tensorflow. from os.path import join as _j, abspath as _a, exists as _e, dirname as _d, basename as _b import fnmatch import argparse from glob import glob import shlex import os import re impo...
from setuptools import setup,find_packages setup( name = 'Veda', version = '0.1', packages = find_packages(), author = 'shihua', description = 'Veda Module', install_requires = ['ansible','clickhouse-driver'], entry_points = { 'console_scripts': [ ...
from django.shortcuts import render from creative.models import Sheet1,Worksheet,EquipmentInfo2,EquipmentOrg # Create your views here.
import os import warnings from subprocess import call import requests from tqdm import tqdm from .create import create_embedding_database DEFAULT_GLOVE_DOWNLOAD_PATH = os.path.join('/', 'tmp', 'glove', 'glove.zip') def download(target_path=None, url=None): """Download GloVe Common Crawl 840B tokens. (840B...
from django.contrib import admin from . models import * # Register your models here. admin.site.register(Customer) admin.site.register(Supplier) admin.site.register(Country) admin.site.register(Item) admin.site.register(Category) admin.site.register(Promotion) admin.site.register(Report) admin.site.register(Document) a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/10/15 12:06 上午 # @Author : lambert # @Site : # @File : Permutations.py # @Software: PyCharm class Solution: def permute(self, nums: list): # def gen_permute(nums:list): if len(nums) == 1: return [nums] resul...
# coding: utf-8 # In[1]: import pandas as pd import sys sys.path.append('../feature engineer/') from feature_combine import feature_combine # In[5]: def nan_process(): print('NaN process ...'.center(50, '*')) train, test, y = feature_combine() print(train.shape, test.shape) train = train.fillna(-...
from VotingMachine import VotingMachine as VoMa from Candidate import Candidate as Can import numpy import pickle def main(): # ------------------------------------------------- # ------ Candidate and Preference Creation -------- # ------------------------------------------------- manual_input = Fals...
import game_framework import title_state from pico2d import * name = "StartState" image = None logo_time = 0.0 def enter(): global image open_canvas() image = load_image('resource/kpu_credit.png') f = open('data/money_data.txt', 'w') first_money_data = {'money': 300 } json.dump(first_money_d...
from datetime import datetime user_input = input("Enter your goal with a deadline separated by colon\n") input_list =user_input.split(":") goal = input_list[0] deadline = input_list[1] deadline_date = datetime.strptime(deadline, "%d.%m.%Y") today_date = datetime.today() time_till = deadline_date - today_date # Calc...
from django.db import models # Create your models here. class StudentsInfoManager(models.Manager): def all(self): return super().filter(is_delete=False) def create_student(self, id, name, age): student = self.model() student.sid = id student.sname = name student.sage =...
import requests import requests.exceptions from bs4 import BeautifulSoup import re from money_parser import price_str headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3829.0 Safari/537.36 Edg/77.0.197.1'} def get_names_and_prices_of_products_...
"""urlconf for the base application""" from django.conf.urls import url, patterns urlpatterns = patterns('radiator.views', url(r'^$', 'index', name='index'), url(r'^alarm/(?P<id>[^/]+)/$', 'alarm', name='alarm'), # url(r'^info$', 'info', name='info'), url(r'^light/(?P<val>[^/]+)/$', 'light_action', na...
#!/usr/bin/env python3 # Imports from pwn import * import base64 from Crypto.Util.number import long_to_bytes # Connection host = "chal.b01lers.com" port = 25003 s = remote(host, port) context.log_level = 'debug' # Get losing ticket >n< s.recvuntil('raffle ticket:\n') ticket = base64.b64decode(s.recvuntil('\n', ...
import torch import time import numpy as np import atexit from collections import defaultdict cuda_timers = defaultdict(list) timers = defaultdict(list) class CudaTimer: def __init__(self, timer_name=''): self.timer_name = timer_name self.start = torch.cuda.Event(enable_timing=True) self...
import consul import sys c = consul.Consul() def register_server(server): c.agent.service.register( 'server-'+server['port'], service_id='server-'+server['port'], tags=["primary", "v1"], port=int(server['port']) ) if __name__ == "__main__": num_server = 1 if len(sys.ar...
import datetime from fabric import Connection from invoke import Collection from fabric import Config from fabric import task from patchwork import files from fabfile.core import * """ Resque This also installs basic ruby stuff, including rbenv so that we can isolate the ruby and gem installs to a known version and n...
# You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. # Merge all the linked-lists into one sorted linked-list and return it. # Example 1: # Input: lists = [[1,4,5],[1,3,4],[2,6]] # Output: [1,1,2,3,4,4,5,6] # Explanation: The linked-lists are: # [ # 1->4->5, # 1->3->4, # ...
from PIL import Image, ImageDraw import random import numpy as np INF = 1e9 mode = 'RGB' im = Image.open('dataset/Lenna.png') nimg = Image.new(mode, im.size) draw = ImageDraw.Draw(nimg) pix = im.getdata() k = 256 claster = [0] * len(pix) centers = [[random.randint(0, 255), random.randint(0, 255), random.randint(0, 25...
# Generated by Django 3.1.7 on 2021-03-07 12:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0005_auto_20210305_1728'), ] operations = [ migrations.AddField( model_name='group', name='is_active', ...
#!/usr/bin/env python ''' simple plotting tool Author: T.M.Perry UW ''' import ROOT from ROOT import TH1F,TFile,TCanvas,TLegend,TLine,TLatex from ROOT import gStyle import cmsPrelim #import cmsPrelim as cpr gStyle.SetOptStat('') tex = ROOT.TLatex() tex.SetTextAlign(13) tex.SetNDC(True) # for "legend" xpos = 0.58 ypos ...
import logging from django.core.management.base import NoArgsCommand, BaseCommand from django.core.exceptions import ObjectDoesNotExist from settings import ARCH_IMP_ROOT, IMP_REFS, DELIM_CSV import csv import os from aluminio.models import Referencia,Acabado,Aleacion,Temple,SapAluminio COL_REFS = { 'referenc...
import json import boto3 user_table = 'user-profile' dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(user_table) cognito = boto3.client('cognito-idp') def lambda_handler(event, context): access_token = event['headers']['access_token'] try: resp = cognito.get_user( AccessToken=ac...
celery_config = { "broker_url": "redis://localhost:6379/3", "result_backend": "redis://localhost:6379/3", }
from flask import Flask, render_template, request from faker import Faker import random import requests from bs4 import BeautifulSoup fake = Faker('ko_KR') app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/naver/') def naver(): return render_template('naver....
def Madlib(): a = input('Adjective: ') b = input('Noun: ') c = input('Past tense verb: ') d = input('Adverb: ') e = input('Adjective: ') f = input('Noun: ') print(f'Today I went to the zoo. I saw a(n) {a} {b} jumping up and down in its tree. He {c} {d} through the large tunnel that le...
import smbus import numpy # For gyro class L3GD20: WHO_AM_I = 0X0F CTRL_REG1 = 0X20 CTRL_REG2 = 0X21 CTRL_REG3 = 0X22 CTRL_REG4 = 0X23 CTRL_REG5 = 0X24 REFERENCE = 0X25 OUT_TEMP = 0X26 STATUS_REG = 0X27 OUT_X_L = 0X28 OUT_X_H = 0X29 OUT_Y_L = 0X2A OUT_Y_H = 0X2B ...
# gen.py - use whenever sequencing is needd # top-level syntax, function -> underscore method # x() __call__ def add1(x, y): return x + y class Adder: def __init__(self): self.z = 0 def __call__(self, x, y): self.z += 1 return x + y + self.z add2 = Adder() ...
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' def circle(mat): mat1 = mat[0] mat2 = mat[1] mat3 = mat[2] a = [] b = [] if len(mat1)==len(mat2)...
import unittest import BinaryTree class MyTest(unittest.TestCase): def testIsEmpty(self): t = BinaryTree.Tree() self.assertEqual(t.IsEmpty(), True) def testFind(self): t = BinaryTree.Tree() t.add(7) node = BinaryTree.Node(7) self.assertEqual(t.find(7).Value(), node.Value()) if __name__ == '__main__': ...
""" Read through a text file on disk. Use a dict to track how many words of each length are in the file — that is, how many 3-letter words, 4-letter words, 5-letter words, and so forth. Display your results """ import sys, operator # Uncomment the line below to read the script file as the input text file and comment...
"""Common settings and globals.""" import os import environ from os.path import basename ROOT_DIR = environ.Path(__file__) - 3 APPS_DIR = ROOT_DIR.path("clowning_around") env = environ.Env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Site name: SITE_NAME = basename(ROOT_DIR) # SECURI...
from PyQt4.QtGui import QMainWindow, QAction, QIcon, qApp, QFileDialog, QMessageBox, QPrintDialog, QDialog, QPrinter, \ QPainter import pickle from ReactionFile import ReactionFile from gui.ReactionProfile import ReactionProfile from gui.ReactionWidget import ReactionWidget class MainWindow(QMainWindow): def ...
"""Read nifti (nii.gz) files.""" import os import numpy as np from .dependencies import is_nibabel_installed from .path import path_to_visbrain_data from ..utils.transform import array_to_stt from vispy.visuals.transforms import (MatrixTransform, ChainTransform, STTransform) d...
import downloader from utils import Soup, urljoin, Downloader, LazyUrl, get_imgs_already, clean_title, get_ext, get_print, errors, check_alive from constants import try_n import ree as re, os from timee import sleep import page_selector from translator import tr_ import json class Page: def __init__(self, url, t...
from typing import List, Union from rply.token import BaseBox class Node(BaseBox): def __init__(self, name: str, attributes={}): self.name = name self.attributes = attributes def __eq__(self, right): return self.name == right.name def __ne__(self, right): return self.na...
import sys dictionary_file = sys.argv[1] rules_file = sys.argv[2] test_file = sys.argv[3] global count count = 0 global found found = False #----------------------------------------Dictionary-------------------------------------------------------- def create_dict(): list_k = [] list_v = [] list1 = open(dictionar...
# -*- coding: utf-8 -*- """ Created on Fri Nov 4 07:20:37 2022 @author: A.Kuzmin """ import numpy as np import matplotlib.pyplot as plt from scipy import interpolate from scipy.interpolate import make_lsq_spline from scipy.interpolate import InterpolatedUnivariateSpline #, BSpline #from scipy.in...
from django.utils import simplejson from dajaxice.decorators import dajaxice_register from dajax.core import Dajax @dajaxice_register def init_form(request): dajax = Dajax() dajax.assin('.form','innerHTML','Hello') return dajax.json()
# coding=utf-8 """ display.py Read file like italics.txt and display a neighborhood of lines from mwadj.txt for each instance. """ import sys, re,codecs import collections # requires Python 2.7+ class Italics(object): def __init__(self,line): line = line.rstrip('\r\n') self.line=line parts = line.split('@...
"""Code for running ingestion stage""" import json import pathlib import subprocess import tempfile from subprocess import CalledProcessError from typing import Collection, Optional import orjson import pydantic from sentry_sdk import set_tag from vaccine_feed_ingest_schema import location from vaccine_feed_ingest.u...
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: wangye(Wayne) @license: Apache Licence @file: Replace All Digits with Characters.py @time: 2021/05/02 @contact: wang121ye@hotmail.com @site: @software: PyCharm # code is far away from bugs. """ class Solution: def replaceDigits(self, s: str) -> s...
from django.db import models class URL_Shortener(models.Model): url_name = models.CharField(max_length=800) shortened_url = models.CharField(max_length=800) def __str__(self): return self.url_name
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import pytest import numpy as np import prestools.bioinf as pb # pb.hamming_distance def test_hamming_distance_zero(): expect = 0 result = pb.hamming_distance("CAGATA", "CAGATA") assert result == expect def test_hamming_distance_...
import cffi class Utils: def __init__(self): pass @staticmethod def print_binary(msg): mm = '\n ' for x in range(0, 16): mm += format(x, 'x').zfill(2) + ' ' for x in range(0, len(msg)): if x % 16 == 0: mm += '\n' + ...
import xml.etree.ElementTree as ET import re from regex import regex class Reader: g_time = 0 def __init__(self, chunk_size): self.chunk_size = chunk_size def read_in_chunks(self, file_object): while True: data = file_object.read(self.chunk_size) if not data: ...
""" python vaccine_availability.py """ # standard imports import requests import datetime import json # import pandas as pd import smtplib def logger(line): with open('log.txt', 'a+') as f: f.write(line+"\n") """ To get the state code for state_code in range(1,40): # print("State code: ", state_cod...
from runners.python import Submission class DavidSubmission(Submission): def run(self, s): # :param s: input in string format # :return: solution flag # Your code goes here n = 256 lst = list(range(n)) lengths = [int(x) for x in s.split(',')] pos = 0 # current position index skip_size = 0 for len...
# -*- coding: utf-8 -*- """ This program fits curves to the PSTH. INPUT: PSTH data, dose OUTPUT: parameters Hint: The INPUT is matrix (PSTH , duration and dose), so this program execute 3d fitting. In order to realize 3d fitting, the INPUT is formed as below: input = [[spike, spike, spike, ...], [dose, dose, dose, ....
import pytest import drjit as dr import mitsuba as mi def test01_discr_empty(variants_all_backends_once): # Test that operations involving the empty distribution throw d = mi.DiscreteDistribution() assert d.empty() with pytest.raises(RuntimeError) as excinfo: d.update() assert 'empty dist...
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Frames Explorer Plugin.""" # Local imports from spyder.config.base import _ from spyder.api.plugins import Plugins, SpyderDockablePlugin from spyder.api.plugin_re...
import requests import json def get_canvas_data(domain, path, access_key): payload = { 'per_page': 100, 'access_token': access_key } r = requests.get(domain + path, data=payload) data_list = r.json() while r.links['current']['url'] != r.links['last'][...
"""Renders the documentation.""" __license__ = 'MIT' from subprocess import run from pathlib import Path root = Path(__file__).resolve().parent.parent process = run(['sphinx-build', 'docs', 'deploy/docs'], cwd=root) if process.returncode: raise RuntimeError('Error while rendering documentation.')
from collections import Counter from bs4 import BeautifulSoup import sys from processors.abstract_processor import AbstractProcessor from utils.text_utils import tokenizer __author__ = 'Shyam' class SectionProcessor(AbstractProcessor): def __init__(self, wikipath, lang): super(SectionProcessor, self)._...
from marketsim import (registry, types, _, ops, event) from .._basic import Strategy from .._wrap import wrapper2 from ..side import FundamentalValue class _Suspendable_Impl(Strategy): def __init__(self): Strategy.__init__(self) event.subscribe(self.inner.on_order_created, _(sel...
#!/usr/bin/evn python # coding:utf-8 import sys sys.path.append('..') import time from lib.science import * from waypoint import Waypoint from lib.config import config from lib.logger import logger class Attribute(object): def __init__(self, ORB): self.ORB = ORB logger.info('Drone Type:{}'.forma...
import random class Grid: """Represents a grid map stored in a tuple of tuples.""" def __init__(self, filename): grid_li = [] with open(filename, 'r') as f: for line in f: temp = [] for c in line: if c == ' ': temp.append(None) # blank space elif c == '0': temp.append(0) # 0s are...
#primeiramente definimos as variaveis a=float(input("numero a")) b=float(input("numero b")) c=float(input("numero c")) #definmos a variavel da formula matematica chernobyl=((a**2)+(b**2)+(c**2))/(a+b+c) real=round(chernobyl, 7) #imprimimos o resultado print(real)
from flask import Blueprint, request from datetime import datetime from bs4 import BeautifulSoup from models import ProvView, TotalView, db import json from common import get_page, wrap_response from sqlalchemy import func, and_, or_ import pytz wuhan = Blueprint( 'wuhan', __name__, url_prefix='/wuhan' ) ...
from sys import stdin input = stdin.readline from collections import defaultdict N, M, V = map(int, input().split()) edges = defaultdict(list) for _ in range(M): a, b = map(int, input().split()) edges[a].append(b) edges[b].append(a) for k in edges.keys(): edges[k].sort() # dfs visited = [] stack = ...
from sets import Set from math import log import re import operator import sys P = Set() NP = Set() Si = Set() M = dict() Mcopy = dict() L = dict() PR = dict() newPR = dict() d = 0.85 d1 = 1 - d perplexity_list = [] infile = sys.argv[1] input_file = open(infile,"r") perplexity_output = open("perplexity.txt","w") de...
import viz import vizact import vizshape import vizinfo import viztracker viz.setMultiSample(4) viz.fov(60) viztracker.go() myTracker = viz.add('sensor.dls') viztracker.get("movable").setPosition([0,-1.8,-1]) z_coordinates=[-1,-3,-5,-7,-12,-17,-53,-75,-400] x_coordinates=[-5,0,5,10,17,30,50,80,-40...
from ..grpc_gen import status_pb2 from ..grpc_gen.milvus_pb2 import TopKQueryResult as Grpc_Result from ..client.abstract import TopKQueryResult from ..client.exceptions import ParamError def merge_results(results_list, topk, *args, **kwargs): """ merge query results """ def _reduce(source_ids, ids, ...
print ('meu primeiro programa em Python') a = 2 b = 3 soma = a + b print(soma) #Interagir com usuario a = int(input('Entre com o primeiro valor:')) b = int(input('Entre com o segundo valor:')) print(type(a)) soma = a + b subtracao = a - b multiplicacao = a * b divisao = a / b resto = a % b print ('soma: {}'.format(...
def group_words(words): groups = {} for word in words: sorted_word = ''.join(sorted(word)) if sorted_word not in groups: groups[sorted_word] = [] groups[sorted_word].append(word) ans = [] for sorted_word in groups: ans.append(groups[sorted_word]) return an...
import asyncio import logging from dataclasses import dataclass from decimal import Decimal from typing import List, Optional from hummingbot.core.data_type.trade_fee import TokenAmount, TradeFeeBase from hummingbot.core.event.events import OrderType, TradeType from hummingbot.core.rate_oracle.rate_oracle import RateO...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 31 01:18:11 2020 @author: amanda """ from sklearn import tree clf = tree.DecisionTreeClassifier() clf.fit(train_x, train_y) prediction = clf.predict(test_x) from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_es...
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine from eralchemy import render_er Base = declarative_base() class Follower(Base): __tablename__="follow...
import psycopg2 import config import psycopg2.extras import json import sys class Database: def __init__(self): with psycopg2.connect(dbname=config.DB_NAME, user=config.USER_NAME, password=config.USER_PASSWORD, host=config.DB_HOST) as connection: self.connection =...
import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() layers = list() layers += [nn.Conv2d(1, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.ReLU()] layers += [nn.Conv2d(64, 128, 3, 1, 1), nn.BatchNorm...
from OpenGL.GL import * from OpenGL.GLU import * import math as m import numpy as np from mesh import Mesh class Cube( Mesh ) : def __init__( self , n ) : Mesh.__init__( self , buffers = self.gen_v( n , n ) ) def gen_v( self , nx , ny ) : nx += 1 ny += 1 v = np.zeros( (6,nx,ny,3) , np.float64 ) n = ...
import data_preprocessing import model import tensorflow as tf import numpy as np # data loading (pickle) dataset_detection_video, classlbl_to_classid = data_preprocessing.load_data() # ====== GRID SEARCH TRAINING========= frame_batch = [15] lstm = [32] relu = [16] for i in lstm: for j in relu: for k in fram...
import distutils.command.bdist_rpm as orig class bdist_rpm(orig.bdist_rpm): """ Override the default bdist_rpm behavior to do the following: 1. Run egg_info to ensure the name and version are properly calculated. 2. Always run 'install' using --single-version-externally-managed to disable eggs...
#Direct_Cam_ver_0.3.py #################################### ### running parameters #################################### TOOL_DIAMETER=0.125 DRILL_PLUNGE_FEED_RATE = 2 HOME_X=0 HOME_Y=0 SAFE_HEIGHT=0.6 #################################### ### CAM details #################################### CUT_STEP_DEPTH=0.02 CUT_FAC...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 10 12:16:28 2019 @author: tnye """ ############################################################################### # Script that goes through observed waveforms from the 2010 M7.8 Mentawai event, # calculates intensity measures, and stores it all i...
import os import random as rd import numpy as np import torch import time import pandas as pd import tqdm from torch.utils.data import DataLoader from graph_recsys_benchmark.utils import * class BaseSolver(object): def __init__(self, model_class, dataset_args, model_args, train_args): self.model_class = ...
#!/usr/bin/env python # _#_ coding:utf-8 _*_ import logging from django.http import JsonResponse import time, hmac, hashlib from django.shortcuts import render from assets.models import * from django.contrib.auth.decorators import permission_required from django.contrib.auth.decorators import login_required from djang...
#HelloWorld 파스칼표기법 #helloWorld 낙타표기법 #hello_world 언더스코어(파이썬) #타입추론 #모든 것이 오브젝트 #인터프리터 #1.숫자 a = 1 b = 1.2 c = 4e5 print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) #연산자 +,-,*,/,% e = 3 f = 4 print(e**f) # ** 제곱 print(e//f) # // 몫 print(4%3) # % 나머지 #2. 문자열 # " ", ' ' 둘다 구분 안함 둘중 하나 아무거나 써...
# My first Python script import sys # Load a ibrary module print(sys.platform) # Print the name of the platform in use print(2**100) # Print 2 to a power of 100 x = "spam" # Assing the string "spam" to the variable x print(x*8) # Print the x variable 8 times
# Copyright 2019 EPFL, Google LLC # # 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 wri...
''' Classic dp problem with the twist that single digits has to be betwwen 1 and 9 and double digits has to be between 10 and 26. We save i's value on i+1 and handle the base/error case. Since we can only gurantee 1 as out put(after handline error case) we set dp[0:1] as 1 and start iterating on index 2 Time O(n) | Sp...
def test_nogarbage_fixture(testdir): testdir.makepyfile(""" def test_fail(nogarbage): assert False def test_pass(nogarbage): pass def test_except(nogarbage): try: assert False except AssertionError: pass ...
import os import sqlite3 from flask import Flask, redirect, abort, g, request, jsonify app = Flask(__name__) DATABASE = "data.db" REGISTER_SUCCESS = 0 REGISTER_FAIL_TOO_SHORT = 1 REGISTER_FAIL_ALIAS_TOO_SHORT = 2 REGISTER_FAIL_EXISTED = 3 REGISTER_FAIL_AUDITING = 4 REGISTER_FAIL_ADDR_EXISTED = 5 REGISTER_FAIL_ALIAS_...
# Generated from sfql.g4 by ANTLR 4.9.2 from antlr4 import * if __name__ is not None and "." in __name__: from .sfqlParser import sfqlParser else: from sfqlParser import sfqlParser # This class defines a complete listener for a parse tree produced by sfqlParser. class sfqlListener(ParseTreeListener): # En...
import pygame, os class Ruoka(pygame.sprite.Sprite): def __init__(self, tileMap, pos): pygame.sprite.Sprite.__init__(self) for x, y, gid, in tileMap.get_layer_by_name("ruoka"): image = tileMap.get_tile_image_by_gid(gid) if image: self.image = image break self.rect = self.image.get_rect() self.re...
import sys import time import warnings from queue import PriorityQueue from sys import stdout import numpy as np import sim.debug import sim.devices.components.processor import sim.simulations.constants import sim.tasks.job import sim.tasks.subtask from sim import debug from sim.clock import clock from sim.devices.co...
import sys import logging from pbcommand.common_options import add_log_debug_option from pbcommand.cli import pacbio_args_runner, get_default_argparser from pbcommand.utils import setup_log from pbcommand.cli.utils import main_runner_default from pbcommand.validators import validate_file import pbsmrtpipe.report_rend...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import signal import pygame import time import os import subprocess from pygame import mixer from pygame.locals import * from random import randint class Player: def __init__(self): self.list = [] self.play_flag = False self.pause_flag ...
import os import csv from collections import defaultdict import argparse def ReadMyCsv(SaveList, fileName): csv_reader = csv.reader(open(fileName)) for row in csv_reader: SaveList.append(row) return def StorFile(data, fileName): with open(fileName, "w", newline='') as csvfile: ...
# -*- coding: utf-8 -*- { 'name': "Activar Cliente / Proveedor en Socio", 'summary': """ Activar si es Cliente / Proveedor en Socio""", 'description': """ Activar si es Cliente / Proveedor en el módulo de Partner. """, 'author': "TH", 'website': "http://www.cabalcon.com", ...
# -- coding: utf-8 -- from sys import argv #调用 sys 模块的 argv 函数 script, filename = argv # 把两个值赋给 argv 运行的时候要把变量给 argv可以是文件 txt_file = open(filename) print "Here's your file %r." % filename print txt_file.read() filename_again = raw_input ("Please type:\n") the_file = open(filename_again) #打印txt 文件 a = the_file.read...
from Perceptron import * import pandas as pd import matplotlib.pyplot as plt data_frame = pd.read_csv("seeds_dataset.txt", header=None) #Select Rosa (2) and Canadian (3) #7th column gives species class y = data_frame.iloc[70:210, 7].values #if species is "2" label as -1, else (if "3") as 1 y = np.where(y == 2, -1, 1...
# Generated by Django 2.0.1 on 2018-03-11 20:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('shows', '0001_initial'), ] operations = [ migrations.CreateModel( name='Genre', fie...
#encoding: utf-8 from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from feitec.projeto.models import * from django.forms import ModelForm, TextInput, PasswordInput, HiddenInput from django.shortcuts import render_to_response,get_object_or_404 from django.template im...
import json def is_json(myjson): try: test = json.dumps(myjson) json.loads(test) except ValueError: return False return True
""" Auth Utils """ import cloudstorage as gcs import endpoints import json import os import webapp2 import logging import re from datetime import datetime from datetime import date from google.appengine.api import app_identity from google.appengine.api import mail from google.appengine.api import urlfetch from apicli...