content stringlengths 5 1.05M |
|---|
from neuron import *
h('''
begintemplate A
public x, s, o, xa, oa, f, p
strdef s
objref o, oa[2]
double xa[3]
proc init() { \
x = $1 \
}
func f() { return $1*xa[$2] }
proc p() { x += 1 }
endtemplate A
''')
class A1(hclass(h.A)) :
def __init__(self, arg) : # note, arg used by h.A
#self.bp = hoc.HocObject.basea... |
import time
def prefixes(word):
"A list of the initial sequences of a word, not including the complete word."
return [word[:i] for i in range(len(word))]
def readwordlist(filename):
file = open(filename)
text = file.read().upper()
wordset = set(word for word in text.splitlines())
prefixset = s... |
import os
import numpy as np
from deeptam_tracker.evaluation.rgbd_sequence import RGBDSequence
def position_diff(pose1, pose2):
"""Computes the position difference between two poses
pose1: Pose
pose2: Pose
"""
return (pose1.R.transpose() * pose1.t - pose2.R.transpose() * pose2.t).norm()
def ang... |
# Copyright 2019 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 os
from http.server import HTTPServer, SimpleHTTPRequestHandler
PORT=8000
def main():
os.chdir("public")
server_address = ('', PORT)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print(f"Server: http://localhost:{PORT}")
httpd.serve_forever()
|
from .registry import register, make, create, lookup
from . import normalize, other, periodic
from . import relu, sigmoid, tanh
|
"""
-------------------------------------------------
Project Name: LearnFlask
File Name: __init__.py
Author: cjiang
Date: 2020/5/22 5:40 PM
-------------------------------------------------
"""
|
#/*
#* SPDX-License-Identifier: Apache-2.0
#* Copyright 2019 Western Digital Corporation or its 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.apac... |
#
# Copyright (C) 2019 DENSO WAVE INCORPORATED
#
# -*- coding: utf-8 -*-
#
# usage: python ./packing_pose.py
#
#!/usr/bin/env python
import os
import sys
import rospy
import actionlib
import math
import moveit_commander
import rosservice
import geometry_msgs.msg
from denso_cobotta_gripper.msg import GripperMoveAction,... |
"""
Tic Tac Toe Player
"""
from exceptions import CustomException
import math
import copy
import sys
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
de... |
import unittest
import xml.etree.ElementTree as ET
from programy.parser.template.nodes.base import TemplateNode
from programy.parser.template.nodes.sraix import TemplateSRAIXNode
from programy.parser.exceptions import ParserException
from programytest.parser.template.graph_tests.graph_test_client import TemplateGrap... |
from .imports import lazy_import
from .version import version as __version__ # noqa
__all__ = [ # noqa
"AbortHandshake",
"basic_auth_protocol_factory",
"BasicAuthWebSocketServerProtocol",
"ClientConnection",
"connect",
"ConnectionClosed",
"ConnectionClosedError",
"ConnectionClosedOK"... |
from .addition_problem import AdditionProblem
from .copy_memory import CopyMemory
from .mnist import MNIST
from .cifar10 import CIFAR10
from .stl10 import STL10
from .cifar100 import CIFAR100
from .speech_commands import (
SpeechCommands,
normalise_data,
split_data,
load_data,
save_data,
)
from .cha... |
# Color Filtering
# using HSV (hue satutaiton value )
# create Blurring image
import cv2
import numpy as np
cap = cv2.VideoCapture(0) # select the first camera in the system
while True:
_ , frame = cap.read()
hsv = cv2.cvtColor(frame , cv2.COLOR_BGR2HSV)
# Now filter the video ( remove N... |
from setuptools import setup, find_packages
requirements = [
'django>=3.1.2',
'django-registration>=3.1.1',
'django-crispy-forms>=1.9.2',
'gunicorn>=20.0.4',
'dj-database-url>=0.5.0',
'psycopg2-binary>=2.8.6',
'django-pwa>=1.0.10',
'whitenoise>=5.2.0',
]
setup(
name='feelya',
... |
from django.contrib.auth.models import User
from .user import Friend, UserProfile, FriendRequest
from .comment import Comment
from .post import Post
from .server import Server
|
import pycep_correios , sys , requests
from bs4 import BeautifulSoup
"""
Agradecimento : Michell Stuttgart , @evertonmatos
E ao Script de https://github.com/th3ch4os/rastreio/blob/master/rastreio , serviu de base para implementar e entender
Requests usando o método post
Alterações Básicas : TH3 CH4OS
""... |
import pickle
import os
class Oneshot:
service_file = '/var/run/stard/running.services'
@classmethod
def mark_running_services(cls, services, trunc=False):
os.makedirs(os.path.dirname(cls.service_file), exist_ok=True)
with open(cls.service_file, 'wb' if trunc else 'ab') as f:
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import setuptools
from setuptools.dist import Distribution
DEPENDENCIES = [
'packaging'
]
CLASSIFIERS = [
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering :: Artificial Intelligence"
]
wi... |
from collections import defaultdict
from aoc import get_input_as, submit
inp = get_input_as(int, sep=',')
lanternfish = defaultdict(int)
triggers = defaultdict(list)
for i in inp:
lanternfish[i + 1] += 1
counter = len(inp)
for i in range(1, 256 + 1):
if i in lanternfish:
counter += lanternfish[i]
... |
'''
user - package supports user management for xtilities products
=========================================================================================
'''
# pypi
from flask import Flask, g
from flask_security import Security, SQLAlchemyUserDatastore, LoginForm, ForgotPasswordForm
# homegrown
from loutilities.co... |
"""
Script to perform batch scoring.
"""
import os
import pickle
import pandas as pd
from utils.constants import FEATURE_COLS
FEATURES_DATA = os.path.join(
os.getenv("TEMP_DATA_BUCKET"), os.getenv("FEATURES_DATA"))
OUTPUT_MODEL_NAME = os.getenv("OUTPUT_MODEL_NAME")
BIGQUERY_PROJECT = os.getenv("BIGQUERY_PROJECT"... |
# encoding=utf8
import logging
from numpy import apply_along_axis, argmin, argmax, sum, sqrt, round, argsort, fabs, asarray, where
from NiaPy.algorithms.algorithm import Algorithm
from NiaPy.util import fullArray
logging.basicConfig()
logger = logging.getLogger('NiaPy.algorithms.basic')
logger.setLevel('INFO')
__all_... |
import uuid
from datetime import datetime
import pytz
from sqlalchemy.dialects.postgresql import JSONB, UUID, TEXT, TIMESTAMP, BOOLEAN
from sqlalchemy import ForeignKey
from lockheed_141310 import db
class CMMeta(db.Model):
__tablename__ = 'cm_meta'
uuid = db.Column(UUID(as_uuid=True), default=uuid.uuid4(),... |
import os
import sys
import Utils.PrimaryKeyInfo
from DbSmellDetector.SmellDetector import SmellDetector
from Model.MetaModel import MetaModel
import shutil
import Aggregator.Aggregator
def get_folder_paths():
if len(sys.argv) <= 1:
print ("Please provide path of the root folder containing SQL statements f... |
from .base import Logger
from .tensorboard import TensorBoardLogger
from .wandb import WandBLogger
|
import mitmproxy
from mitmproxy.net import tcp
from mitmproxy import ctx
class CheckALPN:
def __init__(self):
self.failed = False
def configure(self, options, updated):
self.failed = mitmproxy.ctx.master.options.http2 and not tcp.HAS_ALPN
if self.failed:
ctx.log.warn(
... |
"""
Demonstrate the use of Starlette middleware to Asgineer handlers.
Because Asgineer produces an ASGI-compatible application class, we can
wrap it with ASGI middleware, e.g. from Starlette. Hooray for standards!
"""
import asgineer
from starlette.middleware.gzip import GZipMiddleware
@asgineer.to_asgi
async def ... |
from .._model import scim_exceptions
class ScimResponse(dict):
def __init__(self, data, core_schema_definitions, extension_schema_definitions):
super().__init__()
for key in data.keys():
self[key] = data[key]
(
self._core_meta_schemas,
self._extension_... |
import pandas as pd #to form the dataframe
import folium #for rendering the map
import tkinter as tk #for GUI
win = tk.Tk()
win.title("Covid Hotspot Detector")
win.geometry("512x550")
win.iconbitmap(r'C:\Users\deepa\Downloads\Icons8-Windows-8-Healthcare-Clinic.ico')
def maha(): #Maharashtra
cm_df = pd.DataFrame({'... |
##############################################################################
#
# Copyright (c) 2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# Le 3 valores do usuario (numeros ou strings) e entao retorna o maior valor
# +entre eles.
# Recebe 3 valores e retorna o maior.
def maximumValue ( x, y, z ) :
max = x
if y > x :
max = y
if z > max :
max = z
return max
# Testando a funcao maximumValue com valores inteir... |
# coding: utf-8
# In[1]:
# things we need for NLP
import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
# things we need for Tensorflow
import numpy as np
import tflearn
import tensorflow as tf
import random
# In[2]:
# restore all of our data structures
import pickle
data = ... |
from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.utils import timezone
class FieldsTestMixin():
"""
Provides tests of required and optional fields.
Subclasses are responsible for defining class attributes.
Attributes:
... |
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple, Union
import h5py
import numpy as np
# Default parameters for each heatmap layer
# https://github.com/napari/napari/blob/d5a28122129e6eae0f5ada77cb62c4bd5a714b60/napari/layers/base/base.py#L26
RENDERING_DEFAUL... |
from cluster_manager import ClusterManager
from cluster import Cluster
def main():
physics_cluster = Cluster("Physics", stopwords_threshold=50, champion_list_size=10)
math_cluster = Cluster("Mathematics", stopwords_threshold=50, champion_list_size=10)
health_cluster = Cluster("Health", stopwords_threshol... |
"""
# -*- coding: utf-8 -*-
-------------------------------------------------
# @Project :meiduo_mall
# @File :view_extend.py
# @Date :2021/11/5 16:09
# @Author :turbo
# @Email :2647387166
# @Software :PyCharm
-------------------------------------------------
"""
from django.contrib.auth.mixins import Log... |
from django import forms
from .models import JobOffer
class JobOfferForm(forms.ModelForm):
# Form model for a JobOffer object
class Meta:
model = JobOffer
fields = ('candidate_first_name', 'candidate_last_name', 'candidate_email', 'job_title', 'offer_amount')
# Set form label... |
from glob import glob
import os.path
from setuptools import find_packages, setup
from typing import List
def package_files(directory: str) -> List[str]:
paths = []
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
paths.append(os.path.join('..', path, fil... |
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
__license__ = "Apache License 2.0"
|
import unittest
from rnapipe.samples import *
class TestSamples(unittest.TestCase):
'''Unit tests for Samples'''
def test_sample(self):
f1 = SeqFile("sample.fastq.gz")
samp = Sample(name="sample", condition="c1", covariates=[], files=[f1])
self.assertEqual(samp.name, "sample")
... |
import pytest
from pynormalizenumexp.expression.base import NotationType
from pynormalizenumexp.expression.abstime import AbstimePattern
from pynormalizenumexp.utility.dict_loader import DictLoader
from pynormalizenumexp.utility.digit_utility import DigitUtility
@pytest.fixture(scope="class")
def digit_utility():
... |
# TestSwiftTypeAliasFormatters.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift... |
import os
from db_eplusout_reader.db_esofile import DBEsoFile, DBEsoFileCollection
from db_eplusout_reader.sql_reader import get_results_from_sql
def get_results(
file_or_path, variables, frequency, alike=False, start_date=None, end_date=None
):
r"""
Extract results from given file.
Use a single or ... |
#!/usr/bin/python3
import logging
import asyncio
from hbmqtt.client import MQTTClient, ClientException
from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2
from hbmqtt.session import ApplicationMessage
from mqtt_config import CONFIG_CLIENT as CONFIG
from params import params
import pickle
logger = logging.getLog... |
import bpy
from bpy.props import *
from .. events import propertyChanged
from .. data_structures import BezierSpline, PolySpline
from .. base_types import AnimationNodeSocket, PythonListSocket
from .. data_structures.splines.from_blender import (createSplinesFromBlenderObject,
... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
# Generated by Django 3.2.7 on 2021-09-07 17:05
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('reviews', '0036_auto_20210906_2320'),
migrations.sw... |
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2020 Bootlin
# Author: Joao Marcos Costa <joaomarcos.costa@bootlin.com>
import os
import pytest
from sqfs_common import *
@pytest.mark.boardspec('sandbox')
@pytest.mark.buildconfigspec('cmd_fs_generic')
@pytest.mark.buildconfigspec('cmd_squashfs')
@pytest.mark.buildc... |
import storage
storage.remount("/", readonly=False)
m = storage.getmount("/")
m.label = "INFINITREE"
storage.remount("/", readonly=True)
|
class TableLayoutColumnStyleCollection(TableLayoutStyleCollection,IList,ICollection,IEnumerable):
""" A collection that stores System.Windows.Forms.ColumnStyle objects. """
def Add(self,*__args):
"""
Add(self: TableLayoutColumnStyleCollection,columnStyle: ColumnStyle) -> int
Adds an item to the Syst... |
from datetime import datetime
# @Fábio C Nunes
contador_maior = 0
contador_menor = 0
ano_atual = datetime.today().year
for i in range(1,8):
ano_nasc = int(input(' Em que ano a {}ª pessoa nasceu? '.format(i) ))
idade = ano_atual - ano_nasc
if idade >= 21:
contador_maior += 1
else:
contado... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 Clyde McQueen
#
# 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 ... |
# 2019-11-24 00:33:09(JST)
import collections
import sys
def main():
n, *a = map(int, sys.stdin.read().split())
c = collections.Counter(a)
ans = 'No'
if len(c) == 2 and 0 in c and c[0] == n / 3:
ans = 'Yes'
elif len(c) == 3 and not 0 in c:
for i in c.values():
... |
"""
Author: Nathan Dunne
Date last modified: 16/11/2018
Purpose: Generate a csv and json file from a data set.
"""
import csv # Python has a built in csv library we can use to create a csv file
import json # Python has a built in json library we can use to create a json file.
cla... |
"""
https://github.github.com/gfm/#links
"""
import pytest
from .utils import act_and_assert
# pylint: disable=too-many-lines
@pytest.mark.gfm
def test_reference_links_535():
"""
Test case 535: Here is a simple example:
"""
# Arrange
source_markdown = """[foo][bar]
[bar]: /url "title"
"""
... |
from __future__ import absolute_import, division, print_function
import inspect
import types
import os
from . import config
from .core import HomothetyOperator, IdentityOperator, Operator, ZeroOperator
from .warnings import warn, PyOperatorsWarning
import collections
__all__ = ['rule_manager']
_triggers = {}
_default... |
from typing import Any, Callable, Optional, Tuple
# isort:imports-thirdparty
import torch
from pl_bolts.utils import _TORCHVISION_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
# isort:imports-firstparty
from tra... |
import numpy as np
import random
class DiscreteTable():
"""
Table Environment with clean and dirty dishes during Human Robot Collaboration
"""
def __init__(self, sizes, n_clean=3, n_dirty=2, n_human=1, cam_pos=(2, 2), partial=False, noise=False):
self.rows = sizes[0]
self.cols = si... |
import pandas as pd
import sqlite3
import sys
HANDLE_IDS = sys.argv[1:]
PATH_TO_DB = "" # add your own PATH
conn = sqlite3.connect(PATH_TO_DB)
c = conn.cursor()
# get message df with the handles
command = f"""
SELECT text,
is_from_me,
datetime(date/1000000000 + strftime('%s',... |
#!/usr/bin/env python
import sys
import argparse
import json
import random
import time
import bluetooth
class myClient():
def __init__(self):
self.blah = None
def connect(self, uuid):
for n in range(0, 5):
service_matches = bluetooth.find_service(uuid = uuid)
if len... |
"""Test for the LED-Pi API."""
import pytest
import sys
from unittest.mock import MagicMock, Mock
mock_aiohttp_session = MagicMock()
mock_aiohttp_client = MagicMock()
mock_aiohttp_client.async_get_clientsession.return_value = mock_aiohttp_session
sys.modules["homeassistant.helpers.aiohttp_client"] = mock_aiohttp_clie... |
import datetime
import random
import time
def random_datetime(fix_year=None, fix_month=None, fix_day=None):
try:
new_datetime = datetime.datetime.fromtimestamp(random.randint(1, int(time.time())))
if fix_year:
new_datetime = new_datetime.replace(year=fix_year)
if fix_month:
... |
from collections import namedtuple, defaultdict
from functools import lru_cache
import numpy as np
import itertools
Obstacle = namedtuple('Obstacle', 'up down left right')
Point = namedtuple('Point', 'x y')
Adjacency = namedtuple('Adjacency', 'distance point')
class Agent:
"""
Represents a rectangular Agent ... |
# Find how many numbers from 1 to 1000 are multiples of 7 or 5.
# Constants for first_num and last_num
FIRST_NUM = 1
LAST_NUM = 1000
# Return number of multiples of 7 or 5 from first_num to last_num
def get_multiples(first_num, last_num):
# Initialize count of multiples
count_multiples = 0
... |
from adaptive_alerting_detector_build.exceptions import (
AdaptiveAlertingDetectorBuildError,
)
class DatasourceQueryException(AdaptiveAlertingDetectorBuildError):
"""Raised when query fails."""
class base_datasource:
def __init__(self, **kwargs):
pass
def query(self):
raise NotImpl... |
from .normalizer import ImageNormalizer
|
import subprocess
from datetime import timedelta
from os import path
from config import HEC_HMS_HOME, HEC_HMS_SH, HEC_DSSVUE_HOME, HEC_DSSVUE_SH, HEC_EVENT_SCRIPT,\
PRE_PROCESSING_SCRIPT,POST_PROCESSING_SCRIPT, RAIN_FALL_FILE_NAME, DISCHARGE_FILE_NAME, \
HEC_INPUT_DSS, HEC_OUTPUT_DSS
def execute_pre_dssvue(r... |
"""
The purpose to this module is to provide a convenient way to create static neural
network
"""
from .ordered_set import OrderedSet
from .simple_layers import SimpleOutputBase, SimpleMergeBase, SimpleLayerBase, SimpleModule
from .simple_layers_implementations import Input, OutputClassification, Flatten, Conv2d, ReLU... |
"""main entry for meteolab command-line interface"""
def main():
from meteolab import Meteolab
ret, fwds = Meteolab().run_command()
return ret
if __name__ == "__main__":
main()
|
"""The SolArk Modbus Integration."""
import asyncio
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
fr... |
from zope.interface import classProvides
from twisted.plugin import IPlugin
from axiom.attributes import integer, inmemory
from axiom.item import Item
from eridanus import util as eutil
from eridanus.ieridanus import IEridanusPluginProvider
from eridanus.plugin import Plugin, usage, rest
from eridanusstd import urb... |
import disnake
from dice_roll_game import current_game, game_implementation
from dice_roll_game.game_setup import DiceRollSetup
from disnake.ext import commands
class DiceRollCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot: commands.Bot = bot
@commands.slash_command(name="d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 9 22:30:35 2020
@author: manal
"""
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__,'kernels.cpython-38-x86_64-linux-gnu.so')
# __file__ =... |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import logging
import pathlib
from dataclasses import dataclass
from datetime import datetime
from typing import cast
from vdk.api.job_input import IJobArguments
from vdk.api.plugin.core_hook_spec import JobRunHookS... |
from Snake_Game import *
from Feed_Forward_Neural_Network import *
def run_game_with_ML(display, clock, weights):
max_score = 0
avg_score = 0
test_games = 1
score1 = 0
steps_per_game = 2500
score2 = 0
for _ in range(test_games):
snake_start, snake_position, apple_positi... |
""" This post-process selects which technologies can provide reserves"""
# Standard packages
import os
import shutil
# Third-party packages
import pandas as pd
from switch_model.wecc.get_inputs.register_post_process import post_process_step
@post_process_step(
msg="Removing fossil fuels from reserves.",
)
def p... |
#/dlmp/sandbox/cgslIS/rohan/Python-2.7.11/python
"""
This script will asses and plot the difference is
in allele frequency in the vcf
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib_venn import *
import re
import pprint
from scipy.stats import norm
import scipy.stats as st... |
from . import pyoptsparse
from . import scipy |
import cherrypy
import CanvasLMSTool
import memcache
# This file stores my CANVAS_CLIENT_ID and CANVAS_CLIENT_SECRET. I'm not going to release that on Github
from secretglobals import *
# Do not include the trailing slash - this is where your Canvas installation is located
CANVAS_URL = 'https://my-canvas-installation... |
"""Plot gps information."""
from typing import List, Optional, Sequence
import json
import numpy as np
import plotly.express as px
from constants import (
BLUE_COLOR,
DEFAULT_COLOR,
DEFAULT_SIZE,
LATITUDE,
LONGITUDE,
MAPS_STYLE,
OPACITY_LEVEL,
SIZE_MAX,
)
class PlotlyAutoZoomer:
... |
"""stub action for load
"""
from . import _actions as actions
from .run import Action as BaseAction
class MissingAttribute:
# pylint: disable=too-few-public-methods
"""Raise an attribute error for any get"""
def __get__(self, instance, owner):
raise AttributeError()
@actions.register
class Act... |
import json, requests, urllib3
from flask import Flask, request, jsonify
from datetime import datetime
import time
import traceback
import os
import redis
import cPickle as pickle
import virtualservice_static
import serviceengine_static
import servicediscovery
import pool_static
import controller_static
from multiproc... |
#! /usr/bin/python3
""" Run the Visual Studio AStyleTestI18n test using AppLocale to test non-ASCII files.
"""
# to disable the print statement and use the print() function (version 3 format)
from __future__ import print_function
import os
import subprocess
import time
# local libraries
import libastyle
# global var... |
"""Some syft imports..."""
from . import core
from . import spdz
from .core.frameworks.torch import _SyftTensor
from torch.autograd import Variable
from torch.nn import Parameter
from torch.autograd import Variable as Var
from .core.frameworks.torch import TorchHook
from .core.frameworks.torch import _LocalTensor, _Po... |
try:
import http.server
import thread
from urllib.parse import parse_qs
from urllib.parse import urlencode
except ImportError:
import http.server as BaseHTTPServer
import _thread as thread
# from urllib.parse import urlparse
from urllib.parse import urlencode
from urllib.parse import... |
from astropy.timeseries import LombScargle
from hydroDL import kPath
from hydroDL.app import waterQuality
from hydroDL.data import gageII, usgs, gridMET
from hydroDL.master import basins
from hydroDL.post import axplot, figplot
import matplotlib.pyplot as plt
import importlib
import pandas as pd
import numpy as np
im... |
{
'targets': [{
'target_name': 'uwp',
'type': '<(library)',
'defines': [ 'JS_ENGINE_CHAKRA=1', '_WIN32_WINNT=0x0A00', '_GNU_SOURCE',
'JS_ENGINE_V8=1', 'V8_IS_3_28=1', 'USE_EDGEMODE_JSRT=1',
'WINONECORE=1', 'BUILDING_CHAKRASHIM=1' ],
'sources': [
'binding.gyp',
'index.js',
... |
"""
Betclic odds scraper
"""
import datetime
import json
import re
import urllib
import dateutil.parser
from collections import defaultdict
import sportsbetting as sb
from sportsbetting.auxiliary_functions import merge_dicts, truncate_datetime
from sportsbetting.database_functions import is_player_in_db, add_player... |
#!/usr/bin/env python
# (c) Corey Goldberg (corey@goldb.org) 2008-2009
#
# Get health metrics from a Windows server with WMI
import wmi
import re
from subprocess import Popen, PIPE
class MetricsFetcher:
def __init__(self, computer, user, password):
self.c = wmi.WMI(find_classes=False, c... |
# -*- coding: utf-8 -*-
"""
The Asyncio Runner
~~~~~~~~~~~~~~~~~~
The asyncio runner is a backend for the sync/async experiment that provides
an asyncio interface that otherwise matches the sync interface defined
elsewhere.
"""
import asyncio
class _ClientHTTPProtocol(asyncio.Protocol):
"""
This is a basic H... |
# coding: utf-8
# 这里存放我的class
from chijiuhua import load_json, to_json, to_mongo, load_mongo
class Book():
books = [] # 书的对象s
books_id = []
books_del_id = []
def __init__(self, name, price, shuliang, is_del=0, **kwargs):
self._id = len(self.books)+1 # 书籍的id是当前书籍的+1
self.name = nam... |
from lib.database import connection
from lib.types import TYPES, CASTING_TABLE
from lib.defaults import DEFAULTS
from lib.operators import OPERATORS
from lib.output import Output
from lib.funcs import FUNCTIONS, FUNCTIONS_LIST
from lib import editor
from resources import Verb, ListVerb
from resources.builtin import res... |
from .imdb import load_imdb
from .mnist import load_mnist
from .small_parallel_enja import load_small_parallel_enja
|
import py, os, sys
import numpy as np
sys.path = [os.path.join(os.pardir, 'python')] + sys.path
class TestNOMAD:
def setup_class(cls):
import SQNomad, logging
SQNomad.log.setLevel(logging.DEBUG)
def test01_simple_example(self):
"""Read access to instance public data and verify values... |
# Reference: https://en.wikipedia.org/wiki/Bitwise_operation
# Notice: The following inequality must be satifised for both shifts, n => 0
from math import log
'''
@function left_shift - Finds all the variables within a left bit shift operation
@param k - The value of the right side ("prefix") of the bitwise ... |
import argparse
import pickle
import time
import cv2
# Local
from islib.hashutils import dhash, convert_hash
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-q", "--query", required=True, type=str,
help="Path to input query image")
ap.add_argumen... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: snap.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.... |
# -*- coding: utf-8
from django.apps import AppConfig
class ContributionsDjangoConfig(AppConfig):
name = "contributions_django"
|
from blackboard import BlackBoardContent, BlackBoardClient, BlackBoardAttachment, BlackBoardEndPoints, \
BlackBoardCourse, BlackBoardInstitute
import os
import re
import requests
import datetime
import xmltodict
import argparse
import sys
import json
import getpass
import main
def test():
args = main.handle_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.