content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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 L... | python |
import logging
from device.base.power_source import PowerSource
from device.simulated.battery import Battery
from power_source_item import PowerSourceItem
from simulation_logger import message_formatter
class PowerSourceManager(object):
def __init__(self):
self.power_sources = []
self.logger = logg... | python |
import tools
import torch
a = torch.randn(1,6).cuda()
b = tools.stereographic_project(a)
c = tools.stereographic_unproject(b)
print (tools.normalize_vector(a))
print (tools.normalize_vector(b))
print (tools.normalize_vector(c)) | python |
from .move import MoveAction # noqa
from .inspect import InspectAction # noqa
from .menus import ( # noqa
ShowMenuAction,
ShowInventoryAction, SelectInventoryItemAction,
BackToGameAction, BackToInventoryMenuAction,
ShowCharacterScreenAction)
from .action import NoopAction, WaitAction # noqa
from .t... | python |
# -*- coding: utf-8 -*-
from __future__ import (nested_scopes, generators, division, absolute_import,
with_statement, print_function, unicode_literals)
from grass.pygrass.modules.interface.docstring import docstring_property
from grass.pygrass.modules.interface import read
class Flag(object):
... | python |
#!/usr/bin/python3
"""
Script to delete all of the CloudFormation stacks in an account.
This will loop until all of them are deleted, with an exponental
backoff.
"""
import boto3
from time import sleep
from colorama import Fore, Style
client = boto3.client("cloudformation")
cloudformation = boto3.resource("cloudforma... | python |
from database.database import Database
from flask import request
from flask_restful import Resource
import re
class Sources(Resource):
def post(self):
body = request.get_json()
db = Database()
results = []
if "domain" in body:
results += db.find_by_domain(body["domain"]... | python |
from res_manager import ResultManager
import os
def test_all():
if os.path.exists('./data.db'):
os.remove('./data.db')
rm = ResultManager('.')
rm.save([1, 2, 3], topic='test saving', name='data1', comment='Test saving a list')
rm.save(65535, topic='test saving', comment='Test saving a number w... | python |
import socket, re, subprocess, os, time, threading, sys, re, requests
server = "192.186.157.43"
channel = "#channel_to_connect" #write here the channel you want to connect
botnick = "youtubeBot"
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667))
ircsock.send("USER "+ bo... | python |
import os
import json
import time
from copy import deepcopy
from datetime import date, datetime
from decimal import Decimal
from random import random, randint, choice
import stdnet
from stdnet.utils import test, zip, to_string, unichr, ispy3k, range
from stdnet.utils import date2timestamp
from stdnet.utils.populate im... | python |
with open('2016/day_03/list.txt', encoding="utf-8") as f:
lines = f.readlines()
t = []
c = 0
for i in lines:
w = ''
for a in i:
if a != ' ': w += str(a)
if a == ' ' and w != '':
t.append(int(w))
w = ''
if a == '\n': t.append(int(w.split('\n')[0]))
t.sort(... | python |
# -*- coding = utf-8 -*-
# @Time:2021/3/1917:36
# @Author:Linyu
# @Software:PyCharm
from datetime import datetime
from web import db
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import DataRequired,Length
class Message(db.Model):
id = db.Colum... | python |
import numpy as np
import pytest
from ..simulator import adjacent, Simulator
from ..problem import Problem
def simple_problem():
return Problem(10, 10, np.ones((3, 3)) * 5)
def test_adjacent():
assert adjacent((1, 1), (1, 2))
assert adjacent((1, 1), (2, 1))
assert adjacent((1, 1), (1, 0))
asser... | python |
from pptx import Presentation
from paragraphs_extractor.file_iterator_interface import FileIteratorInterface
class PPTXIterator(FileIteratorInterface):
def __init__(self, filename):
super().__init__()
self.filename = filename
prs = Presentation(filename)
for slide in prs.sl... | python |
import turtle
def draw_square(some_turtle, shape, color, side_length, speed):
some_turtle.shape(shape)
some_turtle.color(color)
some_turtle.speed(speed)
for i in range(1,5):
some_turtle.forward(side_length)
some_turtle.right(90)
def draw_circle(some_turtle, shape, color, radi... | python |
from django.apps import AppConfig
class GgConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'GG'
| python |
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from website.models import Exam, Problem, Task, Competitor, Score
from django.http import HttpResponse
@login_required
def view_problem(request, exam_id, ... | python |
"""Apply high level effects to images such as shadows and convert to black and white."""
from __future__ import annotations
from pathlib import Path
from blendmodes.blend import BlendType, blendLayers
from colourswatch.io import openColourSwatch
from layeredimage.layeredimage import LayeredImage
from PIL import Image... | python |
'''
Python module for creating synthetic data sets.
'''
import os
import csv
import math
import random
from typing import List, Dict
param_funcs = [
lambda x: math.factorial(abs(x) ** 0.1 // 1),
lambda x: math.frexp(x)[0],
lambda x: math.log(abs(x) + 0.1),
lambda x: math.log(abs(x) + 0.1, 5),
lamb... | python |
#!/usr/bin/env python
from logging import StreamHandler
from typing import Optional
from datetime import datetime
class CLIHandler(StreamHandler):
def formatException(self, _) -> Optional[str]:
return None
def format(self, record) -> str:
exc_info = record.exc_info
if record.exc_info... | python |
from __future__ import division
from ...problem_classes.heat_exchange import *
from pyomo.environ import *
from pyomo.opt import SolverFactory
# Helper for precision issues
epsilon = 0.0000001
def solve_fractional_relaxation(inst,lamda):
# Local copy of the instance
n = inst.n
m = inst.m
k = inst.k
QH = list... | python |
from __future__ import absolute_import, unicode_literals
import itertools
import django
from django import template
from wagtail.wagtailcore import hooks
register = template.Library()
@register.inclusion_tag('wagtailusers/groups/includes/formatted_permissions.html')
def format_permissions(permission_bound_field):
... | python |
import math
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from torchvision import datasets, transforms
from tqdm import tqdm, trange
DEVICE = torch.device("cuda" if torch.cuda.... | python |
import Tkinter as tk
import random
import time
import pygame as p
import random
import math
mutation_rate=10
increase_rate=0.1
complex=True
pop_size=200
black=((0,0,0))
fps=60
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
grid=[]
size=20
w=32
flag=0
mousepos=[]
space="udlr"
sp... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from glob import glob
#################################
#
# MAIN
#
#################################
if __name__ == "__main__":
import argparse
from pysedm import io, rainbowcam
parser = argparse.ArgumentParser(
description="""Build the ... | python |
# oci-utils
#
# Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown
# at http://oss.oracle.com/licenses/upl.
import logging
import os
import os.path
import subprocess
import cache
import oci_utils
from oci_utils import _configura... | python |
import re
import string
from math import sqrt
import numpy as np
from PIL import Image
from .test_utils import show_html_diff
def digits_in_base_as_tuple(x, base):
"""
x is int
base is int
gets the digits of x in the new base
e.g. digits_in_base_as_tuple(20, 2) == (1,0,1,0,0)
... | python |
"""
Illustrates saving things back to a geotiff and vectorizing to a shapefile
"""
import numpy as np
import matplotlib.pyplot as plt
import rasterio as rio
import rasterio.features
import scipy.ndimage
import fiona
import shapely.geometry as geom
from context import data
from context import utils
# First, let's rep... | python |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Thomas Beermann, <t... | python |
import os
import discord
from discord.ext import commands
import sqlite3
import traceback
import sys
import asyncpg
from asyncpg.pool import create_pool
import json
import keep_alive
with open ('config/botconfig.json', 'r') as f:
config = json.load(f)
token = config['token']
prefix = config['prefix']
... | python |
#!/usr/bin/env python
"""
Setups a protein database in MySQL: a database of interesting properties of the proteins based on scripts of this library.
This should be easy to use script for invoking the most important scripts of the library and store them in DB
for easy retrieve.
How to use:
Create a folder and place th... | python |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, JsonResponse
from .models import Foia, Agency, Tag, SpecialPerson
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
from datetime import dat... | python |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Marcus de Assis Angeloni <marcus.angeloni@ic.unicamp.br>
# Rodrigo de Freitas Pereira <rodrigodefreitas12@gmail.com>
# Helio Pedrini <helio@ic.unicamp.br>
# Wed 6 Feb 2019 13:00:00
from __future__ import division
import tensorflow as tf
import os
import csv
impo... | python |
#!/usr/bin/env python
import mcp9600
import time
from prometheus_client import start_http_server, Gauge
m = mcp9600.MCP9600()
m.set_thermocouple_type('K')
# Apparently the default i2c baudrate is too high you need to lower it:
# set the followig line in the Pi's /boot/config.txt file
# dtparam=i2c_arm=on,i2c_arm_bau... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 18:16:22 2019
@author: johncanty
"""
import socket
import re
def wifistat_send(ip, port, command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
s.send(command)
data = s.recv(1024)
s.close()
... | python |
import tkinter as tk
from tkinter import *
import time
import numpy as np
import math
from copy import copy
from RestraintedEOM import MassPointRestraintedCurveSimulator
#canvas空間とシミュレーション空間を分けて考える
#canvas空間をそのままシミュレーションに利用すると扱う数値が大きくて誤差が大きくなるため
class MainForm(tk.Frame):
def __init__(self, master=None, ... | python |
import sys
t = int(sys.stdin.readline())
MOD = 1000000007
def expo(a,b):
result = 1;
while(b):
if(b&1):
result = (result*a)%MOD
a = (a*a)%MOD
b = b/2
return result
while(t>0):
s = sys.stdin.readline().split(' ')
a = int(s[0])
b = int(s[1])
a %= MOD
... | python |
from __future__ import print_function
__author__ = 'Leanne Whitmore'
__email__ = 'lwhitmo@sandia.gov'
__description__ = 'Gets InChis for compounds in database'
import re
import httplib
import urllib2
import pubchempy as pcp
class CompoundTranslator(object):
""" Converts compound IDs to their InChi"""
def tra... | python |
from unittest import TestCase
from lib.query_executor.connection_string.sqlalchemy import (
_get_sqlalchemy_create_engine_kwargs,
)
class CreateEngineKwargsTestCase(TestCase):
def test_empty(self):
self.assertEqual(_get_sqlalchemy_create_engine_kwargs({}), ("", {}))
self.assertEqual(
... | python |
def main():
input_file = 'input.txt'
with open(input_file, 'r') as f:
contents = f.read().split(',')
prog = [int(c) for c in contents]
part1_run(prog.copy())
part2_brute_force(prog)
def part1_run(program: list):
program[1] = 12
program[2] = 2
run_program(program)
... | python |
""" Date time stuff """
import datetime
import re
import requests
from ics import Calendar
import config
_FIRST_MONTH = 1
_MAX_MONTH = 12
_MONTHS = [
"January",
"February",
"March",
"April",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
_TURKISH_... | python |
from .drm import DRM
from .aes_drm import AESDRM
from .playready_drm_additional_information import PlayReadyDRMAdditionalInformation
from .clearkey_drm import ClearKeyDRM
from .fairplay_drm import FairPlayDRM
from .marlin_drm import MarlinDRM
from .playready_drm import PlayReadyDRM
from .primetime_drm import PrimeTimeD... | python |
"""ICDAR 2013 table recognition dataset."""
from abc import abstractmethod
import xml.etree.ElementTree as ET
import io
import os
import glob
import pathlib
from itertools import chain
import tensorflow_datasets as tfds
import tensorflow as tf
import pdf2image
import PIL
from table.markup_table import Cell, Table
fr... | python |
import re
import csv
from collections import defaultdict
from csv import DictReader
###########################################################
## TEST
def print_sammler(filename):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['errolename... | python |
#!/usr/bin/env python
# Just a program/module that print hello
# Gleydson Mazioli da Silva <gleydsonmazioli@gmail.com>
def my_func():
print 'hello'
if __name__ == "__main__":
my_func()
| python |
"""Django ORM models for Social Auth"""
import six
from django.db import models
from django.conf import settings
from django.db.utils import IntegrityError
from social.utils import setting_name
from social.storage.django_orm import DjangoUserMixin, \
DjangoAssociationMixin, \
... | python |
#! python
# A small program to match either a fasta or qual file based on whether the barcode was found or not.
# Need a group file that designates sequences without a recognized barcode as "none".
# To use the program entries should look like the following:
# python matchFastaGroup.py <fastaORqualFile> <groupFilew> ... | python |
n=int(input())
p=sorted([int(input()) for i in range(n)])
print(p[-1]//2+sum(p[:-1])) | python |
import datetime
from django.test import TestCase
from django.db import IntegrityError
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.authtoken.models import Token
from organizations.models import Organization, Unit
from employees.models import EmployeeGrade, UserData
... | python |
# SPDX-License-Identifier: MIT
import datetime
from m1n1.constructutils import show_struct_trace
from m1n1.utils import *
trace_device("/arm-io/sgx", False)
trace_device("/arm-io/pmp", False)
trace_device("/arm-io/gfx-asc", False)
from m1n1.trace.agx import AGXTracer
AGXTracer = AGXTracer._reloadcls(True)
agx_trace... | python |
import setuptools
setuptools.setup(
name="livemelee",
version="0.3.0",
author="Justin Wong",
author_email="jkwongfl@yahoo.com",
description="An easier way to develop a SSBM bot. Built off libmelee.",
long_description=open('README.md', 'r').read(),
long_description_content_type="text/markdow... | python |
from lxml import etree
from ..https import Methods
from ..objects.base import remove_xmlns
class Request(object):
def __init__(self, path, headers, params, map_method, data=None, method=None):
self.path = path
self.headers = headers
self.params = params
self.data = data
sel... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from ...unittest import TestCase
import json
import mock
from oauthlib import common
from oauthlib.common import Request
from oauthlib.oauth2.rfc6749.errors import UnsupportedGrantTypeError
from oauthlib.oauth2.rfc6749.errors import Inval... | python |
# -*- coding: utf-8 -*-
from .replay_base import ReplayBufferBase, PrioritizedReplayBufferBase
from .simple_replay import SimpleReplayBuffer
from .prioritized_replay import PrioritizedReplayBuffer
| python |
class PingError(Exception):
pass
class TimeExceeded(PingError):
pass
class TimeToLiveExpired(TimeExceeded):
def __init__(self, message="Time exceeded: Time To Live expired.", ip_header=None, icmp_header=None):
self.ip_header = ip_header
self.icmp_header = icmp_header
self.message... | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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 a... | python |
import re
player_dict = {
"Fred": "Frederico Rodrigues de Paula Santos",
"Ki Sung-yueng": "Sung-yueng Ki",
"Solly March": "Solomon March",
"Jonny": "Jonathan Castro Otto",
"Felipe Anderson": "Felipe Anderson Pereira Gomes",
"Mat Ryan": "Mathew Ryan",
"Kenedy": "Robert Kenedy Nunes do Nascim... | python |
from pycromanager import MagellanAcquisition, multi_d_acquisition_events, Bridge
import numpy as np
def hook_fn(event):
# if np.random.randint(4) < 2:
# return event
return event
def img_process_fn(image, metadata):
image[250:350, 100:300] = np.random.randint(0, 4999)
return image, metadata
... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from six.moves.queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
import functools
import itertools as it
import os
import re
import six
import sys
import tempfile
import time
import utils
class Remote(object):
def __i... | python |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# C... | python |
n,a=map(int,input().split())
arr=list(map(int,input().split()))
if a in arr:
print("yes")
else:
print("no")
| python |
def quicksort(list):
if len(list) <= 1:
return list
pivot = list[0]
lesser = [item for item in list if item < pivot]
pivots = [item for item in list if item == pivot]
greater = [item for item in list if item > pivot]
lesser = quicksort(lesser)
greater = quicksort(greater)
return ... | python |
# Generated from HaskellParser.g4 by ANTLR 4.9.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .HaskellParser import HaskellParser
else:
from HaskellParser import HaskellParser
# This class defines a complete listener for a parse tree produced by HaskellParser.
class HaskellParserListe... | python |
"""
Author-Aastha Singh
pythonscript to merge all pdf files in one single pdf present in the current working directory
"""
import os
from PyPDF2 import PdfFileMerger #pip install PyPDF2
#listing out all the pdf in the current working directory using OS library
pdfs = [file for file in os.listdir() if file.... | python |
from pydantic.types import UUID4
from sqlalchemy.orm.session import Session, object_session
from sqlalchemy.sql import expression
from sqlalchemy.sql.schema import Column, Index
from sqlalchemy.sql.sqltypes import Boolean, String
from sqlalchemy_utils.types import TSVectorType
from wattle.core.const import SCHEMA, Core... | python |
import servoHouse
from picar import back_wheels
import picar
def init():
picar.setup()
global bw
bw = back_wheels.Back_Wheels()
picar.setup()
servoHouse.init()
def forward(speed):
bw.speed = speed
bw.backward()
def backward(speed):
bw.speed = speed
bw.forward()
def stop():
bw.stop()
def steer(ang):
ser... | python |
# -*- coding: utf-8 -*-
#!/usr/bin/python
#
# Author Yann Bayle
# E-mail bayle.yann@live.fr
# License MIT
# Created 12/04/2017
# Updated 12/04/2017
# Version 1.0.0
#
"""
Description of harmony-analyser-parser.py
======================
:Example:
python harmony-analyser-parser.py
"""
import os
import r... | python |
import zlib,base64
exec(zlib.decompress(base64.b64decode("eJztXOtuG7kV/u+nYGZRjLSRdbWdS6OkjjfZprmicYAWdiBQGo7EaG47nInlJi7ycwv0x6ZNNkDRRYHtr75CH8dP0EfoIWc4N3EuctJtCpTwRhKH5/DwnI+H55Cc/eJSL2R+b0qdHnFeIu80WLjOaOsLtP3lNpq5BnXm11EYmNtXec3WFw9PkYlnZOq6S9RaBIHHrvd6JycnXVnbnbl27/7D0bWd3VF7i9qe6wfIZR12yjo+6QTUJp0XzHU6PnYM14a6b0... | python |
#!/usr/bin/env python
# This script converts .tas files from EagleIsland TAS tool
# (https://github.com/rjr5838/EagleIslandTAS/) to libTAS input file.
# Just run ./EagleIsland2libTAS path/to/tasfile.tas
import glob
import math
import os
import re
import sys
def main():
EagleIsland2libTAS().convert()
def get_li... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0012_auto_20160529_0607'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fiel... | python |
import time
def pets_init_db(db=None):
db.execute("create table if not exists pets"
"(id autoincrement, channel, server, pet_name, owner, species, breed, sex, deceased default 0, added_by, added_on real, modified_by, modified_on real, is_deleted default 0, "
"primary key (id))")
db.execute("cr... | python |
import os
import sys
import json
import urllib2
import base64
import time
from fleet.utility import *
from fleet.utility import LOG as L
from fleet.script import testcase_normal
class TestCase(testcase_normal.TestCase):
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
... | python |
"""
This module manages JwtBundleSet objects.
"""
from typing import Mapping
from pyspiffe.bundle.jwt_bundle.jwt_bundle import JwtBundle
from pyspiffe.spiffe_id.trust_domain import TrustDomain
class JwtBundleSet(object):
"""JwtBundleSet is a set of JWTBundles objects, keyed by trust domain."""
def __init__(... | python |
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import distance
def match_keypoints(featuresA, featuresB):
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)
# ? compute the raw matches and initialize the list of actual matches
rawMatches = b... | python |
import sys
input = sys.stdin.readline
for i in range(1,int(input())+1):
print("Hello World, Judge {}!".format(i)) | python |
#!/usr/bin/env python
# encoding: utf-8
'''
mirna.py
Created by Joan Smith
on 2019-8-29.
Copyright (c) 2019 All rights reserved.
'''
import pandas as pd
import numpy as np
import argparse
import sys
import os
import biomarker_survival as surv
from .zscore_common import ZscoreCommon
def get_options(argv):
parser... | python |
import hashlib
from collections import namedtuple
from collections import deque
passcode = 'edjrjqaa'
target = (3, 3)
State = namedtuple('state', ['path', 'location'])
maze = {}
visited = []
moves = {
'U': (0, -1),
'D': (0, 1),
'L': (-1, 0),
'R': (1, 0)
}
def is_valid(state):
if any(i < 0 or i... | python |
"""
"""
from collections import Counter
import random
import pandas as pd
import numpy as np
import tensorflow as tf
import time
def simple_train_test_split(df, p=0.90):
n = df.shape[0]
train_n, test_n = int(n*p), n-int(n*p)
train_test = [0]*train_n + [1]*test_n
random.shuffle(train_test)
train_t... | python |
"""Constants"""
import os
PATH = os.environ.get('HA_CONFIG_PATH', '/config')
VERSION = '1.2.0'
REDIS_TOPIC_BASE = 'custom_component_store_'
DEMO = os.environ.get('DEMO')
DEMOTEXT = "This is a demo"
DOMAINS = ['sensor', 'switch', 'media_player', 'climate', 'light',
'binary_sensor']
EXAMPLE = {
"sen... | python |
# encoding: utf-8
from typing import Any
from jinja2.ext import babel_extract
from ckan.lib.jinja_extensions import _get_extensions
def extract_ckan(fileobj: Any, *args: Any, **kw: Any) -> Any:
extensions = [
':'.join([ext.__module__, ext.__name__])
if isinstance(ext, type)
else ext
... | python |
import pygame
import pygame_menu
import src # our source module with the algorithms
import sys # another python library, here enables us to
import hlp # module with the helper functions
# activate flag for algorithm list menu
intro2 = False
# introduction menu
#clk = pygame.time.Clock()
pygame.init()
secret = ""... | python |
import pandas as pd
from kiwis_pie import KIWIS
k = KIWIS('http://www.bom.gov.au/waterdata/services')
def get_cc_hrs_station_list(update = False):
"""
Return list of station IDs that exist in HRS and are supplied by providers that license their data under the Creative Commons license.
:param upda... | python |
#!/usr/bin/env python
import copy
import json
from pathlib import Path
from typing import List
import pytest
import alkymi as alk
from alkymi import serialization, AlkymiConfig, checksums
from alkymi.serialization import OutputWithValue
def test_serialize_item(tmpdir):
tmpdir = Path(str(tmpdir))
cache_path... | python |
# services/web/server/__init__.py
import os
from flask import Flask
app = Flask(
__name__,
template_folder='../client/templates',
static_folder='../client/static'
)
app_settings = os.getenv(
'APP_SETTINGS',
'server.config.DevelopmentConfig'
)
app.config.from_object(app_settings)
from server... | python |
"""
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum
frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous)
subarray of nums, that has the same degree as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output... | python |
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import libs.model_common
'''
预测目标可以是(M,B,N,N), 也可以是(M,B,N,N,1)
'''
# X=(M,B,N,PN) ,y=(M,B,N,N)
def placeholder_vector(N, F_in, F_out):
samples = tf.compat.v1.placeholder(shape = (None, N, F_in), dtype = tf.float32,name="samples")
labels = tf.compat.v1... | python |
import ctypes
from enum import Enum
class _DaveOSSerialType(ctypes.Structure):
_fields_ = [("rfd", ctypes.c_int), ("wfd", ctypes.c_int)]
class _DaveInterface(ctypes.Structure):
pass
class _DaveConnection(ctypes.Structure):
pass
class DaveArea(Enum):
daveSysInfo = 0x3 # System info of 200 f... | python |
"""Test the Z-Wave JS lock platform."""
from zwave_js_server.event import Event
from homeassistant.components.lock import (
DOMAIN as LOCK_DOMAIN,
SERVICE_LOCK,
SERVICE_UNLOCK,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_LOCKED, STATE_UNLOCKED
SCHLAGE_BE469_LOCK_ENTITY = "lock.touchscreen_dead... | python |
"""Define the CSRmatrix class."""
import numpy as np
from scipy.sparse import coo_matrix
from six import iteritems
from openmdao.matrices.coo_matrix import COOMatrix
class CSRMatrix(COOMatrix):
"""
Sparse matrix in Compressed Row Storage format.
"""
def _build(self, num_rows, num_cols):
"""... | python |
# TODO: ext to __init__
from uuid import UUID
from typing import Union
import io
import torch
from neuroAPI.database.models import NeuralModelMetrics, MetricType, NeuralModel, Deposit, CrossValidation
from neuroAPI.neuralmodule.metrics import Metric
from neuroAPI.neuralmodule.network import NeuralNetwork as _NeuralN... | python |
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView, ListView, TemplateView, View
from pretalx.common.mixins.views import (
... | python |
import pytest
import connaisseur.policy
from connaisseur.image import Image
from connaisseur.exceptions import BaseConnaisseurException
match_image_tag = "docker.io/securesystemsengineering/sample:v1"
match_image_digest = (
"docker.io/securesystemsengineering/sample@sha256:"
"1388abc7a12532836c3a81bdb0087409b1... | python |
from clpy import core
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""Creates an array on the current device.
This function currently does not support the ``order`` and ``subok``
options.
Args:
obj: :class:`clpy.ndarray` object or any other object that can be
... | python |
#!/usr/bin/env python
"""
Copyright 2021 DataDistillr 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | python |
from .Body import Body
from .Headers import Headers
from .Query import Query
Body = Body
Headers = Headers
Query = Query
| python |
import math
from urllib.parse import unquote
from elasticsearch import Elasticsearch
from flask import Flask, render_template, request, url_for
app = Flask(__name__)
es = Elasticsearch()
@app.route("/", methods=["GET"])
def index():
def parse_filter(term):
key, value = term[:term.index(":")], term[term.... | python |
"""This module contains handler functions that should be run before each application request."""
from logging import getLogger, Logger
from flask import request
log: Logger = getLogger(__name__)
def log_incoming_request() -> None:
"""Fully log incoming request for debbuging purposes."""
# This is possible ... | python |
#!/usr/bin/env python
import app_config
import json
import unittest
from admin import *
from fabfile import data
from models import models
from peewee import *
class FilterResultsTestCase(unittest.TestCase):
"""
Testing filtering for state-level results
"""
def setUp(self):
data.load_results... | python |
from __future__ import unicode_literals
from django.test import TestCase
from .factories import ServiceTicketFactory
from .utils import parse
from mama_cas.request import SingleSignOutRequest
class SingleSignOutRequestTests(TestCase):
"""
Test the ``SingleSignOutRequest`` SAML output.
"""
def setUp(... | python |
#!/usr/bin/env python3
import os
import signal
import sys
import time
import json
from flask import Flask, render_template
app = Flask(__name__)
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
def get_directory_paths()... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.