text stringlengths 2 999k |
|---|
# basic library imports
import glob
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy import random
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from PIL import Image
from multiprocessing import Pool
import random
... |
from flask_script import Manager, Command
from flask_migrate import Migrate, MigrateCommand
import redis
import config
from server import app, db
from rq import Worker, Queue, Connection
# command to run the redis worker
class RunWorker(Command):
def run(self):
redis_url = config.REDIS_URL
listen... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Represents a model repository, including pre-trained models and bags of models.
A repo can either be the main remote repo... |
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = "{{ project_name }}.api"
|
# qubit number=4
# total number=28
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += X(3) # number=1
prog ... |
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""The default import path from site
"""
# end_pymotw_header
import sys
import os
import site
if "Windows" in sys.platform:
SUFFIXES = ["", "lib/site-packages"]
else:
SUFFIXES = ["lib/python{}/site-packages".format(sys.version[:3]), "lib/site-python"... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Gareth J. Greenaway <gareth@saltstack.com>`
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, ... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# 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 applicabl... |
# Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3, 4]].values
#y = dataset.iloc[:, 3].values
# K-Means Clustering using sk-learn
from sklearn.cluster... |
import torch
import numpy as np
from scipy.io import loadmat
from skimage.io import imread
def default_loader(path_):
return imread(path_)
def mat_loader(path_):
return loadmat(path_)
def make_onehot(index_map, n):
# Only deals with tensors with no batch dim
old_size = index_map.size()
z = torch... |
# Copyright 2017 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... |
import taichi as ti
@ti.func
def _inside(p, c, r):
return (p - c).norm_sqr() <= r * r
@ti.func
def taichi_logo(pos, scale=1 / 1.11):
p = (pos - 0.5) / scale + 0.5
ret = -1
if not (p - 0.50).norm_sqr() <= 0.52**2:
if ret == -1:
ret = 0
if not (p - 0.50).norm_sqr() <= 0.495**2:... |
#!/usr/bin/python
#-- coding: UTF-8 --
from __future__ import unicode_literals, print_function
from psychopy import event, core, monitors, sound, visual
from random import choice, shuffle, randint
win = visual.Window(allowGUI=False, #monitor=m,
fullscr=False, winType='pyglet', units='pix', rgb=-.5... |
"Profile the performance of downloading fresh chain from peers"
from skepticoin.networking.threading import NetworkingThread
from skepticoin.scripts.utils import (
configure_logging_from_args,
DefaultArgumentParser,
check_chain_dir,
read_chain_from_disk,
)
import cProfile
from datetime import datetime... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017 Moritz Lode
#
# 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... |
import logging
from threading import Thread, Event
from .exceptions import ConnectionError, TimeoutError
class HeartbeatThread(Thread):
daemon = True
def __init__(
self, send_heartbeat,
relax_interval_in_seconds,
hurry_interval_in_seconds):
super(HeartbeatThread,... |
# Cálculos complejos (I)
print('\n\n---[Diapo 22.a]--------------')
print('Cálculos complejos (I)\n')
nota1 = 7
nota2 = 9
nota3 = 4
promedio = (nota1 + nota2 + nota3) / 3
print('La nota promedio es', promedio)
# Cálculos complejos (II)
print('\n\n---[Diapo 22.b]--------------')
print('Cálculos complejos (II)\n')
v... |
from flask import Flask
from flask_bootstrap import Bootstrap
from config import config_options
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_uploads import UploadSet,configure_uploads,IMAGES
from flask_mail import Mail
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager... |
'''
Created on 25 Apr 2012
@author: eeaston
'''
import os
from six.moves import configparser
import sys
import socket
import glob
import shutil
import threading
try:
from path import Path
except ImportError:
from path import path as Path
from wsgiref.simple_server import make_server
from paste.deploy.loadwsg... |
import copy
import os
import re
from pprint import pprint
from tempfile import TemporaryDirectory
import pytest
import requests
from PyPDF2 import PdfFileReader
from ricecooker.classes import files
from ricecooker.classes import nodes
from ricecooker.utils.pdf import PDFParser # SIT
# Fixtures
####################... |
# https://cms-conddb.cern.ch/browser/#search
# default value for all L1T menus
connectionString = "frontier://FrontierProd/CMS_CONDITIONS"
# L1T legacy (Fake) / stage-1 (Fake1)
l1MenuRecord = "L1GtTriggerMenuRcd"
l1MenuLabel = ""
# L1T stage-2
l1tMenuRecord = "L1TUtmTriggerMenuRcd"
l1tMenuLabel = ""
#The snapshot ti... |
# Code generated by optimus dev. DO NOT EDIT.
from typing import Any, Callable, Dict, Optional
from datetime import datetime, timedelta, timezone
from airflow.models import DAG, Variable, DagRun, DagModel, TaskInstance, BaseOperator, XCom, XCOM_RETURN_KEY
from airflow.kubernetes.secret import Secret
from airflow.conf... |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import pytest
import torch
from mmedit.models import build_model
def test_glean():
model_cfg = dict(
type='GLEAN',
generator=dict(
type='GLEANStyleGANv2',
in_size=16,
out_size=64,
style_ch... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('bookmarks', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='bookmark',
name='vali... |
from typing import Any
from argparse import ArgumentParser
from confirmation.models import Confirmation, create_confirmation_link
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.actions import create_stream_if_needed
from zerver.models import MultiuseInvite
class Command(ZulipBaseCommand):
hel... |
from __future__ import absolute_import
from functools import partial
from jinja2 import Template
from .mplexporter.renderers.base import Renderer
import numpy as np
from .utils import iter_rings
svg_template = Template("""<svg width="{{ width|int }}px" height="{{ height|int }}px" viewBox="{{ minx }} {{ miny }} {{ ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "so1n"
__date__ = "2020-02"
import asyncio
import logging
from typing import NoReturn
from aio_statsd.transport_layer_protocol import DatagramProtocol, ProtocolFlag, TcpProtocol
from aio_statsd.utlis import get_event_loop
class Connection(object):
def _... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2017) 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/licen... |
"""Auto-generated file, do not edit by hand. MK metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_MK = PhoneMetadata(id='MK', country_code=389, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[2-578]\\d{7}', possible_number_pattern=... |
"""
Function : WEW2Bento.py
Title : WEW2Bento
Written by: Alejandro Rios
Date : Dezember/2019
Last edit : August/2020
Language : Python
Aeronautical Institute of Technology - Airbus Brazil
Description:
- This module calculates the weight fraction
Future implementations:
-
Inputs:
- AR - Wing ... |
class WhatsappyError(Exception):
"""The base exception type for the errors specific for this library."""
class LoginError(WhatsappyError):
"""Describes an error on the login process."""
class BadPathError(WhatsappyError):
"""Describes an invalid path."""
|
import torch
import torch.nn.functional as F
from torch import nn
from torch_geometric.nn import GCNConv
from . import graph_embed
class Net(torch.nn.Module):
"""docstring for Net"""
def __init__(self, cfg, config=None, PRINT_DEBUG=False):
super(Net, self).__init__()
input_size = cfg.SCENE_GRA... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import sys
import cv2.aruco as aruco
#targetVideo = 0 # カメラデバイス
#targetVideo = "test-video.mp4" # 動画
#targetVideo = "http://{IP Address}:8090/?action=stream" # MJPG-Streamer
targetVideo = "test-video.mp4"
cap = cv2.VideoCapture( targetVideo )
while cap.isOp... |
from multiprocessing import Process, Value
def increment(num):
for _ in range(1000):
num.value = num.value + 1
def decrement(num):
for _ in range(1000):
num.value = num.value - 1
if __name__ == "__main__":
num = Value('i', 0)
print(num.value)
p1 = Process(target=increment, args... |
'''
MIT License
Copyright (c) 2019 Michail Kalaitzakis
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, publ... |
# Copyright (c) 2011 The Chromium Embedded Framework Authors.
# Portions copyright (c) 2006-2008 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.
from gclient_util import *
import os, sys
# The CEF root directory is the pa... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# 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 modifications or derivative wo... |
"""
Name: SURF.py
Authors: Gediminas Bertasius and Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: ryan.j.urbanowicz@darmouth.edu
Created: December 4, 2013
Modified: August 25,2014
Description: Surf algorithm computes the score of each attribute evaluating their str... |
from unittest import TestCase
from lf3py.api.errors import ApiError
from lf3py.api.render import ApiRender
from lf3py.api.response import Response
from lf3py.test.helper import data_provider
class TestRender(TestCase):
@data_provider([
(200, {'statusCode': 200, 'headers': {'Content-Type': 'application/js... |
import os
from conans import ConanFile, tools, CMake
class EncryptionAdapterTestUtilitiesConan(ConanFile):
name = "EncryptionAdapterTestUtilities"
description = "Test utilities for library-agnostic API for C++ to encrypt data"
url = "https://github.com/systelab/cpp-encryption-adapter"
homepage = "http... |
# -*- coding: utf8 -*-
'''
========================================================================
CygnusCloud
========================================================================
File: multithreadingCounter.py
Version: 2.0
Description: thread-safe c... |
# -*- coding: utf-8 -*-
"""
Common RGB Colour Models Utilities
==================================
Defines various RGB colour models common utilities.
"""
from __future__ import division, unicode_literals
from colour.colorimetry import CCS_ILLUMINANTS
from colour.models.rgb import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to... |
class ReplayBuffer(object):
def __init__(self, rand_state, capacity=1e6):
self._capacity = capacity
self._rand_state = rand_state
self._next_idx = 0
self._memory = []
def append(self, transition):
if self._next_idx >= len(self._memory):
self._memory.append(tr... |
import subprocess
from pathlib import Path
from unittest import mock
import pytest
from briefcase.exceptions import BriefcaseCommandError
from briefcase.integrations.xcode import DeviceState, get_device_state
def simctl_result(name):
"""Load a simctl result file from the sample directory, and return the content... |
import argparse
import difflib
import logging
import os
import re
import sys
import srsly
import tqdm
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument(
"sample_file",
type=str,
help="Sample file",
)
parser.add_argument(
'-v', '--verbose',
... |
import random
import numpy as np
import pprint
import json
from workflowgen.vizaction import VizAction
from workflowgen.linkaction import LinkAction
from optparse import OptionParser
import pandas as pd
from common.schema import Schema
from common.vizgraph import VizGraph
#from common.storage import Storage
import pand... |
from django.db import models
import uuid
from django.db.models.deletion import CASCADE
from users.models import Profile
# Create your models here.
class Project(models.Model):
owner = models.ForeignKey(
Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200... |
# Copyright (c) 2016 Uber Technologies, Inc.
#
# 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, publ... |
"""
Join platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.join/
"""
import logging
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_DATA, ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA,
... |
#!/usr/bin/env python -O
"""
This is the test class for testing software CSCI module algorithms and models.
"""
# -*- coding: utf-8 -*-
#
# tests.software.TestCSCI.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 Andrew Rowland andrew.rowland <AT> reliaqual <DOT> com
#
# Redistribut... |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creando nuevo usuario con email es exitoso"""
email = 'test@google.com'
password = 'Testpass123'
user = get_user_mo... |
from typing import *
import torch.nn as nn
import torch.optim as optim
from models.LitBase import LitBase
from .models import AlexNet
class LitAlexNet(LitBase):
def __init__(self, args: Dict[str, Any]):
super().__init__()
self.save_hyperparameters(args)
self.model = AlexNet(
... |
# Copyright [2015] Hewlett-Packard Development Company, L.P.
# Copyright 2016 Tesora 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
#
# Unle... |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
# -*- coding: utf-8 -*-
import json
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
DAY_MAPPING = {
"Mon": "Mo",
"Tue": "Tu",
"Wed": "We",
"Thu": "Th",
"Fri": "Fr",
"Sat": "Sa",
"Sun": "Su",
}
class FreseniusFidneyCare(scrapy... |
#!/usr/bin/env python2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import ctypes
import torch
import random
import numpy
import os
import pkgutil
if pkgutil.find_loader("adversarial") is not None:
# If advers... |
from .moves_table import *
##############################################################################
##############################################################################
import sqlite3 as sql
import sys
con = sql.connect('moveDB.db')
with con:
cur = con.cursor()
ex = cur.execute
def create_tabl... |
color = {
'purple' : '\x1b[95m',
'cyan' : '\x1b[96m',
'darkcyan' : '\x1b[36m',
'blue' : '\x1b[94m',
'green' : '\x1b[92m',
'yellow' : '\x1b[93m',
'red' : '\x1b[91m',
'bold' : '\x1b[1m',
'underline': '\x1b[4m',
'end' ... |
import math as m
import numpy as np
def GSR(f):
print("Input the Lower Limit")
XL[0] = input()
print("Input the Upper Limit")
XU[0] = input()
print("Input the tolerance")
epsilon = input()
while k || |
# Copyright (c) 2021 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 app... |
# 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, Version 2.0 (the
# "License"); you may not u... |
from easyquant import StrategyTemplate
from easyquant import RedisIo
from threading import Thread, current_thread, Lock
import json
import redis
import time
import pymongo
import pandas as pd
import talib
class calcStrategy(Thread):
def __init__(self, code, data, log, chkv, redis):
Thread.__init__(self)
... |
#!/usr/bin/env python
from rucio.db.sqla.session import get_session
# Exit statuses
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3
def purge_bin():
try:
session = get_session()
sql = "select table_name from user_tables"
for table in session.execute(sql):
query = "drop table %s c... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ... |
import json
import argparse
import numpy as np
from bertserini.utils.utils import choose_best_answer, weighted_score
from bertserini.experiments.eval.evaluate_v1 import squad_v1_eval as squad_evaluation
from bertserini.experiments.eval.evaluate_v1_drcd import evaluation as drcd_evaluation
from bertserini.experiments.... |
import requests
import re
import ssl
import json
import time
jobStatus = {"Failure": -1, "Pending": 0, "Processing": 1, "Success": 2, "Failure": 3}
def getSession(api_key, secret_key, insecure=False):
session = requests.Session()
session.headers.update({"Authorization": "Token token=\"{}{}\"".format(api_key, ... |
#!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ... |
"""Defines collections of data products."""
import logging
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from astropy.table import vstack
from . import MPLSTYLE
from .targetpixelfile import TargetPixelFile
log = logging.getLogger(__name__)
__all__ = ['LightCurveCollection', '... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... |
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
# import main objects
from . control import Control
from . tool import Tool
from . view import View
from . export import show, export, debug
from . json import Image
# import main backends
from . import json
from . import svg
# try import ... |
'''
Fine-tune PredNet model trained for t+1 prediction for up to t+5 prediction.
'''
import os
import numpy as np
np.random.seed(123)
from keras import backend as K
from keras.models import Model, model_from_json
from keras.layers import Input
from keras.callbacks import LearningRateScheduler, ModelCheckpo... |
from enum import Enum
class TokenType(Enum):
# single character tokens
LEFT_PAREN = '('
RIGHT_PAREN = ')'
LEFT_BRACE = '{'
RIGHT_BRACE = '}'
COMMA = ','
DOT = '.'
MINUS = '-'
PLUS = '+'
SEMICOLON = ';'
SLASH = '/'
STAR = '*'
# one or two charcter token tokens
B... |
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from common.admin import BaseRegionalAdminMixin
from containers.models import Container
@admin.register(Container)
class ContainerAdmin(BaseRegionalAdminMixin, ModelAdmin):
ordering = ("size_class",)
list_display = (
"id",
... |
from mowgli_etl.pipeline.wdc.wdc_offers_corpus import WdcOffersCorpus
from mowgli_etl.pipeline.wdc.wdc_rounded_size_buckets import WdcRoundedSizeBuckets
from mowgli_etl.pipeline.wdc.wdc_heuristic_product_type_classifier import (
WdcHeuristicProductTypeClassifier,
)
from mowgli_etl.pipeline.wdc.parsimonious_parser.w... |
import numpy as np
import pandas as pd
import os
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score as accuracy
#all required libraries are imported
'''Author: Ankur W [LearnML} '''
de... |
#
# Example python script to generate a BOM from a KiCad generic netlist
#
# Example: Sorted and Grouped CSV BOM
#
"""
@package
Generate a csv BOM list.
Components are sorted by ref and grouped by value
Fields are (if exist)
Item, Qty, Reference(s), Value, LibPart, Footprint, Datasheet
"""
from __f... |
from .factory import LineageMap
from .interface import ToolLineage
from .tool_shed import ToolVersionCache
__all__ = ("LineageMap", "ToolLineage", "ToolVersionCache")
|
from .drawing import DrawingAdapter
try:
from IT8951 import constants
from IT8951.display import AutoEPDDisplay
has_it8951 = True
except ImportError:
has_it8951 = False
import threading
class DrawingAdapterEPD(DrawingAdapter):
def __init__(self, vcom: float):
if has_it8951:
pri... |
import csv
from datetime import datetime, timedelta
from matplotlib.finance import fetch_historical_yahoo
from sqlalchemy import inspect
from sqlalchemy.exc import IntegrityError
from pacioli import db
from pacioli.views.ofx_views import Securities
from pacioli.models import SecurityPrices
def update_ticker_prices(... |
#!/usr/bin/env python3
import icontract
@icontract.require(lambda x: x > 0)
def some_func0(x: int) -> None:
pass
@icontract.require(lambda x: x > 0)
def some_func1(x: int) -> None:
pass
@icontract.require(lambda x: x > 0)
def some_func2(x: int) -> None:
pass
@icontract.require(lambda x: x > 0)
def s... |
import pandas as pd
from helpers.fs_methods import *
from helpers.training import *
import os
def name_dataframe(X,cv_method):
n,m=X.shape
name1='df_accuracy_'
name2='df_ranking_'
name3='df_weights_'
added_str='fold.pkl'
num_splits =cv_method.get_n_splits(X)
if num_splits!=n:
name1... |
"""MeiliSearchHelper
Wrapper on top of the MeiliSearch API client"""
import meilisearch
from builtins import range
def remove_bad_encoding(value):
return value.replace(''', "'")
def clean_one_field(value):
if isinstance(value, bool):
return str(value)
elif isinstance(value, str):
ret... |
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... |
import json
import math
import random
import re
from datetime import datetime, timedelta
from typing import Union
import pandas as pd
import urllib3
from urllib3.exceptions import ReadTimeoutError
from models.BotConfig import BotConfig
from models.Trading import TechnicalAnalysis
from models.config import binancePars... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
def all_combinations_with_value(base_values, desired_value):
all_combinations = find_all_combinations(base_values)
return find_by_value(all_combinations, desired_value)
def find_by_value(all_combinations, desired_value):... |
import os
import numpy as np
from self_supervised_3d_tasks.data.generator_base import DataGeneratorBase
class DataGeneratorUnlabeled3D(DataGeneratorBase):
def __init__(self, data_path, file_list, batch_size=32, shuffle=True, pre_proc_func=None):
self.path_to_data = data_path
super().__init__(fi... |
import urllib.parse
import webbrowser
def traverser_graphe(graphe, oriente):
if oriente:
type_graphe = "digraph"
lien = "->"
else:
type_graphe = "strict graph"
lien = "--"
donnees_graphe = type_graphe + " G { \n"
if len(graphe.sommets()) != 0:
num_som... |
# To use this code, make sure you
#
# import json
#
# and then, to convert JSON from a string, do
#
# result = cameras_from_dict(json.loads(json_string))
from typing import Any, List, TypeVar, Type, cast, Callable
T = TypeVar("T")
def from_str(x: Any) -> str:
assert isinstance(x, str)
... |
#!/home/redcart/Data_Science/velib_streaming/streaming/bin/python
import json
from datetime import datetime
import configparser
import argparse
import requests
import psycopg2
from kafka import KafkaProducer
from connect_sql import config_sql
if __name__ == '__main__':
parser = argparse.ArgumentParser()
... |
from django.db import models
from django.contrib.auth.models import User
class Problem(models.Model):
"""
Problem
"""
id = models.AutoField(
'서로게이트키',
db_column='ID',
null=False,
primary_key=True
)
editor = models.ForeignKey(
User,
verbose_name=... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
########################################
# Changes compared to 30_11_dDQN_light_tweak71.py
# 01.
# lr_optimizer = 7.3e-4
########################################
import sys
import numpy as np
#import pandas as pd
import datetime
import json
from array import *
import os
import math
from random import randrange
imp... |
#
# core.py
#
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sre_constants
from collections.abc import Iterable
import traceback
import types
from operator import itemgetter
from functools import wraps
from threading import RLock
from .util import (... |
import os
os.environ['THEANO_FLAGS'] = 'floatX=float32,device=cpu'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import tensorflow as tf
import tflearn
import argparse
import sys
from multiprocessing import cpu_count
from rllab.misc.instrument import run_experiment_lite
from rllab.misc.instrument import VariantGenerator
fro... |
import os
import numpy as np
import mgplvm
import torch
from mgplvm import kernels, rdist
from mgplvm.manifolds import Torus, Euclid, So3
from mgplvm.models import Core
from mgplvm.training import train
import matplotlib.pyplot as plt
import pickle
from scipy.stats import ttest_1samp
torch.set_default_dtype(torch.float... |
import mock
from django.contrib.auth.models import AnonymousUser
from ginger.forms import GingerForm
import json
from datetime import date, time, datetime
from django import test, forms
from django.core.paginator import Paginator
from ginger import serializer, exceptions, views, forms as jforms
from django.test.utils... |
import threading
from Cb_constants.CBServer import CbServer
from magma_base import MagmaBaseTest
from remote.remote_util import RemoteMachineShellConnection
from sdk_exceptions import SDKException
class KVStoreTests(MagmaBaseTest):
def setUp(self):
super(KVStoreTests, self).setUp()
self.crash_mem... |
# Copyright (c) 2015-2017 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
def qemuMonitorCommand(domain, cmd, flags):
retval = '{"return":[{"current":true,"CPU":0,"pc":-2130513274,' \
'"halted":true,"thread_id":86064},' \
'{"current":false,"CPU":1,"pc":-2130513274,' \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.