content stringlengths 5 1.05M |
|---|
"""Treadmill docker authz plugins for different Docker APIs
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import re
from treadmill import utils
_LOGGER = logging.getLogger(__name__)
# to store ... |
from setuptools import setup, Extension
#
setup(name='flightgym',
version='0.0.1',
author="Yunlong Song",
author_email='song@ifi.uzh.ch',
description="Flightmare: A Quadrotor Simulator",
long_description='',
packages=[''],
package_dir={'': './'},
package_data={'': ['fligh... |
# Generated from DOT.g4 by ANTLR 4.7.2
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\35")
buf.write("\u00b7\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t... |
"""Module exposing tiles related utilities (like Tile and TilePacker)"""
from enum import unique, Enum
from pathlib import Path
from typing import Dict
import pyxel
from bansoko import LEVEL_WIDTH, LEVEL_HEIGHT
from bansoko.graphics import Rect, IMAGE_BANK_WIDTH, TILE_SIZE, TILEMAP_WIDTH
@unique
class T... |
from pyprocessing import *
noFill();
background(204);
camera(70.0, 35.0, 120.0, 50.0, 50.0, 0.0,
0.0, 1.0, 0.0);
translate(50, 50, 0);
rotateX(-PI/6);
rotateY(PI/3);
box(45);
run()
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import itertools
import warnings
warnings.filterwarnings('ignore')
import pprint
from scipy.stats import zscore
from sklearn.preprocessing import PolynomialFeatures
%matplotlib inline
def describe_dataframe(datafr... |
from win32._event import * |
# -*- encoding: utf-8 -*-
# pylint: disable=E0203,E1101,C0111
"""
@file
@brief Runtime operator.
"""
from ._op import OpRun
class Mean(OpRun):
def __init__(self, onnx_node, desc=None, **options):
OpRun.__init__(self, onnx_node, desc=desc,
**options)
def _run(self, *args): # p... |
for num in range(1):
sentence = input()
list = [0]
list2 = []
for i in range(0, len(sentence)):
list.append(ord(sentence[i]))
for i in range(len(list)-1, -1, -1):
for j in range(i):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
for ... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""Table models and functionality for the Replay Mobile DB.
"""
import os
from sqlalchemy import Table, Column, Integer, String, ForeignKey
from bob.db.base.sqlalchemy_migration import Enum, relationship
from sqlalchemy.orm import backref
from sqlalchemy.ext.decla... |
# transfers.txt
from gtfs_util.static import data
from gtfs_util.static.models.base import Base
from gtfs_util.enum import TransferType
from gtfs_util.model import MixIn
from sqlalchemy import Column, types, schema
class Transfer(Base, MixIn):
__tablename__ = 'transfer'
__table_args__ = (
# schema.F... |
#!/usr/bin/env python3
"""Rust Action Builder
#
# 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,... |
def discriminant(a, b, c):
res = (b**2) - (4 * a * c)
return res
|
# -*- coding: utf-8 -*-
# Copyright (C) 2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
import numpy as np
from milk.unsupervised.kmeans import select_best_kmeans, assign_centroi... |
# !/usr/bin/python
# coding=utf-8
import tltk
import re
from pythainlp.corpus.common import thai_words
from pythainlp.tokenize import dict_trie,word_tokenize,syllable_tokenize
from pythainlp.tag import pos_tag
custom_dict = set(thai_words())
custom_dict.add('ซิน')
trie = dict_trie(dict_source=custom_dict)
text = "อีซิ... |
import random
from copy import copy
from typing import List, Dict
from .colors import Color, Colors, LifxColors
from .utils import init_log, even_split
__author__ = 'acushner'
log = init_log(__name__)
Weight = int
class Theme:
"""weighted collection of colors"""
def __init__(self, colors: Dict[Color, Wei... |
try:
from jinja2 import Template
except:
pass
class BrowserAdapter(object):
media_type = "text/html"
@classmethod
def build(self, resource):
template = Template(resource_template)
return template.render(main_resource=resource)
resource_template = """
{% macro resource_markup(reso... |
# -*- coding: utf-8 -*-
"""
@author: Daniel Jiménez-Caminero Costa
"""
import numpy as np
import matplotlib.pyplot as plt
# Project Imports
from mosqito.functions.hearing_model.sone2phone import sone2phone
from mosqito.functions.hearing_model.phone2spl import phone2spl
from mosqito.functions.hearing_model.co... |
"""
Create a .new copy of the lookup table that keep solutions
up to a specified length
"""
# standard libraries
import subprocess
import sys
filename = sys.argv[1]
filename_new = filename + ".new"
step_limit = int(sys.argv[2])
keepers = {}
line_number = 0
with open(filename_new, "w") as fh_new:
with open(filena... |
import plotly
import plotly.plotly as py
# plotly.tools.set_credentials_file(username='sanjivp98', api_key='9EVZEvNLfHMrOyGTuja9')
# plotly.sign_in("sanjivp98", "9EVZEvNLfHMrOyGTuja9")
import plotly.graph_objs as go
import plotly.figure_factory as FF
import numpy as np
import pandas as pd
df = pd.read... |
_base_="../base-domain_net_sketch-config.py"
# this will merge with the parent
model=dict(pretrained='data/basetrain_chkpts/imagenet_r50_supervised.pth')
# epoch related
total_iters=50
checkpoint_config = dict(interval=total_iters)
|
import unittest
from src.assignments.assignment5 import recursive_decimal_binary
#write import for decimal to binary function
class Test_Assign4(unittest.TestCase):
def test_sample_one(self):
self.assertEqual(1,1);
#write test cases with arguments 85 and 63 for recursive_decimal_binary function
... |
# -*- coding: utf-8 -*-
from collections import defaultdict
import torch
from torch import nn
import torch.nn.functional as F
from ...utils.nn import get_rnn_hidden_state
from .. import FF
from ..attention import get_attention
class XuDecoder(nn.Module):
"""A decoder which implements Show-attend-and-tell decoder... |
from django.utils.translation import ugettext_lazy as _
class FreeTranslationPageConstants:
"""
Free translation experiment page constants
"""
FREE_TRANSLATION_TRANSLATE_WORD_TEXT = _("FREE_TRANSLATION_TRANSLATE_WORD_TEXT")
# FREE_TRANSLATION_TRANSLATED_WORD_FIELD_TEXT = _("Type in")
FREE_TRAN... |
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Merge multiple package status CSV files into one csv file.
This simplifies uploading to a Google Docs spreadsheet.
"""
from __future__ import pri... |
import numpy as np
# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).
NdArray = np.arange(1,26).reshape(5,5)
print(NdArray)
# Afterwards use Boolean indexing to pick out only the odd numbers in the array
X_odd = NdArray[NdArray % 2 != 0 ]
print(X_odd)
|
#!/usr/bin/python3
import math
n = int(input())
mi = n-1
ab = lambda x: x if x>=0 else -x
for r in range(1, int(math.sqrt(n))+2): #1e6
# Case 1: all same, n=c*r, %=0
# Case 2: even r, r//2 less, n=c*r - r //2, %=r//2
# Case 3: odd r, (r-1)//2 less, n=c*r - r //2 %=(r+1)//2
# Case 4: odd r, (... |
from display import *
import generators
from colorsys import hsv_to_rgb
import random
LEDS = 512
def fade(colours, ratio):
return [Colour((colours[i].r * ratio, colours[i].g * ratio, colours[i].b * ratio)) for i in range(len(colours))]
def random_static(num_leds, brightness = None):
while True:
yield [Colour... |
from dict_validator import Field
class Any(Field):
""" Wildcard value. """
def _validate(self, value):
pass
class WildcardDict(Field):
"""
Match a dict with any dict with any key/value pairs.
:param key_schema: Field subclass to be used to
validate/serialize/deserialize the key... |
import numpy as np
from openmdao.api import ExplicitComponent
from pycycle.constants import R_UNIVERSAL_SI
class PsCalc(ExplicitComponent):
"""Mach number, Area calculation for when Ps is known"""
def setup(self):
self.add_input('gamma', val=1.4)
self.add_input('n_moles', shape=1)
s... |
import psycopg2
SQL_CONFIG = {
'host': 'database',
'port': '5432',
'database': 'test_database',
'user': 'test_user',
'password': 'changethis'
}
def get_users():
connection = psycopg2.connect(**SQL_CONFIG)
cursor = connection.cursor()
sql = 'SELECT * FROM users'
cursor.execute(sql... |
import os
import numpy as np
import PIL
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
class LSUNBase(Dataset):
def __init__(self,
txt_file,
data_root,
size=None,
interpolation="bicubic",
... |
# Author : Sujit Mandal
import os
import argparse
import requests
import pandas as pd #pip install pandas
from httpRespons import data_info
from httpRespons import userAgent
from httpRespons import httpResponseStatusCodes
def bothDose(request, date, output):
if request.status_code == 200:
data = request.... |
""" Compute the spike-triggered average as an initialization for spatiotemporal
stimulus filters.
"""
import numpy as np
def sta(stim, data, L, Ns=None):
""" Compute the spike-triggered average as an initialization for spatiotemporal
stimulus filters.
data : dictionary containing the following ... |
my_fonts = {
# 'larger': ('freesansbold.ttf', 27),
# 'xl': ('freesansbold.ttf', 35),
# 'display_font': ('freesansbold.ttf', 22),
# 'basic': ('freesansbold.ttf', 16),
# 'medium': ('freesansbold.ttf', 21),
# /!\ on avait cette font partout: 'monogram.ttf'
# -multiples de 16 fortement recomm... |
# A pen_tri, brought to you by PharaohCola13
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.pyplot as plt
from matplotlib import *
from numpy import *
from mpl_toolkits.mplot3d.art3d import *
from matplotlib.animation import *
name = "Penrose Triangle"
def shape(fig, edge_c, edge_w, grid):
points_x = [... |
#!/usr/bin/env python3 -u
# coding: utf-8
__author__ = ["Markus Löning"]
__all__ = ["load_pressure", "load_temperature", "load_experiments"]
import pandas as pd
def _load_data():
"""Helper function to load data for tutorial
References
----------
Data is a small extract from the Tennessee Eastman Pr... |
from unittest import mock
from company import tasks
@mock.patch('company.tasks.lock_acquired', mock.Mock(return_value=True))
@mock.patch('company.tasks.call_command')
def test_retrieve_companies_house_company_status(mocked_call_command):
tasks.retrieve_companies_house_company_status()
mocked_call_command.ass... |
import datetime
import logging
import time
from pathlib import Path
from typing import Dict, List
import nibabel as nib
import numpy as np
import SimpleITK as sitk
from nilearn.image import resample_img
log = logging.getLogger(__name__)
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time(... |
"""
Script principal do projeto Voice Unlocker responsável
por coordenar o recebimento de novos áudios a serem
validados e a execução do modelo preditivo treinado
previamente de modo a apresentar um resultado ao
executor do código.
------------------------------------------------------
SUMÁRIO
... |
# -*- coding: utf-8 -*-
from schedule import Schedule
class SSGS(object):
def __init__(self, problem):
self.problem = problem
def get_schedule(self, activity_list):
S = Schedule(self.problem)
self.al_iter = activity_list.__iter__()
for i in xrange(self.problem.num_activities)... |
from handlers.wechatGZH.wxlogger import logger
"""这是一个处理客户发送信息的文件"""
def reply_text(FromUserName, ToUserName, CreateTime, Content):
"""回复文本消息模板"""
textTpl = """<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgTyp... |
from RGT.XML.SVG.baseStructuralNode import BaseStructuralNode
from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes
from RGT.XML.SVG.Attribs.positionAttributes import PositionAttributes
from RGT.XML.SVG.Attribs.sizeAttributes import SizeAttributes
from types import StringTy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author Florian Schwendinger
"""
import math
import numpy as np
import matplotlib.pyplot as plt
def kdplot(x, width=-1, strech=1):
if width < 0:
width = x['x1'].max()
width = math.ceil(width)
strech = math.ceil(strech)
grid = 0 * np.array(ran... |
import vpython as vp
from robot_imu import RobotImu, ImuFusion
from delta_timer import DeltaTimer
import imu_settings
imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets,
mag_offsets=imu_settings.mag_offsets)
fusion = ImuFusion(imu)
vp.graph(xmin=0, xmax=60, scroll=True)
graph_pitch = vp.gcurve(color... |
# Generated by Django 3.0.6 on 2020-06-16 07:54
from django.conf import settings
from django.db import migrations, models
from django.db.models.signals import post_migrate
def assing_permissions(apps, schema_editor):
def on_migrations_complete(sender=None, **kwargs):
Group = apps.get_model("auth", "Group... |
import pandas as pd
import numpy as np
import lib.image as kmg
class DataLoader():
""" Class used to load csvs
# Arguments
path_vid : path to the folder containing the extracted Jester dataset
path_labels : path to the csv containing the labels
path_train : path to the csv containi... |
from keras.models import load_model
# load model
model = load_model('face_model.h5')
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
def load_image(filename):
# load the image
img = load_img(filename, target_size=(224, 224))
# convert to array
img = ... |
# coding=utf-8
from src.testcase.GN_Y201H.WidgetOperation import *
class GNY201HTimerFunc3(WidgetOperation):
@case_run(False)
def run(self):
self.case_module = u"定时功能(#240)" # 用例所属模块
self.case_title = u'普通定时周期格式检查' # 用例名称
self.zentao_id = "2020" # 禅道ID
# 用例动作
def case(self)... |
"""
Main module for traffic analysis, predictions, API
"""
import argparse
from traffic_analyzer import XGBModel
from traffic_analyzer import create_train_test_data
from traffic_analyzer import load_model, dump_model, load_csv
from sklearn.metrics import f1_score, average_precision_score, roc_auc_score, accuracy_score... |
# https://pandas.pydata.org/docs/user_guide/index.html#user-guide
import numpy as np
import pandas as pd
"""
Numpy 和 Pandas 有什么不同 ¶
如果用 python 的列表和字典来作比较, 那么可以说 Numpy 是列表形式的,没有数值标签,而 Pandas 就是字典形式。
Pandas是基于Numpy构建的,让Numpy为中心的应用变得更加简单。
要使用pandas,首先需要了解他主要两个数据结构:Series和DataFrame。
"""
# 如果是中文路径,可以尝试如上的skipfoot
# 或者e... |
import frappe
from flutterwave import pyflutterwave
def on_payment_authorized(**kwargs):
verification_data = verify_flutterwave_transaction(**kwargs)
if verification_data:
attempt_to_set_payment_entry_as_paid(verification_data)
def verify_flutterwave_transaction(**kwargs):
tx_ref = kwargs.get('tx_... |
from ShitMountainGenerator.shitter import Shitter
if __name__ == '__main__':
shitter = Shitter.from_template("test_case.tmpl")
r = shitter.shit({
"fields" : [
{
"py_name" : "py_name1",
"py_type" : "py_type1"... |
# Copyright (c) Vera Galstyan Jan 25,2018
def make_shirt(size='large',message='I love python'):
print("my shirt is " + size + " and has a print-" + message)
make_shirt()
make_shirt(size='medium')
make_shirt('small','I like C') |
#!/usr/bin/env,python3
#,-*-,coding:,utf-8,-*-
'''
Problem 21
Evaluate the sum of all the amicable numbers under 10000.
'''
from functools import lru_cache
@lru_cache(maxsize=10000)
def div_sum(x):
return sum(filter(lambda z: x%z==0, range(1,x)))
def is_amicable(x):
y = div_sum(x)
return div... |
from .exceptions import *
import random
class GuessAttempt(object):
def __init__(self,char,hit=None,miss=None):
self.char = char
if hit is not None and miss is not None:
raise InvalidGuessAttempt()
self.hit = hit
self.miss = miss
def is_hit(self):
if... |
"""This module handles copying the Electron Cash data dir
to the Electrum ABC data path if it does not already exists.
The first time a user runs this program, if he already uses Electron Cash,
he should be able to see all his BCH wallets and have some of the
settings imported.
"""
import logging
import os
import shut... |
from django.utils import six
from rest_framework import status
from rest_framework.exceptions import ErrorDetail
from rest_framework.views import exception_handler
from kolibri.core import error_constants
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# t... |
import numpy as np
import matplotlib.pyplot as plt
import vplot
import scipy.signal as sig
import sys
# Check correct number of arguments
if (len(sys.argv) != 2):
print('ERROR: Incorrect number of arguments.')
print('Usage: '+sys.argv[0]+' <pdf | png>')
exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != '... |
# Simple test for NeoPixels on Raspberry Pi
import time
import sys
import select
import math
import hexpixels
START_COLOR = {"R":255, "G":0, "B":0}
END_COLOR = {"R":0, "G":0, "B":255}
HP = hexpixels.HexLights(390, 0.7)
HP.clear()
time.sleep(1)
while True:
for i in range(100):
color= HP.get_fade_color(ST... |
import scrapy
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from leviscrape.items import LeviscrapeItem
class LeviSpider(scrapy.Spider):
name = 'levi'
def start_requests(self):
options = webdriver.ChromeOptions... |
import csv
import logging
import os
from tqdm import tqdm
import openbiolink.graphProperties as graphProp
from openbiolink import globalConfig, globalConfig as globConst, utils
from openbiolink.cli import Cli
from openbiolink.edge import Edge
from openbiolink.graph_creation import graphCreationConfig as gcConst
from ... |
# Copyright 2019 TerraPower, 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 writi... |
import logging
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django_fsm import TransitionNotAllowed
from rest_framework import decorators, exceptions, response, status, views
from waldur_core.core import views as core_views
from waldur_core.structure import permissions ... |
import uuid
import datetime
import threading
class Session(threading.local):
"""A thread-local storage for the client"""
def start(self):
self._id = str(uuid.uuid4())
self._started = datetime.datetime.utcnow()
session = Session()
|
# We need this because the production environment runs python2.5
from __future__ import with_statement
import tempfile
from fabric.api import run
from journeyman.buildrunner.registry import registry
def teardown_virtualenv(build_runner, **kwargs):
# Create the virtual env for testing.
output = run('rm -rf %s... |
import pprint
import sys
from pathlib import Path
from mana.generators.model_reader import ModelReader
from jinja2 import Environment, FileSystemLoader
class MetaModelGenerator(ModelReader):
def __init__(self, jobs: dict):
ModelReader.__init__(self, jobs)
def code_name(self, name : str):
... |
from requests import get
def response_method(res, **kwargs):
print(f'kwargs : {kwargs}')
print(f'res : {res}')
print(f'res.status_code : {res.status_code}')
r = get('http://httpbin.org/get', hooks={'response':response_method})
|
import warnings
from privex.helpers.decorators import mock_decorator
from privex.helpers.collections import Mocker, dataclasses_mock
module = Mocker.make_mock_class('module')
def mkclass(name: str = 'module', instance: bool = True, **kwargs):
return Mocker.make_mock_class(name, instance=instance, **kwargs)
de... |
"""IO methods for deployment of a trained model.
--- NOTATION ---
The following letters will be used throughout this module.
E = number of examples (storm objects)
M = number of rows in each radar image
N = number of columns in each radar image
H_r = number of radar heights
F_r = number of radar fields (or "variable... |
#!/usr/bin/python
import datetime
import os
import sys
import time
from multiprocessing import Pool
from watchdog.observers import Observer
from filecheck.fileScan import ReadFile
from filecheck.fileCalculate import CalculateFile
from filecheck.resultProcessing import ResultProcess
from configurate.readyaml import ya... |
import unittest
import clingo
from clingox.program import Program, ProgramObserver, Remapping
from eclingo.solver.tester import CandidateTester
import eclingo.internal_states.internal_control as internal_control
class TesterCase(unittest.TestCase):
def assertEqualPrograms(self, expected_program, program):
... |
# Copyright 2014, 2015, Nik Kinkel
# See LICENSE for licensing information
import ipaddress
import struct
class ExitRequest(object):
'''Represent a connection request.'''
__slots__ = ('port', 'addr', 'host', 'is_ipv4', 'is_ipv6', 'is_host')
def __init__(self, port, addr=None, host=None):
'''
... |
"""Test the GoesReader."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
import numpy as np
from goes_truecolor.lib import goes_predict
from goes_truecolor.lib import goes_reader
TILE_SIZE = 64
class GoesPredictTest(... |
#!/usr/bin/env python
#Name: som.py
# Purpose: 3D Kohonen self-organizing map for multispectral image RGB visualization
# Usage (from command line):
# python som.py [options] fileName
# Mort Canty (c) 2018
import numpy as np
import os, sys, getopt, time
from osgeo import gdal
from osgeo.gdalconst i... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CESNET z.s.p.o..
#
# OARepo is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""ProxyIDP Remote application CLI."""
import click
from flask.cli import with_appcontext
from invenio_accounts.... |
from .robot import *
from .impulse import *
from .ocp import *
from .cost import *
from .constraints import *
from .unconstr import *
from .riccati import *
from .hybrid import *
from .line_search import *
from .solver import *
from .mpc import *
from . import utils |
# coding:utf8
from setuptools import setup, find_packages
version = "2021.12.11"
setup(
name="user_agent2",
version=version,
description="generate random user agent",
long_description=open("README.md", encoding="utf8").read(),
long_description_content_type="text/markdown",
author="Dytttf",
... |
import torch
from efficientnet_pytorch.model import EfficientNet
import torch.nn as nn
import torchvision
import torch.optim as optim
import torchvision.transforms as transforms
from utils.datasets import CustomDataset
from torch.utils.data import DataLoader
import numpy as np
def accuracy(output, target):
output... |
"""The pyhf spec CLI subcommand."""
import logging
import click
import json
from ..workspace import Workspace
from .. import modifiers
logging.basicConfig()
log = logging.getLogger(__name__)
@click.group(name='spec')
def cli():
"""Spec CLI group."""
@cli.command()
@click.argument('workspace', default='-')
@c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 16:42:44 2019
@author: GS, JMA
"""
from firm import Firm
import matplotlib.pyplot as plt
import numpy as np
class TestHousehold():
def __init__(self, z=20, zeta = 0.5, randomized = False):
self.z = z
self.zeta = zeta
... |
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import serializers
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
"""Custom Token seri... |
"""A flexible and expressive pandas validation library."""
from . import errors, constants
from .checks import Check
from .hypotheses import Hypothesis
from .decorators import check_input, check_output
from .dtypes import PandasDtype
from .schemas import DataFrameSchema, SeriesSchema
from .schema_components import Col... |
import os
import time
import pandas as pd
from tqdm import tqdm
from gensim.models import Word2Vec
from skmultiflow.utils import calculate_object_size
from utils import read_log
from utils import sort_alphanumeric
from utils import retrieve_traces
from utils import train_text_model
from utils import average_feature_vec... |
import ete3
import numpy
import copy
import sys
import scipy
import scipy.stats as ss
def normalize(array):
total = numpy.sum(array)
if total != 0:
return (array/total)
else:
return array
def normalize_middle(array):
middle = array[int(len(array)/2)]
if middle != 0:
... |
from typing import Dict
import torch
from allennlp.commands.train import train_model
from allennlp.common import Params
from allennlp.common.testing import AllenNlpTestCase
from allennlp.models import load_archive, Model
SEQUENCE_TAGGING_DATA_PATH = str(AllenNlpTestCase.FIXTURES_ROOT / "data" / "sequence_tagging.tsv... |
# -*- coding: utf-8 -*-
# Copyright (2018) Hewlett Packard Enterprise Development LP
#
# 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... |
from pypylon import pylon
import cv2
class BalserCamera:
def __init__(self, width=2450, height=2052):
self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
self.camera.Open()
self.camera.Width.SetValue(width)
self.camera.Height.SetValue(height)
... |
import tensorflow as tf
import numpy as np
with tf.device("/device:CPU:0"):
model = tf.keras.models.load_model("forennsic/minimal.h5")
sample = np.load("forennsic/sample.npy")
predictions = model(sample)
print(predictions)
|
import torch
import torch.nn as nn
import numpy as np
class L1Pruner:
def __init__(self, pruning_type="unstructured"):
self.pruning_type = pruning_type
def structured_prune(self, model, prune_rate):
# get all the prunable convolutions
convs = model.get_prunable_layers(pruning_type=se... |
{
'targets': [
{
'target_name': 'libshmooze',
'type': '<(library)',
'dependencies': [
'deps/libuv/uv.gyp:libuv'
],
'include_dirs': [
'include',
'>(SHARED_INTERMEDIATE_DIR)'
],
'sources': [
'src/command-lookup.gperf',
'src/parser.c'
... |
#!/usr/bin/env python
from future.standard_library import install_aliases
install_aliases()
import json
import jwt
import requests
import time
import os
import urllib3
import sys
import os
import logging
import watchtower
from urllib3._collections import HTTPHeaderDict
logging.basicConfig(level=logging.INFO)
logger... |
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import subprocess
import sys
import time
import build_projects
import build_version
import buildbot_comm... |
from typing import List
import dictdiffer
from flox.config import prompt, show_diff, apply_diff
from floxcore.config import ParamDefinition
from floxcore.console import info
from floxcore.context import Flox
from floxcore.plugin import Plugin
def save_secrets(flox: Flox, scope: str, profile: str, settings: dict):
... |
# 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... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
import sys
from pathlib import Path
from typing import Dict, List, Optional
from ci_common_utils import Logger
from ci_sonar_qube import ROOT_DIR
LOGGER = Logger()
AVAILABLE_SCAN_FOLDERS = (
"airbyte-integrations/connectors",
"airbyte-... |
import re
import urllib2
import socket
socket.setdefaulttimeout(5)
class GetIpFailed(Exception):
pass
ip_regex= re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
def _is_valid_ip(ip_str):
try:
socket.inet_aton(ip_str)
return True
except socket.error:
return False
def get_ip_in_t... |
import yaml
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
for section in cfg:
print(section)
print(cfg['mysql'])
print(cfg['other']) |
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk.tokenize import sent_tokenize , word_tokenize
import glob
import re
import os
import numpy as np
import sys
nltk.download('stopwords')
nltk.download('punkt')
Stopwords = set(stopwords.words('english'))
all_w... |
from hashlib import sha256
from random import randint
def generate_uri_id():
seed = seed = str.encode(str(randint(0, 10000)))
hash = sha256(seed)
start_index = randint(0, 57)
return hash.hexdigest()[start_index:start_index+8]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.