content stringlengths 5 1.05M |
|---|
"""Support for TPLink HS100/HS110/HS200 smart switch."""
import logging
import time
from homeassistant.components.switch import (
ATTR_CURRENT_POWER_W, ATTR_TODAY_ENERGY_KWH, SwitchDevice)
from homeassistant.const import ATTR_VOLTAGE
import homeassistant.helpers.device_registry as dr
from . import CONF_SWITCH, DO... |
from .Util import *
|
'''This file defines user interfaces to sDNA tools and how to convert inputs to config'''
##This file (and this file only) is released under the MIT license
##
##The MIT License (MIT)
##
##Copyright (c) 2015 Cardiff University
##
##Permission is hereby granted, free of charge, to any person obtaining a copy
#... |
"""
This module contains helpers for the XGBoost python wrapper: https://xgboost.readthedocs.io/en/latest/python/index.html
The largest part of the module are helper classes which make
using a validation set to select the number of trees transparent.
"""
import logging
logger = logging.getLogger(__name__)
import jobl... |
#! /usr/bin/python3.5
# -*- coding: utf-8 -*-
import random
import numpy as np
import matplotlib.pyplot as plt
def subdivied(Liste, Size):
"""
On divise la liste Liste, en :
sum from i = 1 to N - Size [x_i,x_i+1,...x_i+Size]
"""
res = []
# pour chaque éléments de la liste
for index, e... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 2 16:22:45 2019
@author: Soumitra
"""
import math
import numpy as np
import numpy.fft as f
import matplotlib.pyplot as plt
n = np.arange(12);
x = ((-1)**n)*(n+1)
plt.xlabel('n');
plt.ylabel('x[n]');
plt.title(r'Plot of DT signal x[n]');
plt.stem(n, x);... |
"""Iterative Compression Module."""
from experiments import RESULTS_DIR, TABLES_DIR
from pathlib import Path
# Paths
IC_DIR = Path(__file__).parent
SELF_COMPARISON_DATA_PATH = RESULTS_DIR / 'ic_preprocessing_level.csv'
IC_TABLE_FORMAT_STR = 'timeout_{}.tex'
IC_TABLES_DIR = TABLES_DIR / 'ic'
IC_TABLES_DIR.mkdir(exist... |
"""Examples showing how one might use the Result portion of this library."""
import typing as t
import requests
from safetywrap import Result, Ok, Err
# ######################################################################
# One: Validation Pipeline
# ##############################################################... |
from django.shortcuts import render, redirect, render_to_response
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.forms.util import ErrorList
from django.contrib import auth, messages
from django.con... |
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
def to_u_s_miles_per_gallon(value):
return value * 2.35215
def to_miles_per_gallon(value):
return value * 2.82481
def to_litres_per100_kilometres(value):
... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
"""
from pyramid.compat import itervalues_
from everest.entities.utils import get_root_aggregate
from everest.querying.specifications import eq
from everest... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import logging
import logging.config
import os
import sys
import yaml
from datetime import datetime
from importlib import import_module
from pkgutil import iter_modules
from plastron import commands, version
from plastron.exceptions import FailureException... |
alphabet = 'qw2rty534plkjhgfds1zxcvbnm'
alpha_dict = {'q':0,'w':1,'2':2,'r':3,'t':4,'y':5,'5':6,'3':7,'4':8,'p':9,'l':10,'k':11,'j':12,'h':13,'g':14,'f':15,'d':16,'s':17,'1':18,'z':19,'x':20,'c':21,'v':22,'b':23,'n':24,'m':25}
list_out = open("full_pass_list","w")
def reduction(my_letter):
while my_letter >= 0:
my_... |
class Node(object):
"""
Represents a node in the query plan structure. Provides a `parse` function to
parse JSON into a heirarchy of nodes. Executors take a plan consisting of
nodes and use it to apply the Transformations to the source.
"""
@classmethod
def parse(cls, _dict):
raise NotImplemented
d... |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field, asdict
from datetime import datetime
from typing import List
@dataclass(frozen=True)
class SalaryPayment:
basic_payment: int = field(default_factory=int, metadata={"jp": "基本給"})
overtime_fee: int = field(default_factory=int, met... |
import os
def get_ip_name():
return "base_ip"
class base_ip:
ID = "base"
def __init__(self, io_hash):
return
def matched_id(in_key):
return in_key is self.ID
def get_rst_case_text(self):
return ''
def get_dft_case_text(self):
return ''
def get_pinmux_setting(self):
return ""
def ge... |
import requests
import conf
import urllib2
import xml.etree.ElementTree as ET
import io
def get_min_temp_phrase_from_values(min_observed, min_forecast):
if abs(min_forecast) != 1:
degrees_text = "degrees"
else:
degrees_text = "degree"
s = "The temperature tonight will be %s %s, " % (min_fo... |
from flask import Flask
from flask import render_template,redirect,request
import pandas as pd
import sys
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#from sklearn.metrics import mean_squared_log_error
from sklearn.linear_model ... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... |
import os
import platform
import textwrap
from collections import OrderedDict
from jinja2 import Template
from conans.errors import ConanException
from conans.util.files import normalize
sh_activate = textwrap.dedent("""\
#!/usr/bin/env sh
{%- for it in modified_vars %}
export CONAN_OLD_{{it}}="${{it}}"... |
import logging
from copy import copy
from inspect import isfunction
import ibutsu_server.tasks
from flask_testing import TestCase
from ibutsu_server import get_app
from ibutsu_server.tasks import create_celery_app
from ibutsu_server.util import merge_dicts
def mock_task(*args, **kwargs):
if args and isfunction(a... |
#!/usr/bin/env python
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.core.window import Window
from kivy.properties import (ListProperty,
NumericProperty,
ObjectProperty,
ReferenceList... |
# -selenium webdriver-
from logging import fatal
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.... |
import argparse
import os
import numpy as np
import scipy.io as sio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from tqdm import tqdm
from net.models import LeNet_5 as LeNet
import util
os.makedirs('saves', exist_ok=True)... |
import random
import numpy as np
import tensorflow as tf
import tqdm
from pipeline import SEED
from pipeline.dataset.gc import get_client
random.seed(SEED)
TRAIN = tf.estimator.ModeKeys.TRAIN
EVAL = tf.estimator.ModeKeys.EVAL
PREDICT = tf.estimator.ModeKeys.PREDICT
class MNISTDataset:
"""MNIST dataset."""
... |
"""\
Demo app for the ARDrone.
This simple application allows to control the drone and see the drone's video
stream.
Copyright (c) 2011 Bastian Venthur
The license and distribution terms for this file may be
found in the file LICENSE in this distribution.
"""
import pygame
from pydrone import libardrone
if __na... |
from Parameter import Parameter, registerParameterType
from ParameterTree import ParameterTree
from ParameterItem import ParameterItem
import parameterTypes as types |
# encoding: utf-8
import uuid
import os
import random
import json
from collections import Counter
from flask import request, abort, jsonify, g, url_for, current_app, session
from flask_restful import Resource, reqparse
from flask_socketio import (
emit,
disconnect
)
from app.ansibles.ansible_task import INVENT... |
import unittest
from random import uniform
from pysim import epcstd
class TestDataTypes(unittest.TestCase):
def test_divide_ratio_encoding(self):
self.assertEqual(epcstd.DivideRatio.DR_8.code, "0")
self.assertEqual(epcstd.DivideRatio.DR_643.code, "1")
def test_divide_ratio_str(self):
... |
from __future__ import print_function
from builtins import str
import argparse
import os
import sys
import re
from .version import VERSION
from .utils import get_local_ip, DelimiterArgParser
import atexit
def add_parser_args(parser, config_type):
# General arguments
parser.add_argument(
'--trace_gre... |
"""add column source_file_dir
Revision ID: 3880a3a819d5
Revises: 2579e237c51a
Create Date: 2019-11-12 16:49:05.040791
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3880a3a819d5'
down_revision = '2579e237c51a'
branch_labels = None
depends_on = None
def upgr... |
from collections import OrderedDict
from django.db.models import Count
from django.db.models.functions import TruncYear
from .models import Reading
def annual_reading_counts(kind="all"):
"""
Returns a list of dicts, one per year of reading. In year order.
Each dict is like this (if kind is 'all'):
... |
import os
from CPAC.pipeline import nipype_pipeline_engine as pe
import nipype.algorithms.rapidart as ra
import nipype.interfaces.fsl as fsl
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util
from .utils import *
from CPAC.vmhc import *
from nipype.interfaces.afni import preprocess
from CPAC.re... |
##MIT License
##
##Copyright (c) 2019 Jacob Nudel
##Copyright (c) 2019 Yashu Seth
##
##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 righ... |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as f
from torch.autograd import Variable
import os
import numpy as np
from tqdm import tqdm
class ONE_HOT_MLP(nn.Module):
def __init__(self, hidden):
super(ONE_HOT_MLP, self).__init__()
self.cnn ... |
import os
import string
from tqdm import tqdm
#from google.colab import drive
#conda install -c huggingface transformers
import matplotlib.pyplot as plt
#% matplotlib inline
import pandas as pd
import seaborn as sns
import numpy as np
import random
import torch
from torch.utils.data import Dataset, Data... |
import json
import unittest
from mock import Mock, patch
import delighted
get_headers = {
'Accept': 'application/json',
'Authorization': 'Basic YWJjMTIz',
'User-Agent': "Delighted Python %s" % delighted.__version__
}
post_headers = get_headers.copy()
post_headers.update({'Content-Type': 'application/jso... |
#!/usr/bin/env python3
from typing import Any, List
import configargparse
import paleomix
SUPPRESS = configargparse.SUPPRESS
class ArgumentDefaultsHelpFormatter(configargparse.ArgumentDefaultsHelpFormatter):
"""Modified ArgumentDefaultsHelpFormatter that excludes several constants (True,
False, None) and us... |
#!/usr/bin/env nix-shell
#!nix-shell -i python -p python3 -I nixpkgs=../../pkgs
# SPDX-FileCopyrightText: 2020 Daniel Fullmer and robotnix contributors
# SPDX-License-Identifier: MIT
import json
import os
import urllib.request
def save(filename, data):
open(filename, 'w').write(json.dumps(data, sort_keys=True, in... |
from .transformer import TransformerXL |
# encoding: utf-8
from hoopa import const
from hoopa.middlewares.stats import StatsMiddleware
NAME = "hoopa"
# 最大协程数
WORKER_NUMBERS = 1
# 请求间隔, 可以是两个int组成的list,间隔随机取两个数之间的随机浮点数
DOWNLOAD_DELAY = 3
# pending超时时间,超过这个时间,放回waiting
PENDING_THRESHOLD = 100
# 任务完成不停止
RUN_FOREVER = False
# 队列
# 调度器队列,默认redis, memory, mq
QUE... |
from pathlib import Path
SRC = Path(__file__).parent
BLD = SRC.parent.joinpath("bld")
|
from collections import Counter
class Square(Counter):
"""Creates a special purpose counter than can store only one value, and wipes itself when zero."""
def __init__(self):
"""Object should be initialized empty."""
pass
def __setitem__(self, key, cnt):
"""Update the count."""
... |
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View
# model
from timepredictor.models import PrediccionTiempos, UltimosGps
# Create your views here.
class MapHandler(View):
'''This class manages the map where the bus and stops are shown'''
def __init... |
"""
CLI Module.
Handles CLI for the Repository Updater
"""
from os import environ
from sys import argv
import click
import crayons
from . import APP_FULL_NAME, APP_VERSION
from .github import GitHub
from .repository import Repository
@click.command()
@click.option(
"--token",
hide_input=True,
prompt="G... |
'''Functions to calculate seismic noise in suspended optics.
'''
from __future__ import division
import numpy as np
from scipy.interpolate import PchipInterpolator as interp1d
def seismic_suspension_fitered(sus, in_trans):
"""Seismic displacement noise for single suspended test mass.
:sus: gwinc suspension ... |
def func(num):
return x*3
x = 2
func(x)
|
CHECKPOINT = 'model/checkpoint.bin'
MODEL_PATH = 'model/model.bin'
input_path = 'input/train.csv'
LR = 0.01
scheduler_threshold = 0.001
scheduler_patience = 2
scheduler_decay_factor = 0.5
embed_dims = 128
hidden_dims = 128
num_layers = 1
bidirectional = False
dropout = 0.2
out_dims = 128
Batch_Size = 64
Epochs = 100... |
import pygame
# game
from cgame import CGame
def main():
try:
CGame().run()
except Exception as e:
print(e)
if __name__ == '__main__':
pygame.init()
main()
|
from flask import Flask, Request, jsonify, request
from src.driver import FirestoreDriverImpl
from src.interactor import SolverInteractor
from src.repository import RoomRepositoryImpl
from src.rest import BaseException, ClientException, SolverResource
solver_resource = SolverResource(
solver_usecase=SolverInteract... |
import netifaces
import time
from collections import namedtuple
from aplus import Promise
from openmtc_server.exc import InterfaceNotFoundException
from openmtc_server.transportdomain.NetworkManager import NetworkManager
Interface = namedtuple("Interface", ("name", "addresses", "hwaddress"))
Address = namedtuple("Add... |
import elasticsearch
import json
import click
from toolz import iterate, curry, take
from csv import DictReader
from elasticsearch.helpers import streaming_bulk
nuforc_report_index_name = 'nuforc'
nuforc_report_index_body = {
"mappings": {
"properties": {
"text": {
"type": "text"... |
import numpy as np
import sys
class RobotData:
"""
Stores sensor data at a particular frame
Attributes
----------
position : tuple
(x,y) tuple of the robot position
rotation : float
angle of robot heading clockwise relative to up (north)
forward_dir : tuple
(x,y) unit vector indicating the forward direct... |
from makeit.utilities.fastfilter_utilities import Highway_self, pos_ct, true_pos, real_pos, set_keras_backend
from makeit.utilities.fingerprinting import create_rxn_Morgan2FP_separately
from rdkit import Chem
from rdkit.Chem import AllChem, DataStructs
from makeit.interfaces.scorer import Scorer
import numpy as np
impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from distutils.core import setup
import glob
from setuptools import setup
readme = open('README.md').read()
setup(
name='ReMoTE',
version='0.1',
description='Registration of Mobyle Tools in Elixir',
long_description=readme,
author='Hervé Ménager',
... |
class StateMachine:
"""A simple state machine"""
def __init__(self):
self.__states = {} #:dict[string] -> [(check, event, next)]
self.actions = {} #:dict[string] -> action
self.currentState = "start" #:string
self.addState("start")
def addState(self, name):
"""reg... |
import numpy as np
def meshTensor(value):
"""**meshTensor** takes a list of numbers and tuples
that have the form::
mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ]
For example, a time domain mesh code needs
many time steps at one time::
[(1e-5, 30), (1e-4, 30), 1e-3... |
import numpy
C_3 = numpy.array([1, 2]) / 3
a_3 = numpy.array([[3, -1], [1, 1]]) / 2
sigma_3 = numpy.array([[[1, 0], [-2, 1]], [[1, 0], [-2, 1]]])
C_5 = numpy.array([1, 6, 3]) / 10
a_5 = numpy.array([[11, -7, 2], [2, 5, -1], [-1, 5, 2]]) / 6
sigma_5 = numpy.array([[[40, 0, 0],
[-124, 100, 0],
... |
from bs4 import BeautifulSoup
import urllib, requests, re
import json
import datetime
from datetime import date
def cnt1():
year=datetime.datetime.now().year
month=datetime.datetime.now().month
month=str(month)
day=datetime.datetime.now().day
if len(str(month)) == 1 :
month="0"+str(month)... |
"""Time
Calculate the time of a code to run.
Code example: product of the first 100.000 numbers.
"""
import time
def product():
p = 1
for i in range(1, 100000):
p = p * i
return p
start = time.time()
prod = product()
end = time.time()
print('The result is %s digits long.' % len(str(prod)))
print(... |
from roboclaw import Roboclaw
from time import sleep
rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address=0x80
#rc.ForwardM1(address, 50)
# sleep (5)
rc.ForwardM1(address, 0) |
from pathlib import Path
from typing import Optional
import config # type: ignore
import hvac
from aiohttp_micro import AppConfig as BaseConfig # type: ignore
from config.abc import Field
from passport.client import PassportConfig
class StorageConfig(config.PostgresConfig):
host = config.StrField(default="loca... |
import uuid
from operator import attrgetter
from typing import List
from confluent_kafka import Consumer, TopicPartition
from confluent_kafka.admin import AdminClient, TopicMetadata
from kaskade.config import Config
from kaskade.kafka import TIMEOUT
from kaskade.kafka.group_service import GroupService
from kaskade.ka... |
#!/usr/bin/env python
from __future__ import print_function, division
import os
import sys
sys.path.append(os.path.dirname(sys.path[0]))
try:
import cPickle as pickle # python 2
except ImportError:
import pickle # python 3
import socket
import argparse
from random import randint
from numpy import unravel_in... |
from highton.models import Party
from highton.highton_constants import HightonConstants
class AssociatedParty(
Party,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar author_id: fields.IntegerField(name=HightonConstants.AUTHOR_ID)
:ivar background: fields.StringField(name=High... |
import unittest
from column import *
class ColumnTest(unittest.TestCase):
def test_polar2coord(self):
# test55
self.assertEqual(polar2coord( (46, 2.808) ), (1.9506007042488642, -2.019906159350932) )
self.assertEqual(polar2coord( (196, 1.194) ), (-1.1477464649503528, 0.32911100284549705) )
... |
from helpers import *
import shutil
league_info_file = 'league_info.json'
ros_URL = 'https://5ahmbwl5qg.execute-api.us-east-1.amazonaws.com/dev/rankings'
def_expert = 'subvertadown'
kick_expert = 'subvertadown'
weekly_method = 'borischen'
yaml_config_temp = '_config_template.yml'
output_file = 'summary.txt'
yaml_con... |
import re
from typing import List
import pytest
from ja_timex.pattern.place import Pattern
from ja_timex.tag import TIMEX
from ja_timex.tagger import BaseTagger
from ja_timex.timex import TimexParser
@pytest.fixture(scope="module")
def p():
# Custom Taggerで必要となる要素と、TimexParserの指定
def parse_kouki(re_match: ... |
from patternpieces import PatternPieces
from piece import Piece
from piecesbank import PiecesBank
from ui import UI
from board import Board
from arbiter import Arbiter
from ai import Ai
import json
import random
def main():
pb = PiecesBank()
app = UI()
### DO NOT FUCKING REMOVE THIS. I DARE YOU. ###
a... |
import re
import wrapt
from .bash import CommandBlock
class ConfigurationError(Exception):
pass
def add_comment(action):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
def _execute(*args, **kwargs):
return CommandBlock() + '' + 'echo "{} {}"'.format(action, instance.d... |
import logging
from .registry import Registry
from .parsers import RegistryPDFParser
from .securityhandler import security_handler_factory
from .types import IndirectObject, Stream, Array, Dictionary, IndirectReference, obj_factory
from .utils import cached_property, from_pdf_datetime
class PDFDocument(object):
... |
from __future__ import print_function
import logging
import re
from datetime import datetime
from collections import Counter
from itertools import chain
import json
import boto3
import spacy
import textacy
from lxml import etree
from fuzzywuzzy import process
from django.utils.functional import cached_property
from d... |
#!/usr/bin/env python
import time
import datetime
from web3.exceptions import TransactionNotFound, BlockNotFound
from web3.middleware import construct_sign_and_send_raw_middleware
from config import (
CONFIRMATIONS,
TARGET,
TARGET_TIME,
ACCOUNT,
BASE_PRICE,
web3,
INSTANCE,
)
def get_transa... |
from pirate_sources.models import VideoSource, URLSource, IMGSource
from django.contrib import admin
admin.site.register(VideoSource)
admin.site.register(URLSource)
admin.site.register(IMGSource)
|
import os
import sys
import numpy as np
import cv2
import ailia
from logging import getLogger
logger = getLogger(__name__)
def preprocessing_img(img):
if len(img.shape) < 3:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGRA)
elif img.shape[2] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
e... |
import sys
import os
import logging
import time
import gdb
# https://pro.arcgis.com/en/pro-app/latest/help/data/geodatabases/manage-oracle/rebuild-system-table-indexes.htm
if __name__ == '__main__':
geodatabase = gdb.Gdb()
timestr = time.strftime("%Y%m%d-%H%M%S")
targetlog = os.path.join(os.environ['T... |
#!/usr/bin/python
import sys
import getopt
import random
import writer
# Increase maximum recursion depth
sys.setrecursionlimit(100 * sys.getrecursionlimit())
# Generate CNF, order, and schedule files to compare two trees of xor's over a common set of inputs
def usage(name):
print("Usage: %s [-h] [-v] [-f] [-... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# noti... |
# -*- coding: utf-8 -*-
import tkinter
def affiche_touche_pressee():
root.event_generate("<<perso>>", rooty=-5)
def perso(evt):
print("perso", evt.y_root)
root = tkinter.Tk()
b = tkinter.Button(text="clic", command=affiche_touche_pressee)
b.pack()
root.bind("<<perso>>", perso) # on intercepte un é... |
#!/usr/bin/env python
import rospy #importar ros para python
from std_msgs.msg import String, Int32 # importar mensajes de ROS tipo String y tipo Int32
from geometry_msgs.msg import Twist # importar mensajes de ROS tipo geometry / Twist
class Printer(object):
def __init__(self, args):
super(Printer, self).__init_... |
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 6):
print(sys.stderr, "{}: need Python 3.6 or later.".format(sys.argv[0]))
print(sys.stderr, "Your Python is {}".format(sys.version))
sys.exit(1)
ROOT_DIR = os.path.dirname(__file__)
setup(
name="py-pdf-pars... |
"""
Copyright (C) king.com Ltd 2019
https://github.com/king/s3vdc
License: MIT, https://raw.github.com/king/s3vdc/LICENSE.md
"""
import tensorflow as tf
def _session_config() -> tf.ConfigProto:
"""Constructs a session config specifying gpu memory usage.
Returns:
tf.ConfigProto -- session config.
... |
"""Runtimes manager."""
import logging
from contextlib import suppress
from importlib import import_module
from types import ModuleType
from typing import Dict, Optional, Set, Type
from .runtime import Process
logger = logging.getLogger(__name__)
class RegisteredRuntimes:
"""A list of registered base python pro... |
# use lists as stack, LIFO (last-in-first-out)
stack = [1, 2, 3, 4, 5]
print(stack)
print('LIFO stack')
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)
print("\n")
# use lists as FIFO (first-in-first-out)
print('FIFO stack')
stack.append(6)
stack.app... |
from constance import config
from django.http import Http404
from impersonate.decorators import allowed_user_required
from impersonate.views import impersonate, stop_impersonate
from bitcaster.models import User
def queryset(request):
return User.objects.exclude(id=request.user.id).exclude(is_superuser=True).ord... |
import numpy as np
class LogisticRegression(object):
# setting learning rate and iteration times
def __init__(self, alpha=0.0005, lamb=0.1, iters=100):
self.iters = iters
self.alpha = alpha
self.lamb = lamb
# add one line for intercept
self.theta = np.array([0.0] * (X.sh... |
import pickle
def load( path ):
with open(path, 'rb') as ff :
model = pickle.load(ff)[0]
return model
|
#!/usr/bin/env python36
# -*- coding: utf-8 -*-
"""
Created on 2018/10/6 11:48 AM
@author: Tangrizzly
"""
from __future__ import print_function
from collections import OrderedDict
import datetime
import cPickle
import os
from public.GeoIE import GeoIE
from public.Global_Best import GlobalBest
from public.Load_Data_Ge... |
import abc
import rospy
import numpy as np
import matplotlib.pyplot as plt
import math
class JointTrajectoryPlanner(object):
def __init__(self, time_i = 0.0, time_step = 0.1, time_f = None,
movement_duration = None):
self._time_step = time_step
self._time_i = time_i
self._... |
from pymongo import MongoClient
import datetime
def collect_validated_input(prompt, error_msg, validator):
user_input = input(prompt)
validated = validator(user_input)
while not validated:
user_input = input(error_msg)
validated = validator(user_input)
return user_input
if __name... |
import json
import unittest
# from mayday.utils import query_util, ticket_util
from mayday import helpers
from mayday.objects import Query, Ticket
USER_ID = 12345678
USERNAME = 'Mayday'
class Test(unittest.TestCase):
def test_init_ticket(self):
ticket = Ticket(user_id=USER_ID, username=USERNAME).to_dic... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name,missing-docstring,broad-except
# Copyright 2018 IBM RESEARCH. 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
#
# ... |
from setuptools import setup, find_packages
import byte_api
setup(
name='byte-api',
version=byte_api.__version__,
author=byte_api.__author__,
url='https://github.com/byte-api/byte-python',
download_url='https://github.com/byte-api/byte-python/archive/v{}.zip'.format(
byte_api.__version__... |
'''Provides access to a subset of the NAM-NMM dataset.
The North American Mesoscale Forecast System (NAM) is one of the
major weather models run by the National Centers for Environmental
Prediction (NCEP) for producing weather forecasts. Dozens of weather
parameters are available from the NAM grids, fr... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.conf import settings
from operator import itemgetter
from datetime import datetime, timedelta
import json
import urllib2
import re
# Get API user and token from settings
user = se... |
# ここから表面データの処理
import numpy as np
# import matplotlib.pyplot as plt
import pandas as pd
# import os
# import itertools
# from scipy import signal
# import time
class Analysis_surface():
def __init__(self,k0) -> None:
self.sampling_num_surface = int(1023) # 表面粗さや2DFFTを計算したりする点数
if k0 == 1:
... |
"""
An unofficial native Python wrapper for the LivePerson Messaging Operations API.
Documentation:
https://developers.liveperson.com/data-messaging-operations-overview.html
The Messaging Operations API extracts data according to the search query. The API allows agent managers to extract
information about their call ... |
# Generated by Django 2.2.1 on 2019-05-28 11:15
import jsonfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('internet_nl_dashboard', '0030_auto_20190515_1209'),
]
operations = [
migrations.AddField(
model_name='account',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zerlous
# @File : index.py
# @Time : 2019-08-26 18:20
# @Desc :
print "aaaaa"
print ('你好')
flag = False
if flag:
print 'true'
else:
print 'false'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.