content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
def uncentime(jours):
total = [0.01]
for i in range(jours - 1):
total.append(total[-1] * 2)
return sum(total)
print(uncentime(30))
| nilq/baby-python | python |
a=1
for i in range(int(input())):
print(f"{a} {a+1} {a+2} PUM")
a+=4
| nilq/baby-python | python |
import pandas as pd
class Security():
'''
Generic Class that initializes an object to hold price and volume
data on a particular financial security.
'''
def __init__(self, dataframe, security_name, ticker):
'''
Arguments
---------
dataframe Pandas Dataframe. Co... | nilq/baby-python | python |
from pprint import pprint
from intentBox import IntentAssistant
i = IntentAssistant()
i.load_folder("test/intents")
print("\nADAPT:")
pprint(i.adapt_intents)
print("\nPADATIOUS:")
pprint(i.padatious_intents)
print("\nFUZZY MATCH:")
pprint(i.fuzzy_intents)
| nilq/baby-python | python |
"""
1013 : Contact
URL : https://www.acmicpc.net/problem/1013
Input :
3
10010111
011000100110001
0110001011001
Output :
NO
NO
YES
"""
def test(s):
if len(s) == 0:
return True
if s.startswith('10'):
i = 2
if i >= ... | nilq/baby-python | python |
"""
Simple API implementation within a single GET request.
Generally wrap these in a docker container and could deploy to cluster.
I use cherryPy because it was so simple to run, but heard Flask was pretty
good. So I decided to give it a try.
Wanted to try out connecting pymongo to flask, but was spending too much tim... | nilq/baby-python | python |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# 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 ... | nilq/baby-python | python |
import enum
from EoraReader import EoraReader
from PrimaryInputs import PrimaryInputs
from DomesticTransactions import DomesticTransactions
from os import listdir
from os.path import isfile, join
import pandas as pd
class CountryTableSegment(enum.Enum):
DomesticTransations = 1
PrimaryInputs = 2
class CountryTab... | nilq/baby-python | python |
from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import E... | nilq/baby-python | python |
"""
@author: Jim
@project: DataBrain
@file: exceptions.py
@time: 2020/10/4 17:03
@desc:
"""
class StopException(BaseException):
""" 停止爬
"""
pass | nilq/baby-python | python |
import matplotlib
matplotlib.use('Agg')
import numpy as np, scipy as sci, os, pylab as pyl, sys, smtplib
from trippy import pill
from glob import glob
from astropy.io import fits
from astropy.wcs import WCS
from datetime import datetime, timedelta
# Send email.
def sendemail(from_addr, to_addr_list, cc_addr_... | nilq/baby-python | python |
import collections
import dataclasses
import gc
import multiprocessing
import os
import traceback
from multiprocessing import Lock, Pipe, Pool, Process, Value
from typing import Any, Callable, Dict, Iterable, List, Tuple
from .exceptions import (UnidentifiedMessageReceivedError,
WorkerHasNoUse... | nilq/baby-python | python |
from collections import defaultdict
import numpy as np
import torch
class Filter(object):
def __init__(self):
pass
def __call__(self, cube_acts, **kwargs):
'''
Perform filter on an `activity_spec.CubeActivities` object,
returns a filtered `activity_spec.CubeActivities` object... | nilq/baby-python | python |
import argparse
import numpy as np
import time
import torch
import json
import torch.nn as nn
import torch.nn.functional as FN
import cv2
import random
from tqdm import tqdm
from solver import Solver
from removalmodels.models import Generator, Discriminator
from removalmodels.models import GeneratorDiff, GeneratorDiff... | nilq/baby-python | python |
from django.contrib import admin
from django.contrib.admin import register
from .models import Organization, Employee, Position, Phone, PhoneType
from .forms import EmployeeAdminForm
@register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
pass
@register(Employee)
class EmployeeAdmin(admin.ModelAdmin)... | nilq/baby-python | python |
import os
import subprocess
from typing import Tuple
import pandas as pd
LABEL_MAPPING = {
"Negative": 0,
"Positive": 1,
"I can't tell": 2,
"Neutral / author is just sharing information": 2,
"Tweet not related to weather condition": 2,
}
def load_data() -> Tuple[pd.DataFrame, pd.DataFrame, pd.D... | nilq/baby-python | python |
import itertools
import random
import re
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Iterable, Iterator, List, Tuple, cast
FIELD_SIZE = 10
class GameError(Exception):
"""Game error."""
class CellState(Enum):
UNKNOWN = "unknown"
EMPTY = "empty"
WOUNDED = "wounded... | nilq/baby-python | python |
"""
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 4: Storing Text in Strings
Exercise:
1.
a) You're given a string that contains the body of an email.
If the email contains the word "emergency", print out
"Do you wnat to make this email urgent?"
If it contains the word "joke", prin... | nilq/baby-python | python |
import sys
sys.path.append('../')
import codecs
from docopt import docopt
from dsm_creation.common import *
def main():
"""
Weeds Precision - as described in:
J. Weeds and D. Weir. 2003. A general framework for distributional similarity. In EMNLP.
"""
# Get the arguments
args = docopt("""Co... | nilq/baby-python | python |
class renderizar(object):
def savarLegenda(self,legenda,local_legenda):
with open(local_legenda, 'wt') as f:
f.write(legenda)
f.close()
return True
def criarArquivoHTML(self,titulo,local_video,local_legenda,token):
with open('model/template.html','rt') as f:
... | nilq/baby-python | python |
from utils import *
full_exps = []
for k, v in experiments.items():
full_exps.extend(f"{k}={vv}" for vv in v)
print(full_exps) | nilq/baby-python | python |
from mock import patch
print(patch.object)
import mock
print(mock.patch.object) | nilq/baby-python | python |
"""Generate a random key."""
import argparse
import os
from intervention_system.deploy import settings_key_path as default_keyfile_path
from intervention_system.util import crypto
def main(key_path):
box = crypto.generate_box()
crypto.save_box(box, key_path)
if __name__ == '__main__':
parser = argparse... | nilq/baby-python | python |
############################ USED LIBRARIES ############################
from tkinter import *
from tkinter import messagebox
import os, sys, time
import mysql.connector
import queries as q
import datetime as d
import functions as f
from constants import DEBUG, HOST, USER, PASSWORD, DATABASE
###################... | nilq/baby-python | python |
#!/usr/bin/env python3
# Write a program that prints the reverse-complement of a DNA sequence
# You must use a loop and conditional
dna = 'ACTGAAAAAAAAAAA'
rcdna = ''
for i in range(len(dna) -1, -1, -1):
nt = dna[i]
if nt == 'A': nt = 'T'
elif nt == 'T': nt = 'A'
elif nt == 'C': nt = 'G'
elif nt == 'G': nt =... | nilq/baby-python | python |
from math import sqrt
from numpy import matrix
from intpm import intpm
A = matrix([[1, 0, 1, 0], [0, 1, 0, 1]])
b = matrix([1, 1]).T
c = matrix([-1, -2, 0, 0]).T
mu = 100
x1 = 0.5 * (-2 * mu + 1 + sqrt(1 + 4*mu*mu))
x2 = 0.5 * (-mu + 1 + sqrt(1 + mu * mu))
x0 = matrix([x1, x2, 1 - x1, 1 - x2]).T
intpm(A, b, c, x0, ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 10:57:29 2020
@author: cheritie
"""
# modules for the KL basis computation:
import numpy as np
from astropy.io import fits as pfits
from AO_modules.tools.tools import createFolder
import AO_modules... | nilq/baby-python | python |
from collections import deque
from re import sub
from sys import stderr
p1 = deque([], maxlen = 52)
p2 = deque([], maxlen = 52)
n = int(input()) # the number of cards for player 1
for i in range(n):
p1.append(input()) # the n cards of player 1
m = int(input()) # the number of cards for player 2
for i in range(... | nilq/baby-python | python |
import operator
from pandas import notnull, isnull
from zeex.core.utility.collection import Eval
STRING_TO_OP = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod,
'^' : ... | nilq/baby-python | python |
# tensorflow core
import tensorflow as tf
# a=3,b=5,(a+b)+(a*b)=?
node1 = tf.constant(3.0)
node2 = tf.constant(4.0)
print("node1:", node1, "\nnode2:", node2)
sess = tf.Session()
print("sess.run([node1,node2]):", sess.run([node1, node2]))
node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""
display.py is the portion of Death God that manages the screen.
by William Makley
"""
import pygame
from pygame.locals import Rect
from . import colors
from . import settings
from . import fonts
from .map_view import MapView
from . import message
from .status_view import St... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
import re
import logging
from collections import defaultdict
from abc import ABC, abstractmethod
from . import strutil
REPLACER = "**"
REPLACER_HEAD = "*"
REPLACER_TAIL = "*"
REPLACER_REGEX = re.compile(r"\*[A-Z]*?\*") # shortest match
ANONYMIZED_DESC = "##"
_logger = logging.... | nilq/baby-python | python |
import pandas as pd
import numpy as np
from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
from functools import partial
import re
num_months = 4
chunk_size = 1000000
indicators = ['ind_ahor_fin_ult1', 'ind_aval_fin_ult1', 'ind_cco_fin_ult1', 'ind_cder_fin_ult1', 'ind_cno_fin_ult1',
... | nilq/baby-python | python |
""" navigate env with velocity target """
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import rospy
from blimp_env.envs.common.abstract import ROSAbstractEnv
from blimp_env.envs.common.ac... | nilq/baby-python | python |
import os.path
import unittest
import unittest.mock as mock
import psutil
import pytest
import fpgaedu.vivado
def find_vivado_pids():
'''
return a set containing the pids for the vivado processes currently
activated.
'''
vivado_procs = filter(lambda p: 'vivado' in p.name(), psutil.process_iter())... | nilq/baby-python | python |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | nilq/baby-python | python |
#imports
from random import randint
stDevMonthly = 0.07
stDevWeekly = 0.0095
def getDosageStats(popSize):
exposureStats = []
for i in range(0, popSize):
temp = []
temp.append(randint(3,7))
temp.append(stDevMonthly)
temp.append(stDevWeekly)
exposureStats.append(temp)
... | nilq/baby-python | python |
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
name = 'Jhasmany'
return render_template('index.html', name=name)
@app.route('/client')
def client():
list_name = ['Test1', 'Test2', 'Test3']
return render_template('client.html', list=list_na... | nilq/baby-python | python |
#------------------------------------------------------------------------------
# Get the trending colors.
# GET /v1/color_trends/{report_name}/trending_colors
#------------------------------------------------------------------------------
import os
import json
import requests
from urlparse import urljoin
from pprint ... | nilq/baby-python | python |
#coding=utf-8
from __future__ import print_function
import os
import sys
# Do not use end=None, it will put '\n' in the line end auto.
print('test\r\ntest',end=u'')
# 74 65 73 74 0D 0D 0A 74 65 73 74
# Debug in python Windows source code, it run into
# builtin_print() -> PyFile_WriteObject()->file_Pyobject_Print()->
... | nilq/baby-python | python |
from . import serializers
from rest_framework import generics,authentication,permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
class CreateUserView(generics.CreateAPIView):
serializer_class=serializers.UserApiSerializer
class CreateTokenView(O... | nilq/baby-python | python |
#!/usr/bin/env python
# Load required modules
import matplotlib
matplotlib.use('agg')
import sys, os, argparse, json, matplotlib.pyplot as plt, seaborn as sns, pandas as pd, numpy as np
import matplotlib.patches as mpatches
from models import EN, RF, IMPORTANCE_NAMES, FEATURE_CLASS_NAMES
sns.set_style('whitegrid')
# ... | nilq/baby-python | python |
def other_side_of_seven(num):
dist = 7 - num
num = 7 + (2 * dist)
return num
print(other_side_of_seven(4))
print(other_side_of_seven(12)) | nilq/baby-python | python |
import argparse
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("URL", nargs='?')
parser.add_argument("-s", action="store_true")
parser.add_argument("-l", type=str)
parser.add_argument("-t", type=str)
args = parser.parse_args()
return args
| nilq/baby-python | python |
import torch
from torchtext import data
import numpy as np
import pandas as pd
import torch.nn as nn
import torch.nn.functional as F
import spacy
nlp = spacy.load('en')
SEED = 1
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
TEXT = data.Field(tokenize='spacy')
LABEL = data.LabelField(tensor_type=torch.FloatTen... | nilq/baby-python | python |
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Rating, Site, Picture, Like, Category
class CategorySerialier(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'description', 'icon')
class RatingSerializer(serializer... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import time
import re
import sys
import hashlib
import shutil
import pathlib
import traceback
import subprocess
import pandas
import argparse
from ...shared import shared_tools as st
import lxml.etree as et
from pathlib import Path
from datetime import datetime
from job... | nilq/baby-python | python |
# Generated by Django 1.10.5 on 2017-02-15 08:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('admin', '0008_domain_enable_dns_checks'),
]
operations = [
migrations.RenameField(
model_name='domain',
old_name='quota',
... | nilq/baby-python | python |
#assigning the int 100 to "cars"
cars = 100
#assiging the int 4.0 to "space_in_a_car
space_in_a_car = 4.0
#assigning drivers to the int 30
drivers = 30
#assigning passangers to the int 90
passengers = 90
#assigning cars_not_driver to (cars-drivers)
cars_not_driven = cars - drivers
#assigning cars_driven to drivers
cars... | nilq/baby-python | python |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
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 agr... | nilq/baby-python | python |
import codecs
import logging
import time
from concurrent.futures.thread import ThreadPoolExecutor
from pathlib import Path
import frontmatter
from bs4 import BeautifulSoup
from jinja2 import Environment, FileSystemLoader
from aqui_brain_dump import base_url, content_path, get_creation_date, get_last_modification_date... | nilq/baby-python | python |
#! /usr/bin/env python
"""
This script produces the stacks for emission line luminosity limited samples.
"""
import sys
import os
from os.path import join
import glob
import numpy as n
import astropy.io.fits as fits
import SpectraStackingEBOSS as sse
from scipy.interpolate import interp1d
import matplotlib
matplotlib... | nilq/baby-python | python |
import socket
import sys
name = sys.argv[1]
print 'Resolving Server Service Name for ' + name
ipAddress = socket.gethostbyname(name)
print('IP address of host name ' + name + ' is: ' + ipAddress)
| nilq/baby-python | python |
import cStringIO as StringIO
import numpy as np
from sensor_msgs.msg import PointCloud2
#from rospy.numpy_msg import numpy_msg
#PointCloud2Np = numpy_msg(PointCloud2)
import pypcd
import pyrosmsg
pc = pypcd.PointCloud.from_path('./tmp.pcd')
msg = pc.to_msg()
#msg2 = PointCloud2()
#msg2.deserialize(smsg)
def wit... | nilq/baby-python | python |
#!/usr/bin/env python3
# train MNIST with latent equilibrium model
# and track experiment using sacred
import torch
from sacred import Experiment
from sacred.observers import FileStorageObserver
ex = Experiment('layeredMNIST')
ex.observers.append(FileStorageObserver('runs'))
# configuration
@ex.config
def config():... | nilq/baby-python | python |
from django.contrib import admin
from demo_api import models
admin.site.register(models.CustomUser)
# Register your models here.
| nilq/baby-python | python |
# Generated by Django 2.0.7 on 2018-08-06 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20180804_2152'),
]
operations = [
migrations.AlterModelOptions(
name='dac',
options={'ordering': [... | nilq/baby-python | python |
import os
from flask import Flask, redirect
from flask import request
from flask import jsonify
import hashlib
app = Flask(__name__)
c = 0
clients = []
chat = []
#[from, to, status[0sent, 1accepted, 2rejected]]
requests = {}
requests_sent = {}
version = 5
additive = 0
def getUID(ip):
return hashlib.sha256(str(... | nilq/baby-python | python |
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.utils.translation import gettext_lazy as _
class SitesConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "webquills.sites"
label = "sites"
verbose_name = _("Webquills sites")
... | nilq/baby-python | python |
import socket
import select
import threading
import json
import sys
import traceback
import os
import random
from clientInterface import ClientInterface
from constants import LOGIN, LOGOUT, CREATE_ACCOUNT, DELETE_ACCOUNT, EXIT, ACTIVE_USERS, ACTIVE_STATUS, INACTIVE_STATUS, OPEN_CHAT, CLOSE_CHAT, DELETE_MESSAGES, SEND_M... | nilq/baby-python | python |
#!/usr/bin/env python
# The MIT License (MIT)
# Copyright (c) 2017 Lancaster University.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
#... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
from sklearn import neighbors
import numpy as np
from ela.textproc import *
from ela.classification import KNN_WEIGHTING
# These functions were an attempt to have interactive maps with ipywidgets but proved to be a pain... | nilq/baby-python | python |
import os
import six
from six.moves import cPickle
import time
import numpy as np
import modelarts.aibox.ops as ops
from modelarts.aibox.pipeline import Pipeline
import modelarts.aibox.types as types
_R_MEAN = 125.31
_G_MEAN = 122.95
_B_MEAN = 113.87
_CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN]
_R_STD = 62.99
_G_ST... | nilq/baby-python | python |
#!/usr/bin/env python
import flask
from flask import Flask, render_template, request, json, redirect, session, flash
from flaskext.mysql import MySQL
from processor import Processor
from werkzeug import generate_password_hash, check_password_hash
def init_db():
print "Init DB"
print "mysql = ", mysql
pr... | nilq/baby-python | python |
from . import BaseAgent
from pommerman.constants import Action
from pommerman.agents import filter_action
import random
class RulesRandomAgentNoBomb(BaseAgent):
""" random with filtered actions but no bomb"""
def __init__(self, *args, **kwargs):
super(RulesRandomAgentNoBomb, self).__init__(*args, **k... | nilq/baby-python | python |
class Database(object):
placeholder = '?'
def connect(self, dbtype, *args, **kwargs):
if dbtype == 'sqlite3':
import sqlite3
self.connection = sqlite3.connect(*args)
elif dbtype == 'mysql':
import MySQLdb
self.connection = MySQLdb.con... | nilq/baby-python | python |
import re
import requests
import csv
lines = []
with open('01.csv', 'r') as csvFile:
texts = csv.reader(csvFile)
for text in texts:
lines.append(text[0])
datas = []
datass = []
count = 0
# 提取阅读数,评论数,转发数,收藏数
for num in range(0,220):
datas = []
x = lines[num]
w = x[-21:-13]
... | nilq/baby-python | python |
from connaisseur.image import Image
class ValidatorInterface:
def __init__(self, name: str, **kwargs): # pylint: disable=unused-argument
"""
Initializes a validator based on the data from the configuration file.
"""
self.name = name
def validate(self, image: Image, **kwargs) ... | nilq/baby-python | python |
"""
defines:
- CalculixConverter
"""
from collections import defaultdict
from numpy import array, zeros, cross
from numpy.linalg import norm # type: ignore
from pyNastran.bdf.bdf import BDF, LOAD # PBAR, PBARL, PBEAM, PBEAML,
from pyNastran.bdf.cards.loads.static_loads import Force, Moment
class CalculixConvert... | nilq/baby-python | python |
import serial
import serial.tools.list_ports
import time
import threading as thread
class Laser:
def __init__(self):
self.__ser = serial.Serial()
self.pulseMode = None
self.repRate = None
self.burstCount = None
self.diodeCurrent = None
self.energyMode = None
... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-04-15 14:49
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('comments', '0001_initial'),
]
operations = [
migrations.AlterField(
model_na... | nilq/baby-python | python |
from datetime import datetime
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
url_for, request)
from flask_bootstrap import Bootstrap
from flask_login import (LoginManager, current_user, UserMixin,
login_required, login_user, logout_user)
from fl... | nilq/baby-python | python |
from hstest import StageTest, TestedProgram, CheckResult, dynamic_test
class Test(StageTest):
answers = [
'#### Hello World!\n',
'plain text**bold text**',
'*italic text*`code.work()`',
'[google](https://www.google.com)\n',
'1. first\n2. second\n3. third\n4. fourth\n',
... | nilq/baby-python | python |
import pytest
from pasee.__main__ import load_conf
from pasee import MissingSettings
import mocks
def test_load_conf():
"""Test the configuration logging"""
with pytest.raises(MissingSettings):
load_conf("nonexistant.toml")
config = load_conf("tests/test-settings.toml")
assert config["host"] ... | nilq/baby-python | python |
from UR10 import *
u = UR10Controller('10.1.1.6')
x = URPoseManager()
x.load('t1.urpose')
print(x.getPosJoint('home'))
resp = input('hit y if you want to continue')
if resp == 'y':
x.moveUR(u,'home',30) | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Wireshark - Network traffic analyzer
# By Gerald Combs <gerald@wireshark.org>
# Copyright 1998 Gerald Combs
#
# SPDX-License-Identifier: GPL-2.0-or-later
'''Update the "manuf" file.
Make-manuf creates a file containing ethernet OUIs and their company
IDs. It merges the... | nilq/baby-python | python |
from unittest import mock
import json
import time
from aiohttp import web
from aiohttp.web_middlewares import _Handler
from aiohttp.test_utils import TestClient
from typing import Any, Dict
from aiohttp_session import get_session, SimpleCookieStorage
from aiohttp_session import setup as setup_middleware
from typede... | nilq/baby-python | python |
import json
import os
import dotenv
class ConfigError(Exception):
def __init__(self, field):
super().__init__(f'Missing environment variable {field}')
def get_env_var(name: str, default: str = None, prefix='', allow_empty=False):
if prefix:
env = prefix + '_' + name
else:
env = ... | nilq/baby-python | python |
"""Library for Byte-pair-encoding (BPE) tokenization.
Authors
* Abdelwahab Heba 2020
* Loren Lugosch 2020
"""
import os.path
import torch
import logging
import csv
import json
import sentencepiece as spm
from speechbrain.dataio.dataio import merge_char
from speechbrain.utils import edit_distance
import speechbrain ... | nilq/baby-python | python |
from ExceptionHandler import ExceptionHandler
class InputController:
def __init__(self, inputReader, exceptionHandler):
self.InputReader = inputReader
self.ExceptionHandler = exceptionHandler
def pollUserInput(self):
return self.ExceptionHandler.executeFunc()
| nilq/baby-python | python |
import math
def factors(n):
results = set()
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
results.add(i)
results.add(int(n/i))
return results
x = 0
i = 0
while True:
x += i
if len(factors(x)) > 500:
print(x)
i += 1
| nilq/baby-python | python |
"""
MesoNet
Authors: Brandon Forys and Dongsheng Xiao, Murphy Lab
https://github.com/bf777/MesoNet
Licensed under the Creative Commons Attribution 4.0 International License (see LICENSE for details)
The method "vxm_data_generator" is adapted from VoxelMorph:
Balakrishnan, G., Zhao, A., Sabuncu, M. R., Guttag, J., & Dal... | nilq/baby-python | python |
from py.test import raises
from pypy.conftest import gettestobjspace
class AppTestUnicodeData:
def setup_class(cls):
space = gettestobjspace(usemodules=('unicodedata',))
cls.space = space
def test_hangul_syllables(self):
import unicodedata
# Test all leading, vowel and trailing... | nilq/baby-python | python |
# Copyright 2021 Huawei Technologies Co., Ltd.All Rights Reserved.
#
# 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 ap... | nilq/baby-python | python |
class A:
def foo<caret><error descr="Method must have a first parameter, usually called 'self'">()</error>: # Add 'self'
pass
| nilq/baby-python | python |
import copy
import math
import random
import typing as t
import hypemaths as hm
from ..exceptions import (
InvalidMatrixError,
MatrixDimensionError,
MatrixNotSquare,
)
from ..mixins import CopyMixin
class Matrix(CopyMixin):
def __init__(
self,
matrix: t.Union[int, float, list]... | nilq/baby-python | python |
#
# Qutebrowser Config
#
from cconfig import CConfig
# Custom state full config options
cc = CConfig(config)
cc.redirect = True
# ==================== General Settings ==================================
c.hints.chars = 'dfghjklcvbnm'
c.hints.uppercase = True
c.confirm_quit = ['n... | nilq/baby-python | python |
"""Misc funcs for backtester"""
import pandas as pd
from io import StringIO
from . import fb_amzn
def load_example():
"""Load example input data"""
df = pd.read_csv(StringIO(fb_amzn.data))
df['date'] = pd.to_datetime(df['date']).dt.tz_localize('US/Central')
return df
| nilq/baby-python | python |
import pprint
import sys
import numpy as np
def pbatch(source, dic):
ss = np.transpose(source)
for line in ss[:10]:
for word in line:
a = dic[word]
b = a
if a == "SOS":
b = "{"
elif a == "EOS":
b = "}"
elif a =... | nilq/baby-python | python |
from cryptofield.fieldmatrix import *
import unittest
class TestFMatrix(unittest.TestCase):
def testMatrixGetRow1(self):
F = FField(4)
m = FMatrix(F, 3, 3)
m.ident()
r = m.getRow(1)
ans = [FElement(F, 0), FElement(F, 1), FElement(F, 0)]
self.assertEqual(r, ans)
def testMatrix... | nilq/baby-python | python |
# Generated by Django 2.2.5 on 2019-10-28 17:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('service', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='rating',
... | nilq/baby-python | python |
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
found = False
while first <= last and not found:
middle_point = (first + last)//2
if input_array[middle_point] == value:
found = True
else:
if value < input_array[middle_point]:
... | nilq/baby-python | python |
from rest_framework import permissions
class IsBuyerOrSellerUser(permissions.BasePermission):
def has_permission(self, request, view):
if request.user.is_authenticated and request.user.is_buyer_or_seller:
return True
return False
| nilq/baby-python | python |
from copy import deepcopy
from dbt.contracts.graph.manifest import WritableManifest
from dbt.contracts.results import CatalogArtifact
def edit_catalog(
catalog: CatalogArtifact, manifest: WritableManifest
) -> CatalogArtifact:
output = deepcopy(catalog)
node_names = tuple(node for node in output.nodes)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
encryption test_services module.
"""
import pytest
import pyrin.security.encryption.services as encryption_services
import pyrin.configuration.services as config_services
from pyrin.security.encryption.handlers.aes128 import AES128Encrypter
from pyrin.security.encryption.handlers.rsa256 i... | nilq/baby-python | python |
"""
HoNCore. Python library providing connectivity and functionality
with HoN's chat server.
Packet ID definitions.
Updated 23-7-11.
Client version 2.40.2
"""
""" Server -> Client """
HON_SC_AUTH_ACCEPTED = 0x1C00
HON_SC_PING = 0x2A00
HON_SC_CHANNEL_MSG = 0x03
HON_SC_JOINE... | nilq/baby-python | python |
"""A quantum tic tac toe running in command line"""
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import CompositeGate
from qiskit import execute
import numpy as np
from composite_gates import cry,cnx,any_x,bus_or,x_bus
class Move():
def __init__(self,ind... | nilq/baby-python | python |
import os
import foundations
from foundations_contrib.global_state import current_foundations_context, message_router
from foundations_events.producers.jobs import RunJob
foundations.set_project_name('default')
job_id = os.environ['ACCEPTANCE_TEST_JOB_ID']
pipeline_context = current_foundations_context().pipeline_c... | nilq/baby-python | python |
class MySql(object):
pass
| nilq/baby-python | python |
#!/usr/bin/env python3
#
# Author: Jeremy Compostella <jeremy.compostella@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.