content stringlengths 5 1.05M |
|---|
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.master.title("Grid Manager")
for r in range(6):
self.master.rowconfigure(r, weight=1)
for c in range(5):
self.master.column... |
"""Dictionary utility tools"""
from typing import Any
def merge(*dicts: dict) -> dict:
"""Deep merges the right most dictionaries into the left most one.
Args:
*dicts (dict): dictionaries to be merged.
Examples:
>>> a = {'a': 1, 'b': 2}
>>> b = {'b': 3, 'c': {'c1': 4, 'c2': 3}}
... |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4
import enum
import winsdk
_ns_module = winsdk._import_ns_module("Windows.Media.Casting")
try:
import winsdk.windows.devices.enumeration
except Exception:
pass
try:
import winsdk.windows.foundation
except Exception:
... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
L = [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1)]
L = list(filter(lambda x : sum(x) != n, L))
print(L)
|
from meiga import Result
from petisco.controller.errors.http_error import HttpError
from petisco.controller.errors.invalid_token_http_error import InvalidTokenHttpError
from petisco.controller.tokens.jwt_errors import InvalidTokenError
class KnownResultFailureHandler:
def __init__(self, result: Result):
... |
import typing
from django.db.models import Q
from rest_framework import serializers
from iaso.models import OrgUnitType, OrgUnit, Project, Form
from ..common import TimestampField, DynamicFieldsModelSerializer
from ..projects.serializers import ProjectSerializer
from ..forms import FormSerializer
class OrgUnitTypeSe... |
from __future__ import absolute_import
from celery import bootsteps
from celery.tests.case import AppCase, Mock, patch
class test_StepFormatter(AppCase):
def test_get_prefix(self):
f = bootsteps.StepFormatter()
s = Mock()
s.last = True
self.assertEqual(f._get_prefix(s), f.bluepr... |
from src import utils
def test_encrypt_and_decrypt():
msg = 'my very secret message'
code = utils.encrypt(msg)
assert type(code) is str
assert msg == utils.decrypt(code)
|
import datajoint as dj
schema = dj.schema("common_subject")
@schema
class Subject(dj.Manual):
definition = """
subject_id: varchar(80)
---
age: varchar(80)
description: varchar(80)
genotype: varchar(80)
sex: enum('M', 'F', 'U')
species: varchar(80)
"""
def insert_from_nwbfile... |
#!/usr/bin/env python
import sys
import socket
def main():
argv = sys.argv[1:]
cmd = argv[0]
if len(argv) > 0:
cmd = argv[0]
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect("/tmp/pyvoidd.sock")
client.sendmsg([cmd.encode('utf-8')])
clien... |
import smarter
from .models import Page, PageFile
class PageViews(smarter.GenericViews):
model = Page
options = {
'add': {
'redirect': lambda view, request, **kwargs: view.get_url('index')
},
'edit': {
'exclude': ('owner',),
'redirect': lambda view, ... |
# http://alexmic.net/flask-sqlalchemy-pytest/
from os import unlink
import pytest
from os.path import join, exists
from sqlalchemy.orm import scoped_session
# from boucanpy.core import load_env
from boucanpy.core.utils import db_dir, project_dir, storage_dir
# load_env("api.test")
from boucanpy.api.api import api
f... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
from ..models import Release
from .base import BaseDownloadTests
class DownloadModelTests(BaseDownloadTests):
def test_stringification(self):
self.assertEqual(str(self.osx), 'Mac OSX')
self.assertEqual(str(self.release_275), 'Python 2.7.5')
def test_published(self):
published_release... |
'''
@author: xiayuanhuang
'''
import csv
import matchECtoDemog
import riftehr_new_ped
def riftehr(patientFile, ecFile, familyTreeOutput):
reader_p = csv.reader(open(patientFile, 'r'), delimiter = ',')
h_p = next(reader_p)
exp_header_p = ['PatientID', 'FirstName', 'LastName', 'Sex', 'PhoneNumber', 'Zipco... |
import sys
import time
import numpy as np
import operator
import story_maker as sm
# coherences
anyway = ["robot", "detective", "wine", "coffee","waltz","tango","emperor","trip","trap","rob","terrorise","scotch","Wiskhy","rhum","wine", "milk"]
noway = ["poke","badmouth","36Flip","Moulinex","lumberjack","polka","robot ... |
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
ma = Marshmallow(app)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
bcrypt =... |
# -*- coding: utf-8 -*-
'''
File name: code\migrating_ants\sol_393.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #393 :: Migrating ants
#
# For more information see:
# https://projecteuler.net/problem=393
# Problem Statement
'''
An n... |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
#!/usr/bin/env python3
""""
Model that does same hashing as is in MorganFingerprints - AllChem.GetHashedMorganFingerprint(),
so it hashes all active molecules and then it hashed all test molecules and for each test molecule
it computes similarity to all active hashed molecules and it takes the highest one.
Configu... |
print("Punto 15 del taller")
"""
Entradas
Nivel de Hemoglobina = n
Edad = e
Sexo = s
Salidas
Resultado = r
"""
#entrada
n=int(input("Nivel de hemoglobina: "))
e=int(input("Edad en meses: "))
s=int(input("Si es mujer ingrese 1 y si es hombre ingrese 2: "))
#caja negra
if(e>=0 and e<=1):
if(n>=13 and n<=26):
r="Neg... |
# -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from shop.models.defaults.address import ShippingAddress
from shop.models.defaults.customer import Customer
class AddressTest(TestCase):
def setUp(self):
super(Addre... |
import json
import re
from bson.json_util import dumps
from flask import Flask
from flask_restplus import Resource, Api, cors
from pymongo import MongoClient
app = Flask(__name__)
api = Api(app)
# MONGODB CONNECTION
client = MongoClient(
"mongodb+srv://flask_server:x8a1PGutyHAjwyTn@lolproject-hzh6x.gcp.mongodb.n... |
import itertools
import random
def main():
#load(open('2gm-common6'))
#load(open('3gm-bible'))
load(open('4gm-bible'))
print babble(100)
def start(tokens=('<S>',)):
n = the_order()
tokens = tokens[-n:]
lt = len(tokens)
if lt == n:
return tokens
candidates = [state
... |
# https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_ag
import math
x1, y1, r1 = map(int, input().split())
x2, y2, r2 = map(int, input().split())
if r1 < r2:
x1, x2 = x2, x1
y1, y2 = y2, y1
r1, r2 = r2, r1
d = (x1 - x2) ** 2 + (y1 - y2) ** 2
if d == (r1 + r2) ** 2:
print(4)
elif... |
# Generated by Django 2.1.8 on 2019-11-26 21:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('employees', '0014_auto_20191126_2131'),
]
operations = [
migrations.AlterField(
model_name='emp... |
"""GroupAttribute / GroupAttributes Object"""
# standard library
from typing import Union
# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.group_attributes.group_attribute_filter import GroupAttributeFilter
from tcex.api.tc.v3.group_attributes.group_attribute_model import (
G... |
"""
## Script for creating the density matrices and species matrices representations
## Uses MPI4PY to parallelise
## Provide the name of the data folder that contains the properties and structures, as created using query_matrpoj.py
## Example:
## -- python3 create_matrices.py --name heusler
---------------------------... |
# addon modules
from . import ops
from . import imp
|
from setuptools import setup
setup(name='VarP',
version='0.3',
description='This package is aimed at providing a way of retrieving epitope candidates from a vcf file'
'instance.',
url='https://github.com/Mazzafish/neoantigen',
author='Carlo Mazzaferro',
author_email='cma... |
from focused_app import get_focused_app, get_focused_context
from focused_app.linux import lib as linux
for w in linux.get_all_windows():
print(w)
|
# https://github.com/tidyverse/tibble/blob/master/tests/testthat/test-tibble.R
import pandas
import pytest
from datar import f
from datar.base import (
NA,
NULL,
as_character,
c,
factor,
letters,
nrow,
rep,
rev,
rownames,
seq,
seq_along,
seq_len
)
from datar.base.ver... |
# Generated by Django 3.2.9 on 2021-12-07 08:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bongaapp', '0008_auto_20211206_0043'),
]
operations = [
migrations.AlterField(
model_name='like... |
"""
validators
~~~~~~~~~~
This module contains the general validators for the articleone
module.
"""
from re import match, sub
import unicodedata as ucd
import urllib.parse as up
from articleone.model import valfactory
# Validator functions.
def val_text(self, value, charset='utf_8', form='NFC'):
"""Normalize ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import math
import numbers
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch import Tensor
from torch.nn.parameter import Parameter
from typing import Tuple
import importlib
from c... |
from .client_proxy import ClientProxy
from .entry import Entry
from .utils import normalize_select
"""
contentful_management.entries_proxy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module implements the EntriesProxy class.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/... |
class Configuration:
"""
Holds the configuration of books2scrape.
"""
def __init__(self):
self.version = '0.0.0'
self.jobs = 64
self.csv_output_dir = 'output/csv'
self.img_output_dir = 'output/img'
self.failure_attempts = 8
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2017-03-03 13:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0033_auto_20170220_1330'),
]
operations = [
migrations.CreateModel(
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import Timer
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QThread
from Ui_LoadingScreen import Ui_LoadScreenForm
class CProcessingDialog(QtGui.QDialog, Ui_LoadScreenForm):
u"""
Окно выполнения вычислений.
Запускается окно с текстом... |
from collections import defaultdict
from datetime import date, datetime, timedelta
from typing import Any, DefaultDict, Dict, List, Optional, Set, Union
import pytz
from src.constants import (
GRAPHQL_NODE_CHUNK_SIZE,
GRAPHQL_NODE_THREADS,
NODE_QUERIES,
PR_FILES,
REST_NODE_THREADS,
)
from src.data... |
# -*- coding: utf-8 -*-
"""
Classes for protein-ligand docking using the PLANTS software:
PLANTS: Protein-Ligand ANT System.
"An ant colony optimization approach to flexible protein-ligand docking" Swarm Intell. 1, 115-134 (2007).
O. Korb, T. Stützle, T.E. Exner
URL: http://www.tcd.uni-konstanz.de/research/pl... |
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .forms import UserCreationForm
from .models import CustomUser
class CustomUserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHash... |
#@ Dataset data
#@ String(label="Dimension to Project", choices={"X", "Y", "Z", "TIME", "CHANNEL"}) projected_dimension
#@ String(label="Projection Type", choices={"Max","Mean","Median","Min", "StdDev", "Sum"}) projection_type
#@OUTPUT Dataset output
#@ OpService ops
#@ DatasetService ds
# Do a projection of a stack. ... |
import astropy.units as u
import pytest
from benchmark import Benchmark, benchmark
@benchmark(
{
"log.initial.system.Age": {"value": 3.155760e13, "unit": u.sec},
"log.initial.system.Time": {"value": 0.000000, "unit": u.sec},
"log.initial.system.TotAngMom": {
"value": 8.302649e4... |
import ray
from ray import tune
ray.init()
tune.run(
"PPO",
stop={"episode_reward_mean": 200},
config={
"env": "CartPole-v0",
"num_gpus": 0,
"lr": tune.grid_search([0.01, 0.001, 0.0001]),
"eager": False,
},
)
|
# -*- coding: utf-8 -*-
# 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 in writing, softw... |
import cw.client
import cw.slurm
import cw.mp
def completion(jobid, output):
"""A callback function tat is invoked whenever a cluster job
completes. Two arguments: the job ID (provided with submission) and
the return value of the job's function invocation.
"""
print(('the square for job {} is {}'.... |
#!/usr/bin/python
#////////////////////////////////////////////////////////////////////////////
# Copyright (c) 2012 Sagemcom Canada Permission to use this work
# for any purpose must be obtained in writing from Sagemcom Canada
# 5252 de Maisonneuve Blvd. West, suite 400, Montreal, Quebec H4A 3S5
#////////////////////... |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def visualization_str_column_attributes(df):
for column in df.columns:
if column == "train_id" or column == "price":
continue
unique_count = df[column].value_counts()
unique_count.sort_values(ascending=False... |
"""Load notebook and cells"""
import argparse
import os
from reproducemegit.jupyter_reproducibility import config
from reproducemegit.jupyter_reproducibility import consts
from reproducemegit.jupyter_reproducibility.db import connect
from reproducemegit.jupyter_reproducibility.utils import StatusLogger
from reproduce... |
from database.databasehandler import MariaDB_handler
import database.spaceHeatingModel as spaceHeatingModel
import requests
import config
from datetime import datetime, timedelta
import math
#################################################################### Formula Explanation ######################################... |
# Generated by Django 2.1.1 on 2018-09-03 11:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('places', '0005_auto_20180903_1309'),
]
operations = [
migrations.AddField(
model_name='places',
name='thumb_link',
... |
def letter_freq(text):
res = {}
for letter in text:
if letter not in res:
res[letter] = 0
res[letter] += 1
return res
print(letter_freq("good morning"))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela
#
# @project: Memory Analysis Report
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
|
"""
A file to contain specific logic to handle version upgrades in Kolibri.
"""
from shutil import rmtree
from django.conf import settings
from kolibri.core.upgrade import version_upgrade
# Before 0.15 we copied static files to the KOLIBRI_HOME directory.
# After 0.15 we read them directly from their source directo... |
import unittest
import hcl2
from checkov.terraform.checks.resource.azure.MSSQLServerMinTLSVersion import check
from checkov.common.models.enums import CheckResult
class TestMSSQLServerMinTLSVersion(unittest.TestCase):
def test_failure(self):
hcl_res = hcl2.loads("""
resource "azurerm_mssql_... |
import os
import pymongo
from mongo_to_sql.databases.mongo import MongoDatabase
from mongo_to_sql_tests.constants.mongo import (
default_collection, mongo_database_one, simplest_document, simplest_document_key, simplest_document_value
)
from mongo_to_sql_tests.fixtures.databases.mongo_fixtures import ( # noqa: F4... |
import seaborn as sns
import torch
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
def plot_heatmap(data, vmin=-1., vmax=1., save_name='heatmap.pdf'):
""" Plots a heatmap.
:param data: DataFrame or ndarray.
:param vmin:
:param vmax:
:par... |
#!/usr/bin/env python3
############################################################
## Jose F. Sanchez ##
## Copyright (C) 2019-2020 Lauro Sumoy Lab, IGTP, Spain ##
############################################################
"""
Create RNA biotype analysis using STAR and featur... |
# -*- coding: utf-8 -*-
"""
SCHERBELBERG
HPC cluster deployment and management for the Hetzner Cloud
https://github.com/pleiszenburg/scherbelberg
src/scherbelberg/_core/ssl.py: Creating CAs and SSL keys
Copyright (C) 2021 Sebastian M. Ernst <ernst@pleiszenburg.de>
<LICENSE_BLOCK>
The contents of this file... |
#!/usr/bin/env python3
import fire
import json
import os
import numpy as np
import tensorflow as tf
import model
import sample
import encoder
"""Kommentar: My son does not know his way around the house. He really needs his face transforming.
Kommentar: Got it , we have to transform human faces with transformers to... |
# Import the module from restoration
from skimage.restoration import inpaint
# Show the defective image
show_image(defect_image, 'Image to restore')
# Apply the restoration function to the image using the mask
restored_image = inpaint.inpaint_biharmonic(defect_image, mask, multichannel=True)
show_image(restored_image... |
import glob, os
#Set directory here
dir = '.'
def inplace_change(filename, old_string, new_string):
s=open(filename).read()
if old_string in s:
print 'Swapped Day and Night in "{filename}"'.format(**locals())
s=s.replace(old_string, new_string)
f=open(f... |
import tkinter as tk
def btn_press():
print("ボタンが押されました")
root = tk.Tk()
root.geometry("150x80")
bt = tk.Button(bitmap="question",command=btn_press)
bt.pack()
root.mainloop() |
import nextcord
from nextcord.ext import commands
import os
RUNNING = 'TOKEN'
bot = commands.Bot(command_prefix = 'b!') # Im pretty sure Discord are migrating to slash commands fully so this is probably going to be useless soon
@bot.event
async def on_ready():
print('online')
@bot.command()
async def load(ctx, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class TextPost(models.Model):
title = models.CharField(max_length=500)
t = models.TextField()
class ImagePost(models.Model):
embedding = models.CharField(max_l... |
from __future__ import print_function, absolute_import, unicode_literals
from ._compat import input, with_metaclass, string_types
##################################################################
# This module is desired by Django
##################################################################
import sys, os
from o... |
import re
from django.db.models import Count
from users.models import Users, DisallowedUsernames
class UsernamesResolutionHelper(object):
def __init__(self, resolve_type='duplicates', dry_run=True):
self.type = resolve_type
self.dry_run = dry_run
self.disallowed_usernames_list = Disallowe... |
import sqlite3
import argparse
import pytest
from project0 import main
def test_populatedb():
data=main.fetchincidents("http://normanpd.normanok.gov/filebrowser_download/657/2020-02-24%20Daily%20Incident%20Summary.pdf")
conn = sqlite3.connect('NORMANPOLICE.db')
c = conn.cursor()
values=main.extractinc... |
"""Define the request module."""
from httpsig.verify import HeaderVerifier
from .errors import SignatureVerificationError
class Response:
"""Defines a response."""
def to_data(self) -> dict:
"""Create a data structure for the response."""
raise NotImplementedError
class EmptyDataResponse(... |
import numpy as np
import pandas
from pandas import read_csv
import matplotlib.pyplot as plt
import sys
script_dir=sys.path[0]
ds_name=sys.argv[1]
csv_path=script_dir + "/" + ds_name + "/" + ds_name + "_metrics_per_time_lag.csv"
png_plot_path=script_dir + "/" + ds_name + "/" + ds_name + "_metrics_per_time_lag.png"
dat... |
from pydgraphORM.flags_structure import dgraphFlags
from pydgraphORM.model_structure import dgraphModel, dgraphTypes, dgraphUID, dgraphID, dgraphString, dgraphInt, dgraphFloat, dgraphBool, dgraphGeo, dgraphDate, idGen
from pydgraphORM.client_structure import structRequest, staticClient, assembly
#Init Models
class d... |
def _get_data_dir():
import os, warnings
from pathlib import Path
DIR_DATA = os.environ.get('MAGNET_DATAPATH', '~/.data')
if DIR_DATA is None:
warnings.warn('You need to have an environment variable called MAGNET_DATAPATH. Add this to your .bashrc file:\nexport MAGNET_DATAPATH=<path>\n'
... |
import random
from src.dal.models import Wisdom
class WisdomDal:
WISDOM_LIST = [
Wisdom(
text="სიყვარული ვერტიკალურია და თან ბრუნვადი",
animation="https://s4.gifyu.com/images/love.gif",
),
Wisdom(
text="არა, ყმაწვილო, არა! ასეთი ცოდნით ვერ გავფრინდებით,... |
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.contrib.messages.storage.base import LEVEL_TAGS
from django.contrib.sessions.models import Session
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.f... |
# Create flat PDF by converting each input PDF page to a PNG
import os
from tempfile import TemporaryDirectory
from pdfconduit.convert.img2pdf import IMG2PDF
from pdfconduit.convert.pdf2img import PDF2IMG
from pdfconduit.transform.upscale import upscale
from pdfconduit.utils.path import add_suffix
class Flatten:
... |
##
# Copyright (c) 2006-2016 Apple Inc. 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 l... |
import subprocess
from typing import Sequence
import click
from {{ cookiecutter.package_name}} import __version__
@click.group()
@click.version_option(version=__version__)
def main() -> None:
"""\n😎 {{ cookiecutter.project_name }} CLI 😎\n"""
@click.command()
@click.argument("session", default="", type=str)
... |
def min_days_bloom2(roses, k, n):
r_sorted = sorted([(x, i) for i, x in enumerate(roses)], reverse=True)
d = {}
while r_sorted:
x, i = r_sorted.pop()
if i-1 in d and i+1 in d:
start = d.pop(i-1)
end = d.pop(i+1)
d[start] = end
d[end] = start
... |
from models.vgg16 import VGG16
from models.resnet import ResNet18, ResNet34, ResNet50
from models.wideresnet import WideResNet28_2, WideResNet28_4, WideResNet28_10, WideResNet34_10
from models.sparse_vgg16 import SparseVGG16
from models.sparse_resnet import SparseResNet18, SparseResNet34, SparseResNet50
from models.spa... |
#!/usr/bin/python3 -B
import sys
import proc
if __name__ == "__main__":
cmds = [
("sleep 1;echo hello world",None),
("echo hi there",2),
]
with proc.MyPool(processes=4) as pool:
results = pool.starmap(proc.call, cmds)
for i in results:
print(i)
sys.exit(0... |
import json
try:
from web3 import Web3
except ImportError:
print("Couldn't import web3, if you don't need ERC-721 support that's OK")
try:
import jwt
except ImportError:
print("Couldn't import jwt, if you don't need JSON web token support that's OK")
class jwt_erc721_pep:
def __init__(self):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
def prodsum(p, s, c, start):
k = p - s + c
if k < LIMIT:
if p < ans[k]: ans[k] = p
for i in range(start, LIMIT // p * 2):
prodsum(p * i, s + i, c + 1, i)
LIMIT = 12000
ans = [2 * LIMIT] * LIMIT
prodsum(1, 1, 1, 2)
print sum(set(ans[2:]))
|
import logging
from bash import bash as alexcouperbash
from colorama import Fore
from colorama import init as colinit
DEBUG = True
# TODO: https://docs.python.org/3/library/asyncio-subprocess.html
def bash(command):
if DEBUG:
'''
colinit()
print('%s%s%s> %s%s%s' % (Fore.YELLOW, 'bash', ... |
# analysis_results.py
from dataclasses import dataclass
from .gradle_benchmark import GradleBenchmark
@dataclass
class PairedTTestDetails:
pvalue: float
significance_level: float
@dataclass
class AnalysisResults:
baseline: GradleBenchmark
modified: GradleBenchmark
details: PairedTTestDetails
... |
from PuppeteerLibrary.utils.coverter import str2bool, str2int
from PuppeteerLibrary.ikeywords.imouseevent_async import iMouseEventAsync
class PuppeteerMouseEvent(iMouseEventAsync):
def __init__(self, library_ctx):
super().__init__(library_ctx)
async def mouse_over(self, locator):
element = a... |
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^more/(?P<extra>\w+)/$', views.empty_view, name='inner-more'),
]
|
from django.contrib import admin
from fbc_app.models import University, Course, Module, Lecturer, Student
# register the models
admin.site.register(University)
admin.site.register(Course)
admin.site.register(Module)
admin.site.register(Lecturer)
admin.site.register(Student)
|
from typing import Callable, Optional
from fastapi import APIRouter, Depends
from authx.api import UsersRepo
from authx.services import SearchService
def get_router(repo: UsersRepo, admin_required: Callable):
SearchService.setup(repo)
"""Search router, for searching users
"""
router = APIRouter()
... |
"""
A simple hello-world workflow with a single Lambda Task state.
"""
from rhodes.states import StateMachine, Task
def build() -> StateMachine:
workflow = StateMachine(Comment="A simple minimal example of the States language")
workflow.start_with(
Task(
"Hello World",
Resourc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-13 15:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0002_profile_description'),
]
operations = [
migrations.AddFiel... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from fabric import api as fab
from fabric.contrib import files as fab_files
from fabric.contrib.files import exists
from fab_deploy.utils import run_as
from ..base import _, Daemon
from ..deployment import command
from ..utils import ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from codecs import open
import fnmatch
import os
from os import path
import sys
from glob import glob
from setuptools import find_packages, setup, Command
here = path.abspath(path.dirname(__file__))
with op... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from EventSenderBL import EventSenderBL
from flask import Flask, jsonify, request
from flask_restful import Resource, Api, reqparse, abort
class EventSenderApi(Resource):
def __init__(self, **kwargs):
self.__eventSenderBL = kwargs['eventSenderBL']
def ge... |
__author__ = 'Colin'
import logging
from backend.database import DB
logger = logging.getLogger("savvy.models.prices")
class PriceDB(DB):
"""Class to connect to the Prices Datastore."""
def price_stats(self, product_id):
"""Returns the average price of a product."""
result = self.db.price... |
##############################################################################
# Institute for the Design of Advanced Energy Systems Process Systems
# Engineering Framework (IDAES PSE Framework) Copyright (c) 2018-2019, by the
# software owners: The Regents of the University of California, through
# Lawrence Berkeley N... |
import unittest
from jb_vpc_cidrcalc.handlers import CIDR
from jb_vpc_cidrcalc.handlers import Lister
cidr_maps = {
16: 28,
32: 27,
64: 26,
128: 25,
256: 24,
512: 23,
1000: 22,
2000: 21,
4000: 20,
8000: 19,
16000: 18,
32000: 17,
64000: 16
}
class CalculatorTests(u... |
from autouserspawner.autouserspawner import AutoUserLocalProcessSpawner
__all__ = [AutoUserLocalProcessSpawner]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.