content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
# -------------------------------------------#
# author: sean lee #
# email: xmlee97@gmail.com #
#--------------------------------------------#
"""MIT License
Copyright ... | python |
import flask
class RequestDictionary(dict):
def __init__(self, *args, default_val=None, **kwargs):
self.default_val = default_val
super().__init__(*args, **kwargs)
def __getattr__(self, key):
# Enable rd.key shorthand for rd.get('key') or rd['key']
return self.get(key, self.de... | python |
# library
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import gif
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
# 関数化する
## git.frameデコレターを使用する
@gif.frame
def my_plot(df, date, x_min, x_max, y_min, y_max):
# 可視化するデータ
d = df[df["date"] <= date]
... | python |
from collections import defaultdict
from collections.abc import MutableMapping
from copy import deepcopy
from pathlib import Path
from typing import (Any, Dict, List, Literal, Mapping, NamedTuple, Sequence,
Tuple, Union)
import yaml
from more_itertools import unique_everseen
from .md import merge_... | python |
from secml.array.tests import CArrayTestCases
import numpy as np
import copy
from secml.array import CArray
from secml.core.constants import inf
class TestCArrayUtilsDataAlteration(CArrayTestCases):
"""Unit test for CArray UTILS - DATA ALTERATION methods."""
def test_round(self):
"""Test for CArray... | python |
from setuptools import setup
setup(
name='__dummy_package',
version='0.0.0',
install_requires=['html-linter==0.1.9'],
)
| python |
import json, glob
FILES = glob.glob('download/*/*/*/*.json')
good = {}
dups = 0
total = 0
for f in FILES:
with open(f, 'r') as fi:
j = json.load(fi)
for post in j['data']['children']:
i = post['data']['id']
if i == '4hsh42':
continue
if i not in good:
good[i] = post
with... | python |
import torch
import matplotlib.pyplot as plt
import imageio
import numpy as np
# Create data, 100 points evenly distributed from -2 to 2
# Use unsqueeze to add one more dimension, torch needs at least 2D input (batch, data)
x = torch.unsqueeze(torch.linspace(-2,2,100), dim=1)
# y = x^2 + b
y = x.pow(2) + 0.5 * torch.... | python |
import logging
import re
import nltk
from django.utils.text import slugify
from oldp.apps.backend.processing import ProcessingError, AmbiguousReferenceError
from oldp.apps.cases.models import Case
from oldp.apps.cases.processing.processing_steps import CaseProcessingStep
from oldp.apps.laws.models import LawBook
from... | python |
num = int(input("Digite um número inteiro de 0 a 9999: "))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f"O numero {num} possui {u} unidades.")
print(f"O numero{num} possui {d} dezenas.")
print(f"O numero{num} possui {c} centenas.")
print(f"O numero{num} possui {m} milhares.")
| python |
facts=[
'Mumbai was earlier known as Bombay.',
'Mumbai got its name from a popular goddess temple - Mumba Devi Mandir, which is situated at Bori Bunder in Mumbai.',
'On 16 April 1853, Mumbai witnessed the first train movement in India. \
With 14 carriages and 400 passengers, the first train left Bori Bunder, now called... | python |
# Copyright (c) ZenML GmbH 2021. 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 applica... | python |
import os
SQLALCHEMY_DATABASE_URI = os.environ.get('FLASK_DATABASE_URI', 'postgres://user:pass@host/db')
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping':True}
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = b'\xb0\xe2\x16\x16\x15\x16\x16\x16' | python |
# Copyright (c) 2014, 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# ... | python |
from target import TargetType
import os
import re
import cv2
import time
import subprocess
import numpy as np
TARGET_DIR = './assets/'
TMP_DIR = './tmp/'
SIMILAR = {
'1': ['i', 'I', 'l', '|', ':', '!', '/', '\\'],
'2': ['z', 'Z'],
'3': [],
'4': [],
'5': ['s', 'S'],
'6': [],
'7': [],
'8... | python |
from horse import Horse
import random
import os
money = 100
colours = [
"red",
"blue",
"yellow",
"pink",
"orange",
]
def race_horses(horses):
return random.choice(horses)
while money > 0:
print(f"Welcome to the race! You have £{money:.2f}. Your horses are: ")
horses = [Horse.rando... | python |
"""
Django settings for sandbox project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | python |
from django.contrib.auth import password_validation, get_user_model
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator
from rest_framework_simplejwt.exceptions import In... | python |
import math
import cmath
import cairo
from random import randint
IMAGE_SIZE = (5000, 5000)
NUM_SUBDIVISIONS = 6
def chooseRatio():
return randint(0, 6)
colors = [(1.0, 0.35, 0.35), (0.4, 0.4, 1.0), (0.1, 1.0, 0.2), (0.7, 0.1, 0.8)]
def chooseColor():
return colors[randint(0, len(colors) - 1)]
Ratio = chooseRat... | python |
from preprocess.load_data.data_loader import load_hotel_reserve
customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()
# 本书刊登内容如下
# 将iloc函数二维数组的第一维度指定为“:”,提取所有行
# 将iloc函数二维数组的第二维度指定为由列号组成的数组,提取相应的列
# 0:6和[0, 1, 2, 3, 4, 5]表示相同的意思
reserve_tb.iloc[:, 0:6]
| python |
"""
@authors:
# =============================================================================
Information:
The purpose of this script is to serve as the main code for the user.
Use the user's guide that still has not been written to find out how to use
this tool.
Use your python skills to understand... | python |
from django.conf.urls import url, include
#from django.contrib import admin
#from django.urls import path
from usuario.views import registar_usuario,editar_usuario,eliminar_usuario
app_name = 'usuario'
urlpatterns = [
url(r'^nuevo$',registar_usuario.as_view() , name="new"),
url(r'^edit_book/(?P<pk>\d+)/$',edita... | python |
from hashlib import md5
from app import app, db
import sys
if sys.version_info >= (3, 0):
enable_search = False
else:
enable_search = True
import flask_whooshalchemy as whooshalchemy
# This is a direct translation of the association table.
# use the lower level APIs in flask-sqlalchemy to create the table without... | python |
import numpy as np
import pickle
from collections import defaultdict
import spacy
from spacy.symbols import nsubj, VERB
from models import load_models, generate
import argparse
import torch
nlp = spacy.load("en")
def get_subj_verb(sent):
"Given a parsed sentence, find subject, verb, and subject modifiers."
s... | python |
# HTTP Error Code
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
import json
# created main window
window = Tk()
window.geometry("1000x700")
window.title("HTTP Error Code")
# ------------------ this is for adding gif image in the main window ... | python |
is_all_upper = lambda t: t.isupper() | python |
from .drm_service import DRMService
from .fairplay_drm_service import FairPlayDRM
from .aes_drm_service import AESDRM
class TSDRMService(DRMService):
MUXING_TYPE_URL = 'ts'
def __init__(self, http_client):
super().__init__(http_client=http_client)
self.FairPlay = FairPlayDRM(http_client=http... | python |
#!/usr/bin/python
import yaml
import json
#Reading from YAML file
print "\n***Printing from the YAML file***"
yamlfile = 'yamloutput.yml'
with open (yamlfile) as f:
yamllist = yaml.load(f)
print yamllist
print "\n"
#Reading from JSON file
print "\n***Printing from the JSON file***"
jsonfile = 'jsonoutput.json'... | python |
# Copyright 2018 StreamSets 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 by applicable law or agreed to in writi... | python |
import json
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
from labelme import utils
from skimage import img_as_ubyte
import PIL.Image
import random
JSON_DIR = 'json'
LABELCOLOR = { # 设定label染色情况
'product': 1,
'product': 2,
'product': 3,
'product': 4,
}
VOCVersion = 'VOC2012... | python |
from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='nicebytes',
author='Philipp Ploder',
url='https://github.com/Fylipp/nicebytes',
description='human-readable data quantities',
long_description=long_description,
long_description_content_type=... | python |
# -*- coding: utf-8 -*-
"""
profiling.tracing
~~~~~~~~~~~~~~~~~
Profiles deterministically by :func:`sys.setprofile`.
"""
from __future__ import absolute_import
import sys
import threading
from .. import sortkeys
from ..profiler import Profiler
from ..stats import RecordingStatistics, VoidRecordingStatis... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project: Appraise evaluation system
Author: Matt Post <post@cs.jhu.edu>
This script takes a set of parallel files and writes out the XML file used to
setup the corresponding Appraise tasks.
usage:
$ build_xml.py [-h] [-id ID] [-source SOURCELANG] [-target TARGETL... | python |
import datetime
import discord
from dotenv import dotenv_values
TOKEN = dotenv_values(".env")["TOKEN"]
class Client(discord.Client):
async def on_ready(self):
members = getlist(self.guilds[0])
votes = {}
for member in members:
votes[member] = 0
for member in members:
... | python |
from django.template.loader import get_template
from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget
def test_template_exists():
get_template(DynamicArrayWidget.template_name)
def test_format_value():
widget = DynamicArrayWidget()
assert widget.format_value("") == []
assert w... | python |
import collections
class contributor:
def __init__(self, name, index):
self.name = name
self.index = index
self.ratings = collections.defaultdict(list)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return self.name
... | python |
import json
import hashlib
from dojo.models import Finding
class TruffleHogJSONParser(object):
def __init__(self, filename, test):
data = filename.read()
self.dupes = dict()
self.items = ()
for line in data.splitlines():
json_data = self.parse_json(line)
f... | python |
import requests
import csv
key=input('Masukan produk yang akan dicari:')
limit=input('Masukan limit produk:')
hal = input('Masukan berapa halaman ke berapa:')
write = csv.writer(open('eCommerce/hasil/{}.csv'.format(key), 'w', newline=''))
header = ['nama produk','harga','terjual','rating produk','nama toko','lokasi t... | python |
from pytube import YouTube
from tqdm import tqdm
import ffmpeg
import html
# insert test link here!
yt = YouTube('https://www.youtube.com/watch?v=2A3iZGQd0G4')
audio = yt.streams.filter().first()
pbar = tqdm(total=audio.filesize)
def progress_fn(self, chunk, *_):
pbar.update(len(chunk))
yt.register_on_progress_ca... | python |
import argparse
import json
import multiprocessing
import os
import pickle
import random
from multiprocessing import Pool, cpu_count
import nltk
import numpy as np
import torch
from tqdm import tqdm
from src.data_preprocessors.transformations import (
NoTransformation, SemanticPreservingTransformation,
BlockS... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import exp
import os
import re
import sys
# This code implements the non-linear regression method described in:
# Jean Jacquelin 2009,
# Régressions et équations intégrales,
# sec. REGRESSIONS NON LINEAIRES des genres : PUISSANCE, EXPONENTIELLE, LOGARITHME, WEI... | python |
from setuptools import setup
setup(name='pkgtest',
version='1.0.0',
description='A print test for PyPI',
author='winycg',
author_email='win@163.com',
url='https://www.python.org/',
license='MIT',
keywords='ga nn',
packages=['pkgtest'],
install_requires=['numpy>=1.1... | python |
import boto3
import botocore
import sys
import os
class S3Client:
def __init__(self, bucket, key):
self.client = boto3.client('s3')
self.bucket = bucket
self.key = key
def get_content_length(self):
try:
return int(self.client.get_object(Bucket=self.bucket, Key=self.... | python |
import io
import os
import time
import zipfile
import h5py
import numpy as np
import pandas as pd
from PIL import Image
from django.http import HttpResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework... | python |
# Hello, I'm party bot, I will be called from wsgi.py once
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from Bot.models import TelegramUser, Action, Day, WeekDay, Event, Vote, BotMessage, Advertisement
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Re... | python |
from trex_stl_lib.api import *
class STLS1(object):
def get_streams (self, direction = 0, **kwargs):
s1 = STLStream(name = 's1',
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.1")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(... | python |
import collections
from .base import BaseItertool
from .iter_dispatch import iter_
from .tee import tee
_zip = zip
class product(BaseItertool):
"""product(*iterables, repeat=1) --> product object
Cartesian product of input iterables. Equivalent to nested for-loops.
For example, product(A, B) returns t... | python |
r"""
Lattice posets
"""
#*****************************************************************************
# Copyright (C) 2011 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************... | python |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: ctypes.macholib.framework
import re
__all__ = [
'framework_info']
STRICT_FRAMEWORK_RE = re.compile('(?x)\n(?P<location>^.*)(?:^|/)\n(?P... | python |
# bc_action_rules_bc.py
from pyke import contexts, pattern, bc_rule
pyke_version = '1.1.1'
compiler_version = 1
def speed_up(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
tr... | python |
"""
Created_at: 06 Oct. 2019 10:20:50
Target: EPISODES: set nullable `episodes.published_at`
"""
from playhouse.migrate import *
from migrations.models import database
previous = "0002_23052019_migration"
def upgrade():
migrator = PostgresqlMigrator(database)
migrate(migrator.drop_not_null("episodes", "pu... | python |
#!/usr/bin/python
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import os
import sys
hidapi_topdir = os.path.join(os.getcwd(), 'hidapi')
hidapi_include = os.path.join(hidapi_topdir, 'hidapi')
def hidapi_src(platform):
return os.path.join(hidapi_to... | python |
#!/bin/python
import csv
import sys
import struct
filename_in = sys.argv[1]
filename_out = sys.argv[2]
with open(filename_in) as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',');
line_count = 0
fileout = open(filename_out, "wb")
fileout.write(struct.pack('b', 0))
fileout.w... | python |
# Copyright 2015-2021 SWIM.AI 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 by applicable law or agreed to ... | python |
import torch
import random
from layers import SEAL
from tqdm import trange
from utils import hierarchical_graph_reader, GraphDatasetGenerator
class SEALCITrainer(object):
"""
Semi-Supervised Graph Classification: A Hierarchical Graph Perspective Cautious Iteration model.
"""
def __init__(self,args):
... | python |
# Copyright (c) 2017 NVIDIA Corporation
import torch
import argparse
from reco_encoder.data import input_layer
from reco_encoder.model import model
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
import torch.nn as nn
from torch.autograd import Variable
import copy
import time
from pathlib ... | python |
# Copyright 2017 Become Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | python |
"""Module for all encryption"""
# standard imports
import hashlib
import binascii
from os import urandom, getenv
from uuid import uuid4
# third party imports
from authlib.specs.rfc7519 import jwt
# local imports
from api.utilities.constants import CHARSETS
from api.utilities.constants import MESSAGES
from api.utilit... | python |
from common import *
## for debug
def dummy_transform(image):
print ('\tdummy_transform')
return image
# kaggle science bowl-2 : ################################################################
def resize_to_factor2(image, mask, factor=16):
H,W = image.shape[:2]
h = (H//factor)*factor
w = (W //... | python |
import wrapper as w
import json
outFile = open("data/tgt/linear/test.txt", "w")
with open("data/tgt/giant_news0tgt0.txt", "r") as inFile:
for line in inFile:
serialized = json.loads(line[line.index("\t"):])
ex = w.GrapheneExtract(serialized)
linear = ex.linearize()
if linear != "":
outFile.write(line[:lin... | python |
"""
Copyright(c) 2021 Authors
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 rights
to use, copy, modify, merge, publish, distribute, sublicen... | python |
from clases.catastrofe import catastrofe
from clases.catastrofe import AlDiaSiguiente
from clases.yinyang import Yin
from clases.yinyang import Yang
from clases.herenciaMultiple import Pared
from clases.herenciaMultiple import Ventana
from clases.herenciaMultiple import Casa
from clases.herenciaMultiple import ParedCor... | python |
# Exercise 2.12
from math import *
ballRadius = float(input("Please enter the radius: "))
ballVolume = 4 / 3 * pi * ballRadius ** 3
ballSpace = 4 * pi * ballRadius ** 2
print("The Volume of the ball is", ballVolume)
print("The Superficial Area of the ball is", ballSpace)
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# These imports are for python3 compatibility inside python2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import time
import cachetools
from apex.aprs import util as aprs_util
from .util im... | python |
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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.a... | python |
from structural.composite.logic.order_calculator import OrderCalculator
class Product(OrderCalculator):
def __init__(self, name: str, value: float) -> None:
self._name = name
self._value = value
@property
def name(self) -> str:
return self._name
@property
def value(self) ... | python |
# Copyright (C) 2016-2021 Alibaba Group Holding Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | python |
#!/usr/bin/env python3
# Copyright 2019 Kohei Morita
#
# 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 o... | python |
__author__ = 'marcos'
| python |
import pytest
from kgx.config import get_biolink_model_schema
def test_valid_biolink_version():
try:
schema = get_biolink_model_schema("2.2.1")
except TypeError as te:
assert False, "test failure!"
assert (
schema
== "https://raw.githubusercontent.com/biolink/biolink-model... | python |
import os
import tensorflow as tf
from tensorflow.python.client import device_lib
from tensorflow.python.training.distribute import DistributionStrategy
from tensorflow.contrib.distribute import MirroredStrategy, TPUStrategy
from time import time
from estimator import CustomEstimator
from dataset import dataset_fn, da... | python |
from .log import Code, warning, info, debug, debug_line, ModuleError
from . import Config, Export
from .stages import main
from .utils import get_temp_folder
from .checker import check, check_equality
from .dsp import channel_count, size
from .utils import random_file
import soundfile as sf
import numpy as np
import o... | python |
# generated by datamodel-codegen:
# filename: openapi.yaml
# timestamp: 2021-12-31T02:53:00+00:00
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Annotated, Any, List, Optional
from pydantic import BaseModel, Field
class ServiceUpdateNotFoundFault(Base... | python |
from typing import List, Union, Optional, Dict, MutableMapping, Any, Set
import itertools
import math
import numbers
import copy
import operator
import warnings
import attr
from .load_dump import dumps as demes_dumps
Number = Union[int, float]
Name = str
Time = Number
Size = Number
Rate = float
Proportion = float
_... | python |
import json
import urllib3
http = urllib3.PoolManager()
request = http.request('GET','https://booksbyptyadana.herokuapp.com/books')
data = request.data
print(request.status)
if len(data) > 0:
book_dict = dict()
books = json.loads(data.decode('utf-8'))
for book in books:
book_dict[book['book_name'... | python |
from abc import ABC
from distutils.version import LooseVersion
from typing import Union
class Capabilities(ABC):
"""Represents capabilities of a connection / back end."""
def __init__(self, data):
pass
def version(self):
""" Get openEO version. DEPRECATED: use api_version instead"""
... | python |
#!../../../.env/bin/python
import os
import numpy as np
import time
a = np.array([
[1,0,3],
[0,2,1],
[0.1,0,0],
])
print a
row = 1
col = 2
print a[row][col]
assert a[row][col] == 1
expected_max_rows = [0, 1, 0]
expected_max_values = [1, 2, 3]
print 'expected_max_rows:', expected_max_rows
print 'expected_... | python |
from utils import overloadmethod, ApeInternalError
from astpass import DeepAstPass
import cstnodes as E
class Sentinel:
def __init__(self, value):
self.value = value
def __repr__(self):
return f'Sentinel({self.value!r})'
def is_sentinel(x):
return isinstance(x, Sentinel)
def is_iterable(... | python |
import unittest
import numpy as np
from laika.raw_gnss import get_DOP, get_PDOP, get_HDOP, get_VDOP, get_TDOP
from laika.lib.coordinates import geodetic2ecef
class TestDOP(unittest.TestCase):
def setUp(self):
self.receiver = geodetic2ecef((0, 0, 0))
self.satellites = np.array([
[18935913, -3082759,... | python |
# This utility should only be invoked via the itimUtil.sh wrapper script.
# Support utility to submit ITIM object changes via the ITIM API. Changes are specified
# through a text file.
# Changes are submitted asynchronously and status is reported later in the output.
# See usage information in the wrapper script.
# ... | python |
import random
from careers.career_enums import GigResult
from careers.career_gig import Gig, TELEMETRY_GIG_PROGRESS_TIMEOUT, TELEMETRY_GIG_PROGRESS_COMPLETE
from sims4.localization import TunableLocalizedStringFactory
from sims4.tuning.instances import lock_instance_tunables
from sims4.tuning.tunable import TunableRefe... | python |
"""Plugwise Switch component for HomeAssistant."""
from __future__ import annotations
from typing import Any
from plugwise.exceptions import PlugwiseException
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, ca... | python |
# Copyright (c) 2020 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
import numpy as np
from toast.timing import function_timer, Timer
from toast.utils import Logger
from ..sim_hwpss import OpSimHWPSS
def add_sim_hwpss_args(parser):
parser.add_argument(
"--hwpss-file",... | python |
import pandas as pd
import numpy as np
from pyam import utils
def test_pattern_match_none():
data = pd.Series(['foo', 'bar'])
values = ['baz']
obs = utils.pattern_match(data, values)
exp = [False, False]
assert (obs == exp).all()
def test_pattern_match_nan():
data = pd.Series(['foo', np.n... | python |
from __future__ import absolute_import, division, print_function
from appr.models.kv.channel_kv_base import ChannelKvBase
from appr.models.kv.etcd.models_index import ModelsIndexEtcd
class Channel(ChannelKvBase):
index_class = ModelsIndexEtcd
| python |
# coding: utf-8
"""
RLSData.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
* Redi... | python |
# Generated by Django 3.1.2 on 2020-10-30 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='page',
options={'ordering': ['order', ... | python |
import csv
import cv2
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import sklearn
import tensorflow as tf
import pickle
import keras
from sklearn.externals import joblib
from keras.models import Se... | python |
"""Auto-generated file, do not edit by hand. SA metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_SA = PhoneMetadata(id='SA', country_code=966, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[1-467]|92)\\d{7}|5\\d{8}|8\\d{9}', p... | python |
from rest_framework.viewsets import ModelViewSet
from exam.models import TblExamRecord as Model
from exam.serializers import RecordSerializer as Serializer
class RecordViewset(ModelViewSet):
queryset = Model.objects.all().order_by('-id')
serializer_class = Serializer | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class MybankCreditSupplychainCreditpayAmountQueryResponse(AlipayResponse):
def __init__(self):
super(MybankCreditSupplychainCreditpayAmountQueryResponse, self).__init__()
s... | python |
import string
import numpy
import copy
from domrl.engine.agent import Agent
"""
class Agent(object):
def choose(self, decision, state):
return decision.moves[0]
class StdinAgent(Agent):
def choose(self, decision, state):
# Autoplay
if len(decision.moves) == 1:
return [0]... | python |
"""Functional tests for pylint."""
| python |
import time
from wrf.cache import _get_cache
from wrf import getvar
from netCDF4 import Dataset as nc
#a = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_00:00:00")
#b = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_03:00:00")
a = nc("/Users/ladwig/Documen... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .get_key import *
from .get_managed_hsm ... | python |
import datetime
import json
from flask_testing import TestCase
from config import create_app
from db import db
from models import ParkModel
from models.pay_type import PayType
from tests.base import generate_token
from tests.factories import AdminUserFactory
from tests.helpers_for_tests import GenerateTarifeData
cl... | python |
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.views.decorators.http import require_http_methods, require_GET
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.contrib.auth impo... | python |
import re
from datetime import datetime
class HadoopSeriesParser:
def __init__(self):
self.attribute_count = 8
self.foundation_date_regex = r'^([^\t]*\t){1}"\d{4}"\^\^<http://www.w3.org/2001/XMLSchema#date>.*$'
def parse(self, result_data):
lines_attributes = []
### Structure
# <http://dbpedia.org/resour... | python |
import sys
import os
import pytest
import pandas as pd
import arcus.ml.dataframes as adf
import logging
from unittest.mock import patch
from collections import Counter
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
# initialize list of lists
categorical_data = [['BE', 10], ['FR', 15], ['BE... | python |
#/usr/bin/python
# Copyright 2013 by Hartmut Goebel <h.goebel@crazy-compilers.com>
# Licence: GNU Public Licence v3 (GPLv3), but not for military use
import subprocess
import argparse
GRAPH_HEADER = '''
digraph "%s"
{
nodesep=0; sep=0; ranksep=0
ratio="compress"
packmode="node"; pack=1
pad=0
splines=true
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.