content stringlengths 5 1.05M |
|---|
import unittest
import json
import schemavalidation
class SchemaValidationTestCase(unittest.TestCase):
def test_event_schema_is_valid(self):
message = json.dumps({
'Timestamp': 1596717736,
'EventType': 'EVENT_TEST',
'ID': 'random-id',
'EmitterId': 'random-e... |
from django.contrib import admin
from .models import ProductImage, Product
from rest_framework.authtoken.admin import TokenAdmin
TokenAdmin.raw_id_fields = ('user',)
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
#list_display = ('id', 'image')
def get_changeform_initial_data(self, r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2014 Loek Wensveen
#
# 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 the righ... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, dataset.shape[1]-1].values
#Fitting the Decision Tree Regression
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(r... |
#!/usr/bin/env python
# Copyright (c) 2013-2017, Rethink Robotics Inc.
#
# 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 ... |
"""
IIPP Mini-Project 2: Guess the Number
Author: Weikang Sun
Date: 6/9/15
codeskulptor source:
http://www.codeskulptor.org/#user40_9uCFBsoLw2_2.py
"""
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import sim... |
class MockECR(object):
@property
def aws_account_id(self):
return '12345678'
@property
def registry(self):
return []
@property
def project_repo(self):
return 'nginxdemos'
def project_repo_exists(self):
return True
def create_project_repo(self):
return True
def get_login(self):... |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def add_bundle_page_view(request):
"""
This view Renders Create Bundle Page
"""
if not request.user.is_viewer :
context = {
"title": "Create B... |
import os
import time
from django.conf import settings
from django.db import models
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from rest_framework.reverse import reverse
from osmaxx.conversion import coordinate_reference_system as crs, output_format, status
from osmax... |
A, B = map(int, input().split())
result = []
if A >= B:
result.extend(range(1, A + 1))
result.extend(-x for x in range(1, B))
result.append(-sum(result))
else:
result.extend(-x for x in range(1, B + 1))
result.extend(range(1, A))
result.append(-sum(result))
print(*result)
|
def minion_game(s):
vowels = 'AEIOU'
k_score = 0
s_score = 0
for i in range(len(s)):
if s[i] in vowels:
k_score += (len(s)-i)
else:
s_score += (len(s)-i)
if k_score > s_score:
print ("Kevin", k_score)
elif k_score < s_score:
print ("Stuart... |
from django.apps import AppConfig
class NewscategoryConfig(AppConfig):
name = 'newsCategory'
|
from django.db import models
from rest_framework import serializers
class sponsors(models.Model):
name = models.CharField(max_length= 150, null= True, blank= True)
sponsor_type = models.CharField(max_length= 150, null= True, blank= True)
website = models.CharField(max_length= 150, null= True, blank= True) ... |
# -*- coding: utf-8 -*-
"""
@file inductionloop.py
@author Michael Behrisch
@author Daniel Krajzewicz
@date 2011-03-16
@version $Id: inductionloop.py 15031 2013-11-05 19:52:41Z behrisch $
Python implementation of the TraCI interface.
SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
Copyright (C) 2... |
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit ... |
import json
from pathlib import Path
from typing import List, Union
from PIL import Image
from torchvision import transforms
from torch.utils.data import Dataset
NORMALIZE_DEFAULT = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
class EasySet(Dataset):
"""
A ready-to-use dataset. Will work for... |
from flask import Flask, request, jsonify
from config import config
import logging
import boto3
app = Flask(__name__)
logging.basicConfig(
filename=config['log_file'],
level=config['log_level']
)
def get_aws_client(request):
aws_access_key_id = request.args.get("aws_access_key_id")
aws_secret_access... |
# -*- coding: utf-8 -*-
"""
Parses EPBD XML data and puts it in a PostgreSQL database.
Based on epbdparser.py made by RVO.
@author: Chris Lucas
"""
import argparse
import xml.sax
import psycopg2
from psycopg2.extensions import AsIs
class EqualError(Exception):
def __init__(self, msg):
self.msg = msg
... |
from ._response import Response
class Me(Response):
@property
def account_status(self) -> str:
return self['accountStatus']
@property
def account_type(self) -> str:
return self['accountType']
@property
def pin_status(self) -> str:
return self['pinStatus']
@proper... |
import discord
from discord.commands.commands import Option, slash_command
from discord.commands.context import AutocompleteContext
from discord.ext import commands
import json
import re
import traceback
import urllib
import aiohttp
from datetime import datetime
from yarl import URL
from data.services.guild_service im... |
from sanic_testing.manager import TestManager
__version__ = "22.3.0"
__all__ = ("TestManager",)
|
#
# Copyright (c) 2018 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... |
import time
import mysql.connector
import hashlib
import zlib
inp = input('Enter something: ')
salt = input('Enter salt ')
dk = hashlib.pbkdf2_hmac('sha256', inp.encode('utf-8'), salt.encode('utf-8'), 100000)
print(dk)
|
#! /home/znfs/pyenv_pyrobot_python2/bin/python
from robot_utils import *
import tf
import yaml
from geometry_msgs.msg import Pose
param_file = '/home/znfs/project_ws/intera/src/iros2021/files/kinect_calibration.yaml'
def quaternion_to_trans_matrix(x, y, z, w, trans_x, trans_y, trans_z):
x_2, y_2, z_2 = x * x, y... |
import time
from random import randint
import getpass
def log(func):
def inner(*args, **kwargs):
start_time = time.perf_counter()
ret = func(*args, **kwargs)
elapsed_time = time.perf_counter() - start_time
ms_flag = False
if elapsed_time < 1:
elapsed_time *= 100... |
import pandas as pd
from common import PathLike
def clean_data(
input_path: PathLike,
output_path: PathLike
):
df = pd.read_csv(input_path)
df = df.dropna()
df.to_csv(output_path)
clean_data(
input_path="data.csv",
output_path="clean_data.csv"
)
|
from django.contrib import admin
from .models import (
OHLCV,
Account,
Bot,
Currency,
Market,
Order,
OrderErrorLog,
Saving,
Trade,
)
class BotInline(admin.TabularInline):
model = Bot
extra = 0
class OrderInline(admin.TabularInline):
model = Order
extra = 0
clas... |
import logging
import random
import time
from .. import Sampler, submit_models, query_available_resources
from .strategy import BaseStrategy
_logger = logging.getLogger(__name__)
class RandomSampler(Sampler):
def choice(self, candidates, mutator, model, index):
return random.choice(candidates)
class Ran... |
#
#
# Copyright (C) 2007, 2011, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list ... |
import sys, os.path
from datetime import datetime, timedelta
if len(sys.argv) < 2:
print(f'usage: {sys.argv[0]} [log_files]')
sys.exit()
last_line = None
start_datetime = None
duration = timedelta(0)
for log_file in sys.argv[1:]:
with open(log_file) as f:
lines = f.readlines()
for line in... |
def checkio(number: int) -> str:
result = []
if (number % 3) == 0:
result.append("Fizz")
if (number % 5) == 0:
result.append("Buzz")
if not result:
result.append(str(number))
return " ".join(result)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from datetime import datetime, timedelta
import sys
import time
import random
from random import uniform
from collections import Counter
from pgoapi.utilities import f2i
from pokemongo_bot import inventory
from poke... |
"""
Gather basic scene timing information from the profiler,
with and without the invisibility evaluator active.
"""
from maya.analytics.decorators import makeAnalytic
from maya.debug.emModeManager import emModeManager
from maya.analytics.decorators import addHelp
from maya.analytics.BaseAnalytic import BaseAnalytic
f... |
import pytest
@pytest.mark.parametrize(
"text,expected_tokens", [("d'un", ["d'", "un"]), ("s'ha", ["s'", "ha"])]
)
def test_contractions(ca_tokenizer, text, expected_tokens):
"""Test that the contractions are split into two tokens"""
tokens = ca_tokenizer(text)
assert len(tokens) == 2
assert [t.te... |
# import modules
import tkinter as t
from random import randrange
tk = t.Tk()
tk.title("Guessing Game")
tk.iconbitmap("logo-ico.ico")
lblInst = t.Label(tk, text = "Guess a number from 0 to 9",)
lblLine0 = t.Label(tk, text = "*********************************************************************")
lblNoGuess = t.Label(... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import UserChangeForm
from .forms import UserCreationForm
from .models import IllumiDeskUser
User = get_user_model()
@admin.reg... |
"""
Copyright 2018 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
import requests
import re
import numpy as np
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
url = 'https://www.baidu.com/s?wd=%E7%95%99%E4%B8%8B%E9%82%AE%E7%AE%B1'
response = requests.get(url,headers=headers)
... |
import numpy as np
def shear_matrix(night, expid, mjd, data):
"""
Computes the second moment matrix
"""
profiles = data['GUIDE']
shear_data = dict()
for camera in profiles:
Q = np.zeros((2, 2))
profile = profiles[camera]['model']
center = profile.shape[0] / 2
... |
class Solution:
def spiral(self, matrix, direction):
if not matrix or not matrix[0]:
return []
direction += 1
if direction % 4 == 0: # right
return matrix[0] + self.spiral(matrix[1:], direction)
elif direction % 4 == 1: # down
new = [i[-1] for i ... |
"""
echopype data model that keeps tracks of echo data and
its connection to data files.
"""
import os
import warnings
import datetime as dt
from echopype.utils import uwa
import numpy as np
import xarray as xr
class ModelBase(object):
"""Class for manipulating echo data that is already converted to netCDF."""
... |
from math import copysign, isnan
import numpy as np
test = False
with open(f"../input/{'test_' if test else ''}day7.txt") as f:
# :pinchers:
crabs = np.array([int(x) for x in f.read().strip().split(",")])
def sim_p1(h):
# d/dh | x - h | = sgn(h - x)
return np.sum(np.abs(crabs - h)), np.sum(np.sign(h ... |
#!/usr/bin/python
import time
from org.apache.pig.scripting import *
__author__ = 'wangwei'
def getParams():
params=[]
cdate=startDate
while cmp(cdate, endDate) != 0:
d={"DATE":cdate}
params.append(d)
timeArray = time.strptime(cdate, "%Y-%m-%d")
timeStamp = int(time.mktime(timeArray))
timeStamp += 86400
... |
#!/usr/bin/env python
import os
import re
import subprocess
import sys
from argparse import ArgumentParser, ArgumentError
from datetime import datetime
import yaml
from ebi_eva_common_pyutils import command_utils
from ebi_eva_common_pyutils.command_utils import run_command_with_output
from ebi_eva_common_pyutils.confi... |
# -*- coding: utf-8 -*-
"""
:Author: Dominic
"""
import sys
sys.path.append("../")
import pytest
import itertools
import numpy as np
from fitAlgs.fitAlg import FitAlg
from modelGenerator import ModelGen
from fitAlgs.fitSims import FitSim
@pytest.fixture(scope="function")
def model_setup():
num... |
class Memory:
def __init__(self, sizeInBytes):
self.array = bytearray(sizeInBytes)
def get(self, address):
return self.array[address]
def get16(self, address):
return (self.array[address] << 8) + self.array[address+1]
def set(self, address, value):
... |
#!/usr/bin/python
import sys
import subprocess
import urllib
from limitedstringqueue import LimitedStringQueue
PROGRAM = sys.argv[1]
COMPILER = sys.argv[2]
#ARGS = sys.argv[3]
ARGS = urllib.unquote(sys.argv[3])
IMAGE_ADDR = sys.argv[4]
IMAGE_PASSWD = sys.argv[5]
LOG_FILE = sys.argv[6]
OS_TYPE=sys.argv[7]
EXECID = sys... |
import numpy as np
import json
from vis_utils.scene.components import ComponentBase
import socket
import threading
import time
import sys
from vis_utils import constants
STANDARD_DT=1.0/120
def write_to_json_file(filename, serializable, indent=4):
with open(filename, 'w') as outfile:
print("save to ", fil... |
# Create Subreddit network using networkx
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import ast
import collections
from tqdm import tqdm
from itertools import count
import networkx as nx
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
input_subreddi... |
#!C:\python27
import time
def performance(f):
def exec_time(*args,**kw):
time_s=time.time()
res=f(*args,**kw)
time_e=time.time()
print 'call %s in %fs'%(f.__name__,(time_e-time_s))
return res
return exec_time
@performance
def factorial(n):
return reduce(lambda x,y:x*y,range(1,n+1))
print... |
import json
def render_stack(error):
return '\n '.join(error.get('stack'))
def render_error(component_name, data):
return """
<div style="background-color: #ff5a5f; color: #fff; padding: 12px;">
<p style="margin: 0">
<strong>Warning!</strong>
The <code>{}</code> component ... |
from tkinter import *
from tkinter.filedialog import asksaveasfilename, askopenfilename
import subprocess
import sys
Window = Tk()
Window.title("Pycoder")
font = ("Comic Sans MS", 16)
fontcolor = "black"
fontback = "gray"
try:
FilePath = sys.argv[1]
except:
FilePath = ""
def prompt(message):
messagewid... |
from flask import Flask
import requests
import json
#Import App ID and App Secret from Config file
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('secret.cfg')
|
import tensorflow.compat.v1 as tf
import os
from tensorflow.python.tools.freeze_graph import freeze_graph
from model import CycleGAN
import utils
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string('checkpoint_dir', 'checkpointsce/20211125-1624', 'checkpoints directory path')
tf.flags.DEFINE_string('XtoY_model', 'cbct2sct.... |
from tests.test_yuos_client import VALID_PROPOSAL_DATA
from yuos_query.utils import (
deserialise_proposals_from_json,
serialise_proposals_to_json,
)
def test_converting_proposals_to_json_and_back():
proposal_json = serialise_proposals_to_json(VALID_PROPOSAL_DATA)
proposals = deserialise_proposals_fro... |
from sys import argv
from os import getenv
from configparser import ConfigParser
from logging import getLogger, FileHandler, Formatter, StreamHandler
from praw.models import Submission
from praw import Reddit
LOG_LEVEL = getenv("LOG_LEVEL", "INFO")
log_formatter = Formatter(
"%(asctime)s, %(levelname)s [%(filena... |
import bpy
import sys
def print_usage():
print("usage: export.py target_file")
argv = sys.argv[1:]
if '--' not in argv:
print_usage()
exit(1)
argv = argv[argv.index("--") + 1:]
if len(argv) != 1:
print_usage()
exit(1)
target_file = argv[0]
bpy.ops.export_scene.gltf(filepath=target_file, expo... |
##
# Torsional Drillstring Model
# Parameters for Well B
#
# @Authors: Ulf Jakob Aarsnes, Roman Shor, Jonathan McIntyre
#
# Copyright 2021 Open Drilling Project
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to... |
import csv, numbers, os
from enum import Enum
from models.Person import *
from Utilities import Logger
def get_acs_person_data(filepath, year):
# set up personal logger
logger = Logger()
current_path = os.getcwd()
logger.define_issue_log(os.path.join(current_path, 'files/issues.log'))
dictionary... |
from digitize import digitize
from bincount import bincount |
########################################################
# evaluator.py
# Author: Jamie Zhu <jimzhu@GitHub>
# Created: 2014/2/6
# Last updated: 2015/8/30
########################################################
import numpy as np
from numpy import linalg as LA
import time, sys, os
import random
import logging
import m... |
from typing import Protocol, Iterable, runtime_checkable
from datetime import date
from decimal import Decimal
from quickforex.domain import CurrencyPair, DateRange
@runtime_checkable
class ProviderBase(Protocol):
identifier: str
def get_latest_rates(
self, currency_pairs: Iterable[CurrencyPair]
... |
"""
Write a Python program that randomizes 7 numbers
and prints their sum total.
If the sum is divisable by 7, also print the word "Boom"
"""
|
# from django.test import TestCase
import requests
# from django.utils.timezone import utc
# Create your tests here.
# default=datetime.datetime(2019, 8, 23, 17, 59, 40, 153036, tzinfo=utc)
url = 'http://localhost:8004/api/v1/crs/'
# url = 'https://test.cpims.net/api/v1/crs/'
# url = 'http://childprotection.go.ke/api... |
import frappe
def execute():
try:
frappe.get_doc({
'doctype': 'Letter Head',
'letter_head_name': 'Niyopolymers - Default',
'is_default': 1,
'source': 'Image',
'image': '/assets/niyopolymers/images/niyopolymer_letter_head.png'
}).insert()
... |
"""Console script for xweights."""
import sys
import dask
from dask.distributed import Client
from .xweights import compute_weighted_means
from ._parser import args
from ._regions import (which_regions,
which_subregions)
def main():
"""Console script for xweights."""
if args.which_reg... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns(
'',
# Examples:
# url(r'^$', 'webkeeper.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.s... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
from ActionHelper import *
def main():
CreateArtsAction("as90000.dat")
CraftAction((
"移动", # 00 0
"移动", # 01 1
"移动", # 02 2
"移动", # 03 3
"移动", ... |
from twisted.internet import reactor, protocol, threads
from twisted.python.failure import Failure
from twisted.internet.error import ProcessDone, ProcessTerminated
from twisted.internet.defer import inlineCallbacks, Deferred
from autobahn.twisted.util import sleep as dsleep
from twisted.logger import Logger, FileLogOb... |
###-----------###
### Importing ###
###-----------###
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
###------------------###
### Helper Functions ###
###------------------###
## Time series management
def national_timeseries(df, log=False)... |
from Bio import SeqIO
from argparse import (ArgumentParser, FileType)
import os, sys, re, collections, operator, math, time,base64
import pandas as pd
import hashlib, copy
from subprocess import Popen, PIPE
from Bio import GenBank
from parsityper.helpers import read_fasta
from parsityper.version import __version__
def... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>.
# All rights reserved.
#
# 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 ... |
import logging
from docserver.config import config
from docserver.db import models as db_models
logger = logging.getLogger(__name__)
def add_permission(username: str, permission: str, provided_permissions=None):
db = config.db.local_session()
global_admin_permission = db_models.Permission.read_unique(db, d... |
from flask import Flask, render_template
from flask import request, escape, send_file, send_from_directory, current_app
from PIL import Image
import random
import pandas as pd
from datetime import date
import os
from barcode import EAN13
from barcode.writer import ImageWriter
import numpy as np
import PyPDF2
import shu... |
s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
return "0" if not n else to_base(n//b, b).lstrip("0") + s[n%b]
n, m = map(int, input().split())
print(to_base(n, m))
|
from rest_framework import serializers
from goods2.models import Deviceid, DeviceidPrecision, DeviceidTrain, Image, ImageGroundTruth, ImageResult, UpcBind, TrainImage, TrainAction, TrainModel, TrainActionUpcs, ImageTrainModel, TaskLog
class DeviceidPrecisionSerializer(serializers.ModelSerializer):
class Meta:
... |
# for matplotlib stuffs
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox, TextArea
# for iss api
import urllib.request
import json
import time
# for os
import sys, os
# setting map image
# map_image = 'assets\\1024px-Land_shallow_topo_2048.jpg'
map_image = os.path.join('... |
from django.urls import path
from . import views
app_name = 'geonames_place'
urlpatterns = [
path('place_autocomplete/', views.PlaceAutocompleteJsonView.as_view(),
name='place_autocomplete'),
]
|
import json
import requests
from xmltodict import parse
from datetime import datetime
testURL="https://dev.libraries.ou.edu/api-dsl/data_store/data/congressional/hearings/?format=json"
s = requests.session()
r = s.get(testURL).text
dateList =[]
htmlList = []
rjson = json.loads(r)
for x in rjson['results']:
for y... |
n1 = int ( input ('Digite um número: ')
n2 = int ( input('Digite mais um número: ')
s = n1 + n2
print('a soma vale', s) |
#!/usr/bin/python
# coding: utf-8
r"""geom/vector.py
"""
from __future__ import division
import logging
import numpy as np
import OCC.gp
import aocutils.tolerance
import aocutils.exceptions
import aocutils.geom._three_d
logger = logging.getLogger(__name__)
class Vector(aocutils.geom._three_d.ThreeD):
r"""3D... |
import praw
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from .constants import USER_AGENT, BOT_NAME
from ..db import (
create_event,
create_job,
set_job_status,
get_or_create_subreddit,
Event,
SubredditActions,
SubredditFilters,
JobStatus,
Job,
S... |
"""
An anchor's behavior is a cascading list of Attrs where the hooks/pipelines/etc
are carried from each class to its subclasses.
Implicit in discussing anchors is class hierarchy. We use the terms parent/child
where child is always the current context. Which means that we don't touch the
child when processing the pa... |
import uuid
import pytest
from prices import Money, TaxedMoney
from .....account.models import User
from .....order.models import Order
ORDER_COUNT_IN_BENCHMARKS = 10
@pytest.fixture
def users_for_benchmarks(address):
users = [
User(
email=f"john.doe.{i}@exmaple.com",
is_active=... |
import os
from airflow.configuration import conf
from ewah.dag_factories import dags_from_yml_file
for dag in dags_from_yml_file(conf.get("core", "dags_folder") + os.sep + "dags.yml"):
# Must add the individual DAGs to the global namespace,
# otherwise airflow does not find the DAGs!
globals()[dag._dag_id... |
knoevenagel_c = ruleGMLString("""rule [
ruleID "Knoevenagel C"
labelType "term"
left [
edge [ source 1 target 2 label "=" ]
edge [ source 3 target 4 label "-" ]
]
context [
node [ id 1 label "C" ]
node [ id 2 label "O" ]
node [ id 3 label "C" ]
node [ id 4 label "H" ]
node [ id 5 label "*" ]
node ... |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import ssl
import time
import unittest
import libcloud.common.types as cloud_types
import mock
import arvnodeman.computenode.driver.ec2 as ec2
from . import testutil
class EC2ComputeNodeDriverTestCase(testutil.DriverTestMixin, unittest.Te... |
import re
fname = input("Enter file: ")
fhand = open(fname)
numlist = list()
for line in fhand:
line = line.rstrip()
numStr = re.findall('^New Revision: ([0-9]+)', line)
if len(numStr) == 1:
num = float(numStr[0])
numlist.append(num)
print(sum(numlist)/len(numlist))
|
"""
Subpackage for future language-specific resources and annotators
"""
|
from ipaddress import ip_address
import six
from sqlalchemy import types
from ..exceptions import ImproperlyConfigured
from .scalar_coercible import ScalarCoercible
class IPAddressType(ScalarCoercible, types.TypeDecorator):
"""
Changes IPAddress objects to a string representation on the way in and
chang... |
import pytest
pytest.importorskip("pytorch_lightning")
from pugh_torch.callbacks import TensorBoardAddClassification
from pugh_torch.utils import TensorBoardLogger
import torch
@pytest.fixture
def fake_batch():
x = torch.rand(5, 3, 224, 224)
torch.manual_seed(0)
y = torch.LongTensor([4, 3, 1, 0, 2, 9])
... |
import flask
from werkzeug.exceptions import NotFound
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from .blueprints import api_v1
def create_app():
app = flask.Flask(__name__)
app.register_blueprint(api_v1.blueprint)
app.register_error_handler(NotFound, _no... |
from swampdragon.serializers.model_serializer import ModelSerializer
from swampdragon.testing.dragon_testcase import DragonTestCase
from .models import SDModel
from django.db import models
class FooOne2One(SDModel):
name = models.CharField(max_length=20)
class BarOne2One(SDModel):
foo = models.OneToOneField... |
from pathlib import Path
from setuptools import setup, find_packages
package_dir = 'python_data_utils'
root = Path(__file__).parent.resolve()
# Read in package meta from about.py
about_path = root / package_dir / 'about.py'
with about_path.open('r', encoding='utf8') as f:
about = {}
exec(f.read(), about)
# G... |
#you will need to install keyring
from platform import system
import os
import tkinter.messagebox
import tkinter.simpledialog
from tkinter import *
from shutil import rmtree
import keyring
from hashlib import sha256
#generic names
FILENAME_USER = "folder_locker.v2.USER"
FILENAME_PASS = "folder_locker.v2.PASS"
GENUSER =... |
"""create_game_table
Revision ID: 492408566602
Revises: 5a503b995cfd
Create Date: 2021-04-04 23:03:42.761266
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "492408566602"
down_revision = "5a503b995cfd"
branch_labels = ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .vimba_object import VimbaObject
from ctypes import c_void_p
# system features are automatically readable as attributes.
class VimbaSystem(VimbaObject):
"""
A Vimba system object. This class provides the minimal access
to Vimba function... |
import os
import cohmo
from cohmo import app
import unittest
import tempfile
from unittest.mock import *
import time
from base64 import b64encode
from flask import json, jsonify
from cohmo.table import Table, TableStatus
from cohmo.history import HistoryManager
from cohmo.authentication_manager import AuthenticationMa... |
#!/usr/bin/python
#coding:utf-8
'''
mail_hunter for brute mail weakpass
'''
import poplib
import argparse
import time
import os
def tencent(usernames,suffix):
server="pop.exmail.qq.com"
try:
pop = poplib.POP3_SSL(server,995)
welcome = pop.getwelcome()
print welcome
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.