content stringlengths 5 1.05M |
|---|
from __future__ import absolute_import
from .utils import (gen_404, load_configuration, db_connect, load_schemas,
_unpack_params, _return2client, _stringify_data)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 11:13:47 2018
https://jeremykun.com/2013/11/08/adversarial-bandits-and-the-exp3-algorithm/
@author: shivap
"""
import random
# draw: [float] -> int
# pick an index from the given list of floats proportionally
# to the size of the entry (i.e. normalize to a ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from __future__ import absolute_import, unicode_literals
import json
import argparse
import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
from .__... |
#############
#JSON output#
#############
FEED_FORMAT = "json"
FEED_EXPORT_ENCODING = "utf-8"
FEED_URI = "scrapy_generator %(time)s.json"
FEED_EXPORT_INDENT = 4
FEED_EXPORT_FIELDS = items_generator
|
# author: PyShine
# website: http://www.pyshine.com
# import the necessary packages
import numpy as np
import cv2
import socket,time
import queue
import sounddevice as sd
import threading
import matplotlib
import copy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animati... |
#!/usr/bin/python
# Python script to delete all C++ source and header files from a root directory
import os
import sys
import time
import datetime
import logging
from optparse import OptionParser
FILE_EXTENSIONS = ['.h', '.cpp']
# -----------------------------------------------------------------------------
def s... |
# Copyright 2017 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 json
import os
import sys
from gpu_tests import common_browser_args as cba
from gpu_tests import color_profile_manager
from gpu_tests import gpu_inte... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from os import sys
try:
from skbuild import setup
except ImportError:
print('scikit-build is required to build from source.', file=sys.stderr)
print('Please run:', file=sys.stderr)
print('', file=sys.stderr)
print(' python -m pip instal... |
import sys
import re
for i, x in enumerate(sys.stdin):
val = str(x).strip().lower()
if(re.match(r'(\w*([s])\2+)', val)):
print("hiss")
else:
print("no hiss") |
R, B = map(int, input().split())
x, y = map(int, input().split())
def is_ok(n):
r = R - n
if r < 0:
return False
b = B - n
if b < 0:
return False
return r // (x - 1) + b // (y - 1) >= n
ok = 0
ng = 10 ** 18 + 1
while ng - ok > 1:
m = (ok + ng) // 2
if is_ok(m):
ok... |
from getpass import getpass
from mysql.connector import connect, Error
try:
# Establishing a connection with MySQL
with connect(
host="localhost",
user=input("Enter username: "),
password=getpass("Enter password: "),
database="online_movie_rating",
) as connection:
... |
from .core import *
from .logger import * |
#!/usr/bin/env python
# $Id: test_language.py 8372 2019-08-27 12:11:15Z milde $
# Authors: Engelbert Gruber <grubert@users.sourceforge.net>;
# David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
Tests for language module completeness.
Specify a language code... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Script to demonstrate the use of ciscosparkapi for the people API
The package natively retrieves your Spark access token from the
SPARK_ACCESS_TOKEN environment variable. You must have this environment
variable set to run this script.
"""
# Use future f... |
''' Opening and Reading Files
Syntax to open file.
f-open("myfile.txt)
''' |
import sys
import eann
import gym
import time
from float_binary_conversion import float_to_binary_list, binary_list_to_float
from Preprocessing import preprocess_inputs
env = gym.make('HalfCheetah-v2')
action_len = env.action_space.shape[0]
print("brain input size: " + str(len(preprocess_inputs(env.reset()))))
assert(... |
from app.schema.item import ItemInDatabase
from app.schema.seller import SellerInDatabase
from app.test.client import client
from app.test.sample_data import (
item_1_raw,
item_2_raw,
seller_1_raw,
seller_2_raw,
)
from requests import Response
def create_seller_1() -> tuple[Response, SellerInDatabase]... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ozpcenter', '0023_auto_20170629_1323'),
]
operations = [
migrations.AddField(
model_name='review',
n... |
import os
import re
import numpy as np
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, \
UnexpectedAlertPresentException, StaleElementReferenceException, \
NoSuchWindowException, WebDriverException
from enum import Enum, auto
from threading import Thread, Event
f... |
import logging
from telebot import types
from botstarter import bot
logging.basicConfig(level=logging.INFO)
bot.init_bot()
@bot.user_handler(commands=["echo"])
def echo_handler(msg, user, **kwargs):
received_msg = msg.text.replace("/echo", "", 1).strip()
if received_msg:
reply = f"Hello {user.firs... |
"""exercism armstrong numbers module."""
def is_armstrong_number(number):
"""
Determine if the number provided is an Armstrong Number.
An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits
:param number int - Number to check.
:return b... |
import subprocess
from termcolor import colored
import os
import cPickle as pickle
import argparse
from read_credentials import readCredentials, ssh, scp
parser = argparse.ArgumentParser()
parser.add_argument("--start", type=int, default=1800)
parser.add_argument("--end", type=int, default=2009)
args = parser.parse... |
from setuptools import setup, find_packages
import codecs
import os
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
long_description = "\n" + fh.read()
VERSION = "0.1.1"
DESCRIPTION = "Notification/Alert for django users"
LONG_DESCRIPTI... |
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
import pandas as pd
import mplfinance as mpf
api_key = "WA57b7Xw7jhd5P1t78Z3gj6AuB8D9iSgbaZJEs16TjyJCfw2ds8mIUJdQDqmAVXG"
api_secret = "9m2mU7iWLWS2v0q2rgFzkdyGx3gSUIMi1n6Sx9ItBInWL1y7Cxl6Tf5A2AwTYzA7"
client = Client(api_key, ap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
import pip
from pip.req import parse_requirements
from setuptools import find_packages, setup, Command
from setuptools.comma... |
import gdb
global path
path = [];
def is_container(v):
c = v.type.code
return (c == gdb.TYPE_CODE_STRUCT or c == gdb.TYPE_CODE_UNION)
def is_pointer(v):
return (v.type.code == gdb.TYPE_CODE_PTR)
def print_struct_follow_pointers(s, file, level = 0, counter = 0):
indent = ' '
if not is_contai... |
"""
Kombu modules.
"""
import logging
import socket
import ssl
from mtb.modules import md5_hash
from mtb.string import get_uuid
import auth.credential as credential
from messaging.message import Message
from amqpclt import common
from amqpclt.errors import AmqpcltError
LOGGER = logging.getLogger("amqpclt")
class ... |
## Send a Single Email to a Single Recipient
# import os
# import json
# from sendgrid import SendGridAPIClient
# from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException
# message = Mail(from_email=From('dx@sendgrid.com', 'DX'),
# to_emails=To('elmer.t... |
#!/usr/bin/env python3
#
# Based on http://www.prooffreader.com/2014/05/graphing-distribution-of-english.html
#
import colorsys
import matplotlib.pyplot as plt
ALPHABET = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
BUCKETS_COUNT = 720
FILENAME = 'data/ru.txt'
def color(current, minimum, maximum):
s = (current - minimum... |
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from scipy.spatial import distance
import scipy.sparse as ss
class DataInput(object):
def __init__(self, params:dict):
self.params = params
def load_data(self):
prov_day_data = ss.load_npz(se... |
from collections import OrderedDict
import hashlib
import json
import logging
import requests
import urllib.parse
import uuid
from django import forms
from django.conf import settings
from django.core import signing
from django.http import HttpRequest
from django.template.loader import get_template
from django.utils.t... |
# -*- coding: utf-8 -*-
from data.reader import wiki_from_pickles, corpus_to_pickle
from filtering.speaker_restriction import filter_speaker_restrict
import argparse
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("--lang", type=str)
p.add_argument("--n_tokens", type=int)
p.ad... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 requi... |
#!/usr/bin/env python3
from aws_cdk import core
from dockerpipeline.docker_pipeline import DockerPipelineConstruct
from fluxcd.fluxcd_construct import FluxcdConstruct
from cluster.cluster_construct import ClusterConstruct
import os
git_auth_user = os.environ["GIT_AUTH_USER"]
git_auth_key = os.environ["GIT_AUTH_KEY"]
... |
"""Add audit_events type, object and created_at indexes
Revision ID: 280_switch_g7_framework_to_open
Revises: 270_add_audit_events_indexes
Create Date: 2015-09-01 13:45:44.886576
"""
# revision identifiers, used by Alembic.
revision = '280_switch_g7_framework_to_open'
down_revision = '270_add_audit_events_indexes'
... |
from dataclasses import dataclass, field
from datetime import datetime
from typing import ClassVar, Set
import marshmallow # type: ignore
from marshmallow import fields, post_load # type: ignore
from ..json import CamelCaseSchema, Serializable
from ..util import normalize_datetime
class DatasetSchema(CamelCaseSch... |
DEBUG = False
SITE_ID = 3
STATIC_ROOT = '/home/navin/webapps/{{project_name}}t_staticx'
STATIC_URL = 'http://static.test.{{project_name}}.com/'
# Here you can over-ride ADMINS, MANAGERS
# And pretty much everything else
EMAIL_HOST = 'smtp.webfaction.com'
EMAIL_HOST_USER = 'navin_{{project_name}}'
SERVER_EMAIL = 'info... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20160206_1539'),
]
operations = [
migrations.RenameField(
model_name='servicearea',
... |
'''
Dimensions in Arrays
* A dimension in arrays is one level of array depth (nested arrays).
* nested array: are arrays that have arrays as their elements.
0-D Arrays
* 0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
1-D Arrays
* An array that has 0-D arrays as its el... |
'''
Given a positive integer n, find the least number of perfect square numbers
(for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
'''
class SolutionDP(object):
... |
def grasp2dict(res):
pred = {
"x": res.grasp.center.x,
"y": res.grasp.center.y,
"angle": res.grasp.angle,
"q": res.q_value,
"approachAxis": [int(res.grasp.approach_axis[0]), int(res.grasp.approach_axis[1]), int(res.grasp.approach_axis[2])],
"axis": [res.grasp.axis[0... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'video_maker_prompt_ui.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VideoMakerPrompt(object):
def setupUi(self,... |
#-*- coding: utf-8 -*-
"""
Copyright (C) 2013 Roman Bondarenko
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 u... |
#!/pxrpythonsubst
#
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
from PIL import Image
import json
import os
from django.conf import settings
from django.db import transaction
from django.http.response import JsonResponse
from dataCRUD.forms import ImgForm
from dataCRUD.models import ImageMetadata, Dataset, WorkspaceDataset
from common.models import UserWorkspace, Workspace
from ... |
"""
MVPD - Linear Regression Model + L2 Regularization
"""
import sklearn
from sklearn import linear_model
def L2_LR(ROI_1_train, ROI_2_train, ROI_1_test, ROI_2_test, alpha):
"""
Build a linear regression model with L2 regularization.
"""
# initialize and fit model on training data
ridgereg = line... |
# coding: utf-8
# train_numeric.csv -
# train_date.csv
# In[1]:
# Import the packages
import pandas as pd
import numpy as np
from sklearn import cross_validation
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.tree import *
from sklearn.ensemble import *
fr... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import logging
import os
from smartcard.util import toHexString, toASCIIString, PACK
from model.plugin.plugins.base_plugin import base_plugin
from model.plugin.api.fcp import get_data_length, get_record_count
from model.plugin.api.convert import convert_bcd_to_string, co... |
#!/usr/bin/env python
"""
quick.py
Quickly Plot SBOL Designs
Usage:
------
python quick.py -input "p.gray p.lightblue i.lightred r.green c.orange t.purple -t.black -c.yellow -p.yellow" -output out.pdf
allowed part types:
p: promoter i: ribozyme r: rbs c: cds t: terminator s: spacer =: scar
re... |
import json
import os
import requests
id_phone = os.environ['ID_PHONE']
product_id = os.environ['PRODUCT_ID']
base_url = f"https://api.maytapi.com/api/{product_id}"
token = os.environ['TOKEN']
headers = {
'content-type': 'application/json',
'x-maytapi-key': token
}
def send_text(phone: str, text: str):
"... |
import hashlib,os
def hash(y):
hasher = hashlib.md5(y.encode())
return (hasher.hexdigest())
def askCredentials(x):
if x!=0:
os.chdir("Data")
username=input("Enter Username: ")
password=input("Enter Password: ")
mainPass,mainUser=hash(password),hash(username)
if mainUs... |
# Standard Library
# Django Library
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
# Thirdparty Library
from apps.base.models import PyCompany, PyFather
from apps.base.views.sequence import get_next_value
from taggi... |
from abc import abstractmethod
import torch.nn as nn
from graph4nlp.pytorch.data.data import GraphData
from graph4nlp.pytorch.modules.graph_embedding_initialization.embedding_construction import (
EmbeddingConstruction,
)
class GraphEmbeddingInitialization(nn.Module):
def __init__(
self,
word... |
import os
import subprocess
import pytest
@pytest.mark.parametrize(
"filename",
[
"base-with-nbs-pys.yml",
"base-with-nbs.yml",
"base-with-pys.yml",
"base-without-nbs.yml",
"material-with-nbs-pys.yml",
"material-with-nbs.yml",
"material-with-pys.yml",
... |
myNumber = list(range(0,10))
for number in myNumber:
if number % 2 == 0:
print(f"\nThe Number {number} Is Even.")
else:
print(f"\nThe Number {number} Is Odd.")
else:
print("\nLoop Is Finished.")
|
import traceback
from django.db.models import query
import funcy
from eraserhead.model_instance_wrapper import ModelInstanceWrapper
from eraserhead.request_storage import RequestStorage
from eraserhead.queryset_storage import QuerySetStorage
current_request_storage = RequestStorage()
@funcy.once
def patch_queryse... |
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from mpl_toolkits.basemap import Basemap
import glob
import struct
import time
import sys
import getopt
import string
from datetime import date
import datetime
obsid_dict = {5525:'SST', 5522:'SSS', 5351:'ADT', 307... |
import unittest
import at_checks
import daemons_check
import modem_checks
import python_checks
import sim_checks
import simple_cmd_checks
from plmn.utils import *
from plmn.results import *
if __name__ == '__main__':
nargs = process_args()
suite = unittest.TestSuite()
# Add all regression test-cases to... |
"""
Barrido del chi2 en el parametro b para el resto de los parametros fijos.
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.constants import c as c_luz #metros/segundos
c_luz_km = c_luz/1000
import sys
import os
from os.path import join as osjoin
from pc_path import definir_path
path_git, pa... |
def string_compression(str1):
compress_string = ""
current_count = 1
for i in range (1, len(str1)):
if str1[i] == str1[i-1]:
current_count += 1
else:
compress_string = compress_string + str1[i-1] + str(current_count)
current_count = 1
if i == len... |
##
# Contains information about products, regions, etc. for each site
# in the country.
# region= two-letter regional identifier, mainly used for installation of
# text product templates
SiteInfo= {
'ABQ': {
'region': 'SR',
'fullStationID': 'KABQ',
'wfoCityState': 'Albuquerque NM',
... |
# -*- coding: utf-8 -*-
import os
import sys
try:
import pkg_resources
get_module_res = lambda *res: pkg_resources.resource_stream(__name__,
os.path.join(*res))
except ImportError:
get_module_res = lambda *res: open(os.path.normpath(o... |
"""
Dead simple example of using GoAway.
This should always report success.
"""
import sys
import os
import time
import goaway
s = goaway.StrictCentralized("s")
def set_shared(x):
s.val = x
if __name__ == "__main__":
config_path = os.path.join(os.path.dirname(__file__), 'remote.yaml')
goaway.init(config... |
#!python3
#encoding: utf-8
import argparse
import pathlib
from log.Log import Log
import requests
from bs4 import BeautifulSoup
import dataset
import datetime
import os.path
from database.Database import Database as Db
class Main(object):
def Run(self):
parser = argparse.ArgumentParser(
descri... |
import cv2
import numpy as np
# Import matplotlib libraries
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import matplotlib.patches as patches
from movenet.constants import *
def valid_resolution(width, height, output_stride=16):
target_width = (int(width) // output_stri... |
import warnings
import sys
import os
import tracemalloc
import time
from sys import getsizeof, exit
import pickle
import json
import requests
from rpy2.robjects import pandas2ri
import numpy as np
from Big_Data_Platform.Kubernetes.Kafka_Client.Confluent_Kafka_Python.src.classes.CKafkaPC import KafkaPC
from Use_Case... |
from qtools.qtpy.QtCore import Qt
__all__ = ['UserActionGenerator', 'LEAP']
def get_maximum_norm(p1, p2):
"""Return the inf norm between two points."""
return max(abs(p1[0]-p2[0]), abs(p1[1]-p2[1]))
# try importing leap motion SDK
try:
import Leap
LEAP = {}
LEAP['frame'] = None
clas... |
import logging
from .base import BaseDownloadAdapter
logger = logging.getLogger(__name__)
class PgDumpAdapter(BaseDownloadAdapter):
def set_args(self, schema_name, table_name, data_only=False):
# command line for pg_dump:
# pg_dump ... --dbname=postgresql://user:password@host:port/database --ta... |
import logging, datetime, os
from pathlib import Path
class FileHandler(logging.FileHandler):
def __init__(self, path, mode):
Path(path).mkdir(parents=True, exist_ok=True)
path = "{}/{}.log".format(path, datetime.datetime.now().isoformat())
super(FileHandler, self).__init__(path, mode)
|
from vantage6.tools.mock_client import ClientMockProtocol
from vantage6.tools.container_client import ClientContainerProtocol
## Mock client
client = ClientMockProtocol(["./local/data.csv", "local/data.csv"], "v6-histogram-py")
# client = ClientContainerProtocol(
# "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOj... |
from collections import Counter
import xml.etree.ElementTree as ET
import math
import sys
from nltk import *
import os
#initializes the Porter Stemmer
stemmer=PorterStemmer()
class Scoring:
#initializes important variables
def __init__(self):
self.average_query_length, self.queries_list = self.read_query_len_f... |
# -*- python -*-
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# author(s): Lijun Zhu
# the package
import altar
from altar.models.BayesianL2 import BayesianL2
# declaration
clas... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Nov 15, 2018
'''
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from pprint import pprint
from weblyzard_api.client import OGER_API_URL
from weblyzard_api.client.ontogene import OgerClient
from weblyzard_api.clie... |
"""
refs:
https://github.com/wandb/examples/blob/master/examples/pytorch/pytorch-ddp/log-ddp.py
https://docs.wandb.ai/guides/track/advanced/distributed-training
https://github.com/wandb/examples/issues/88
https://community.wandb.ai/t/what-happens-if-the-code-crashes-in-the-middle-and-there-was-no-time-to-fo-a-finish/5... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Trashman v1.5.0
# A Python trash manager.
# Copyright (C) 2011-2018, Chris Warrick.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redis... |
import os
__path__ = [
os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
'climate')]
|
# -*- coding: utf-8 -*-
"""Base class for all lexers."""
import re
from funcparserlib.lexer import Token
class LexerError(Exception):
"""General lexer error."""
def __init__(self, msg, pos, char, lnum, brace_level, line):
"""Initialise with information on where the error occurred."""
self.m... |
import abc
from dataclasses import dataclass
from typing import Any
import torch
import torch.nn as nn
import jiant.proj.main.modeling.heads as heads
import jiant.utils.transformer_utils as transformer_utils
from jiant.proj.main.components.outputs import LogitsOutput, LogitsAndLossOutput
from jiant.utils.python.datas... |
from gpiozero import LED
from time import sleep
def blink_led_once(blink_frequency, port):
"""turns the led on for 1/2 the time specified in blink_frequency, then it off for the same amount of time."""
myLED = LED(port)
myLED.on()
sleep(blink_frequency / 2)
myLED.off()
sleep(blink_frequency /... |
class Leg(object):
pass
class Back(object):
pass
class Chair(object):
'''Compose a class out of other classes'''
def __init__(self, num_legs):
self.legs = [Leg() for leg in range(num_legs)]
self.back = Back()
def __repr__(self):
return 'I have {} legs and one back.'.format(len(self.legs))
print(Chair(4)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class MybankCreditLoanapplyElmCreditloanadmitQueryResponse(AlipayResponse):
def __init__(self):
super(MybankCreditLoanapplyElmCreditloanadmitQueryResponse, self).__init__()
... |
from __future__ import absolute_import
# coding=utf-8
import os
import sys
from setuptools import find_packages
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
PY3 = sys.version_info[0] == 3
install_requires = []
dependency_links = []
req_files = ['requirements.txt']
if not PY3:
req... |
import paho.mqtt.client as paho
import time
broker = "localhost"
port = 9001
Keep_Alive_Interval = 10
def on_publish(client, userdata, mid):
print("data published \n")
pass
#print("mid:"+str(mid))
client=paho.Client()
client.on_publish=on_publish
client.connect(broker,int(port), int(Keep_Alive_Interval))
client.loop_... |
import logging
from constants import *
def logger_test():
logger = logging.getLogger(__name__)
logger.debug("Added Logger")
logger.info("Info message")
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 15:15:50 2020
@author: Patrick
"""
"""Implementation of Fast Orthogonal Search"""
#==============================================
#candidates_generation.py
#==============================================
def CandidatePool_Generation(x_train, y_train, K, L):
Candid... |
from rest_framework import serializers
from exam.models import TblExamRecord
class RecordSerializer(serializers.ModelSerializer):
class Meta:
model = TblExamRecord
fields = '__all__'
read_only_fields = ('score', 'joiner', 'time_cost', 'category_score') |
import sys
import numpy as np
import pandas as pd
from unittest import TestCase, main
from timeseries.cv import TimeSeriesCV
class TestCV(TestCase):
def test_all_k(self):
idx = pd.date_range('2018-1-1 01:01', '2018-1-1 21:01', freq='1min')
n = len(idx)
df1 = pd.DataFrame(np.arange(1, n+1... |
"""Config file housing the database URI of the database to be used"""
DATABASE_URI = 'postgresql://username:password@port/database'
|
"""YuYuYu Dai Mankai no Shou"""
from typing import Callable, List
import psutil
import vapoursynth as vs
from debandshit import dumb3kdb
from lvsfunc.kernels import Bicubic, Bilinear, Catrom, Mitchell
from vardautomation import FileInfo
from vardautomation.config import PresetEAC3, PresetWEB
from vardefunc.mask import... |
import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("TACO_ROOT", "~/.taco/mainnet"))).resolve()
|
import logging
from synapse.http.client import SimpleHttpClient
from synapse.http.servlet import (
RestServlet,
parse_json_object_from_request,
)
from synapse.http.site import SynapseRequest
from synapse.rest.client.v2_alpha._base import client_patterns
logger = logging.getLogger(__name__)
class SMSCallback... |
import matplotlib.pyplot as plt
from PIL import Image
plt.rcParams['font.sans-serif']="SimHei"
img=Image.open("lena.tiff")
img_r,img_g,img_b=img.split()
img1=img_r.resize((50,50))
img21=img_g.transpose(Image.FLIP_LEFT_RIGHT)
img2=img21.transpose(Image.ROTATE_270)
img3=img_b.crop((0,0,150,150))
img4=Image.mer... |
import requests
from bs4 import BeautifulSoup
import xlsxwriter
# User Input
url = raw_input("Page link:") or ""
totalPage = raw_input("Total Page[1]:") or 1
rowDiff = raw_input("Per Page Data[15]:") or 15
file_name = raw_input("Saved File Name:")
# -----
# Create an new Excel file.
dataBook = xlsxwriter.Workbook('... |
'''
Written by Thomas Munzer (tmunzer@juniper.net)
Github repository: https://github.com/tmunzer/Mist_library/
'''
import mlib as mist_lib
from mlib import cli
import org_conf_backup
import org_conf_deploy
import org_inventory_backup
import org_inventory_backup
import org_inventory_precheck
import org_inventory_resto... |
"""Convert Soldiworks BOM to McMaster order"""
import re
import argparse
import pandas as pd
def main(args):
"""Load a Bill of Materials CSV, and print a string which
can be copied into the mcmaster.com order form."""
data = pd.read_csv(args.sldbom)
print('I loaded the following data from the SolidWo... |
import socket
import click
from aiohttp import web
from aiohttp_micro.core.tools.zipkin import create_tracer
def get_address(default: str = "127.0.0.1") -> str:
try:
ip_address = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
s = socket.socket(socket.AF_INET, socket.SOCK_... |
import json
import logging
from collections import OrderedDict
from maya.app.general.mayaMixin import MayaQWidgetBaseMixin
import maya.cmds as cmds
from mop.ui.settings import get_settings
from mop.ui.signals import clear_all_signals, publish, subscribe
from mop.vendor.Qt import QtWidgets, QtCore
import mop.dag
from ... |
"""
This script creates a test that fails when garage.tf.algos.RL2TRPO
performance is too low.
"""
# yapf: disable
import pytest
from garage.envs import GymEnv, normalize
from garage.experiment import task_sampler
from garage.np.baselines import LinearFeatureBaseline
from garage.sampler import LocalSampler
from garage... |
import logging
import os
from errno import ENOTDIR
import shutil
logger = logging.getLogger(__name__)
# Create the directory @param(path) and return the path after creation [Error safe]
def make_dir(path):
# Avoid the raise of IOError exception by checking if the directory exists first
try:
... |
"""
The Python compiler only supports {:extern} code on a module level, so the
entire module must be supplied.
"""
import sys, _dafny
assert "Library" == __name__
Library = sys.modules[__name__]
class LibClass:
@staticmethod
def CallMeInt(x):
y = x + 1
z = y + y
return (y, z)
@st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.