content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
from .login import *
from .action import *
from .box import *
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' | python |
"""Created by Alysha Kester-Terry 3/12/2021 for GoodRx
This file is to set up the driver for a specific site.
We want to make this scalable in case there could be multiple environments or web UI URLs we may want to hit.
"""
import logging
def get_app_url(App, environment='test'):
"""To define the search engine URL by... | python |
# Copyright 2019 Contributors to Hyperledger Sawtooth
#
# 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 ... | python |
##############################################
# sudo apt-get install -y python3-picamera
# sudo -H pip3 install imutils --upgrade
##############################################
import multiprocessing as mp
import sys
from time import sleep
import argparse
import cv2
import numpy as np
import time
try:
from armv... | python |
from argparse import ArgumentParser
from os import rename, walk
from os.path import join, splitext
PLACEHOLDER_VARIABLE = 'base-angular-app'
PLACEHOLDER_TITLE = 'Base Angular App'
PLACEHOLDER_OWNER = 'BaseAngularAppAuthors'
EXCLUDED_DIRECTORIES = ['.git', '.idea', 'node_modules']
EXCLUDED_FILES = ['replacer.... | python |
import os
import datetime
import json
from officy import JsonFile, Dir, File, Stime
from rumpy import RumClient
father_dir = os.path.dirname(os.path.dirname(__file__))
seedsfile = os.path.join(father_dir, "data", "seeds.json")
infofile = os.path.join(father_dir, "data", "groupsinfo.json")
FLAG_JOINGROUPS = True
PORT ... | python |
from gquant.dataframe_flow import Node
from gquant.dataframe_flow._port_type_node import _PortTypesMixin
from gquant.dataframe_flow.portsSpecSchema import ConfSchema
class DropNode(Node, _PortTypesMixin):
def init(self):
_PortTypesMixin.init(self)
cols_required = {}
self.required = {
... | python |
# todo: strict version
class Accessor:
def split_key(self, k, *, sep="/"):
return [normalize_json_pointer(x) for x in k.lstrip(sep).split(sep)]
def split_key_pair(self, k, *, sep="@"):
if sep not in k:
return self.split_key(k), []
else:
access_keys, build_keys = ... | python |
#!/usr/bin/env python3
from os import listdir
from os.path import isdir, isfile, join
def get_focus(day):
day = int(day.split(" ")[1].split(":")[0])
if day == 1:
return "Chest"
elif day == 2:
return "Quads"
elif day == 3:
return "Back"
elif day == 4:
ret... | python |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from scipy import interpolate
import torch
import tqdm
from neural_clbf.controllers import NeuralObsBFController, ObsMPCController
from neural_clbf.experiments import (
RolloutSuccessRateExperiment,
ExperimentSuite,
... | python |
import pandas as pd
from pdia.extendedInfoParser.parseExtendedInfo import errorCode
def parseCalculatorEvents(eInfo):
"""Parse a calculator event string, return parsed object or None
"""
assert (isinstance(eInfo, pd.Series))
try:
res = eInfo.apply(lambda x: {"Calculator": x})
except:
... | python |
import csv
import datetime as dt
import hashlib
import io
import re
from decimal import Decimal
from django.utils.dateparse import parse_date
from django.utils.encoding import force_str
from django.utils.text import slugify
def parse_zkb_csv(data):
f = io.StringIO()
f.write(force_str(data, encoding="utf-8", ... | python |
import time
import pygame
from pygame.locals import K_ESCAPE, K_SPACE, QUIT, USEREVENT
COUNTDOWN_DELAY = 4
def timerFunc(countdown, background):
print("Timer CallBack", time.time())
print(countdown)
print("--")
# Display some text
font = pygame.font.Font(None, 36)
text = font.render(str(cou... | python |
#!/usr/bin/env python
# coding=utf-8
import re
import time
import string
from urlparse import urlparse
from comm.request import Req
from conf.settings import DICT_PATH
from core.data import result
from core.data import fuzz_urls
from Queue import Empty
class FuzzFileScan(Req):
def __init__(self, site, timeout, d... | python |
from gql.schema import make_schema_from_path
from pathlib import Path
def test_make_schema_from_path():
schema = make_schema_from_path(str(Path(__file__).parent / 'schema'))
assert set(schema.query_type.fields.keys()) == {'me', 'addresses'}
assert set(schema.mutation_type.fields.keys()) == {'createAddres... | python |
# -*- coding: utf8 -*-
import requests, json, time, os
requests.packages.urllib3.disable_warnings()
cookie = os.environ.get("cookie_smzdm")
def main(*arg):
try:
msg = ""
SCKEY = os.environ.get('SCKEY')
s = requests.Session()
s.headers.update({'User-Agent':'Mozilla/5.0 (Windows NT... | python |
from setuptools import setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="streambook",
author="Alexander Rush",
author_email="arush@cornell.edu",
version="0.1.2",
packages=["streambook"],
long_description=long_description,
long_descript... | python |
class WebserialError(Exception):
pass
class EqualChapterError(WebserialError):
pass
class NoChaptersFoundError(WebserialError):
pass
class LocalAheadOfRemoteError(WebserialError):
pass
| python |
"""
Lambdas
AS known as expression lambda or lambdas. Function anonymous
# FUnction Python
def sum(a, b):
return a + b
def function(x):
return 3 * x + 1
print(function(4)) # 13
print(function(7)) # 22
# Expression lambda
lambda x: 3 * x + 1
# How can I use expression lambda?
calculation = lambda x: 3... | python |
from userbot.utils import admin_cmd
from telethon.tl.functions.users import GetFullUserRequest
import asyncio
@borg.on(admin_cmd(pattern="pmto ?(.*)"))
async def pmto(event):
if event.reply_to_msg_id:
reply_message = await event.get_reply_message()
chat_id=await event.client(GetFullUserRe... | python |
import asyncio
import sys
import os
project_root = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..'))
sys.path.insert(0, project_root)
from ahk import AHK, AsyncAHK
from unittest import TestCase, IsolatedAsyncioTestCase
from PIL import Image
from itertools import product
import time
cl... | python |
from django.contrib import admin
from certificates.models import ProductionSiteCertificate
from certificates.models import DoubleCountingRegistration, DoubleCountingRegistrationInputOutput
class ProductionSiteCertificateAdmin(admin.ModelAdmin):
list_display = ('production_site', 'get_certificate_type', 'certifica... | python |
# Copyright 2019 Google LLC
#
# 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, ... | python |
"""tipo torneo
Revision ID: 016
Revises: 015
Create Date: 2014-05-27 22:50:52.173711
"""
# revision identifiers, used by Alembic.
revision = '017'
down_revision = '016'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('tipo_torneo',
sa.Column('id', sa.Integer, primary_key=... | python |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return None
slow = head
fast = head
while fast.next and fast.next.next:
... | python |
import logging
import subprocess
LOG = logging.getLogger(__name__)
def run(*cmd, **kwargs):
"""Log and run a command.
Optional kwargs:
cwd: current working directory (string)
capture: capture stdout and return it (bool)
capture_stderr: redirect stderr to stdout and return it (bool)
env: env... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mask_selection2.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import config
import numpy as np
class Ui_MaskWindow(object):
def set... | python |
import argparse, os
import torch
from sampling_free.config import cfg
from sampling_free.data import make_data_loader
from sampling_free.engine import do_inference
from sampling_free.modeling import build_model
from sampling_free.utils import Checkpointer, setup_logger, mkdir
def eval_checkpoint(cfg, model, output_d... | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 19:08:39 2019
@author: Tim Hohmann et al. - "Evaluation of machine learning models for
automatic detection of DNA double strand breaks after irradiation using a gH2AX
foci assay", PLOS One, 2020
"""
# main file for training machine learning models using previ... | python |
import textwrap
import uuid
from moviepy.editor import *
import os
from moviepy.video.tools.drawing import *
os.chdir('../')
cwd = os.getcwd()
os.chdir('src')
TITLE_FONT_SIZE = 40
FONT_SIZE = 35
TITLE_FONT_COLOR = 'white'
BGM_PATH = rf'{cwd}\assets\bgm.mp3'
STATIC_PATH = rf'{cwd}\assets\static2.mp4'
SIZE = (1080, 192... | python |
from __future__ import absolute_import
from flask import request, abort
from flask.views import MethodView
from huskar_sdk_v2.consts import OVERALL
from more_itertools import first
from huskar_api import settings
from huskar_api.models import huskar_client
from huskar_api.models.auth import Authority
from huskar_api.... | python |
import os
import numpy as np
import glob
import fire
import pandas as pd
from PIL import Image
import platform
# fix for windows
if platform.system() == 'Windows':
print('INFO: Path to openslide ddl is manually added to the path.')
openslide_path = r'C:\Users\ls19k424\Documents\openslide-win64-20171122\bin'
... | python |
#client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 3333 ... | python |
"""
Calculations that deal with seismic moment tensors.
Notes from Lay and Wallace Chapter 8:
* Decomposition 1: Mij = isotropic + deviatoric
* Decomposition 2: Mij = isotropic + 3 vector dipoles
* Decomposition 3: Mij = isotropic + 3 double couples
* Decomposition 4: Mij = isotropic + 3 CLVDs
* Decomposition 5: Mij =... | python |
#!/usr/bin/python
import sys,os
FUNC_NAME_LEN_MAX = 48
def ext_time_sec(l):
l = l.strip()
tks = l.split(" ")
try:
return float(tks[-1][:-1])
except:
print 'Invalid line to extract time duration: ' + l;
return None
def print_array_info(arr,detail=False):
arr.sort(reverse=T... | python |
from stockfish import Stockfish
class StockfishPlayer:
def __init__(self, stockfishpath):
conf = {
"Write Debug Log": "false",
"Contempt": 0,
"Min Split Depth": 0,
"Threads": 1,
"Ponder": "false",
"Hash": 16,
"Mu... | python |
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2017 Dan Persons (dpersonsdev@gmail.com)
#
# 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 limita... | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict
from ax.core.base import Base
if TYP... | python |
"""
AUTHOR - Atharva Deshpande
GITHUB - https://github.com/AtharvaD11
QUESTION LINK - https://www.codechef.com/LRNDSA01/problems/FCTRL
"""
"""
ALGRITHM - Factorials of all n>= 5 contains trailing zeroes. So, we keep on dividing n till n becomes < 5 and simultaneously keep on summing the quotient. ... | python |
from mlflow.pyfunc import PyFuncModel
from mlserver.types import InferenceRequest
from mlserver_mlflow import MLflowRuntime
from mlserver_mlflow.encoding import DefaultOutputName
def test_load(runtime: MLflowRuntime):
assert runtime.ready
assert type(runtime._model) == PyFuncModel
async def test_predict(r... | python |
#!/usr/bin/env python
from __future__ import print_function
import math
def intercept(pt, dt, pb, n):
return math.pow((pb * float(dt)**(n+1.0))/float(pt), 1.0/(n+1.0))
def main():
for i in range(0, 4):
print(intercept(45, 30, 30, i))
if __name__ == '__main__':
main()
| python |
from django.apps import AppConfig
class EmailAppConfig(AppConfig):
name = 'app.emails'
label = 'email_app'
verbose_name = 'Emails App'
default_app_config = 'app.emails.EmailAppConfig'
| python |
from django import template
# These are custom template filters.
register = template.Library()
@register.filter(name='author_url_converter')
def author_url_converter(value):
# We take in the value, in this case the url of our author, and then return the one that takes them to the front-facing profile page.
r... | python |
import socket
import re
from threading import Thread
from threading import Lock
import os
from mimetypes import MimeTypes
import Queue
class ClientHandler:
def __init__(self, clientSocket, clientAddress):
print "New thread."
self.mSocket = clientSocket
self.mSocket.settimeout(15... | python |
# load the train and test
# train algo
# save the metrices, params
import os
import warnings
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassif... | python |
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib import cm
import numpy as np
# 6 October 2021
# https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html
# https://stackoverflow.com/questions/11647261/create-a-colormap-with-white-centered-around-zero
# https://matpl... | python |
from flask import Blueprint, jsonify
from flask_user import current_user, login_required, roles_accepted
from flask import Blueprint, redirect, render_template
from app.models.pizza_models import Restaurant, PromoCode
# When using a Flask app factory we must use a blueprint to avoid needing 'app' for '@app.route'
rest... | python |
'''
Created on 2015/11/08
@author: _
'''
from inspect import getargspec
ORIGINAL_ARGSPEC_ATTRIBUTE = "__originArgSpec__"
def getOriginalArgSpec(func):
'''
Returns a ArgSpec of the function
@param func: a target function
@return: ArgSpec instance of the function
'''
if not hasattr(func, ... | python |
from rift.data.handler import get_handler
from rift import log
LOG = log.get_logger()
TENANT_COLLECTION = "tenants"
class Tenant(object):
def __init__(self, tenant_id, name=None):
self.tenant_id = tenant_id
self.name = name
def as_dict(self):
return {
"tenant_id": self.te... | python |
DB_NAME = "server.db"
ANALYTICS_NAME_JSON = "analytics.json"
ANALYTICS_NAME_PNG = "analytics.png"
| python |
from typing import List
class RemoveCoveredIntervals:
def get_intervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: (x[0], -x[1]))
resultIntervals = [intervals[0]]
for current_left, current_right in intervals[1:]:
previous_left, previous_right = r... | python |
# coding: utf-8
'''
Created on Oct 20, 2014
@author: tmahrt
To be used in conjunction with get_pitch_and_intensity.praat.
For brevity, 'pitch_and_intensity' is referred to as 'PI'
'''
import os
from os.path import join
import math
import io
from praatio import dataio
from praatio import tgio
from praatio.utilities... | python |
"""
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. There is
at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance
between him and the closest person to him is maximized. Return that maximum distance to cl... | python |
import re
import string
import shortuuid
alphabet = string.ascii_lowercase + string.digits
su = shortuuid.ShortUUID(alphabet=alphabet)
def shortuuid_random():
return str(su.random(length=8))
def to_snake_case(words):
regex_pattern = r'(?<!^)(?=[A-Z])'
if isinstance(words, str):
return re.sub... | python |
from collections import MutableSet
from . import helpers
FORWARD = 1 # used to look at Node children
BACKWARD = -1 # used to look at Node parents
class NodeSet(MutableSet):
"""
A mutable set which automatically populates parent/child node sets.
For example, if this NodeSet contains `children` no... | python |
# -*- coding: utf-8 -*-
"""
__title__ = '画出类、大组、小组的树状曲线'
__author__ = xiongliff
__mtime__ = '2019/7/16'
"""
import json
import os
from innojoy_calculate.common import const
from innojoy_calculate.utils import read_xls_data
class Node:
def __init__(self, id, value,is_leaf, parent_id):
self.id =... | python |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_task_utils"""
from __future__ import print_function
from resilient_circuits.util import *
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_task_utils package"""
reload_params = {"package": u"fn_task_ut... | python |
"""This module contains the class declaration for the MapViewWidget."""
from math import pi, sin, cos
from PySide6.QtCore import QPoint, QPointF, Qt
from PySide6.QtGui import QCursor, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QApplication, QWidget
from sailsim.sailor.Commands import Waypoint
# Map ... | python |
from .uia_control import UIAControl
class HeaderItem(UIAControl):
CONTROL_TYPE = "HeaderItem"
| python |
#!/usr/bin/env python3
# This is awful. What it does is scan the specified root paths, recursively,
# for zip files (checking magic number, not extension), and unzips those which
# contain only a single file. The file's name inside the zip is ignored, except
# for the extension, which is combined with the extension-l... | python |
nun = int(input('Digite um número para ver sua tabuada: '))
print('-' * 12)
print('{} x {} = {}'.format(nun, 1, nun*1))
print('{} x {} = {}'.format(nun, 2, nun*2))
print('{} x {} = {}'.format(nun, 3, nun*3))
print('{} x {} = {}'.format(nun, 4, nun*4))
print('{} x {} = {}'.format(nun, 5, nun*5))
print('{} x {} = {}'.for... | python |
# Copyright (C) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.
from mmlspark.vw._VowpalWabbitContextualBandit import _VowpalWabbitContextualBandit, _VowpalWabbitContextualBanditModel
from pyspark.ml.common import inherit_doc
from pyspark impor... | python |
"""
/*
* -----------------------------------------------------------------
* $Revision: 1.3 $
* $Date: 2010/12/01 23:08:49 $
* -----------------------------------------------------------------
* Programmer(s): Allan Taylor, Alan Hindmarsh and
* Radu Serban @ LLNL
* --------------------------------... | python |
class NetworkNode:
nodeClass = 'IoT'
def __init__(self, serialNumber, os, ip, location='5th Floor Storage Room'):
self.serialNumber = serialNumber
self.os = os
self.ip = ip
def nodeInfo(self):
print('-' * 79)
return '{} {} {} {}'.format(self.serialNumber, self.os, ... | python |
import json
import os
from collections import OrderedDict
def load_characters():
fname = os.path.join(os.path.dirname(__file__), 'charactersdata.json')
with open(fname, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
def load_locations():
fname = os.path.join(os.p... | python |
from behave import use_step_matcher, step, when, then
use_step_matcher("re")
@when('I want to calculate (?P<number_a>\d) and (?P<number_b>\d)')
def step_impl(context, number_a, number_b):
context.number_a = int(number_a)
context.number_b = int(number_b)
@step('use addition method')
def use_addition_method(... | python |
from django.apps import AppConfig
class DeliverymanagementConfig(AppConfig):
name = 'DeliveryManagement'
| python |
import groups
import config
import discord
import log.logging
from discord import Option
from discord.ext import commands
from utility import EncodeDrawCode
class Draw(commands.Cog):
def __init__(self, bot):
self.bot = bot
@groups.fun.command()
async def draw(
ctx: commands.Context,
... | python |
from math import ceil
def find_median(arr):
n = len(arr)
median = find_median_util(arr, n/2+1, 0, n-1)
print(median)
def find_median_util(arr, k, low, high):
m = partition(arr, low, high)
length = m - low + 1
if length == k:
return arr[m]
if length > k:
return find_medi... | python |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2021 Aarno Labs LLC
#
# Permission is hereby granted, free of charg... | python |
"""init
Revision ID: 51b36c819d5f
Revises:
Create Date: 2019-12-07 22:55:45.980654
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '51b36c819d5f'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by ... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as sk
import copy
import warnings
import pickle
import joblib
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import math
from sklearn.model_selection import train_test_split
from sklearn.mo... | python |
from constants import CURRENCY_SYMBOLS_MAP
class CurrencySymbols(object):
# Checks if the input currency name exists in the map
# If it exists, return the symbbol
@staticmethod
def get_symbol(currency):
if not currency:
return None
else:
return CURRENCY_SYMBOLS_... | python |
class WorkflowException(Exception):
pass
class UnsupportedRequirement(WorkflowException):
pass
| python |
# BSD 3-Clause License
#
# Copyright (c) 2017 xxxx
# All rights reserved.
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 th... | python |
from .model import TapisModel
from .searchable import SearchableCommand
| python |
from cfnlint.core.BaseYamlLinter import BaseYamlLinter
class Linter(BaseYamlLinter):
def lint(self):
resources = self.file_as_yaml['Resources']
lintingrules = self.lintingrules['ResourceTypes']
for resource_name, resource in resources.items():
# Skip custom resources, canno... | python |
from rest_framework import serializers
from app_idea_feed.serializers import IdeaFeedItemSerializer
from user_profiles_api.serializers import UserProfileSerializer
from app_user_actions.serializers import UserLikedIdeasSerializer, \
IdeaLikedByUsersSerializer, IdeaCommentByUsersSerializer
from app_user_actions.mo... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Customer, CreditCard, Transaction, Product, ScheduledPayment
class CustomerAdmin(admin.ModelAdmin):
"""CustomerAdmin"""
list_display = ('owner_id', 'name', 'mobile', 'email', 'company')
class... | python |
from dunderfile import __FILE__, __LINE__, __func__, helper
assert __FILE__() == __file__
assert helper.__FILE__ == __FILE__()
assert helper.__LINE__ == __LINE__()
# Because we're at top-level in the module.
assert __func__() == '<module>'
def my_function():
assert __func__() == 'my_function'
assert __func__... | python |
import requests
from datetime import datetime
def str_parse_time(string):
"""Parses given string into time"""
r = requests.get("https://dateparser.piyush.codes/fromstr", params={"message": string})
data = r.json()
return data["message"]
def format_time(time):
"""Formats the time"""
format = time.strftime("%a, ... | python |
import django.forms
from .models import City
class CityForm(django.forms.ModelForm):
class Meta:
model = City
fields = ['name']
widgets = {'name': django.forms.TextInput(attrs={'class': 'input', 'placeholder': 'City Name'})}
| python |
from nose.tools import *
from pysb.core import Model, SelfExporter
import pickle
def with_model(func):
"""Decorate a test to set up and tear down a Model."""
def inner(*args, **kwargs):
model = Model(func.__name__, _export=False)
# manually set up SelfExporter, targeting func's globals
... | python |
# Copyright (C) 2007 Samuel Abels
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distri... | python |
ascii_snek = """\
--..,_ _,.--.
`'.'. .'`__ o `;__.
'.'. .'.'` '---'` `
'.`'--....--'`.'
`'--....--'`
"""
def main():
print(ascii_snek)
if __name__ == '__main__':
main() | python |
if __name__ == '__main__':
from pino.ino import Arduino, Comport, PinMode, PinState
from pino.config import Config
# from pino.ui.clap import PinoCli
from time import sleep
# com = Comport().set_baudrate(115200) \
# .set_port("/dev/ttyACM0") \
# .set_inofile("$HOME/Experimental/pino... | python |
""""""
from sys import stdout
from typing import List, Dict, Optional, Union, Tuple, Any, Iterable
import logging
import json
from itertools import product
import pandas as pd
from pandas import DataFrame
from shimoku_api_python.exceptions import ApiClientError
from .data_managing_api import DataValidation
from .expl... | python |
import numpy as np
from pyscf.pbc import scf as pbchf
from pyscf.pbc import dft as pbcdft
import ase
import ase.lattice
import ase.dft.kpoints
def run_hf(cell, exxdiv=None):
"""Run a gamma-point Hartree-Fock calculation."""
mf = pbchf.RHF(cell, exxdiv=exxdiv)
mf.verbose = 7
print mf.scf()
return ... | python |
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sites.models import Site
import urllib.request
import json
import pytz
import datetime
from django.utils import timezone
import html
import uuid
from time import sleep
from apps.pages.models import SuperintendentMessage
from apps.imag... | python |
import os
import unittest
import sqlite3
import datetime
import pandas
from gtfspy.gtfs import GTFS
from gtfspy.filter import FilterExtract
from gtfspy.filter import remove_all_trips_fully_outside_buffer
from gtfspy.import_gtfs import import_gtfs
import hashlib
class TestGTFSFilter(unittest.TestCase):
def setU... | python |
#!/usr/bin/python3
#
# Elliptic Curve test code
#
# Copyright (c) 2018 Alexei A. Smekalkine <ikle@ikle.ru>
#
# SPDX-License-Identifier: BSD-2-Clause
#
import time
import ec, ec_swj, ecdsa, ecgost
from field import Fp
count = 100
rounds = 0
test_ecdsa = True
test_ecgost = True
test_swj = True
o = ecgost.group (... | python |
from django.urls import path
from departamento.views import IndexView, DetalleDepartamentoView, Register, ExitoRegistro
from django.contrib.auth.decorators import login_required
app_name="departamento"
urlpatterns=[
path("",login_required(IndexView.as_view()),name="index_departamento"),
path("crear/",login_requ... | python |
import hashlib
# https://en.wikipedia.org/wiki/Linear_congruential_generator
class lcg(object):
def __init__(self, seed=1):
self.state = seed
def _random(self):
self.state = (self.state * 1103515245 + 12345) & 0x7FFFFFFF
return self.state
def random(self):
retu... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 1 23:01:34 2017
@author: kt12
"""
# Reversed
""" If there is no __reversed__ function, Python will call __len__ and
__getitem__ which are used to define a sequence
"""
normal_list = [1,2,3,4,5]
class CustomSequence():
def __len__(self):... | python |
def mkdir_p(path):
"""Make directories for the full path, like mkdir -p."""
import os
import errno
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
mkdir_p('my_dir/hi/test')
print('R... | python |
#!/usr/bin/env python
"""
patser_annotate_genome.py
search all chromosomes in a genome sequence file for specified matrix. Annotate hits as rows in sqlite table
"""
import sys
import sqlite3
import fasta_subseq_2
import patser_tools
#from multiprocessing import Pool
#from pprint import pprint as pp
class searchObj(o... | python |
acesso=2502
while True:
senha=int(input('digite sua senha'))
if senha== acesso:
print('acesso permitido')
break
else:
print('acesso negado')
| python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Settings/Master/Pokemon/CameraAttributes.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _messag... | python |
import os
import sys
import platform
import pandas as pd
import easygui as eg
mtst_programs = pd.read_csv('mtst_programs.csv')
current_os = platform.system()
# change default file open directory depending on operating system
if current_os == 'Windows':
default_dir = "C:\\Users\\%USERNAME%\\Documents\\{}*.xlsx"
el... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.