content stringlengths 5 1.05M |
|---|
from datetime import datetime
import argparse
class ArgParser:
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--dataset-dir', dest='dataset_dir', type=str, default='../celeba')
self.parser.add_argument('--condition-file', type=str, default='./list_a... |
import requests
from bs4 import BeautifulSoup, ResultSet
import pandas as pd
import time
import numpy as np
from typing import Union
class Scraper(object):
def __init__(
self,
id: str = "Turing-College-capstone-project-work",
web_browser: str = "Mozilla/5.0",
url_for_movie_categori... |
import os
import sys
def _hook(name,value,out):
if name == 'extra_drop_list':
if len(value) <= 0 :
out.write("{}")
return True
temp_array = value.split('|')
out.write("{");
for i in range(len(temp_array)):
out.write(temp_array[i] + ",")
out.write("}")
return True
elif name == 'open_copy_list':
... |
from pwn import *
from pwnlib.util.hashes import *
from pwncli.utils import *
from pwncli.cli import *
|
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
@dataclass
class Detail:
hours: int
kind: str
@dataclass
class Day:
date: datetime
hours: int = 0
details: list[Detail] = field(default_factory=list)
def add_work(self, hours: int, work_kind: str... |
import ast
import operator
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Iterator, List, Set, Union
if sys.version_info >= (3, 8):
from typing import Literal # unimport: skip
else:
from typing_extensions import Literal
__all__ = ["Import", "ImportFrom", "Name", "Scope"]
... |
class TaskInstanceConfig(object):
def __init__(self, task_config):
self.cpu = task_config.cpu
self.memory = task_config.memory
self.disk = task_config.disk
self.duration = task_config.duration
class TaskConfig(object):
def __init__(self, task_index, instances_number, cpu, memor... |
# -*- Python -*-
def _cc_configure_make_impl(ctx):
out_includes = ctx.actions.declare_directory(ctx.attr.name + "-includes.h")
out_lib = ctx.actions.declare_file("{}.a".format(ctx.attr.name))
outputs = [out_includes, out_lib]
cpp_fragment = ctx.fragments.cpp
compiler_options = [] # cpp_fragment.c... |
import os
import imp
import sys
import click
import utilities_common.cli as clicommon
from natsort import natsorted
from sonic_py_common.multi_asic import get_external_ports
from tabulate import tabulate
from utilities_common import multi_asic as multi_asic_util
from utilities_common import constants
# mock the red... |
import datetime
from pathlib import Path
import pytest
import dateutil
from naucse import models
TZINFO = dateutil.tz.gettz('Europe/Prague')
@pytest.fixture
def model():
path = Path(__file__).parent / 'fixtures/test_content'
return models.Root(path)
def test_run_with_times(model):
run = model.runs[2... |
import argparse
import sys
import os
from datetime import datetime
from tensorflow.keras.models import *
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.datasets import mnist
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing.image import load_img
from tensorf... |
from cffi import FFI
from PIL import Image
ffi = FFI()
ffi.cdef("""
typedef struct {
double x, y, z;
} point_t;
typedef struct {
double x, y, z;
} vector_t;
typedef struct {
float red, green, blue;
} color_t;
typedef void* coloration;
colorat... |
import pandas as pd
import numpy as np
class DataSet(object):
def __init__(self):
pass
def append(self):
pass
def sample(self):
pass
def clear(self):
pass
class NPArrayDataSet(DataSet):
def __init__(self,X,Y, batch_mode=False, batch_size=32):
self.X = X
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and... |
import asyncio
# A wrapper class for asyncio.Future so we can use errorBacks
# (also so I don't have to change a hundred lines of code...)
class Deferred:
def __init__(self):
self.f = asyncio.Future()
def __cb(self, fut, func):
# might want to remove .done() check to better catch errors
... |
import asyncio
from pipelines.plumber import Plumber
from test_workflow import StringFunc
def getcoro(name):
d = {
'StringFunc.reverse' : StringFunc.reverse,
'StringFunc.toupper' : StringFunc.toupper,
'StringFunc.tolower' : StringFunc.tolower,
'StringFunc.input_str': StringFunc.input_str,
'StringFunc.output... |
import re
from itertools import cycle
########
# PART 1
'''
Vixen can fly 8 km/s for 8 seconds, but then must rest for 53 seconds.
Blitzen can fly 13 km/s for 4 seconds, but then must rest for 49 seconds.
Rudolph can fly 20 km/s for 7 seconds, but then must rest for 132 seconds.
Cupid can fly 12 km/s for 4 seconds, b... |
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
### /usr/bin/python
### /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
"""
This Python script is written by Zhiyang Ong to determine if
a BibTeX key is valid.
Synopsis:
Check the validity of a BibTeX key.
Notes/Assumptions:
A... |
FRAME_METHOD = 1
FRAME_HEADER = 2
FRAME_BODY = 3
FRAME_HEARTBEAT = 8
FRAME_MIN_SIZE = 4096
FRAME_END = 206
REPLY_SUCCESS = 200
CONTENT_TOO_LARGE = 311 # soft-error
NO_ROUTE = 312 # soft-error
NO_CONSUMERS = 313 # soft-error
ACCESS_REFU... |
import os, sys, subprocess, signal
import logging
import optparse
import util
def isValidOpts(opts):
"""
Check if the required options are sane to be accepted
- Check if the provided files exist
- Check if two sections (additional data) exist
- Read all target libraries to be debloated ... |
"""Module for handling the different draw options for nodes. Used when creating a .dot file respresentation of the pipeline."""
_DEFAULT_DRAW_OPTIONS = {'shape': 'box', 'style': 'filled'}
_DEFAULT_AQP_OPTIONS = {'fillcolor': '#ffffff'}
_DEFAULT_VISQOL_OPTIONS = {'fillcolor': '#F0E442B3'}
_DEFAULT_PESQ_OPTIONS = {'fill... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
import os
import html
import re
import decimal
import math
from collections import OrderedDict
from contextlib import suppress
import requests
from SFIWikiBotLib import Config
from SFIWikiBotLib import SmallConstants
from SFIWikiBotLib import Gener... |
# bot.py
import os
import ast
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
@client.event
async def on_member_join(member):
await member.crea... |
from random import randint
import torch
from ...stability.blur import TFMSBoxBlur
class TFMSRandomBoxBlur(torch.nn.Module):
def __init__(self, min_kernel_size=(11, 11), max_kernel_size=(51, 51), border_type='reflect'):
super(TFMSRandomBoxBlur, self).__init__()
self.min_kernel_size = min_kernel_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ROS-RBDL simulator
This 'simulator' is not per se a simulator, it communicates with the real robots in the real world using ROS [1], and
computes any necessary kinematic and dynamics information using the RBDL library [2].
Specifically, this 'simulator' starts the `ros... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
import numpy as np
from scipy.optimize import fsolve
from scipy.linalg import expm
import matplotlib.pyplot as plt
# Some utilities
# map a vector to a skew symmetric matrix
def skew(x):
return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
# map a twist to its adjoint form
def adjoint(x):
r... |
import pytest
import os
import datetime
import osmdigest.detail as detail
def test_OSMElement():
el = detail.OSMElement("tag", {"id":"298884269", "lat":"54.0901746", "lon":"12.2482632", "user":"SvenHRO",
"uid":"46882", "visible":"true", "version":"1", "changeset":"676636",
... |
import json
from typing import Dict, List, Optional, Union
from redbot.core.utils.chat_formatting import text_to_file
from redbot.vendored.discord.ext import menus
from .typehint import UserInfosResult
class MembersPage(menus.ListPageSource):
def __init__(self, data, *, json: Optional[List[dict]] = None):
... |
#! /usr/bin/python3
import os
os.system("wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=140d4U-YJs7pnSYQ3Q1nEIX5NKbUNz-ze' -O mit_voting.csv") |
#!/usr/bin/env python
import os
from flask_script import Manager
from server import create_app
app = create_app(os.environ.get('CONFIG') or 'default')
manager = Manager(app)
if __name__ == '__main__':
manager.run()
|
from typing import Dict
from typing import List
import pytest
from pytest_aiomoto.aws_lambda import aws_lambda_src
from pytest_aiomoto.aws_lambda import aws_lambda_zip
from pytest_aiomoto.aws_lambda import lambda_handler
def test_lambda_handler_echo():
event = {"i": 0}
result = lambda_handler(event=event, c... |
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from whoosh import store
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
import logging
SEARCHSC... |
import requests
import itertools
import configparser
import os
config = configparser.ConfigParser()
config.read(os.environ['PARACHUTE_CONFIG_FILE'])
HOST = config['tests']['host']
PORT = config['tests']['port']
ADDRESS = 'http://{}:{}'.format(HOST, PORT)
API_ROUTE = config['routes']['api']
USER_API_KEY = config['te... |
__author__ = ["Francisco Clavero"]
__email__ = ["fcoclavero32@gmail.com"]
__status__ = "Prototype"
from nltk import word_tokenize
def remove_stopwords_set(sentence, stop_words):
"""
Transforms a given text to its lemmatized form. Assumes clean text separated by spaces.
:param sentence: the text from whi... |
"Memoization to the rescue"
'''
Memoization is a technique in which you store the results of computational tasks when
they are completed so that when you need them again, you can look them up instead
of needing to compute them a second (or millionth) time.
'''
from typing import Dict
memo: Dict[int, int] = {0: 0, 1: ... |
class Solution:
def canJump(self, nums: List[int]) -> bool:
|
from .plotter import Plotter
from .evaluator import Evaluator
__all__ = [
'Plotter',
'Evaluator',
]
|
import pygame as pg
import json as js
n = 32
m = 26
Ancho = n*32
Alto = m*32
class Colisionable(pg.sprite.Sprite):
def __init__(self, img, x, y):
pg.sprite.Sprite.__init__(self)
self.image = img
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class Otros... |
import requests
import os
import filecmp
#the following is needed, because at this stage PLATFORMIO_HOME_DIR is undefined
from os.path import expanduser
home = expanduser("~")
if os.name == 'nt': # Windows
basePath = home + '\.platformio'
else:
basePath = home + '/.platformio'
patchPath = basePa... |
from tvm import te
from tvm.topi.utils import get_stages_and_cfgs
from .libxsmm_intrin import intrin_libxsmm_brgemm
from .schedule_utils import get_layer_cfg
def schedule_conv_conv_fused_nchwc(cfg, outs):
outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs
s = te.create_schedule([x.op for x in outs])... |
TASK_NAME = 'TaggingTask'
JS_ASSETS = ['']
JS_ASSETS_OUTPUT = 'scripts/vulyk-tagging.js'
JS_ASSETS_FILTERS = 'rjsmin'
CSS_ASSETS = ['']
CSS_ASSETS_OUTPUT = 'styles/vulyk-tagging.css'
CSS_ASSETS_FILTERS = 'cssmin'
|
import crea as stm
import sys
_shared_cread_instance = None
def get_config_node_list():
from creabase.storage import configStorage
nodes = configStorage.get('nodes', None)
if nodes:
return nodes.split(',')
def shared_cread_instance():
""" This method will initialize _shared_cread_instance a... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Version 1.0
# Author: WildfootW
# GitHub: github.com/WildfootW
# Copyleft (C) 2020 WildfootW All rights reversed.
#
from pwn import *
class Error(Exception):
"""
Base class for exceptions in this module.
"""
pass
class LengthError(Error):
"""... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from mwptoolkit.module.Graph import gcn,graph_module |
import base64
import random
import re
import string
import cv2
import numpy as np
import pytesseract
class CaptchaDecode:
def decode_response(self, response):
image_b64 = response["result"]["image"]
image_data = self.decode_b64(image_b64)
path = self.generate_random_name()
self.wr... |
"""
author : abhishek goswami
abhishekg785@gmail.com
audio.py module
simply handles all the i/o operations related to the audio
such as user audio input and output
"""
import pyaudio # handles the record and play of the audio files
import audioop # lib for handling math operations on the audio f... |
#!/usr/bin/python3
from string import Template
from bottle import route, run, request, redirect, HTTPError
import FigClasses as fc_
import HTML_Templates as ht_
#####=====----- Variables -----=====#####
#####=====----- Classes -----=====#####
#####=====----- Functions -----=====#####
@route('/')
def server_root(... |
from django.forms import ModelForm
from .models.order import Order
from .models.comment import Comment
from .models.personorder import PersonOrder
from .models.person import Person
from django import forms
import re
from django.utils.translation import gettext_lazy as _
from datetime import date
from dateutil.relatived... |
import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
def graph_data(stock):
stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=99y/csv'
source_code = urllib.request.urlopen(stock_price_url).read().decode()
... |
import csv
from django.core.management.base import BaseCommand
from grid.models import Element, Grid, GridPackage, Feature
from package.models import Project
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('filename', type=str)
def handle(self, *args, **kwargs):
... |
class Solution:
def reorderSpaces(self, text: str) -> str:
wo = text.split()
if len(wo) == 1: return wo[0] + ' '*text.count(' ')
sp = text.count(' ')
be = sp//(len(wo)-1)
af = sp - (sp//(len(wo)-1))*(len(wo)-1)
ans = ' '*be
ans = ans.join(wo) + ' '*af
... |
import spacy
# Carga el modelo es_core_news_sm
nlp = spacy.load("es_core_news_sm")
# Imprime en pantalla los nombres de los componentes del pipeline
print(nlp.pipe_names)
# Imprime en pantalla el pipeline entero de tuples (name, component)
print(nlp.pipeline)
|
#!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
parser = argparse.ArgumentParser()
parser.add_argument('input')
args = parser.parse_args()
data = []
with open(args.input) as f:
lines = f.readlines()
for line in lines:
line = lin... |
import uvicorn
from fastapi import FastAPI
from fastapi_versioning import VersionedFastAPI
from config import config
from routers import root, auth
from databases.database import engine, Base
app = FastAPI(
title='py-auth',
description='Authentication service made by Python'
)
# Config
configuration = confi... |
from enum import Enum
class sms(object): # (unknown name)
class AboutInfo(vmodl.DynamicData): # sms.AboutInfo
name = ""
fullName = ""
vendor = ""
apiVersion = ""
instanceUuid = ""
vasaApiVersion = ""
class EntityReference(vmodl.DynamicData): # sms.EntityReference
id = ... |
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Conv2D, DepthwiseConv2D, BatchNormalization, Dropout, GlobalAveragePooling2D, Reshape, multiply, add, Activation
from skimage.transform import resize
CONV_KERNEL_INITIALIZER = {
'class_name': 'VarianceScaling',... |
from typing import Union
from urllib.parse import parse_qs
from hw.alexander_sidorov.common import Errors
from hw.alexander_sidorov.common import api
from hw.alexander_sidorov.common import typecheck
Data = dict[str, list[str]]
@api
@typecheck
def task_06(query: str) -> Union[Data, Errors]:
"""
Splits HTTP ... |
from __future__ import absolute_import, division, print_function
from stripe_modern.api_resources.abstract import CreateableAPIResource
from stripe_modern.api_resources.abstract import ListableAPIResource
from stripe_modern.api_resources.abstract import nested_resource_class_methods
@nested_resource_class_methods("l... |
"""Declare the Requests client interface and register it."""
import typing
import zope.interface
import zope.interface.verify
if typing.TYPE_CHECKING:
import requests
from . import interface
@zope.interface.implementer(interface.IRequest)
class Requests:
"""ClientAdapter used with the Requests library."""
... |
"""Tests the gps module."""
import unittest
from mock import patch
import pynmea2
import pytest
import control.gps
# mock gps nmea 0183 messages
NMEA_MSG_GGA = "$GNGGA,183236.00,3311.64266,N,08730.77826,W,1,07,1.24,85.4,M,-29.8,M,,*4A"
NMEA_MSG_GGA2 = "$GNGGA,183235.00,3311.64268,N,08730.77830,W,1,07,1.24,85.5,M,-29.8... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
import ConfigParser
class ConfigurationOptions(object):
"""
generic shell object for storing attributes
"""
pass
class ConfigurationParser(object):
def __init__(self,path=""):
self._options = {}
self._path = path
def set_path(self,path):
self._path = path
def ... |
"""Test the TcEx Batch Module."""
# third-party
import pytest
# pylint: disable=no-self-use
class TestUtils:
"""Test the TcEx Batch Module."""
@pytest.mark.parametrize(
'variable,value',
[
('#App:0002:te1!TCEntity', {'id': '001', 'value': '1.1.1.1', 'type': 'Address'}),
... |
# # -*- coding: utf-8 -*-
# """
# models.planning
# ~~~~~~~~~~~~~~~
# Planning specific models. This might get re-named or simply re-ordered.
# TODO: Work out what these are
# """
# # 3rd Party
# import sqlalchemy as sa
# # Module
# from .core import BaseModel
# class MaxAnnualOperationalThroughp... |
import json
from chalice.app import SQSEvent
from chalice.app import SQSRecord
from tests.unit.helpers.aws.sqs_helper import get_sqs_event_stub, get_sqs_message_stub
def create_chalice_sqs_record(event_dict, context=None):
event = event_dict
if event_dict[0]:
event = event_dict[0]
else:
... |
import pygame, easygui, sys
import constants
pygame.init()
try:
centerFontObj = pygame.font.Font("resources/font.ttf", 32)
except pygame.error:
easygui.msgbox("font.ttf doesn't exist.")
pygame.quit()
sys.exit()
fontObj = pygame.font.Font("resources/font.ttf", 16)
class centerText:
def __init__(self, text):
... |
import socket
myso = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
myso.connect(('www.py4inf.com', 80))
myso.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = myso.recv(512)
if(len(data)<1):
break
print data
myso.close()
|
# импортируем специальные поля Алхимии для инициализации полей таблицы
from sqlalchemy import Column, Boolean, Integer, ForeignKey
# импортируем модуль для связки таблиц
from sqlalchemy.orm import relationship, backref
# импортируем модуль инициализации декларативного класса Алхимии
from DB.dbcore import Base
# импорт... |
# coding:utf8
"""
Description:实战案例5:Gensim实现新闻文本特征向量化
Author:伏草惟存
Prompt: code in Python3 env
"""
import os,time,sys
from mydict import *
from StopWords import *
from gensim import corpora, models
#******************** 高效读取文件***********************************
class loadFolders(object): # 迭代器
def __init__(se... |
from factory import *
if __name__ == "__main__":
CONNECT = DatabaseFactory.get_database('tsql').instance().connect()
EXECUTE = DatabaseFactory.get_database('tsql').instance().execute()
DISSCONECT = DatabaseFactory.get_database('tsql').instance().disconnect()
print(CONNECT)
print(EXECUTE)
... |
from rest_framework import serializers
from .models import AssetInfo
class AssetSerializer(serializers.ModelSerializer):
class Meta:
model = AssetInfo
fields = '__all__'
|
# Copyright 2015 The TensorFlow 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 applica... |
"""
test_inference_lf.py
Author: Jordan Mirocha
Affiliation: McGill
Created on: Wed 25 Mar 2020 11:01:32 EDT
Description:
"""
import os
import glob
import ares
import numpy as np
import matplotlib.pyplot as pl
from ares.physics.Constants import rhodot_cgs
def test():
# Will save UVLF at these redshifts and m... |
from datetime import timedelta as td
from hc.api.models import Check
from hc.test import BaseTestCase
class GetBadgesTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self.a1 = Check(project=self.project, name="Alice 1")
self.a1.timeout = td(seconds=3600)
self.a1.grace = t... |
# Generated by Django 2.1.1 on 2019-03-16 21:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deliveries', '0002_auto_20190316_2128'),
]
operations = [
migrations.AddField(
model_name='customer',
name='nickname... |
import numpy as np
from typing import Callable
from autograd import hessian
from .newton_base import NewtonBase
class Newton(NewtonBase):
def __init__(self, stop_criterion, step_optimizer) -> None:
super().__init__(stop_criterion, step_optimizer)
def _get_inverse_h(self, xk: np.ndarray) -> np.ndarra... |
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
DATA_DIR = BASE_DIR + '/data/'
SAMPLE_DIR = BASE_DIR + '/sample/'
MODEL_DIR = BASE_DIR + '/model/'
PARAM_DIR = BASE_DIR + '/output/param/'
OUTPUT_DIR = BASE_DIR + '/output/result/'
for DIR in [DATA_DIR, SAMPL... |
# -*- coding: utf_8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# Crypto Key Database
import os
import sqlite3
import shutil
import uuid
import random
import base64
import Crypto.PublicKey.RSA
import Crypto.Random.random
import Crypto.Cipher.PKCS1_OAEP
import Crypto.Hash.SHA256
# increment keydb_ver... |
"""Unit tests for protein_query module"""
from db_searcher import DbSearcher
from protein_query import ProteinSearcher
import os
import pandas as pd
TEST_FOLDER = os.path.dirname(__file__)
DB_SEARCHER_DATA_FOLDER = os.path.join(TEST_FOLDER,"db_searcher_data")
# DB_SEARCHER_DATA_FOLDER is a folder exclusive for... |
import datetime
from datetime import date
from typing import List
import sqlalchemy as sa
import sqlalchemy.orm as orm
from mealie.db.models.model_base import BaseMixins, SqlAlchemyBase
from mealie.db.models.recipe.api_extras import ApiExtras
from mealie.db.models.recipe.category import Category, recipes2categories
fr... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""A module for data of monitor."""
import json
import numbers
from datetime import datetime
from superbench.benchmarks import ReduceType
class MonitorRecord:
"""Record class to save all monitoring data."""
reduce_ops = {
'gpu... |
# Sascha Spors, Professorship Signal Theory and Digital Signal Processing,
# Institute of Communications Engineering (INT), Faculty of Computer Science
# and Electrical Engineering (IEF), University of Rostock, Germany
#
# Data Driven Audio Signal Processing - A Tutorial with Computational Examples
# Feel free to conta... |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class OrderItemEdiLot(object):
... |
from django.conf import settings
from django.db import models
from django.urls import reverse
from . import global_request
class AuditedModel(models.Model):
"""
CHECK IF THIS IS TRUE
CAVEAT 1:
If using a custom user model, add the following line to the top:
from api.models.user_profile import Us... |
"""
Defines classes and utility methods used to communicate with the Index of Composable Elements
(ICE), a.k.a. the "registry of parts". This API is designed to minimize dependencies on other
libraries (e.g. Django model objects) so that it can be used from any part of the EDD codebase,
including remotely-executed code... |
from ..file_utils import convert_VariantFile_to_IndexedVariantFile, common_filepaths
from .load_utils import parallelize_per_pheno
def run(argv):
parallelize_per_pheno(
get_input_filepaths = lambda pheno: common_filepaths['pheno'](pheno['phenocode']),
get_output_filepaths = lambda pheno: common_f... |
# Copyright (c) 2018 Tsinghuanet, Inc.
# 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 req... |
import sqlite3
import pandas as pd
import numpy
import matplotlib.pyplot as plt
import re
con = sqlite3.connect('works.sqlite')
df = pd.read_csv("works.csv")
cursor = con.cursor()
def clean(field):
return re.sub(r'\<[^>]*\>', '', str(field))
df['skills'] = df['skills'].apply(clean)
df['otherInfo'] = df['otherInfo... |
import pathlib
import mypyc.build
def build(setup_kwargs: dict) -> None:
"""
This function is mandatory in order to build the extensions.
"""
project_dir = pathlib.Path(__file__).resolve().parent
ext_modules = [
str(file)
for file in (project_dir / "{{cookiecutter.package_name}}")... |
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
numerical_columns_selector = selector(dtype_exclude=object)
numerical_columns = numerical_columns_selector(data)
preprocessor = make_column_transformer(
(StandardScaler(), numerical_columns),
(... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
from v2x_solution.road import models as road_models
class Events(APIView):
def get(self, req, format=None):
# 1. get all events
events = model... |
from rest_framework import serializers
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('title', 'description', 'framework', 'image', 'owner') |
# debugcommands.py - command processing for debug* commands
#
# Copyright 2005-2016 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import codecs
import collec... |
# Copyright 2019-present MongoDB, 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 wri... |
from functools import partial
from typing import Union
import numpy as np
import pandas as pd
from dask import dataframe as dd
from dask.distributed import Client
from .core import BaseLFApplier, _FunctionCaller
from .pandas import apply_lfs_to_data_point, rows_to_triplets
Scheduler = Union[str, Client]
class Dask... |
from DyCommon.DyCommon import *
from EventEngine.DyEvent import *
from ..DyStockDataCommon import *
from .Common.DyStockDataCommonEngine import *
class DyStockDataDaysEngine(object):
""" 股票(指数)历史日线数据,包含股票代码表和交易日数据 """
def __init__(self, eventEngie, mongoDbEngine, gateway, info, registerEvent=True):
s... |
""" Generic common schemas """
from marshmallow import Schema, fields
class IdSchema(Schema):
""" Simple ID schema """
id = fields.Integer()
|
import shutil
import os
import random
import numpy as np
from tensorflow import random as tf_random
import yaml
from pathlib import Path
from datetime import datetime
import pytz
import git
from gcp_utils import copy_folder_locally_if_missing
from image_utils import ImagesAndMasksGenerator
from models import generate_c... |
"""EM field example"""
import dtmm
import numpy as np
import matplotlib.pyplot as plt
WAVELENGTHS = [500,600]
SIZE = (128,128)
window = dtmm.aperture((128,128))
field_data = dtmm.illumination_data(SIZE, WAVELENGTHS,window = window,jones = (1,0),
pixelsize = 200, beta = (0,0.1,0.2), phi = (0.,0.,np.pi/6))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.