content stringlengths 5 1.05M |
|---|
# Generated by Django 3.0.5 on 2020-05-04 12:17
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0002_auto_20200504_1032'),
]
operations = [
migrations.AlterModelOptions(
name='order',
opt... |
import sys
import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import Qt, QTimer, QElapsedTimer
from PyQt5.QtWidgets import (
QApplication, QCheckBox, QGridLayout, QGroupBox, QMenu, QPushButton, QRadioButton, QVBoxLayout, QWidget, QSlider)
from bg_gurney import BasalGanglia
class Window(QWidget):
def ... |
# Generated by Django 3.0.3 on 2020-05-07 12:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project_first_app', '0003_auto_20200507_1248'),
]
operations = [
migrations.AlterField(
model_name='user',
name='pas... |
#!/usr/bin/env python
# Load firmware onto the Digital Bitbox.
#
# The Digital Bitbox must be in bootloader mode to use this script:
# 1- Unlock the bootloader using send_command.py to send '{"bootloader":"unlock"}'
# 2- Hold the touch button 3 seconds to permit unlocking.
# 3- Replug the device, and briefly tou... |
"""
This is a script to scrape COVID19 data from the PowerBI visualization for Wake County NC:
- https://covid19.wakegov.com/
- https://app.powerbigov.us/view?r=eyJrIjoiNTIwNTg4NzktNjEzOC00NmVhLTg0OWMtNDEzNGEyM2I4MzhlIiwidCI6ImM1YTQxMmQxLTNhYmYtNDNhNC04YzViLTRhNTNhNmNjMGYyZiJ9
This script:
- scrapes infection and de... |
import os
import glob
from catsndogs.data import get_training_data
folder = get_training_data()
cats = glob.glob(os.path.join(get_training_data(), "cat", "*.jpg"))
dogs = glob.glob(os.path.join(get_training_data(), "dog", "*.jpg"))
|
import json
import os
import urllib.request, urllib.parse, urllib.error
from io import StringIO
import csv
from tests.fixtures.base_test import BasePlenarioTest, fixtures_path
# Filters
# =======
# Constants holding query string values, helps to have them all in one place.
# The row counts come from executing equival... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are me... |
from github import Github, GithubException
import time
from server import app, celery, logger
from server.utils.utils import getAllFilesWPathsInDirectory
from server.utils.githubUtils import createNewRepo
from server.api.messageApi import postEvent
@celery.task
def add(x, y):
return x + y
@celery.task(bind=True)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 08:49:25 2017
Recursive execution
@author: laci
"""
import multiprocessing as mp
import time
import sparse_methods as m
import sparse_move as sm
import sparse_contract as sc
import graph
startTime = time.time()
lo = 0
up = 15000
g = graph.BA... |
from .boxes import *
from .demo_utils import *
from .logger import WandbLogger, setup_logger
from .model_utils import *
from .visualize import *
|
# -*- coding:utf-8 -*-
import turbo.log
from base import BaseHandler
from helpers import dc as dc_helper
from db.conn import dc_files
logger = turbo.log.getLogger(__file__)
db_dc = dc_helper.dc
class HomeHandler(BaseHandler):
_get_params = {
'option': [
('skip', int, 0),
('li... |
import numpy as np
import pandas as pd
from glob import glob
import os
import sys
from morphomnist import io
def get_data(path):
df_train = pd.read_csv(os.path.join(INPUT_PATH, 'train-morpho.csv'))
df_test = pd.read_csv(os.path.join(INPUT_PATH, 't10k-morpho.csv'))
return df_train, df_test
def uniform_res... |
from django.urls import include, re_path
urlpatterns = [
re_path(r"^", include("dpaste.urls.dpaste_api")),
re_path(r"^", include("dpaste.urls.dpaste")),
re_path(r"^i18n/", include("django.conf.urls.i18n")),
]
# Custom error handlers which load `dpaste/<code>.html` instead of `<code>.html`
handler404 = "dp... |
import itertools
def chunks( iterable, size=1000 ):
"""
Make digestible chunks of something that can be iterated
Arguments
---------
iterable: list, tuple, generator
Just have to support the iter function will break it
in digestible chunks
size: size of the digestibles chunks
... |
DATABASES = {'default': {'ENGINE': 'django.db.backends.', 'NAME': '', 'HOST': '', 'USER': '', 'PASSWORD': '', 'PORT': ''}}
DEBUG = True
INSTALLED_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles')
ROOT... |
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.Random import new
class Client:
"""!
Client is created with a 4096 bit RSA key pair.
The public key is exported then hashed with sha256.
The hex outp... |
__copyright__ = 'Copyright 2018-2021, The RADICAL-Cybertools Team'
__license__ = 'MIT'
from .base import RMInfo, ResourceManager
# ------------------------------------------------------------------------------
#
class Debug(ResourceManager):
# -----------------------------------------------------------------... |
import os
from yUMItools.datasim import *
import numpy as np
import matplotlib.pyplot as plt
def test__read_fasta_file():
import Bio.Seq
# filepath
test_data_fasta_filepath = 'test_data/reference_sequence/Rp0-reference.fa'
# create sequence object and load fasta file
s = TestTube(test_data_fast... |
import os
import random
import numpy as np
from decord import VideoReader
from decord.base import DECORDError
def _get_default_test_video():
return VideoReader(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'examples', 'flipping_a_pancake.mkv')))
def _get_corrupted_test_video():
ret... |
# -*- coding: utf-8 -*-
import sqlite3
from .cost_breakdown import CostBreakdown
from .stock import Stock
from .manufacturing_expense import ManufacturingExpense
from .me2 import ManufacturingExpense2
from .product_price import ProductPrice
from .product_cost import ProductCost
class TableAdaptorFactory:
shortc... |
import frappe
import latte
from frappe.utils import formatdate, format_datetime
from frappe.core.doctype.data_export.exporter import DataExporter
from frappe.core.doctype.data_export.exporter import export_data
def add_data_row(self, rows, dt, parentfield, doc, rowidx):
d = doc.copy()
meta = frappe.get_meta(dt)
if ... |
import numpy as np
def compute_homography(src, dst):
"""computes the homography from src, to dst using inversion method."""
if src.shape[1] == 2 :
p1 = np.ones((len(src),3),'float64')
p1[:,:2] = src
elif src.shape[1] == 3 : p1 = src
if dst.shape[1] == 2 :
p2 = n... |
# coding=utf-8
# @Time : 2021/1/6 10:45
# @Auto : zzf-jeff
import torch
from tqdm import tqdm
import time
import numpy as np
def eval(model, valid_dataloader, post_process_class, metric_class):
if isinstance(model, torch.nn.DataParallel):
# TypeError: expected sequence object with len >... |
import json
class App(object):
def __init__(self):
self.routers = dict()
def router(self, path):
def decorator(fun):
self.routers[path] = fun
return fun
return decorator
def server(self, path, arg = None):
fun = self.routers.get(path)
if fu... |
import tensorflow as tf
import keras.backend as K
import numpy as np
from config import get_config
def log_normals_loss(y_true, y_pred):
# Get batch sie
config, unparsed = get_config()
batch_size = config.batch_size
# Print batch
y_true = tf.Print(y_true, [y_true], message='y_true', summarize=30)
y_pred = tf.Pri... |
## module midpoint
''' yStop = integrate (F,x,y,xStop,tol=1.0e-6)
Modified midpoint method for solving the
initial value problem y' = F(x,y}.
x,y = initial conditions
xStop = terminal value of x
yStop = y(xStop)
F = user-supplied function that returns the
array F(x,y) =... |
"""
frpy
A simple reverse proxy to help you expose a local server behind a NAT or firewall to the internet. (a imitator of frp)
[Architecture]
frpy_server —— worker_server —— user_side
|
frpy_client —— local_server_side
[Usage]
-- server side --
# start frpy.py server on 8000 port
$ python frpy.py server 0.0.0.0 8000... |
import pickle
import operator
def explore_model(standardize, model_type='rf', for_submission=True):
submission = "_submission" if for_submission else ""
standardized = "_standardized" if standardize else ""
model_file_name = "08_reg_model_" + model_type + standardized + submission + ".p"
print("Opening " + model... |
"""MongoDB queries for titanic database."""
import pymongo
if __name__ == "__main__":
# Username and password to be set by user.
username = "TODO"
cluster = "TODO"
password = "TODO"
group = "TODO"
# Create access to MondoDB rpg database.
s = "mongodb+srv://{}:{}@{}-{}.mongodb.net/titanic... |
valor = int(input('Qual valor você quer sacar? R$'))
total = valor
dinheiro = 50
totaldinheiro = 0
while True:
if total >= dinheiro:
total -= dinheiro
totaldinheiro += 1
else:
if totaldinheiro > 0:
print(f'Total de {totaldinheiro} cédulas de R${dinheiro}')
... |
# Generated by Django 3.1.7 on 2021-08-04 19:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('experiments', '0003_auto_20210804_1906'),
]
operations = [
migrations.RenameField(
model_name='battery',
old_name='insturcti... |
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)
class DoubleMaStrategy(CtaTemplate):
author = " use Python traders "
fast_window = 10
slow_window = 20
fast_ma0 = 0.0
fast_ma1 = 0.0
... |
"""
Create a 2-dimensional array, , of empty arrays. All arrays are zero indexed.
Create an integer, , and initialize it to .
There are types of queries:
Query: 1 x y
Find the list within at index .
Append the integer to the .
Query: 2 x y
Find the list within at index .
Find the value of element where is the nu... |
default_app_config = 'django_sms_toolkit.apps.DjangoSMSToolkitConfig'
|
"""
Feature agglomeration. Base classes and functions for performing feature
agglomeration.
"""
# Author: V. Michel, A. Gramfort
# License: BSD 3 clause
import numpy as np
from ..base import TransformerMixin
from ..utils.validation import check_is_fitted
from scipy.sparse import issparse
###############... |
# Copyright 2011 Branan Purvine-Riley and Adam Johnson
#
# 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 ... |
"""Definitions of the segment classes."""
# flake8: noqa: F401
from sqlfluff.core.parser.segments.base import BaseSegment, UnparsableSegment
from sqlfluff.core.parser.segments.generator import SegmentGenerator
from sqlfluff.core.parser.segments.raw import (
RawSegment,
CodeSegment,
UnlexableSegment,
C... |
"""
vodka data handlers, allows to modify data retrieved by
vodka data plugins
"""
import vodka.config
import vodka.component
import vodka.storage
import vodka.data.data_types
import vodka.util
handlers = {}
class register(vodka.util.register):
class Meta:
objects = handlers
name = "data handler... |
def search_and_set(mem_blocks,block_id,thread_id):
if block_id not in mem_blocks:
mem_blocks[block_id] = [0]*8
mem_blocks[block_id][thread_id] = 1
|
# Copyright 2016 Google LLC 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 ag... |
__author__ = "Gordon Ball <gordon@chronitis.net>"
__version__ = "0.4.3"
from .ipyrmd import ipynb_to_rmd, rmd_to_ipynb, ipynb_to_spin, spin_to_ipynb
|
import numpy as np
from numpy.testing import assert_allclose
import unittest
from pb_bss_eval.distribution import CACGMMTrainer
from pb_bss_eval.distribution import ComplexAngularCentralGaussian
from pb_bss_eval.distribution import sample_cacgmm
import itertools
from pb_bss_eval.utils import labels_to_one_hot
def sol... |
import torch
import torch.nn as nn
import numpy as np
import os
import glob
from libs.utils.data_utils import extract_length_angles
class RnnDetector(nn.Module):
def __init__(self):
super(RnnDetector, self).__init__()
def forward(self, model, inputs):
outs = model(inputs)
return out... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os;
import sys;
import datetime;
import string;
import shutil;
EPSILON = 1e-10;
Product_volume_dict = {};
START_TIME='20:55:00';
END_TIME='02:45:00';
if len(sys.argv) != 3:
print 'Usage: ./cmd src_md_dir dest_dir';
quit();
src_md_path = sys.argv[1];
dest_dir =... |
import datajoint as dj
# -------------- group_shared_topopaper_horst_imaging --------------
schema = dj.Schema('group_shared_topopaper_horst_imaging')
vmod0 = dj.VirtualModule('vmod0', 'group_shared_topopaper_main_imaging')
@schema
class AlignmentPoints(dj.Manual):
definition = """
# User specified align... |
from mitmproxy.web import master
__all__ = ["master"]
|
#!/usr/bin/env python
"""
Unittests for the kuralib middleware
"""
import unittest, sys, string, codecs, time
import kuraapp
class KuraAppTestCase(unittest.TestCase):
def testCreateRepository(self):
kuraapp.initApp("boud", "andal", "", "localhost")
app = kuraapp.app
assert len(app.tabl... |
import unittest
from buzzer import QuestionDataset, RNNBuzzer, create_feature_vecs_and_labels
import numpy as np
import torch
import torch.nn as nn
torch.set_printoptions(precision=10)
ex1 = {'feature_vec':torch.FloatTensor([[[0.1334, 0.1011, 0.0932], [0.1501, 0.1001, 0.0856], [0.1647, 0.0987, 0.0654]]]).view(1, 3, ... |
# Copyright 2021 Northern.tech AS
#
# 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 ag... |
import bisect
import functools
import itertools
import logging
import time
from uuid import UUID
from abc import (
ABCMeta,
abstractmethod
)
from typing import (
cast,
Dict,
Iterable,
List,
Set,
Tuple,
Type,
TYPE_CHECKING,
Union,
Optional,
)
from hvm.types import Timest... |
import time
import uuid
from minifw.db.orm import Model, StringField, BooleanField, FloatField, TextField
def next_id():
return '%015d%s000' % (int(time.time() * 1000), uuid.uuid4().hex)
class User(Model):
__table__ = 'users'
id = StringField(primary_key=True, default=next_id, column_type='varchar(50)'... |
import hashlib
# Укажите ваше ФИО.
name = 'Стасенко Дмитрий Сергеевич'
reviewers = [
'lodthe',
'darkkeks',
'danlark1'
]
print(reviewers[int(hashlib.md5(name.encode('utf-8')).hexdigest(), 16) % len(reviewers)]) |
import gettext
import os.path
from climsoft_api.api.stationelement.schema import StationElementWithStation
from climsoft_api.utils.response import translate_schema
ROOT_DIR = os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.abspath(__file__)
)
)
)
LOCALE_DIR = os.path.j... |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs a test repeatedly to measure its flakiness. The return code is non-zero
if the failure rate is higher than the specified thresh... |
# -*- coding: utf-8 -*-
import configparser
import os
cf = configparser.ConfigParser()
cf.read("/etc/face_recognition/config/db.ini")
db_host = cf.get("database", "host")
db = cf.get("database", "db")
db_user = cf.get("database", "user")
db_pass = cf.get("database", "pass")
def get_db_host():
return db_host
def ... |
"""
List Events -
Small program used to list all events in a match and give examples to those events.
"""
import datetime
import json
from gamelocker import wrapper
api_key = "API_KEY_HERE" # VG API Key
api = wrapper.Vainglory(api_key)
# Vainglory game modes
game_modes = {"casual": "casual", "ranke... |
import numpy as np
import matplotlib.pyplot as plt
import csv
#PATH1 = '/Users/alihanks/Google Drive/NQUAKE_analysis/PERM/PERM_data/lbnl_sensor_60.csv'
PATH1 = '/Users/alihanks/k40_test_2019-02-06_D3S.csv'
def make_int(lst):
'''
Makes all entries of a list an integer
'''
y = []
for i in lst:
y.app... |
import numpy as np
import torch
import torch.nn.functional as functional
from grasp_det_seg.modules.losses import smooth_l1
from grasp_det_seg.utils.bbx import ious, calculate_shift, bbx_overlap, mask_overlap
from grasp_det_seg.utils.misc import Empty
from grasp_det_seg.utils.nms import nms
from grasp_det_seg.utils.pa... |
from django.urls import path
from . import views
app_name = "accounts"
urlpatterns = [
path("logg-inn/", views.login_user, name="login"),
path("registrer/", views.register, name="register"),
path("logg-ut/", views.logout_user, name="logout"),
]
""" accounts/ login/ [name='login']
accounts/ logout/ [nam... |
from peewee import *
from playhouse.fields import CompressedField
from playhouse.fields import PickleField
from .base import db
from .base import ModelTestCase
from .base import TestModel
class Comp(TestModel):
key = TextField()
data = CompressedField()
class Pickled(TestModel):
key = TextField()
d... |
from .models import Notification_Id, Analytics_event, Notification
from rest_framework import generics, permissions
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
from django.http import JsonResponse
from django.db import IntegrityErr... |
n = int(input())
for i in range(1,n+1):
start=(i*5)-4
lst=[e for e in range(start,start+5)]
if i%2==1:
print(*lst)
if i%2==0:
lst.reverse()
print(*lst)
|
from flask import Flask, render_template, session, url_for, escape, request, redirect
from app import app
import json, random
from os import listdir, system, chdir
from os.path import isfile, join, abspath, dirname
jspath = abspath(join(dirname( __file__ ), '..', '..','javascript'))
@app.route('/group1', methods=['PO... |
""" Testing module for the DDoS implementation
of the blockchain client.
"""
import hashlib
import time
from queue import Queue
import nacl.encoding
import nacl.signing
import chains
import utils
VERSION = 0.7
class TestDDos(object):
""" Testcase used to bundle all tests for the
DDoS blockchain
"""
... |
from shortest_path import gen_data, solve_model, solve_all_pairs, solve_tree_model, critical_tasks
def main():
import sys
import random
import tableutils
n=13
header = ['P'+str(i) for i in range(n)]
if len(sys.argv)<=1:
print('Usage is main [data|run|all|tree|pm] [seed]')
return... |
import transaction
import zeit.cms.checkout.interfaces
import zeit.content.article.testing
import zope.component
class RecensionTest(zeit.content.article.testing.FunctionalTestCase):
def setUp(self):
super(RecensionTest, self).setUp()
repository = zope.component.getUtility(
zeit.cms.r... |
'''Example of autoencoder model on MNIST dataset using 2dim latent
The autoencoder forces the encoder to discover 2-dim latent vector
that the decoder can recover the original input. The 2-dim latent
vector is projected on 2D space to analyze the distribution of codes
in the latent space. The latent space can be navig... |
import unittest
import asyncio
import canopy
class RequestWithRetryTest(unittest.TestCase):
def test_it_should_return_result_if_no_error(self):
request = DummyRequest(0)
result = canopy.run(canopy.request_with_retry(lambda: request.execute('abc'), 'request', True))
self.assertEqual(resul... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from ..builder import LOSSES
@LOSSES.register_module()
class AdaptiveWingLoss(nn.Module):
"""Adaptive wing loss. paper ref: 'Adaptive Wing Loss for Robust Face
Alignment via Heatmap Regression' Wang et al. ICCV'2019.
Args... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
"""
tf2onnx.rewriter.rnn_unit_base - lstm support
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import numpy as np
from onnx import onnx_pb
... |
import unittest
import unishark
import os
import shutil
from unishark.util import get_interpreter
class TestProgramTestCase(unittest.TestCase):
def setUp(self):
super(TestProgramTestCase, self).setUp()
self.dest = 'results'
if os.path.exists(self.dest):
shutil.rmtree(self.dest)... |
# -*- coding: utf-8 -*-
import time
from collections import namedtuple
from application import Application
from middleware import Middleware
from render import render_basic
# TODO: what are some sane-default intervals?
Hit = namedtuple('Hit', 'start_time url pattern status_code '
' elapsed_time con... |
import datetime
from datetime import date
import pytest
from resources.models import Period, Day
from .utils import assert_hours
def daterange(start_date, end_date):
for n in range((end_date - start_date).days):
yield start_date
start_date += datetime.timedelta(days=1)
@pytest.mark.django_db
de... |
import os
import numpy as np
import pandas as pd
import pytest
from scvi.data import synthetic_iid
from scvi.model import PEAKVI, SCANVI, SCVI, TOTALVI
def single_pass_for_online_update(model):
dl = model._make_data_loader(model.adata, indices=range(0, 10))
for i_batch, tensors in enumerate(dl):
_, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
import getpaid.abstract_mixin
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.GETPAID_ORDER_MODEL),
]
operat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
file="lines.txt"
f = open(file,"r")
for line in f:
print line
|
import sys
import time
import frida
import random
import traceback
from time import sleep
from bLib.const import *
from bLib.Mutator import Mutator
from bLib.Executor import Executor
from bLib.FuzzServer import FuzzServer
from bLib.Cov import BreakPointCoverage
from bLib.FuzzClient import BreakpointClient
inp_path =... |
import sys
import itertools as it
from collections import defaultdict
from random import random
import numpy as np
import numpy.linalg as la
from numpy.random import choice
import mdtraj as mdj
from wepy.boundary_conditions.boundary import BoundaryConditions
from wepy.resampling.distances.openmm import OpenMMRebindi... |
import os, sys
def get_token():
config_file = os.path.join(os.path.expanduser('~'), '.todoist')
token = None
if os.path.isfile(config_file):
with open(config_file) as f:
token = f.read().strip()
if not token:
sys.exit('Put your Todoist API token in ~/.todoist')
else:
... |
import urllib2
from BeautifulSoup import BeautifulSoup
from win32com.client import Dispatch
import csv, sys, os
import codecs
import time
import datetime
import win32file
import random
import re
def get_data(majors):
for con in majors:
print con['href']
url=con['href']
url = 'https://servic... |
"""User auth token columns
Revision ID: bdb195ed95bb
Revises: 534c4594ed29
Create Date: 2016-07-28 15:38:18.889151
"""
# revision identifiers, used by Alembic.
revision = 'bdb195ed95bb'
down_revision = '534c4594ed29'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by ... |
from __future__ import print_function
from . import utils
from .utils import *
from . import asp
from .asp import *
from . import nn
from .nn import *
__all__ = utils.__all__
__all__ += asp.__all__
__all__ += nn.__all__ |
import sqlite3
class db (object):
def __init__(self, filename):
self._ctx = sqlite3.connect(filename)
self._ctx.cursor().execute('''
create table if not exists guild (
guildid integer primary key,
channel integer null
)
''')
se... |
from typing import Tuple, Union, Dict, List, Iterable, Optional
from torch.utils.data import Dataset
from .common import LABEL_KEY, SENT_KEY, ANTI_KEY, form_sentence, chunks_from_iterable
class LevyHolt(Dataset):
def __init__(
self, txt_file: str, num_patterns: int = 1,
num_tokens_per_pat... |
"""Load all entry poins"""
import os
import sys
from logging import basicConfig
from argparse import ArgumentParser, SUPPRESS, REMAINDER
from wmc import __version__
from wmc.dispatch import load_entry_points
def help_commands():
"""Print the command help."""
commands = load_entry_points()
for cls in comma... |
#!/usr/bin/env python
import pandas as pd
import sys
from argparse import ArgumentParser
def read_df(f):
df = pd.read_csv(f, header=0, sep="\t", index_col=0)
return df
def calc_means(dfsum, sample_info, info_col):
# Create dictionary to rename columns to their corresponding samplegroup
rename_dict ... |
import random
import time
f = open("python-basic-project/unit09/data.txt")
lines = f.readlines()
f.close()
random.shuffle(lines)
for line in lines:
line = line.strip()
print(line)
start = time.time()
user = input("")
end = time.time()
if line.strip() == user:
elapsed = end - start... |
import PySAM.BatteryStateful as bt
def test_stateful():
b = bt.new()
params = {"control_mode": 0, "input_current": 1, "chem": 1, "nominal_energy": 10, "nominal_voltage": 500,
"initial_SOC": 50.000, "maximum_SOC": 95.000, "minimum_SOC": 5.000, "dt_hr": 1.000, "leadacid_tn": 0.000,
"... |
nome = str ( input ('Digite o seu nome completo: '))
print ('Seu nome em letras maisculas fica assim: ', nome.upper())
print ('seus nome em letras minsuculas fica assim: ', nome.lower())
print ('Quantidade de letras do seu nome: ', len ( nome.replace(' ','')))
nome = nome.split(' ')
print ('{}'.format (len(nome[0])))
... |
#!/usr/bin/python
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import datetime
import dateutil.relativedelta
# PUT YOUR DEVELOPER KEY HERE
DEVELOPER_KEY = "## PUT YOUR KEY HERE"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
de... |
import ujson
from typing import Union, List, Optional
from waio.keyboard.list import ListMainButton
class KeyboardButton(ListMainButton):
def __init__(self, title: str):
super().__init__(title)
class QuickReplyContentBase:
def __init__(self, text: str, caption: str):
self.text = text
... |
from pyot.utils import loop_run
from pyot.models import lol
def test_status():
status = loop_run(lol.Status(platform="na1").get())
status.dict(recursive=True) |
#!/usr/bin/python
# requires
# urllib3, python-pip
# pip install boto BeautifulSoup
import sys
import os
from Config import Config
config = Config()
config.create_html = True
config.create_movie = True
config.create_snapshot = True
config.data_file = "sample.csv"
config.data_definition_file = "data.definition"
con... |
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip()
if not s:
return 0
if s[0] == '-':
is_negative = True
start_index = 1
elif s[0] == '+':
is_negative = False
start_index = 1
else:
is_negative... |
import tempfile
import numpy as np
import pandas as pd
from paysage import batch
from paysage import backends as be
import pytest
def test_hdf_table_batch():
# the temporary storage file
store_file = tempfile.NamedTemporaryFile()
# create data
num_rows = 10000
num_cols = 10
df_A = pd.DataFra... |
#-----------------------------------------------------------------------------
# Runtime: 128ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
word1_length, word2_length = len(wor... |
#coding:utf-8
#
# id: bugs.core_1009
# title: Restoring RDB$BASE_FIELD for expression
# decription: RDB$BASE_FIELD for expression have to be NULL
# tracker_id: CORE-1009
# min_versions: []
# versions: 2.1
# qmid: bugs.core_1009
import pytest
from firebird.qa import db_factory, isql_act... |
import falcon
import simplejson as json
import mysql.connector
import config
from anytree import Node, AnyNode, LevelOrderIter
import excelexporters.equipmenttracking
class Reporting:
@staticmethod
def __init__():
pass
@staticmethod
def on_options(req, resp):
resp.status = falcon.HTTP... |
"""
Created on Mon Jun 14 15:24:21 2021
Represents a transaction with its inputs and outputs
@author: tj
"""
import hashlib
import struct
from binascii import hexlify, unhexlify
from script import BTCScript
from script import DEFAULT_TX_SEQUENCE
DEFAULT_TX_VERSION = b'\x02\x00\x00\x00'
DEFAULT_TX_LOCKTIME = b'\x00... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.