text stringlengths 38 1.54M |
|---|
"""Module managing the whole air drums process."""
from collections import deque
import logging
from threading import Thread
import sys
import drums.settings
from drums.drum_set import DrumSet
from drums.streaming import InputVideoStream, OutputVideoStream
from drums.tracker import Tracker
LOG = logging.getLogger(_... |
import configparser
config = configparser.ConfigParser() # 创建对象
config.read("config.ini", encoding="utf-8") # 读取配置文件,如果配置文件不存在则创建
def getKeysValue(section):
return config.items(section)
def getsystemIndex():
return int(config.get('system', 'index')) # 获取指定节点的指定key的value
def setsystemIndex(index):
... |
from config import db, login_manager
from flask_login import UserMixin
collects = db.Table('collects',
db.Column('listId', db.Integer, db.ForeignKey('list.id'), primary_key=True),
db.Column('productId', db.Integer, db.ForeignKey('product.id'), primary_key=True)
)
class User_own_product(db.Model):
__tablen... |
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied
from django.db.models import Sum
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, I... |
import numpy as np
from astropy import constants as cte
from astropy import units
from astropy.io import fits
import matplotlib.pyplot as plt
import sys
############################################################
# Q_phi
#hdulist=fits.open("PDS_70_2016-03-26_QPHI_CROPPED.fits")
#data=hdulist[0].data
###############... |
from eulerlib import primes
from eulerlib import Divisors
from math import sqrt
import itertools
def isPrime(n):
if n <= 1:
return False
else:
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
#43
"""
dig=[0,1,2,3,4... |
from hy.core.language import flatten
from pprint import pprint
from sparql import dbpedia_sparql
from colorize import colorize_sparql
def dbpedia_get_relationships(s_uri, o_uri):
query = (
"SELECT DISTINCT ?p {{ {} ?p {} . FILTER (!regex(str(?p), 'wikiPage', 'i')) }} LIMIT 5"
.format(s_uri, o_uri... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2016 Contributor
#
# 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... |
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.activations import *
from keras.losses import *
from keras.datasets import *
from keras.metrics import *
from keras.callbacks import *
import theano
import numpy as np
import keras
experiment_name="_2CONVNET2_... |
def split(str):
word_len = len(str)
#start_idx, end_idx, len_square
dp = [[0, 0, 0]]
for i in range (1, word_len + 1):
splits = dp[max(0, i - max_word_len):i]
max_split = [0, i, 0]
for s in splits:
sufix = str[s[1]:i]
if sufix in words_len_square:
... |
#!/usr/bin/env python
# ARTIST Benchmarking Controller
# Copyright 2014 Engineering Ingegneria Informatica S.p.A.
#
# 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/lic... |
from typing import List, Dict
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
if not intervals:
return [newInterval]
res = []
i = 0
while intervals[i][1] < newInterval[0]:
res.append(intervals[... |
from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple
from grobber.anime import SourceAnime
from grobber.anime.group import AnimeGroup
from grobber.uid import MediumType, UID
from .medium import Medium, MediumData, medium_from_document, source_anime_from_medium
__all__ = ["MediumGroup",
... |
def main():
#escribe tu código abajo de esta línea
a = float(input("Calificación de la materia: "))
b = float(input("Calificación de la materia: "))
c = float(input("Calificación de la materia: "))
d = float(input("Calificación de la materia: "))
prom = (a + b + c + d) / 4
print("El promedio... |
# Generated by Django 3.1.8 on 2021-05-03 09:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("coop", "0003_auto_20210411_1012"),
]
operations = [
migrations.AddField(
model_name="draftuser",
name="phone_number"... |
from django.forms import ModelForm
from .models import Scooter
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class ScooterForm(ModelForm):
class Meta:
model= Scooter
fields= ['serial_number','brand', 'city', 'helmet', 'st... |
#!/usr/bin/python
import os
import math
def computeEff(names):
# Loop on the first file to initialize the map
effs={}
file = open("parallelCutEfficiency_"+names[0]+".txt")
for line in file:
effs[line.split()[0]] = float(line.split()[1])
# print effs[line.split()[0]]
# Loop on the ... |
def slice_bananas(count: int) -> int:
return 10 * count
def make_smoothies(pieces: int) -> str:
return f"{pieces} smoothies"
def make_cider(count: int) -> str:
return f"{count} cider"
def make_lemonade(count: int) -> str:
return f"{count} lemonade"
def main() -> None:
fresh_fruit = {
... |
from researcher import Researcher
import json,os
from elasticsearch_dsl.connections import connections
# Define a default Elasticsearch client
connections.create_connection(hosts=['localhost'])
Researcher.init()
path = os.path.realpath('../ScrapeResearchGate/scrapy_RG')
path = path + "/members_url_instit_loc_exp.js... |
import argparse
from pathlib import Path
from vocab import Vocab
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from dataset import Pix2CodeDataset
from utils import collate_fn, save_model, ids_to_tokens, generate_visualization_object, resnet_img_transformation
from models impor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frontend.models import *
from django.template.response import TemplateResponse
from django.contrib.auth import get_user_model
from mezzanine.utils.views import paginate, is_spam, set_cookie
from mezzanine.conf import settings
from django.utils.transl... |
import re
import os
import errno
from urlparse import urljoin
from urlparse import urlparse
from py_quick_crawlers.constants import Regex
class URLUtils(object):
@staticmethod
def get_domain(url):
match = Regex.PT_DOMAIN_FROM_URL.match(url)
if not match:
raise InvalidArgumentErro... |
from numpy import array
from pyspark.mllib.linalg import Vectors
# 创建稠密向量<1.0, 2.0, 3.0>
denseVec1 = array([1.0, 2.0, 3.0]) # NumPy数组可以直接传给MLlib
denseVec2 = Vectors.dense([1.0, 2.0, 3.0]) # 使用Vectors类来创建
print(denseVec1)
print(denseVec2)
# 创建稀疏向量<1.0, 0.0, 2.0, 0.0>;该方法只接收
# 向量的维度(4)以及非零位的位置和对应的值
# 这些数据可以用... |
#
# tcp.py
#
# Written by Franco Gasperino <franco.gasperino@gmail.com>, 2016
#
"""
Input generator which consumes an lazy sequence of content from a TCP socket.
"""
import socket
from demo.input import filelike
def consume(address='127.0.0.1', port=9990):
"""
Lazily read a TCP/IP client as a file-like obj... |
'''
CosmoSpectra package is meant for Fourier analysis of cosmological simulations.
One can also get documentation for all routines directory from
the interpreter using Python's built-in help() function.
For example:
>>> import cosmospectra as cs
>>> help(cs.power_spect_1d)
Python's built-in dir() function can be use... |
#!/usr/bin/env python3
import sys
import os
import numpy as np
from sklearn.metrics import accuracy_score
from utils.tfpkg.models import Evaluator
from utils.io import read_pkl
from utils.location import distance
model_path = sys.argv[1]
nodes = read_pkl('tmp/nodes.pkl')
loc_db = read_pkl('tmp/location.pkl')
candid... |
"""agenda URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.pet, name='pet')
Class-based vi... |
#!/usr/bin/env python3
from pathlib import Path
import setuptools
project_dir = Path(__file__).parent
setuptools.setup(
name="sierraecg",
version="0.2.1",
description="Sierra ECG Tools for Python",
# Use UTF-8 encoding for README even on Windows by using the encoding argument.
long_description=p... |
#Autor: guilleCM
#coding=utf-8
#Enunciado:
#Crea una función que transfigura las columnas de una matriz en una nueva
#lista de filas, es decir las filas de la nueva lista creada deben
#corresponderse a los valores de las columnas de la matriz dada.
#CASOS TEST#
#Para la siguiente lista:
#print (columnasMatriz ([[1,... |
#!/usr/bin/env python
import sys
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("TopTitleStatistics")
conf.set("spark.driver.bindAddress", "127.0.0.1")
sc = SparkContext(conf = conf)
lines = sc.textFile(sys.argv[1],1)
counts = lines.map(lambda line: int(line.strip().spli... |
def inp():
dna1 = input()
dna2 = input()
return dna1, dna2
def main(dna1, dna2):
first_index = second_index = min(len(dna1), len(dna2))
for i, (a, b) in enumerate(zip(dna1, dna2)):
if a != b:
first_index = i
break
second_index -= first_index
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
class Company(models.Model):
_inherit = "res.company"
_check_company_auto = True
def _default_confirmation_mail_template(self):
try:
return self.... |
#!/usr/bin/python
import datetime
from argparse import Namespace
import code
import operator, collections, re, argparse
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.db import models
import contacts.models as cont
import command_utils
from transports.e... |
import random
def main():
times = ["утром", "днём", "вечером", "ночью", "после обеда", "перед сном"]
advices = ["ожидайте", "предостерегайтесь", "будьте открыты для"]
promises = ["гостей из забытого прошлого", "встреч со старыми знакомыми",
"неожиданного праздника", "приятных перемен"]
generated_pr... |
# -*- coding: utf-8 -*-
import json
from django.core.management import call_command
from django.test.client import Client
from django.test.utils import override_settings
from django.utils import unittest
from django.conf import settings
from ikwen.accesscontrol.models import Member
from ikwen.accesscontrol.backends i... |
# performs nmap scan on given ip address
import os
def nmap(options, ip):
"""executes nmap tool upon given ip address"""
command = "nmap " + options + " " + ip
process = os.popen(command) # opens command line and executes nmap
results = str(process.read())
return results
|
import numpy as np
from .controller import Controller
class Damping(Controller):
""" Base class for common null space controllers.
Parameters
----------
robot_config : class instance
contains all relevant information about the arm
such as: number of joints, number of links, mass infor... |
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
fname = models.CharField(max_length=255)
lname = models.CharField(max_length=255)
email = models.CharField(max_length=255)
def __repr__(self):
return "<User: {}|{} {} {}>".format(self.id, self.fname... |
def main():
of = open('lastword-large.out', 'w', 1)
with open('A-large.in', 'r') as f:
count = int(f.readline().rstrip('\n'))
for i in range(count):
line = f.readline().rstrip('\n')
string = line
output = ''
for ch in string:
... |
#!/usr/bin/env python3
from __future__ import with_statement
import time
import numpy as np
import math
import random
import collections
from PyQt4.uic import loadUi
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
<<<<<<< HEAD
#from lantz.ui.qtwidgets import connect_driver
#from lantz import Q_
#
#um ... |
# coding=gb2312
__author__ = 'xuxin'
def h():
#²âتش
print 'test1'
yield 5
print 'test2'
c = h()
# c.next() |
import sys
import csv
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("lp_files", help="The label pair need to be converted")
parser.add_argument("dir2pubmed", help="The directory to the place for pubmed articles")
parser.add_argument('out_path', help="The path to store finaltraining ... |
# -*- coding:utf-8 _*-
"""
@author:zhangjianlang
@file: StartReportServer.py
@time: 2019/9/19 11:12
"""
import os
def startserver(parent_path):
# current_path = os.path.dirname(__file__) # 脚本目录
# parent_path = os.path.dirname(current_path) # 上级目录,即项目根目录
goto_report = 'cd ' + parent_path + r"/report" # ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-09 23:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Store', '0007_auto_20160609_1652'),
]
operations = [
migrations.AlterField(
... |
import pytz
import datetime
country = "Africa/Lagos"
tz_to_display = pytz.timezone(country)
local_time = datetime.datetime.now(tz=tz_to_display)
print(f'The time in {country} is: ', local_time)
print(f'UTC is {datetime.datetime.utcnow()}')
# for countries in pytz.all_timezones:
# print(countries)
|
# the HTML parser
from html.parser import HTMLParser
class SOSParser(HTMLParser):
header_list = []
parse_header = False
parse_title = False
parse_summary = False
summary = ''
title = ''
def clear(self):
self.header_list = []
self.title = ''
self.summary = ''
d... |
import sklearn.ensemble as es
import sklearn.preprocessing as pp
from sklearn.grid_search import RandomizedSearchCV, GridSearchCV
import numpy as np
class Trainer(object):
def __init__(self, model, data_to_train, features, target):
self.model = model
self.y = data_to_train[target].values
s... |
#!/usr/bin/python3
import array
import string
#Taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
... |
# Generated by Django 3.0.3 on 2020-07-05 19:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0004_auto_20200705_1919'),
]
operations = [
migrations.AlterField(
model_name='stock',
name='arrival_date',... |
#!/usr/bin/python
## Import Python package modules
import sys, getopt, os, random
def parse_options(argv):
opts, _args = getopt.getopt(argv[1:], "hi:o:",
["help",
"input-file",
"output-file"])
output_filename = ... |
def findAndReplace(words):
index=words.find('day');
words=words.replace("day","month", 1);
print("Index of the word day: " + str(index))
print(words)
# function run here
def minAndMax(list):
print("Max is: "+ str(max(list)))
print("Min is: "+ str(min(list)))
def firstAndlast(list):
print("first and l... |
# External Libraries
import unittest
import pandas as pd
import sys,os
sys.path.append(os.pardir)
# Internal Libraries
import Algorithms.Utilities.DataFrameChecker as dc
class TestDataFrameChecker(unittest.TestCase):
def test_is_df_num(self):
df = pd.read_csv('Data/numeric.csv',header=0)
self.asse... |
import json
x = json.loads('{"bar":["baz", null, 1.0, 2]}')
x["f"] = "k"
print(x) #{'bar': ['baz', None, 1.0, 2], 'f': 'k'}
print(json.dumps({"name": "John", "age": 30})) #'{"name": "John", "age": 30}'
print(json.dumps(["apple", "bananas"]))#'["apple", "bananas"]
print(json.dumps(("apple", "bananas")))#'["apple", "ban... |
#!/usr/bin/env
############################################
# exercise_11_pipeline.py
# Author: Paul Yang
# Date: June, 2016
# Brief:
############################################
wwwlog = open("access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
bytes = (int(x) for x in bytecolumn if x != '-')
p... |
import math
T = int(input())
for _ in range(T):
x, y = [int(x) for x in input().split()]
if y > x:
print('2')
else:
k = x // y
if (k % y) != 0:
k += 1
print(k) |
from ChessPiece import ChessPiece
class Knight(ChessPiece):
def __init__(self, color, x, y):
"""This method initiliaze Knight's attributes and rules.
Parameters
----------
color : string
Color of Knight.
x : int
Location x of Knight.
y : int
... |
import hashlib
import random
import secrets
import time
import json
class Transaction:
def __init__(self,voterId,candidateId):
self.voterId=voterId
self.salt=secrets.token_hex(5)
self.candidateHash=hashlib.sha256((str(candidateId)+str(self.salt)).encode()).hexdigest()
def displayEmployee(self):
print("Vote... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#import uniout
import pandas as pd
from os import listdir
from os.path import isfile, isdir, join
import numpy
import os
import obspy
from obspy.core import read
import glob
import numpy as np
import csv
# 指定要列出所有檔案的目錄
data_path = 'D:\\test\\Application_Math\\Oil'... |
# coding=utf-8
# http://blog.csdn.net/beckel/article/details/3945147
# function with decorator
'''
@A(args)
def f ():
......
Python will convert the below into:
def f():
......
_deco = A(args)
f = _deco(f)
'''
from __future__ import print_function
import logging
LOG = loggi... |
# Apurva Badithela
# 7/21/2020
# Folder to connect noisy black-box tree search with robust satisfaction value and falsification
|
from ann.activation import SigmoidActivation
from ann.ann import AbstractAnnFactory
from ann.layer import Layer, CtrnnLayer
from ann.network import Network, CtrnnNetwork
from ann.neuron import CtrnnNeuron
class BeerTrackerAnnFactory(AbstractAnnFactory):
def create(self, pull_extension, wraparound):
activa... |
import math
import time
import logging as log
import numpy as np
import tags
import database as db
_questions = []
_descriptions = []
def ask(question_id, object, game, answer_data, answers, pO, Pi, p_tags, objects):
"""
Ask a question
"""
# Takes best question and updates all object probabilies based on the a... |
# -*- coding: utf-8 -*-
'''
线上环境的环境变量,主要是mysql和mongo接口
'''
import logging
from default import Config
class ProdConfig(Config):
LOG_TO_FILE = True
LOG_LEVEL = logging.INFO
# 存放推荐点信息的mysql,使用的是sqlalchemy连接字符串
DB_URL = "mysql+pymysql://geo_pickups:123qwe,./@gut1.epcs.bj2.yongche.com:3306/geo_pickups?c... |
'''
URLify: Write a method to replace all spaces in a string with '%20'.
You may assume that the string has sufficient space at the end to hold the additional characters,
and that you are given the "true" length of the string. (Note: If implementing in Java,
please use a character array so that you can perform this ope... |
from flair.data import Corpus
from flair.datasets import ColumnCorpus
from flair.embeddings import TokenEmbeddings, TransformerWordEmbeddings, StackedEmbeddings
from flair.models import SequenceTagger
from flair.trainers import ModelTrainer
from typing import List
from pathlib import Path
class FlairTrainer:
def ... |
from tests.testcases.test_base import TestBase
from core.element.base_element import BaseElement
import pytest
class TestAndroid(TestBase):
@pytest.mark.mobile_native
def test_android_01(self):
graphics = BaseElement('accessibility_id=Graphics')
graphics.wait_for_visible()
graphic... |
from __future__ import print_function, absolute_import
import os
import time
import sys
import glob
import argparse
import numpy as np
import matplotlib as mpl
mpl.rcParams['mathtext.fontset'] = 'cm'
mpl.rcParams['mathtext.rm'] = 'serif'
mpl.use("Agg")
import matplotlib.pyplot as plt
import mdtraj as md
import simula... |
# Import and Initialize Sentiment Analyzer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
for filepath in ["Sample1.txt", "Sample2.txt", "Sample3.txt"]:
with open(filepath, 'r') as input_file:
sample = input_file.read()
compound = analyzer.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Leopold Schabel
# This file is part of MetaWatch Simulator.
#
# This software is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, eith... |
#!/usr/bin/env python
import pdf_translator, os.path
file_to_translate = ""
while True:
file_to_translate = raw_input("PDF File To Translate : ")
if os.path.exists(file_to_translate):
break
else:
print("[-] The Indicated File Does Not Exist")
continue
output_path = raw_input("Outp... |
import findapet
state = 'NO_QUERY'
context = {}
# findapet = findapet.py file
# findapet.ON_ENTER_STATE function
# state defined @ top as 'no_query
# it returns context = no_query_on_enter_state
# findapet.ON_ENTER_STATE['NO_QUERY'] = findapet.no_query_on_enter_state
func = findapet.ON_ENTER_STATE[state] # ... |
ilksayi = 1
ikincisayi = 1
fibo = [ilksayi , ikincisayi]
for i in range(0,20):
ilksayi,ikincisayi = ikincisayi,ilksayi + ikincisayi
fibo.append(ikincisayi)
print(fibo) |
import requests
import urllib3
import sys
from base64 import b64encode
#urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
#proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
try:
HOST = "http://" + sys.argv[1]
BTPATH = "/" + sys.argv[2]
USERNAME = sys.argv[3]
... |
# -*- coding: utf-8 -*-
__author__ = 'florije'
import urllib, json
import urllib.parse, urllib.request
query_args = {'pass': 'b6ce159334e155d8',
'word': 'U2FsdGVkX1/7IVjirkhwvDYzNDPDDyiDWbXHmETFG3+RlJtHwYBtXUL+tr3Gbu17/xak/TACBGRpGfsbEQdnnuwAGmVtf36QRsMHUWNv5hbyQ/+Ymf/J5REE94DfRqQUvOjeh6lbGz4VoblsXK54Aq... |
# 279. Perfect Squares
# Runtime: 168 ms, faster than 91.50% of Python3 online submissions for Perfect Squares.
# Memory Usage: 15.1 MB, less than 33.64% of Python3 online submissions for Perfect Squares.
class Solution:
# Greedy Tree | Breadth-First Search
def numSquares(self, n: int) -> int:
squar... |
#!/usr/bin/python3.6
import soundcloud as sc
import random
# Id of user which followers you would follow
reference_user_id = 1
token = 'access_token'
client = sc.Client(access_token=token)
me = client.get('me')
# Here you put comments you'd like to put on tracks while following
comments = []
with open('reject.txt',... |
from os.path import basename
import os
import glob
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import csv
from preprocessing import load_data, load_obj, device
from train import Car196Dataset
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argumen... |
def command(args):
import os
import subprocess
import sys
from sr.tools.inventory import assetcode
from sr.tools.inventory.inventory import get_inventory
inv = get_inventory()
cwd = os.getcwd()
parts = []
for c in args.assetcodes:
code = assetcode.normalise(c)
try... |
from django.db import models
from django.contrib.auth.models import User
import datetime
class Player(models.Model):
""" Defines additional skills, knowledge, etc. regarding staff members
"""
user = models.ForeignKey(User, unique=True)
hp = models.IntegerField()
xp = models.IntegerField()
curre... |
from services import func_timer
A = [25, 1, 19, 22, 9, 18, 30, 24, 34, 25, 49, 15, 13, 10, 1, 0, 32, 6, 40, 34]
@func_timer
def insertion_sort(sort_list: list) -> list:
for i in range(1, len(sort_list)):
while sort_list[i] < sort_list[i - 1] and i != 0:
sort_list[i - 1], sort_list[i] = sort_l... |
primero=int(input("Introduce un número: "));
segundo=int(input("Introduce otro número: "));
if primero<segundo:
for i in range (primero, segundo):
if i%2==0:
print ("El número %d es par" %(i));
else:
print ("El número %d es impar" %(i));
elif segundo<primero:
for i in ran... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018/11/23 13:57 @Author : xycfree
# @Descript:
from coinmarketcap import Market
from pyalgotrade import logger as log
logger = log.getLogger("common")
def base_usdt_price(coin=''):
""" Valid cryptocurrency values are: "BTC", "ETH" "XRP", "LTC", and... |
""" RNN """
import numpy as np
import math
import os
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.models import model_from_json
# Used to limit accurecy for those trying to repoduce our results.
np.random.seed(... |
trainingSet, testSet = train_test_split(data, test_size=0.2)
sample = testSet.tail(10)
sample2 = testSet.head(10)
print(sample.reset_index(drop=True))
print(sample2.reset_index(drop=True))
result = DataFrame({'class': []})
result = sample.reset_index(drop=True)['class'] ==sample2.reset_index(drop=True)['class']
print(r... |
def sum(numbers):
n = len(numbers)
if n <= 0:
return 0
return sum(numbers[0: n - 1]) + numbers[n - 1] |
import random
import numpy as np
from scipy.misc import imresize
from cv2 import integral
from modules.datastructures.patch import Patch
def get_downsampled(img):
ret = imresize(img, (24, 24))
return ret
def get_integral_image(img):
return integral(img)
def to_rgb(im):
# as 3a, but we add an extr... |
# Generated by Django 2.0.1 on 2018-06-25 23:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kvasaheim', '0008_auto_20180625_1117'),
]
operations = [
migrations.AlterField(
model_name='problem',
name='equation... |
import torch
from torch.nn import Module
from torch.nn import Sequential
from torch.nn import Conv2d, Dropout2d, MaxPool2d, ReLU, UpsamplingNearest2d
# Based on https://github.com/divamgupta/image-segmentation-keras/blob/master/keras_segmentation/models/unet.py#L19
class UNetMini(Module):
def __init__(self, num_... |
from StatisticFunctions.Mean import Mean
from MathOperations.Division import Division
from MathOperations.Addition import Addition
class MeanDeviation:
@staticmethod
def meanDev(data):
newlist = []
meanOfData = Mean.mean(data)
for i in data:
newlist.append(abs(i - meanOfDa... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import sys
from twi... |
#visualising top 100 most, least and mid frequent words using t-SNE
from tsne import *
from numpy import array
word_vectors = []
path_vec_file = '/mnt/filer01/word2vec/twitter_vectors.txt'
word_vector_dim = 200
labels = dict()
X_word = []
windex=0
with open(path_vec_file, 'rb') as fr:
next(fr)
for line... |
# noxfile.py
import nox
locations = "src", "noxfile.py"
@nox.session(python=["3.7"])
def lint(session):
args = session.posargs or locations
session.install("flake8")
session.run("flake8", *args)
@nox.session(python="3.7")
def black(session):
args = session.posargs or locations
session.install("... |
from django.urls import path
from .views import *
urlpatterns = [
path('contact/', ContactCreateView.as_view()),
path('newsletter/', NewsletterCreateView.as_view()),
path('report/', ReportCreateView.as_view()),
] |
from firebase import firebase
class MyDb:
def get_user(id):
fb = firebase.FirebaseApplication(dsn='https://sandbox-dannel.firebaseio.com', authentication=None)
result = fb.get('/users', None)
return result |
from django.db import models
class Author(models.Model):
firstName = models.CharField(max_length=64)
lastName = models.CharField(max_length=64)
def __str__(self):
return "%s %s" % (self.firstName, self.lastName)
def __unicode__(self):
return "%s %s" % (self.firstName, self.lastName)
... |
#!/usr/bin/python3
import paramiko, sys, getpass
if len(sys.argv) > 1:
hostname = sys.argv[1]
username = sys.argv[2]
message = sys.argv[3]
password = getpass.getpass()
else:
(hostname,username,password)=('192.168.90.20','vagrant','vagrant')
message='default values'
client = paramiko.SSHClient()
client.set_miss... |
from Graph import DirectedGraph
class DetectCycle(DirectedGraph):
def __init__(self):
DirectedGraph.__init__(self)
def clearGraph(self):
DirectedGraph.__init__(self)
def isCycle(self, start):
visited = [False] * (self.V+1)
recStack = [False] * (self.V+1)
print('Contain Cycle') if self.DFS(start, v... |
# coding: utf-8
# In[2]:
get_ipython().magic('matplotlib notebook')
import numpy as np
import matplotlib.pyplot as plt
from time import time
import sys
import pyDOE
get_ipython().magic('load_ext autoreload')
get_ipython().magic('autoreload 2')
# In[3]:
### FOR DATA REPRODUCTIBILITY
### RANDOMSEED = 2662 ### f... |
# Buchhaim Stage 1
# Basic Roguelike
import tkinter as tk
from gameworld import GameWorld
def main():
root = tk.Tk()
root.title("In den Labyrinthen von Buchhaim")
root.resizable(0, 0)
gameworld = GameWorld(root)
gameworld.mainloop()
if __name__ == "__main__":
main()
|
import sys
import pytest
sys.path.append('src/compiler')
from js_parser import javascript_parser
from antlr4 import *
test_paths = [
("example/example9.js", "src/compiler/test/codegen-test/right-test1.txt"),
("example/example10.js", "src/compiler/test/codegen-test/right-test2.txt"),
("example/example11.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.