text stringlengths 38 1.54M |
|---|
import coverage
import simplest
import os
def run_tests():
simplest.foo(1, 2)
simplest.foo(1, 1)
simplest.foo(2, 1)
command = "sudo coverage html -d /var/www/html"
print "Executing {}".format(command)
os.system(command) |
from django.conf.urls import url
from views import *
urlpatterns = [
url(r'home/$' , home , name='home') ,
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import traceback
import discord
from discord.ext import commands
from MultilineBot import MultilineBot
from LakshmiHelpCommand import LakshmiHelpCommand
import LakshmiErrors
from contents.LakshmiBrainStorage import LakshmiBrainStorage
bot = Mult... |
rule call_variants:
input:
bam=get_sample_bams,
ref=config["ref"]["genome"],
int="targets_GATK.list"
output:
gvcf=protected("called/{sample}.g.vcf.gz")
log:
"logs/gatk/haplotypecaller/{sample}.log"
params:
gatk=config["modules"]["gatk"],
files=lamb... |
from utils import convert_to_pdf, save_document
import io
import asyncio
from aiogram import Bot, Dispatcher, executor, types, filters
from aiogram.dispatcher import FSMContext
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.dispatcher.filters.state import State, StatesGroup
import log... |
from keras.engine import Model
from keras.models import Sequential
from keras.layers import Flatten, Dense, Input, Activation, Dropout, Conv2D, MaxPooling2D, Lambda
from keras_vggface.vggface import VGGFace
from keras_vggface import utils
from keras.optimizers import Adadelta, rmsprop
from keras.callbacks import Early... |
from sqlalchemy import create_engine, Column, ForeignKey, Integer, String, Boolean, BLOB
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
engine = create_engine('sqlite:///game.db')
Base = declarative_base()
Session = sessionmaker(bind = engine)
# class P... |
import json
from resources.user.service import UserService
from services.service_web import WebService
from flask_restful import Resource
from flask import request
class UserController(Resource):
url = "/user"
# Create
# TODO: Only Admin role can reach this endpoint
def post(self):
# Services... |
# 逆波兰表达式求值
class Solution:
def evalRPN(self, tokens: list) -> int:
if not tokens:
return 0
length = len(tokens)
num_stack = []
i = 0
while i < length:
if tokens[i] not in '+-*/':
num_stack.append(int(tokens[i]))
else:
... |
import overloading
from overloading import *
from test_overloading import *
@overload
def f(*args):
return 'default'
@overload
def f(foo):
return ('any')
@overload
def f(foo, bar:int):
return ('any', 'int')
@overload
def f(foo, bar, baz):
return ('any', 'any', 'any')
@overload
def f(foo, bar:int, ... |
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from __future__ import print_function, absolute_import, division
import os
from distutils.version import LooseVersion
... |
# This is the file you'll use to submit most of Lab 0.
# Certain problems may ask you to modify other files to accomplish a certain
# task. There are also various other files that make the problem set work, and
# generally you will _not_ be expected to modify or even understand this code.
# Don't get bogged down with ... |
import functions
import sklearnClassify
import pandas as pd
import random
def learnfunction(path, pathTweet, numberUsedAll, numberUnlabeled, algorithm):
numberForTraining = int (0.8 * numberUsedAll)
numberForTesting = int (0.2 * numberUsedAll)
input_list, input_score = functions.readTestComment(path, numb... |
from django.db.models import (
CharField,
IntegerField,
Model,
)
from gbetext import day_of_week
class EmailFrequency(Model):
email_type = CharField(max_length=128)
weekday = IntegerField(choices=day_of_week)
class Meta:
app_label = "gbe"
|
# -- coding: utf-8 --
'''
===========================================================================
-- PROJECT NAME : Traxium
-- SOURCE FILE : lista_arb_fis.py
-- REVISION : 1.1
-- AUTHOR :
-- LAST UPDATE : Mayo 6, 2020
--=======================================================================... |
def if_neutral_planet_available(state):
return any(state.not_my_planets())
def have_largest_fleet(state):
return sum(planet.num_ships for planet in state.my_planets()) \
+ sum(fleet.num_ships for fleet in state.my_fleets()) \
> sum(planet.num_ships for planet in state.enemy_planets()... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the artifact definitions validator."""
import glob
import os
import unittest
from artifacts import errors
from tools import validator
class ArtifactDefinitionsValidatorTest(unittest.TestCase):
"""Class to test the validator."""
def testArtifactDefinitionsV... |
# -*- encoding: utf-8 -*-
class GenericFilter:
def filter_queryset(self, request, queryset, view):
filter_fields = getattr(view, "filter_fields")
kw = {}
for field in filter_fields:
value = request.query_params.get(field)
if not value:
cont... |
import os
import os.path
from datetime import datetime
from config_parse import Deleter_config
CONF_WAY = "./bc_deleter.conf"
DIR_WATCHERS = []
class ConfigDirError(Exception):
pass
class NonPositiveCountError(ValueError):
pass
class Dir_watcher:
def __init__(self, dir, num):
if not os.path.exi... |
# # class Rectangle:
# # def __init__(self, b):
# # self.a =5
# # self.b = b
# # def perimeter(self):
# # return 2 * (self.a + self.b)
# # rec1 = Rectangle(2)
# # print(rec1.perimeter())
# class Pryamougolnik:
# def __init__(self, s1, s2):
# self.a = s1
# self.b... |
"""Given a list of tuples featuring names and grades on a test,
write a function normalize_grades to normalize the values of the grades to a linear scale between 0 and 1."""
import numpy as np
def normalize_grades(tuples):
low_value = min(x[1] for x in tuples)
high_value = max(x[1] for x in tuples)
return ... |
# -*- coding:utf-8 -*-
import os
import time
import unittest
from BeautifulReport import BeautifulReport
from selenium import webdriver
from zhangjinjin.render.case.common import *
class studentTest(unittest.TestCase):
def setUp(self):
global driver
options = webdriver.ChromeOptions()
opt... |
# """
# This is Master's API interface.
# You should not implement it, or speculate about its implementation
# """
# class Master:
# def guess(self, word: str) -> int:
# TAGS heuristic, interactive
#
# First see there's no way for this to work always in less than 10 attempts.
# Consider aaaaa bbbbb cccccc ddddddd ... |
from bs4 import BeautifulSoup
import requests
import csv
import re
import os
sku_i_need = []
with open('./skus_lambda.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=",")
for row in reader:
sku_i_need.append(row[0])
file_name = './lambdatek/'
new_row = []
for i in range(1, 4):
resu... |
with open('Chapter 9.py',encoding='gb18030',errors='ignore') as file_object:
contents = file_object.read()
filename = 'Chapter 9.txt'
with open(filename,"w") as file_object:
file_object.write(contents)
words = file_object.split()
words_number = len(words)
print("The text has " + str(wor... |
from rest_framework import serializers
from workouts.models import Workout, Exercise, Set
class SetSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(required=False)
class Meta:
model = Set
fields = ('id', 'reps', 'weight')
class ExerciseSerializer(serializers.ModelSerial... |
from app.models import User,Student,Role, Bank_Account, His
import flask
from app import app
from flask import json, render_template, request, session, Response,jsonify,redirect,url_for,flash,make_response
from app.database import mysql_db
from werkzeug.security import generate_password_hash, check_password_hash
from d... |
'''
Conceptual Aircraft Design Tool
(for PRJ-22 and AP-701 courses)
Cap. Eng. Ney Rafael Secco (ney@ita.br)
Aircraft Design Department
Aeronautics Institute of Technology
07-2021
The code uses several historical regression from
aircraft design books to make a quick initial
sizing procedure.
Generally, the user shou... |
#!/usr/bin/env python
# -*- utf-8 -*-
import sys
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:8000')
if len(sys.argv) != 4:
print "%s 1: min, 2: max, 3: try count" % sys.argv[0]
sys.exit(1)
for i in range(0, int(sys.argv[3])):
print s.random(int(sys.argv[1]),int(sys.argv[2]))
|
def name():
return "CSVtoVector"
def description():
return "This plugin has no real use."
def category():
return "Vector"
def version():
return "Version 0.1"
def qgisMinimumVersion():
return "2.0"
def authorName():
return "Alexander Lisovenko"
def classFactory(iface):
from csv2ve... |
from selenium import webdriver
from openpyxl import Workbook, load_workbook
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import time
try:
wb = Workbook()
wb.save('vehicles.xlsx')
ws = w... |
import numpy as np
import math
from qcodes.instrument.base import Instrument
from qcodes import validators as vals
#%% Create funciton for two-qubit readout and spectroscopy
class MultiQ_PulseBuilder(Instrument):
def __init__(self,name,number_read_freqs,alazar,alazar_ctrl,awg,qubit,cavity,**kwargs):
supe... |
# ----------------------------------------------
# -*- coding: utf-8 -*-
# @Time : 2019-11-07 18:50
# @Author : 吴林江
# @Email : wulinjiang1@kingsoft.com
# @File : test-sanic.py
# ----------------------------------------------
from sanic import Sanic
from sanic import response
from pprint import pprint
app = S... |
import logging
from typing import Dict, Optional, Tuple
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from transformers import (
AutoModel,
AutoTokenizer,
PreTrainedModel,
PreTrainedTokenizerBase,
)
from clrcmd.utils import... |
from appium import webdriver
desired_caps = {
'platformName': 'Android',
'deviceName': 'emulator-5554',
'platformVersion': '7.0',
'appPackage': 'com.android.calculator2',
'appActivity': 'com.android.calculator2.Calculator'
}
driver = webdriver.Remote('http://localhost:4723/w... |
import pygame
from settings import SCREEN_WIDTH, SCREEN_HEIGHT
# FIXME: Bad naming
class Score:
global_score = 0
player_life = 3
@staticmethod
def add_score(score):
Score.global_score += score
@staticmethod
def draw_score(display_surface):
font = pygame.font.Font(None, 32)... |
from flask import Flask, render_template, request
from .utils.parser import Parser
from .utils.predictor import Predictor
from .config import API_KEY
from .database import database
import pyowm
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///clothes.db"
app.config["SQLALCHEMY_TRACK_MODIFICATI... |
import os
import json
# 根据key列表读取配置参数
def load_config(keys):
configs = {}
cur_path = os.path.dirname(__file__) + '/'
with open(cur_path + '../config/config.json', 'r', encoding='utf-8') as json_file:
json_obj = json.load(json_file)
for key in keys:
try:
configs[... |
from rest_framework import serializers
from .models import Book, Assignment, User
class AssignmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assignment
fields = ('id', 'user', 'book')
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
... |
import numpy as np
from math import ceil, floor
from random import shuffle
class Cluster:
"""
Immutable object containing properties of the cluster:
numIslands
nodesPerIsland
islandBandwidth
singleNodeBandwidth
"""
def __init__(self, numIslands=2, nodesPerIsland=8, islan... |
def add(param1, param2):
return param1 + param2
###
def centuryFromYear(year):
return year/100 + 1 if year%100 != 0 else year /100
###
def checkPalindrome(inputString):
return inputString == inputString[::-1]
###
def adjacentElementsProduct(inputArray):
output = - sys.maxint - 1
for i in range(1,... |
from channels.generic.websocket import WebsocketConsumer
import json
import time
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from lora_networks.models import Device_info, Device, Node
class LoraConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def d... |
import pytest
from yamlpath.enums import CollectorOperators
from yamlpath.path import CollectorTerms
class Test_path_CollectorTerms():
"""Tests for the CollectorTerms class."""
@pytest.mark.parametrize("path,operator,output", [
("abc", CollectorOperators.NONE, "(abc)"),
("abc", CollectorOperators.ADDITION, "+(... |
"""
Test ILPSolver in Cassiopeia.solver.
"""
import os
import unittest
import itertools
import networkx as nx
import numpy as np
import pandas as pd
import pathlib as pl
import cassiopeia as cas
from cassiopeia.solver.ILPSolver import ILPSolver
from cassiopeia.mixins import ILPSolverError
from cassiopeia.solver impor... |
import argparse
import json
import bisect
from itertools import chain
__FORMAT_TYPE__ = "bp-corpus"
__FORMAT_VERSION__ = "v8f"
IGNORE_QUAD_CLASS = True # applicable for Abstract events
class Corpus:
def __init__(self,data):
self.__corpus_id = data.get('corpus-id', '')
self.__format_type = data.ge... |
import hashlib
# obj = hashlib.md5(b"jflkasdjklfjaskljfdfjdsakljfklajslfjaskljfklasjklasj") # 加盐
# obj.update("123456".encode("utf-8")) # 把要加密的内容给md5
print(hashlib.md5(b"jflkasdjklfjaskljfdfjdsakljfklajslfjaskljfkcclasjklasj").hexdigest())
|
def no_of_pies(N,pie_weight,total_pie,rack_cap,total_rack):
count = N
if rack_cap >= pie_weight:
print N
return(N)
else:
total_pie = total_pie - max(pie_weight)
pie_weight.remove(max(pie_weight))
N = N-1
no_of_pies(N,pie_weight,total_pie,rack_cap,total_pie)
T = input()
for t in xrange(T):
N = inp... |
from datetime import date
from typing import List
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import RedirectResponse
from easydoc_api.config.config import app_config
from easydoc_api.models.api_models import BaseResponse, ResponseStatus
from easydoc_api.models.db_models import ExpenseByTime
... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from PIL import Image
from datetime import date
import dateutil
from django.core.files.storage import default_storage as storage
# Create your models here.
cla... |
#!/usr/bin/env python
from tthAnalysis.HiggsToTauTau.safe_root import ROOT
from tthAnalysis.HiggsToTauTau.common import SmartFormatter, logging
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf as backend_pdf
import os
import argparse
import collections
i... |
# Following map_filter_01.py
# Comprehension dictionnary
dic_number = {10112: 'jean', 15324: 'eric', 21654: 'martine'}
print(dic_number)
print('User with number 15324: {}'.format(dic_number[15324]))
print()
# Now we want to know the number for a name
# We are converting key to value and value to key
dic_nam... |
"""
Climate support for Toon thermostat.
Only for the rooted version.
configuration.yaml
climate:
- platform: toon_climate
name: Toon Thermostat
host: <IP_ADDRESS>
port: 80
scan_interval: 10
min_temp: 6.0
max_temp: 30.0
logger:
default: info
logs:
custom_co... |
# Generated by Django 3.0.5 on 2020-05-04 02:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0006_auto_20200426_2254'),
]
operations = [
migrations.AddField(
model_name='chapter',
name='game_icon',
... |
num_customers = [1,2,3,4,5,6,7,8,9,10]
# TODO: Fill in values for the variables below
print 'average of first 7: '+str(sum(num_customers[:7])/7)
print 'average of last 7: '+str(sum(num_customers[-7:])/7)
print 'max no: '+str(max(num_customers))
print 'min no: '+str(min(num_customers))
|
#!/usr/bin/env python
from bluepy import btle
import binascii
def dump_services(dev):
services = sorted(dev.services, key=lambda s: s.hndStart)
for s in services:
if s.hndStart == s.hndEnd:
continue
chars = s.getCharacteristics()
for i, c in enumerate(chars):
pr... |
import pytest
from otx.mpa import Stage
from otx.mpa.cls.stage import ClsStage
from tests.test_suite.e2e_test_system import e2e_pytest_unit
from tests.unit.algorithms.classification.test_helper import setup_mpa_task_parameters
class TestOTXClsStage:
@pytest.fixture(autouse=True)
def setup(self) -> None:
... |
from flask import Flask, render_template, request, redirect, json, url_for, request, abort
from flask_dance.contrib.google import make_google_blueprint, google
from flask_dance.contrib.github import make_github_blueprint, github
import os
import sqlite3
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
application ... |
import random
def name_to_number(name):
"""
Helper function to convert number to string
"""
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
... |
# Unit tests should be fast, isolated, and repeatable
# The response of the LUISE engine depends of a a specific context
# in the futur add a CI/CD workflows, batch testing
class test_retrieve_luis_intent(object):
'''
tests :
- mock the api call
- topIntent
- entities
- scores exceeds a t... |
import pandas
import requests
movies = pandas.read_csv('https://raw.githubusercontent.com/davidbailey/Notes/master/Movies.csv')
for movie in movies.Title:
r = requests.get('https://www.omdbapi.com/?t=' + movie)
print(r.json()['Title'], r.json()['Year'])
|
#!/usr/bin/env python3
"""
@author lsipii
"""
import sys, getopt
from flask import Flask
from apps.DeviceApp.DeviceApp import DeviceApp
from apps.DeviceApp.http.controllers.CoffeesHasWeController import CoffeesHasWeController
# Creates the device app
app = DeviceApp()
# Creates the flask router app
routerApp = Flask(_... |
import pandas as pd
import psycopg2
import sqlalchemy
import matplotlib as plt
#%matplotlib inline
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, database_exists, drop_database
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import bpy
from ..rig import RigInfo
class MHC_OT_PoseRightOperator(bpy.types.Operator):
"""This is a diagnostic operator, which poses both the capture & final armatures one frame at a time."""
bl_idname = 'mh_community.pose_right'
bl_label = 'Next Frame'
bl_... |
# -*- coding: utf-8 -*-
from app import db
import datetime
class Repo(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), index = True, unique = True)
path = db.Column(db.String(120), index = True, unique = True)
comment = db.Column(db.Text(), index = False, uniqu... |
# use dynamic programming, bottom up
# space O(n) if original data can't be overwritten
# time O(n^2), where n is the length of row
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if not triangle: return []
... |
from smartninja_nosql.odm import Model
class User(Model):
def __init__(self, id, name, email, secret_number, **kwargs):
self.id = id
self.name = name
self.email = email
self.secret_number = secret_number
super().__init__(**kwargs)
|
t = (3, 30, 2019, 9, 25)
hour = str(t[0]).zfill(2)
minutes = str(t[1]).zfill(2)
year = str(t[2]).zfill(4)
month = str(t[3]).zfill(2)
day = str(t[4]).zfill(2)
print("{month}/{day}/{year} {hour}:{minutes}".format(month=month, day=day, year=year, hour=hour, minutes=minutes)) |
import logging
from urllib import urlencode
<<<<<<< HEAD
from ewt.scraper import EWTScraper
=======
from EWTScraper import EWTScraper
>>>>>>> ace1da00fd9afc9f38280055e9751ec1562994bb
class FantasyFootballCalculatorScraper(EWTScraper):
'''
Obtains html content of NFL fantasy projections or ADP page of fantasy... |
import matplotlib.pyplot as plt
import numpy as np
'''
demonstrating a support whose dimension is lower than the space in which it is embedded
'''
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
'''
# Cylinder
x=np.linspace(-1, 1, 100)
z=np.linspace(0, 1.0/(2.0*3.14159), 100)
Xc, Zc=np.meshgrid(x, z)
Y... |
# Generated by Django 3.0.2 on 2020-06-28 21:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
... |
from django.core.cache import cache
from TechSekai.forms import RegisterDjangoUserForm, LoginDjangoUserForm
from TechSekai.models import *
from TechSekai.templatetags.auth_extras import *
def category_context_processor(request):
categories = cache.get('categories')
if not categories:
categories = Cat... |
from flask import Flask
from flask import render_template, request
from function import artist_data, get_recommandation, recommandation_for_you, for_you, for_you_sim
import pandas as pd
import numpy as np
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def index():
artist = artist_data()
if r... |
def switch(a, n):
d = ""
for x in reversed(a[:n]):
d += x
d2 = ""
for l in d:
if l=="+":
d2 += "-"
else:
d2 += "+"
for q in a[n:]:
d2 += q
return d2
with open("/Users/danielvebman/Downloads/pancake.in.txt", "r") as input:
cases = []
for line in input:
if "+" in line.rstrip() or "-" in line.... |
# -*- coding: utf-8 -*-
import pymysql
from maotuying_test import settings
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MaotuyingTestPipeline(object):
def __init__(self):
self.c... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 an... |
"""
Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
"""
def remove_duplicate_characters(string):
unique_chars_c... |
# Generated by Django 3.1.7 on 2021-03-26 10:53
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Gallery',
fields=[
('id', model... |
# encoding UTF-8
# Autor: Mauricio Medrano Castro, A01272273
# Calcular el costo de la renta de peliculas de estreno y normales
def calcularRenta(numeroEstrenos,numeroNormales): #calcula el total por pagar por las peliculas estrenadas y normales
numeroEstrenos = numeroEstrenos * 45
numeroNormales =... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
# https://leetcode.com/problems/insert-interval/
class Solution(object):
def insert(self, intervals, new):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
# find last idx nums[idx][1] < interval[0]
# find first idx... |
no_of_properties = 5
no_of_combinations = 5
no_of_rules = 15
properties = [["Red", "Green", "Yellow", "Blue", "White"], ["Dogs", "Cats", "Fish", "Birds", "Horses"], ["Tea", "Water", "Beer", "Milk", "Coffee"], ["Brit", "Swede", "Dane", "Norwegian", "German"], ["Pall Mall", "Dunhill", "Blend", "Bluemaster", "Prince"]]
re... |
# %%
import re
import sys
import os
import glob
from collections import Counter
from quantities import units
from quantities.units.area import D
from quantities.unitquantity import UnitQuantity as UQ
import scipy
import pandas as pd
import spacy
import corenlp
import sklearn_crfsuite
from sklearn.model_selection impo... |
# Предложить пользователю ввести ряд чисел, разделяя их пробелом;
# Посчитать количество четных и нечетных чисел введенных пользователем;
# Вывести на экран сообщение с количеством четных и нечетных чисел.
# Подсказка, чтобы проверить четность или нечетность числа, нужно узнать его остаток от деления на 2.
# Четное чи... |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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... |
from boltons import dictutils
alcoholic_drinks = [
("distilled", "Gin"),
("undistilled", "Beer"),
("distilled", "Brandy"),
("distilled", "Whiskey"),
("undistilled", "Wine"),
("distilled", "Rum"),
("undistilled", "Hard Cider"),
("distilled", "Rum"),
("undistilled", "Hard Cider"),
... |
"""
This type stub file was generated by pyright.
"""
from .vtkAbstractWidget import vtkAbstractWidget
class vtkPolyLineWidget(vtkAbstractWidget):
"""
vtkPolyLineWidget - widget for vtkPolyLineRepresentation.
Superclass: vtkAbstractWidget
vtkPolyLineWidget is the vtkAbstractWidget subclass f... |
import logging
import re
import networkx as nx
import matplotlib.pyplot as plt
import os
import pathlib
import copy
import pygraphviz
import math
from datetime import datetime
def add_root(G, maxnode):
"""
break the edge between the max node and next largest node connected to max node
insert a rootnode ... |
# Generated by Django 2.0.6 on 2018-10-25 20:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('moretvtime', '0008_auto_20181024_2328'),
]
operations = [
migrations.CreateModel(
name='TrackingSummary',
... |
from flask import Flask, render_template, request, redirect
from flask import Blueprint
from models.booking import Booking
import repositories.booking_repository as booking_repository
import repositories.member_repository as member_repository
import repositories.yogaclass_repository as yogaclass_repository
bookings_bl... |
import platform
import sys
import os
dir = os.path.dirname(os.path.realpath(__file__ ))
sys.path.append(dir)
from robots import Wikipedia
from robots import Diretorios
from robots import Text_Robots
from robots import Docx
if __name__ == '__main__':
def clear():
so = platform.system()
if so == 'Wi... |
#!/usr/bin/python
import os
import urllib2
import numpy as np
import theano
import theano.tensor as T
import pdb
#from ipdb import set_trace
def download_embeddings(embbeding_name, target_file):
'''
Downloads file through http with progress report
Obtained in stack overflow:
http://stackoverflow.... |
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
from gym.spaces import Dict
from rllab.misc.instrument import VariantGenerator
import rlkit.torch.pytorch_util as ptu
from rlkit.envs.wrappers import NormalizedBoxEnv
from rlkit.launchers.launcher_util import setup_logger, set_se... |
import sys
inputs = sys.stdin.readline().split()
a = int(inputs[0])
b = int(inputs[1])
if (b == 1):
print a
exit()
div = a / b
result = div
a = a - div * b
while (True):
b = b - a
result += 1
if (b == 1):
result += a/b
break
div = a / b
result += div
a = a - div * b
... |
# -*- coding: utf-8 -*-
"""
Kakao Hangul Analyzer III
__version__ = '0.4'
__author__ = 'Kakao Corp.'
__copyright__ = 'Copyright (C) 2018-, Kakao Corp. All rights reserved.'
__license__ = 'Apache 2.0'
__maintainer__ = 'Jamie'
__email__ = 'jamie.lim@kakaocorp.com'
"""
###########
# imports #
###########
from distuti... |
import PySimpleGUI as sg
from operator import itemgetter
from src.enums.guiState import GuiState
from src.enums.modelType import ModelType
from src.enums.scalerType import ScalerType
from src.helpers.datasetHelper import DatasetHelper
from src.helpers.plotterHelper import PlotterHelper
from src.models.dataset import D... |
#operadores aritméticos
# Soma 5+2==
# Subtração 5-2==
# Multiplicação 5*2==
# Divisão 5/2==
# Potenciação 5**2==
# Divisão Inteira 5//2==
# Resto da Divisão (módulo) 5%2==
# Exemplo: 5+3*2==11 5+(3*2)
# Exemplo: 3*5+4**2==31 ((3*5)+(4**2))
# Exemplo: 3*(5+4)**2==243
|
from utilities import *
def read_diary(day=time.strftime('%d'),month=time.strftime('%m'),year=time.strftime('%Y')):
try:
filename="diary/"+day+"_"+month+"_"+year+".wav1"
play_wav(filename)
except IOError:
voice("Oops! Couldnot find, a diary entry, for,this date!")
read_diary('22','07','2017')
|
# Generated by Django 2.1 on 2018-09-03 00:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20180902_1817'),
]
operations = [
migrations.RemoveField(
model_name='events',
name='city',
),
... |
# Generated by Django 3.1.7 on 2021-04-10 08:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account_profile', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='awardhistory',
name='create_time',
... |
from flask import Flask, request, render_template
from datetime import datetime
from pytz import timezone
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index_06.html")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.