text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" BaseProducer class
All producer must be inherit form this class
"""
from abc import ABCMeta, abstractmethod
from typing import Union, Awaitable, List, Dict
from tonga.models.records.base import BaseRecord
from tonga.models.store.store_record impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
logs= sys.stderr
import mxnet as mx
import numpy as np
import time
import math
import logging
from collections import namedtuple
import data_iter
ReLUModel = namedtuple("ReLUModel", ['relu_exec', 'symbol',
'data', 'label'... |
import json
import logging
from constants import *
import utils
class DialogState:
"""State of dialog agent.
Attributes:
trigger (dict): Slots and values related to Triggers. The structure can
be found in `state-example.py`.
action (dict): Slots and values related to Actions. The... |
import os
sg1 = "sg-0964887a556e1b9ff"
sg2 = "sg-0e42e8154106ab899"
sg3 = "sg-04b98dd0a613e4873"
sg4 = "sg-034aef491d100e6a1"
sg5 = "sg-0d778ff6c38911f20"
os.system("aws ec2 delete-security-group --group-id {}".format(sg1))
os.system("aws ec2 delete-security-group --group-id {}".format(sg2))
os.system("aws ec2 delete... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 10:18:40 2017
@author: lcao
"""
import pandas as pd
from WeiboSpyder import weibo
Users_id = pd.read_csv('WeiboStat\Weibo_users_id.csv')
Users_id = Users_id['User_id']
print len(Users_id)
for i in range(2,len(Users_id)):
#使用实例,输入一个用户id,所有信息都会存储在wb实例中
user_... |
for i in range(0,5):
print(str(i)*5)
i+=1
|
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
from mock import patch
from wadebug.config... |
#!/usr/bin/env python3
import argparse
import sys
import json
from genderbias import ALL_SCANNED_DETECTORS, Document
def main():
parser = argparse.ArgumentParser(
description="CLI for gender-bias detection"
)
parser.add_argument(
"--file", "-f", dest="file", required=False,
help="... |
#!/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import rootpy.ROOT as ROOT
class readIn:
############Constructor#########################
def __init__(self, filename):
self.pdfs = {}
self.voltDict={}
self.peakDict={}
self.nameList=[]
self.yDict={}
... |
import json
from Expedia import mainExpedia
import Redis
from models import Flight
def get_cheapest_flight(source, destination, start_date, end_date):
key = "%s:%s:%s:%s" % (source, destination, start_date, end_date)
cached_cheapest_flight = Redis.get_from_db(key)
if cached_cheapest_flight is N... |
number_list = int(input("Enter the number of element in the list-:"))
alist = []
for number in range(number_list):
in_list = int(input("Enter the number on the list-:"))
alist.append(in_list)
def sort_list(alist):
for index in range(0, len(alist)):
current = alist[index]
position = index
... |
"""
Ambience
This is a system for sending intermittent messages to a room to provide
ambiance.
A series of Mixins, allows all objects to optionally hold messages which
have a chance to be intermittently displayed to the objects around them.
These messages are collected with the return_ambient_msgs() function.
By def... |
from node import Node
from bst import BST
import random
class RedBlackNode(Node):
RED = True
BLACK = False
def __init__(self, key, val, color=RED):
self.color = color
super().__init__(key, val)
def __str__(self):
return "({},{},{})".format(self.key, self.val, "RED" if self.color else "BLACK")
def __repr_... |
INF = float("inf")
class WEN: #Weighted edge node
def __init__(self,nodde,weigght=0):
self.node = nodde
self.weight = weigght
class WG: #Weighted graph
def __init__(self,everticies):
self.evertices = everticies
self.adjencylist = {}
self.vertices... |
import math
import zbar
import cv2
import numpy
from PIL import Image
from img_data import QrData
MS = 10.0 # model side size
class ImgProcessor:
def __init__(self):
self.scanner = zbar.ImageScanner()
self.scanner.parse_config('enable')
self.qr_3d_model = numpy.array([
(0.0... |
from __future__ import print_function
import numpy as np
import time
import tensorflow as tf
import ops as my_ops
import os
import re
import itertools as it
class Agent:
def __init__(self, sess, args):
'''Agent - powered by neural nets, can infer, act, train, test.
'''
self.sess = sess
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2018-01-18 02:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import helpers.base.jsonfield
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operation... |
import os
import numpy as np
from imageio import imwrite
from ..io import segRelabel, mkdir, segToVast
class zwDecoder(object):
def __init__(self, aff_file, output_folder='./', job_id = 0, job_num = 1):
self.aff_file = aff_file
self.output_folder = output_folder
self.job_id = job_id
... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
from kafka.partitioner.hashed import murmur2
from uuid import uuid4
import random
def partioner(key, all_partitions, available):
idx = (murmur2(key) & 0x7fffffff) % len(all_partitions)
return idx
all_parts = [0, 1, 2, 3, 4, 5]
available_par... |
from ._surface import Surface
from ._stream import Stream
from ._spaceframe import Spaceframe
from ._slices import Slices
from plotly.graph_objs.isosurface import slices
from ._lightposition import Lightposition
from ._lighting import Lighting
from ._hoverlabel import Hoverlabel
from plotly.graph_objs.isosurface import... |
import numpy as np
import pandas as pd
import matrix_factorization_utilities
# Load user ratings from both the training and testing csv files
raw_training_dataset_df = pd.read_csv('movie_ratings_data_set_training.csv')
raw_testing_dataset_df = pd.read_csv('movie_ratings_data_set_testing.csv')
# Convert the running li... |
number = int(input("Input your number: "))
result =""
while number !=0:
remainder = number % 2
number = number // 2
result = str(remainder) + result
print(result) |
# -*- coding: utf-8 -*-
import calendar, datetime, logging, uuid, pytz
import inject
from model.systems.assistance.date import Date
from model.systems.assistance.logs import Logs
from model.systems.assistance.justifications.exceptions import *
from model.systems.offices.offices import Offices
from model.systems.ass... |
#checks validity of a date
def main():
right = True
months_with_31days = [1, 3, 5, 7, 8, 10, 12]
months_with_30days = [4, 6, 9, 11]
months_with_28days = [2]
date=input("Enter the date(mm/dd/yy format): ")
mm,dd,yy=date.split('/')
mm=int(mm)
dd=int(dd)
yy=int(yy)
if mm ... |
class CoordValue:
def __get__(self, instance, owner):
return self.__value
def __set__(self, instance, value):
self.__value = value
def __delete__(self, obj):
del self.__value
class Point:
coordX = CoordValue()
coordY = CoordValue()
def __init__(self, x = 0, y = 0):
... |
# 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... |
from _typeshed import Incomplete
def group_betweenness_centrality(
G,
C,
normalized: bool = True,
weight: Incomplete | None = None,
endpoints: bool = False,
): ...
def prominent_group(
G,
k,
weight: Incomplete | None = None,
C: Incomplete | None = None,
endpoints: bool = False,
... |
"""holds all the independent functions for the secret_messages.py game.
Specifically, when a cipher is selected from the pick_a_cipher function,
it runs the corresponding function from this module.
"""
import os
# Need a way to handle selections based on the chosen cipher
# one function per cipher with a description a... |
#!/usr/binv/env python3
import functools
import os
import csv
import boto3
def ssm_describe_instance_information(client):
instances = []
paginator = boto3.client('ssm').get_paginator('describe_instance_information')
page = paginator.paginate()
for response in page:
for instanceinfo in response... |
import os
import re
import jieba
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
import collections
import gensim
from interval import Interval
try:
fr... |
# BP神经网络Python实现
import numpy as np
from numpy import random
import math
import copy
import sklearn.datasets
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
# 获取数据并分为训练集与测试集
trainingSet, trainingLabels = sklearn.datasets.make_moons(400, noise=0.20)
plt.scatter(trainingSet[trainingLabels==1][:,... |
import PySimpleGUI as sg
from process import process_crawl, validate_start_url
sg.theme('DarkAmber')
# Inside the window
layout = [
[sg.Text('Start URL:', key='start-url'), sg.InputText(tooltip='https://example.com')],
[sg.Text('Output:'), sg.InputText(), sg.FolderBrowse()],
[sg.Button('Start')]
]
# Creat... |
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin, RetrieveModelMixin, DestroyModelMixin
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.exceptions import ValidationError, PermissionDenied
from ... |
import sys
import numpy as np
from Modules.helper import EventTimer
def MAP(T, R):
def AP(T, R):
precisions = []
cnt = 0
for i, d in enumerate(R):
if d in T:
cnt += 1
precisions.append(cnt / (i + 1))
return sum(precisions) / len(T)
AP... |
import copy
Class Solution:
def combinationSum(self, candidates, target):
self.line=[]
self.res=[]
return res;
def helper(self, data, target):
if 0== target:
return
for ie in data:
temp = target - ie
if temp > 0:
... |
from workprogramsapp.models import WorkProgram, EducationalProgram, AcademicPlan
from rest_framework import serializers
from dataprocessing.serializers import userProfileSerializer
from dataprocessing.serializers import userProfileSerializer
from workprogramsapp.models import WorkProgram, WorkProgramInFieldOfStudy
fro... |
# insult simulator
import random as r
insult = r.randint(100)
if 0 <= insult < 50:
print('your fingers are fatter than your toes')
if 50 < insult <= 75:
print('uganda knuckles are more patriotic to mexico than you are to russia you communist')
if 75 < insult <= 90:
print('belgium makes decent waffles. ... |
import os
import re
from math import floor
class WorkOut:
def __init__(self, gender):
# temporary variables for workout names
TAKING_A_WALK = "taking a walk"
GOING_FOR_A_RUN = "going for a run"
RIDING_A_BIKE = "riding a bike"
self.DEFAULT_WORKOUTS = [TAKING_A_WALK, ... |
print ("Hello Poland again :)") |
in_order = ['T', 'b', 'H', 'V', 'h', '3', 'o', 'g', 'P', 'W', 'F', 'L', 'u', 'A',
'f', 'G', 'r', 'm', '1', 'x', 'J', '7', 'w', 'e', '0', 'i', 'Q', 'Y',
'n', 'Z', '8', 'K', 'v', 'q', 'k', '9', 'y', '5', 'C', 'N', 'B', 'D',
'2', '4', 'U', 'l', 'c', 'p', 'I', 'E', 'M', 'a', 'j', '6', 'S', 'R',
'O', 'X', 's', '... |
from common.run_method import RunMethod
import allure
@allure.step("小程序/商品/课程套餐详情")
def applet_package_course_detail_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认jso... |
import random
Player_Hand = []
Shuffled_Deck = []
Deck = []
Suits = [" Of Spades", " Of Hearts", " Of Diamonds", " Of Clubs"]
Ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
Random_Card1 = random.choice(Ranks)
Random_Card2 = random.choice(Suits)
print("You Drew A " + Random_Card1 ... |
from django.contrib import admin
from django.db.models.loading import get_models
for m in get_models():
exec "from %s import %s" % (m.__module__, m.__name__)
class ChoicesInline(admin.TabularInline):
model = QuestionChoice
extra = 0
class VarsInline(admin.TabularInline):
model = QuestionVariable
extra = 0
c... |
from machine import I2C, Pin
import m5stack
import utime
from mpu6886 import MPU6886
from maze import *
import maze_reader as reader
from maze_renderer import MazeRenderer
print('Maze game started')
s = """
+-+-+-+-+-+-+-+-+
|. . .|o|. . . .|
+ +-+-+ +-+-+-+ +
|.|. . .|. .|. .|
+ + ... |
#!/usr/bin/env python
import sys
for line in sys.stdin:
sys.stdout.write( line )
|
# Day 6: Custom Customs
# <ryc> 2021
def inputdata( ):
stream = open('day_06_2020.input')
data = [ ]
record = [ ]
for line in stream:
if len(line) == 1:
data.append(record)
record = [ ]
else:
record.append(line[ : -1 ])
data.append(record)
str... |
VOWELS = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}
def vowel_2_index(string):
return ''.join(str(i) if a in VOWELS else a
for i, a in enumerate(string, start=1))
|
class node:
def __init__(self,val=None, next=None):
self.val = val
self.next = next
class List:
def createList(self):
nhead = node(0)
print("nhead.next", nhead.next)
temp = nhead
temp.next = node(2)
print("nhead.next", nhead.next)
temp= temp.next
... |
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name="add_class")
def add_class(field, class_name):
return field.as_widget(attrs={
"class": " ".join((field.css_classes(), class_name))
})
@register.filter(name='has_group')
... |
#!/usr/bin/env python
import os
import sys
import time
import random
import requests
import argparse
parser = argparse.ArgumentParser(description="Kepps a webapp up.")
parser.add_argument("--pidfile", action="store",
default="/var/run/webapp-up-keeper.pid", help="where to save the pidfile.")
parser.add_argumen... |
import numpy as np
from sklearn.manifold import TSNE
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
''''''
from PIL import Image
import numpy as np
import matplotlib.image
img=np.array(Image.open('/home/jiawei/Pictures/lookup-table.png'))
for i in range(512):
for j in range(512):
r=(i%64)*4
g=(j%64)*4
b=(i//64... |
from dateutil.parser import parse
from fileinput import input
from collections import defaultdict
import random
import re
class Guard:
def __init__(self, gid):
self.gid = gid
self.events = []
def addEvent(self, event):
self.events.append(event)
def __eq__(self, other):
... |
from torch.nn.modules.module import Module
from ..functions.psroi_align import PSRoIAlignFunction
class PSRoIAlign(Module):
def __init__(self, out_size, spatial_scale, sample_num=0, output_dim=10, group_size=7):
super(PSRoIAlign, self).__init__()
self.out_size = out_size
self.spatial_sca... |
#Define is_palindrome function thatr take one word in string as input
#and return True if it is palindrome else return False
a=input("ingrese la palabra para saber si es palindroma: ")
def is_palindrome(a):
if a==a[::-1]:
return True
else:
return False
print(is_palindrome(a))
|
import pickle
import numpy as np
import pandas as pd
import sys
import math
import requests
from pyimzml.ImzMLParser import ImzMLParser
from annotation_pipeline.utils import logger, get_pixel_indices, append_pywren_stats, read_object_with_retry, \
read_cloud_object_with_retry, read_ranges_from_url
from concurren... |
# Mapping of roman numerals to equivalent decimal values.
# Includes each roman numeral and the subtractive value of one significant
# numeral smaller.
MAP = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.contrib.auth.models import User
from . import models
from . import serializers
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
def home(request):
print("home")
... |
import numpy as np
def batch_gradient_descent(model, eta, max_iterations=1e4, epsilon=1e-5, weights_start=None):
"""
Batch Gradient Descent
============================================================
Parameters::
````````````````````````````````````````````````````````````
+ model :... |
numeral = input('Введите целое положительное число: ')
while True:
if str(numeral).isdigit():
numeral = int(numeral)
break
else:
numeral = input('Число введено некорректно, повторите попытку: ')
max_num = 0
while numeral != 0:
new_num = numeral % 10
if new_num > max_num:
... |
import os
import tarfile
import urllib.request
from urllib.parse import urlparse
from pathlib import Path
from tqdm import tqdm
class DownloadProgressBar(tqdm):
def update_to(self, b=1, bsize=1, tsize=None):
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n)
def... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 16:09:56 2020
@author: vikaa
"""
#import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Load the data
df=pd.read_csv('Dia.csv') # Use to load data on Google Colab
print(df.head(7))#print the 7 ro... |
from __future__ import division
import natsort
# 1. Sort File Names in a proper way
## Make a list of file names like P_0.png, P_1.png
file_names = [f'P_{index}.png' for index in range(200)]
print('New List\t', file_names)
## Sort by sort()
file_names.sort()
print('Sort by sort\t', file_names)
## Sort by index
def... |
#The Running time is O(n)
def maxset(A):
subarrays = []
length = len(A)
#print length
start = 0
end = 0
flag=0
maxsum=0
globalsum=0
maxarray=[]
globalarray=[]
for i in range(0,length-1):
if (A[i] >= 0 ):
if(A[i+1]>=0):
star... |
import sqlite3
import json
#facebookid to json
conn = sqlite3.connect("users.db")
c = conn.cursor()
def create_table_user_info():
c.execute('CREATE TABLE IF NOT EXISTS accessUser(firstName TEXT, lastName TEXT, facebookID TEXT, smartcarToken TEXT, expDate TEXT)')
def check_new_user(FBid):
c.execute("SELECT f... |
from django.db import models
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
import time
import django_rq
from decimal import Decimal
import socket
from django.conf import settings
from exchange.audit_logging import AuditLogger
from exchange.thread_local import get_current_logg... |
from rest_framework import serializers
from progress_analyzer.models import CumulativeSum,\
OverallHealthGradeCumulative, \
NonExerciseStepsCumulative, \
SleepPerNightCumulative, \
MovementConsistencyCumulative, \
ExerciseConsistencyCumulative, \
NutritionCumulative, \
ExerciseStatsCumulative, \
AlcoholCumulat... |
from collections import defaultdict
import random
class Dice:
""" Representation of the five dice
Attributes:
throws (int): How often the dice were rolled.
faces (list[int]): the current faces of the dice.
counts (dict[int->int]): occurances of each face value.
"""
def __init__(se... |
from ui.UI import UI
from battle.round.RoundAction import RoundAction
# Contains the processing for fighters and round actions
class Round:
def __init__(self, round_actions):
self.round_actions = round_actions
# processes the round actions one by one...
def process_round_actions(self):
fo... |
from ELMo.ELMoNet import ELMoNet
import torch
class sent2elmo():
def __init__(self, char_lexicon, config, device, model_path):
self.char_lexicon = char_lexicon
self.config = config
self.device = device
self.model_path = model_path
checkpoint = torch.load(se... |
#VIEWS IS THE HANDLER
# / means the root of the current drive;
# ./ means the current directory;
# ../ means the parent of the current directory.
#Defining what you will show
#gets information from the front-end
#all you are doing here is post
from django.shortcuts import render, HttpResponse, HttpRespon... |
from __future__ import print_function
import numpy as np
from numpy import linalg as la
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
ACTIVATION_THRESHOLD = 4.5
NO_PREDICTION_PENALTY_COST = 2
def preprocess_activations(sigmoid_gradient, things):
#return 1 /(1+np.e... |
import math
dic = {}
com_dic = {}
white = 0
black = 1
range_x = 25
range_y = 25
def readFile(f,value):
for line in f:
dic[line[0:-1]] = value
def writFile(fileNameBlack,fileNameWhite):
f1 = open(fileNameBlack, 'w', encoding='utf-8')
count1 = 0
f2 = open(fileNameWhite, 'w', encoding='utf-8')
... |
def make_pretty(func):
print("it is outer function")
def thecaller():
print("I got decorated")
func() # calling the passed function
return thecaller
def ordinary():
print("I am ordinary")
# driver code
ordinary()
pretty = make_pretty(ordinary) # a f... |
from dronekit import connect, VehicleMode, LocationGlobalRelative, APIException
import time
import socket
import exceptions
import math
import argparse #To import some values from command line and use it on our python script
#####################functions####
def connectMyCopter():
parser=argparse.ArgumentPa... |
# !/usr/bin/python27
# coding: utf8
from sklearn import neighbors
import hocmidp
import warnings
import cPickle
warnings.filterwarnings("ignore")
seg1 = hocmidp.hocmidp('sac1.hoc')
seg2 = hocmidp.hocmidp('sac2.hoc')
seg3 = hocmidp.hocmidp('sac3.hoc')
seg4 = hocmidp.hocmidp('sac4.hoc')
seg5 = hocmidp.hocmidp('sac5.hoc... |
import argparse
from pyrosetta import *
from pyrosetta.rosetta.core.select.residue_selector import InterGroupInterfaceByVectorSelector, ChainSelector, ResidueIndexSelector, OrResidueSelector, NotResidueSelector, AndResidueSelector
from pyrosetta.rosetta.core.pack.task import TaskFactory
from pyrosetta.rosetta.core.... |
#!/usr/bin/env python3
import VariablesParser as vp
import Command
import io
class PipeParser:
"""
класс, который обрабатывает часть пайплайна
то есть все между "|", вызывая нужные команды
"""
def __init__(self):
self.var_parser = vp.VarParser()
# имена наличествующих команд
... |
import argparse
import logging
import os
import sys
from string import Template
class Reshaper:
""" Reshapes race results with lap data into a Tableau-readable form """
def __init__(self, inFoldName, outFileName, raceName=""):
self.__logger = logging.getLogger(__name__)
self.__inFoldName = ... |
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
# The element value in the i-th row and j-th column of the array should be i*j.
# Note: i=0,1.., X-1; j=0,1,¡Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should b... |
from graph import *
import math
import random
def oval_with_angle(x, y, size, angle, color):
"""Function draw the oval with given angle , coordinates, size, color"""
brushColor(color)
penColor(color)
angle = math.radians(angle)
point_massive_for_oval = []
for j in range(361):
a = 2 * s... |
import subprocess
import os
import sys
import re
sys.path.insert(0, os.path.join("tools", "families"))
import fam
import fam_data
import saved_metrics
import run_all_species
import generate_families_with_subsampling
from run_all_species import SpeciesRunFilter
import plot_speciesrax
import generate_families_with_filter... |
from pymytools import (
timerun,
systools,
pyio,
basemap,
)
|
import cv2 as cv
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3),np.uint8)
cv.namedWindow('image')
cv.createTrackbar("parameterA","image",0,20,nothing)
cv.createTrackbar("parameterB","image",0,20,nothing)
cv.createTrackbar("parameterC","image",0,20,nothing)
switch = "0:OFF\n1:ON"
cv.createTrackb... |
# -*- coding: utf-8 -*-
# flake8: noqa: E501
from __future__ import unicode_literals
from kinopoisk.person import Person
from .base import BaseTest
class PersonTest(BaseTest):
def test_person_manager_with_one_result(self):
persons = Person.objects.search('Гуальтиеро Якопетти')
self.assertEqual(le... |
# /usr/bin/env python
"""
kmer extraction: a script to crate clr kmer profles from 4mers
usage: kmer_extraction.py infile outfile ksize
"""
import os
import sys
import csv
from Bio import SeqIO
from Bio.Seq import Seq
import skbio.stats.composition
import vica
def _write_kmers_as_csv(infile, outfile, ksize, kmers,... |
#%% [markdown]
# Load XML File:
#%%
import os
import re
from lxml import etree, objectify
#%% [markdown]
# This is a testing comment
#%%
#xml_file = open(os.getcwd()+'/combined_output.xml')
# print('TYPE: ' + str(type(xml_file)))
all_xml_data = None
xml_file_path = os.getcwd()+'/combined_output.xml'
with open(os.ge... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
"""Analog exceptions."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class AnalogError(RuntimeError):
"""Exception base class for all Analog errors."""
class MissingFormatError(AnalogError):
"""Error raised when ``Analyzer`` is called withou... |
# -*- encoding: utf-8 -*-
from debauto.remessa import Remessa
from debauto.utils import formata_data, formata_valor
class Caixa(Remessa):
"""
Caixa
"""
__a = "A{:1}{:20}{:20}{:3}{:20}{:8}{:6}{:2}{:17}{:45}{:0>7}\r\n"
__e = "E{:0>25}{:0<4}{:14}{:8}{:0<15}{:2}{:60}{:6}{:8}{:0>6}{:1}\r\n"
__z = ... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from mpl_toolkits.mplot3d import Axes3D
def target(x, y):
z = np.exp(-(x-2)**2)+np.exp(-(x-6)**2/5)+1/(x**2+1)+0.1*np.... |
class Author:
def __init__(self,book):
# self.name = name
self.books = book
# self.publishedTime= publishedTime
def info(self):
print("Writer name :" ,self.name.title())
print("Published Year :" ,self.publishedTime.title())
# def booklist(self):... |
import os
import random
import Tkinter
import Tkconstants
import tkFileDialog
import tkMessageBox
import DES
import RSA
def gen_primes(n):
return filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, n))
def num_to_binstr(num):
num = bin(num)[2:]
return '0' * (max(0, 128 - len(num))) + n... |
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# 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... |
import cvrp.const as const
import cvrp.learnHeuristic as LH
import os.path
startFolder = 'toExecute2'
arrivalFolder = 'resultats'
dFile = 'GoldenEye'
allinstances = os.listdir(startFolder)
allinstances.sort()
for fileInstance in allinstances:
instance,demand,capacity = const.define(fileInstance,startFolder,arriv... |
"""
A vendor at a food court is in the process of automating his order management system.
The vendor serves the following menu – Veg Roll, Noodles, Fried Rice and Soup and also maintains the quantity available for each item. The customer can order any combination of items. The customer is provided the item if the reque... |
def scoreboard(who_ate_what):
scores = {'chickenwings': 5, 'hamburgers': 3, 'hotdogs': 2}
return sorted((
{'name': a.pop('name'),
'score': sum(scores.get(k, 0) * v for k, v in a.iteritems())}
for a in who_ate_what), key=lambda b: (-b['score'], b['name']))
|
import sys
import torch
import utils
import dataloader
# generate submissions.csv file
def inference():
device = "cuda:0" if torch.cuda.is_available() else "cpu"
save_file = input("save model name : ")
try:
if torch.cuda.is_available():
model = torch.load(save_file, map_location={"cpu"... |
import pytest
from unittest import mock
import builtins
import numpy
def inner_numpy():
a=input('')
b=input('')
A = numpy.array(list(map(int, a.split())))
B = numpy.array(list(map(int, b.split())))
return numpy.inner(A, B)
def outer_numpy():
a=input('')
b = input('')
A = numpy.array(l... |
from flask import Flask
from app.settings import DEBUG
app = Flask(__name__)
app.debug = DEBUG
from . import urls
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.