content stringlengths 5 1.05M |
|---|
from unittest import mock
from transiter import parse
from transiter.parse import utils
def test_clean_all_good():
trip_cleaners = [mock.MagicMock() for __ in range(3)]
for cleaner in trip_cleaners:
cleaner.return_value = True
stop_event_cleaners = [mock.MagicMock() for __ in range(3)]
gtfs_c... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 09:43:24 2019
Script for merging TNO and NAEI emission files
;
; This is based on Doug Lowes NCL script to do the same thing
; but with TNO/NAEI whereas we will use EDGAR/NAEI
; - treatment of the emission variables will be hardcoded,
; ... |
'''
Created on Jun 21, 2018
@author: moffat
'''
from django import forms
from edc_form_validators import FormValidator
class IneligibleSubjectFormValidator(FormValidator):
def clean(self):
self.screening_identifier = self.cleaned_data.get('screening_identifier')
self.reasons_ineligible = self.c... |
from discharge_data import *
from gumbel_reduce import gumbel_reduce_data
from plot_discharge import PlotDischarge
from log import *
time_list = [50, 100, 150, 200, 500, 1000]
def verify_gumbel(func):
"""
A wrapper function, Wrapper decorator @ should be placed right on
top of function that is to be wrap... |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Import
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Import Standard libraries
from abc import ABC, abstractmethod
import streamlit as st
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Classes
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class... |
import cv2
import os
import pickle
import imutils
import numpy as np
import time
# IU - Concert Live Clip 2018 Tour.mp4
image_path = "D:/Github/FR-AttSys/test_imgs/IU-2.png"
detector_path = "./face_detection_model"
# OpenCV深度学习面部嵌入模型的路径
embedding_model = "./face_detection_model/openface_nn4.small2.v1.t7"
# 训练模型以识别面部... |
from mmfutils import optimize
import numpy as np
from uncertainties import ufloat
class Test(object):
def test_usolve(self):
n = ufloat(2.0, 0.1, 'n')
c = ufloat(1.0, 0.1, 'c')
a = ufloat(3.0, 0.1, 'a')
def f(x):
return x**n - a*c
ans = optimize.ubrentq(f, 0... |
from JumpScale import j
from .Code import Code
j.code = Code()
|
###############################################################################
# Imports
import sys
###############################################################################
# General utility
# Exit the program
def terminate_app(code, message=None):
if message:
print("Exiting program with code {}... |
# -*- coding: utf-8 -*-
# @Time : 2021/8/17 21:41
# @Author : lovemefan
# @Email : lovemefan@outlook.com
# @File : client.py
import logging
import grpc
from tzrpc.proto.py.Server_pb2_grpc import toObjectStub
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] - %(levelname)s - %(threadName)s - %(module)s.... |
from django.contrib import admin
from .models import RedirectUrl, RedirectUrlsEntry
# Register your models here.
admin.site.register(RedirectUrl)
admin.site.register(RedirectUrlsEntry)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Create by Albert_Chen
# CopyRight (py) 2020年 陈超. All rights reserved by Chao.Chen.
# Create on 2020-03-22
from __future__ import absolute_import
import json
import logging
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.options
import torn... |
import mimetypes
from typing import List, Union
from pathlib import Path
import magic
from haystack.nodes.base import BaseComponent
DEFAULT_TYPES = ["txt", "pdf", "md", "docx", "html"]
class FileTypeClassifier(BaseComponent):
"""
Route files in an Indexing Pipeline to corresponding file converters.
"""... |
import numpy as np
import pandas as pd
import math
import random
import re
simulationDuration = 100
minFeatureDuration = 1
maxFeatureDuration = 20
minFeatureValue = 0
maxFeatureValue = 10000
maxDuration = 5
numRuns = 1000
class QDisc:
def sort(self, anArray):
return anArray
def name(self):
re... |
#!/usr/bin/python
import yaml
from pprint import pprint
from netmiko import ConnectHandler
from ciscoconfparse import CiscoConfParse
with open('netmiko.yml', 'r') as file:
devices=yaml.load(file)
cisco4 = devices.get('cisco4')
ssh = ConnectHandler(host=cisco4.get('host'), username=cisco4.get('username'), passwor... |
import pandas as pd
from comvest.utilities.io import files, read_from_db, write_result
from comvest.utilities.logging import progresslog, resultlog
def cleandata(df,date,keepcolumns=['ano_vest','cod_curso','desc_curso','he','mod_isencao']):
df.insert(loc=0, column='ano_vest', value=date)
df.drop(columns=['area'],... |
# %%
#######################################
def registryget_regkey_summary(key_object: RegistryKey):
from Registry.Registry import RegistryKey
#
if isinstance(key_object, RegistryKey):
results = {}
results['values_num'] = key_object.values_number()
results['subkeys_num'] = key_object.su... |
from typing import Dict
from typing import List
from treasury.session import FederalTreasurySession
class RevenueAndPayments():
"""
## Overview:
----
Revenue:
Daily overview of federal revenue collections such as income tax
deposits, customs duties, fees for government service, fines, and
... |
from train_QNet import *
import torch
import numpy as np
from torch import optim
import random
import copy
import utils
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from torch import optim
from tqdm import tqdm as _tqdm
import random
def repeat_trajectory(trajectory, seed, env_... |
# Copyright (C) 2011-2012 Andy Balaam and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from itertools import imap
from buildstep import BuildStep
from parse.pepperstatements import PepperStatements
# We would like to do these imports inside _parse_tree_string_to_va... |
"""
Instapush notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.instapush/
"""
import json
import logging
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.compone... |
{
"targets": [
{
"target_name": "tree_sitter_markdown_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"src/parser.c",
"bindings/node/binding.cc",
"src/scanner.cc"
],
"cflags_c": [
"-std=c99",
... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import googlemaps
import base64
from cartodb_services.google.exceptions import InvalidGoogleCredentials
class GoogleMapsClientFactory():
clients = {}
@classmethod
def get(cls, client_id, client_secret, channel=None):
cache_key = "{}:{}:{}".format(c... |
"""Bosch regular sensor."""
from ..const import SIGNAL_SENSOR_UPDATE_BOSCH
from .base import BoschBaseSensor
class BoschSensor(BoschBaseSensor):
"""Representation of a Bosch sensor."""
signal = SIGNAL_SENSOR_UPDATE_BOSCH
_domain_name = "Sensors"
@property
def device_name(self):
return "B... |
from __future__ import absolute_import
import deployer.logger
from celery.signals import setup_logging
__version__ = '0.5.2'
__author__ = 'sukrit'
deployer.logger.init_logging()
setup_logging.connect(deployer.logger.init_celery_logging)
|
from . import TestStdoutReader
import pyprogress
class TestCounter(TestStdoutReader):
def tearDown(self):
self.c.stop()
self.c.join()
TestStdoutReader.tearDown(self)
def test_counter_no_total(self):
output = ['0', '\b1', '\b2', '\b3', '\b4', '\b5']
self.c = pyprogres... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/17 9:17 AM
# @Author : Insomnia
# @Desc : 约瑟夫环问题, n个人围成环隔m个击毙, 最后剩下
# @File : LastInCircle.py
# @Software: PyCharm
class Solution:
def lastInCircle(self, n, m):
if n < 1 or m < 1:
return -1
last = 0
for i i... |
# Copyright 2017 The UAI-SDK 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 applicable... |
"""
Copyright 2018 Johns Hopkins University (Author: Jesus Villalba)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
Class to make/read/write k-fold x-validation lists
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from six.moves import xra... |
try:
import ConfigParser as configparser
except Exception:
import configparser
def getvalues(filepath, section, keys):
parser = configparser.ConfigParser()
if not parser.read(filepath):
raise ValueError('read() failed -- "{}"'.format(filepath))
values = []
for key in keys:
valu... |
import re
import time
import logging
import operator
import pandas as pd
import numpy as np
from datetime import datetime
from datetime import timedelta
from collections import Counter
from pycoingecko import CoinGeckoAPI
from expiringdict import ExpiringDict
start = datetime.now()
logger = logging.getL... |
import os,sys
import json
import facebook
if __name__ == '__main__':
token = "EAANXc609TdkBAO3HmSoswBZCTIbmZBMOcdzvLa8c97fdDZBzCjZCL2vAhJYPhyKt5sURY5VlozyHOZABZB6lxrPU5Bb8jM0PLFHh0xCj376nqu6EQZA6PoGbnI1cKyGYiOtrNNyLUebm55GGjNGI5VL6Tj1R9IstsIUSQHBbW7WVP7ZBUbZAn4occ"
graph = facebook.GraphAPI(access_token... |
from .. import math
import numpy as np
def TM(t, C_a, K_trans, k_ep=None, v_e=None, v_p=None):
if k_ep is None:
k_ep = Conversion.k_ep(K_trans=K_trans, v_e=v_e)
tofts = K_trans*np.exp(-t*k_ep)
return math.NP.convolve(tofts, C_a, t)
def ETM(t, C_a, K_trans, k_ep=None, v_p=None, v_e=None):
if k_ep is None:
k_ep... |
from sqlalchemy_continuum_vendored import make_versioned
# make_versioned(user_cls=None, options={'strategy' : 'subquery'})
# Import the DB things.
from common.main_archive_db import WebPages
from common.main_archive_db import WebFiles
from common.main_archive_db import PluginStatus
from common.main_archive_db impo... |
from ...primitives import Int
from .. import List, range as wf_range
def test_range():
assert isinstance(wf_range(10), List[Int])
assert isinstance(wf_range(0, 10), List[Int])
assert isinstance(wf_range(0, 10, 2), List[Int])
|
#!/usr/bin/env python
"""
Pyomo Solver Performance Benchmarking Library
"""
import sys
from setuptools import setup, find_packages
def warn(s):
sys.stderr.write('*** WARNING *** {}\n'.format(s))
kwargs = dict(
name='pysperf',
packages=find_packages(),
install_requires=[],
extras_require={},
... |
from pyecg.annotations import ECGAnnotationSample
def test_equality():
annotation1 = ECGAnnotationSample("N", 1)
annotation2 = ECGAnnotationSample("N", 1)
assert annotation1 == annotation2
def test_inequality_0():
annotation1 = ECGAnnotationSample("A", 1)
annotation2 = ECGAnnotationSample("N", 1... |
import smtplib
# bring in the by fault email module
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# turned into a function to import into scrape.py
# put your own values in the from & to email fields
def send(filenam... |
from django.db.models.signals import pre_save
from django.dispatch import receiver
from periodic_tasks.models import PeriodicTask
@receiver(pre_save, sender=PeriodicTask)
def set_next_run_timestamp(sender, instance=None, **kwargs):
"""
Signal to set next run before PeriodicTask instance saving
"""
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import tensorflow as tf
from invoke import run, exceptions
log = logging.getLogger('biomedbert')
log.setLevel(logging.INFO)
def fine_tune_squad(v1: bool, model_type: str, bucket_name: str, model_dir: str, train_file: str, predict_file... |
from __future__ import absolute_import
import blinker
from collections import deque
from functools import wraps, partial
from threading import local
import sys
from .compat import reraise, iteritems, is_nextable
def noop(*_, **dummy):
pass
class StopIterationWithValue(StopIteration):
value = None
def _... |
from setuptools import find_packages, setup
setup(
name='museum_app',
version='1.0.0',
packages=find_packages(),
include_package_data=False,
zip_safe=False,
install_requires=[
'flask', 'graphene', 'mongoengine', 'werkzeug'
],
) |
import augeas
from jadi import interface
class AugeasError(Exception):
def __init__(self, aug):
self.message = None
self.data = {}
aug.dump('/')
for ep in aug.match('/augeas//error'):
self.message = aug.get(ep + '/message')
for p in aug.match(ep + '/*'):
... |
import tensorflow as tf
from metrics.chamfer.nearest_neighbour_cuda import nn_distance as nn_distance_cpu
def bidirectionalchamfer(pointCloud1, pointCloud2):
with tf.name_scope('bidirectionalchamfer'):
shape1 = pointCloud1.shape.as_list()
shape2 = pointCloud2.shape.as_list()
pointCloud1... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import collections
import sys
from .exc import SpaceTrackEntityNotSupported
if sys.version_info >= (3, 0, 0):
basestring = str
unicode = str
SUPPORTABLE_ENTITIES = (
'tle_latest',
'tle_publish',
'omm',
'boxscore',
'satcat',... |
import json
from typing import Optional
import zipcodes
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.exceptions import InvalidExpectationConfigurationError
from great_expectations.execution_engine import (
PandasExecutionEngine,
SparkD... |
import turtle
# fill_box(x, y, dx, dy, [color=None])
# box((x1,y1), (x2,y2), [color=None], [width=None])
# box(x1,y1,x2,y2, [color=None], [width=None])
# fill_box_array(x, y, dx, dy, cnt, [add_x=0], [add_y=0], [color=None])
# line(x1, y1, x2, y2, [color=None], [width=None])
# multiline((x1,y1), (x2,y2), ...., (xn,yn) ... |
import mechanize
import cookielib
import urllib
import os,time,datetime,re
from dateutil.relativedelta import relativedelta
from BeautifulSoup import BeautifulSoup
svc_domain = r'http://jps-amiprod2.jps.net:9090/'
user_name = os.environ.get('SVC_USER')
user_pass = os.environ.get('SVC_PASS')
start_date = datetime.date... |
import datetime
import os.path
import re
import string
import sys
from rust import RustHelperBackend
from stone import ir
from stone.backends.python_helpers import fmt_class as fmt_py_class
class Permissions(object):
@property
def permissions(self):
# For generating tests, make sure we include any in... |
###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2013-2014, NYU-Poly.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... |
""" This process performs a backup of all the application entities for the given
app ID to the local filesystem.
"""
import argparse
import cPickle
import errno
import logging
import multiprocessing
import os
import random
import re
import shutil
import sys
import time
sys.path.append(os.path.join(os.path.dirname(__fi... |
from qqbot import QQBotSlot as qqbotslot, QQBot
from qqbot.qcontactdb import QContact
from tenhoubot import main as starttenhou
import threading
import re
import random
import time
is_playing = False
qq_group = None
class BotConnector(object):
def __init__(self, qqbot):
self.qbot = qqbot
self.stop... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import socket
import logging
import dateutil.parser
from constants import MSG_DATE_SEP, END_MSG
from moves import initialize_keyboard, press_keys
logging.basicConfig(filename='jagger_server.log', level=logging.DEBUG)
logger = logging.getLogger("jagger_se... |
"""
69. Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Outp... |
import requests
def fetchFromAPI(query):
'''Fetches response data from API'''
URL = f"https://the-words.herokuapp.com/api/v2/definitions/en-US/entries/{query}"
HEADERS={'Accept': 'application/json'}
response = requests.get(URL, headers=HEADERS)
print(response.status_code)
#print(response.heade... |
from __future__ import unicode_literals
import frappe, sys
import erpnext
import frappe.utils
from erpnext.demo.user import hr, sales, purchase, manufacturing, stock, accounts, projects, fixed_asset, education
from erpnext.demo.setup import education, manufacture, setup_data, healthcare
"""
Make a demo
1. Start with ... |
#!/usr/bin/env python3
def show_banner(value: str, times: int):
print(value * times)
def show_strings_demo1():
first_name = "Mohd"
last_name = 'Azim'
person_description = """
My Name is
Mohd Azim
"""
show_banner('=', 50)
... |
import TestHelperSuperClass
import unittest
import json
import pytz
import datetime
import copy
serverInfo = {
'Server': {
'Version': TestHelperSuperClass.env['APIAPP_VERSION'],
"APIAPP_APIDOCSURL": TestHelperSuperClass.env['APIAPP_APIDOCSURL'],
"APIAPP_FRONTENDURL": TestHelperSuperClass.... |
import numpy as np
import cv2 as cv
import argparse
from deep_text_detect import text_detect, text_spotter
from read_license import read
parser = argparse.ArgumentParser()
parser.add_argument("image", help="Path to car image")
args = parser.parse_args()
image_path = args.image
image = cv.imread(image_path)
original =... |
import torch.nn as nn
from typing import Dict
from yolact_edge.yolact import Yolact
class YolactWrapper(nn.Module):
def __init__(self, yolact_module: Yolact, extras: Dict):
super().__init__()
self.yolact_module = yolact_module
self.extras = extras
def forward(self, x):
out_dic... |
from violas_client.canoser.int_type import Uint8
from violas_client.canoser.tuple_t import TupleT
from violas_client.canoser.map_t import MapT
from violas_client.canoser.str_t import StrT
from violas_client.canoser.bytes_t import BytesT, ByteArrayT
from violas_client.canoser.bool_t import BoolT
from violas_client... |
# V1.43 messages
# PID advanced
# does not include feedforward data or vbat sag comp or thrust linearization
# pid_advanced = b"$M>2^\x00\x00\x00\x00x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x007\x00\xfa\x00\xd8\x0e\x00\x00\x00\x00\x01\x01\x00\n\x14H\x00H\x00H\x00\x00\x15\x1a\x00(\x14\x00\xc8\x0fd\x04\x00\xb1"
p... |
import os
import re
class Interpreter:
def __init__(self, file_path):
self._data_path = file_path
self._file_list = []
for root, dirs, files in os.walk(self._data_path):
# 存储了文件夹下所有的文件
all_files = files
# 抽取出.txt文件
for i in range(0, len(all_files)):
... |
import pickle
import bz2
import io
import torch
from torch import nn
from torch.utils import data
from torch.nn import functional as F
# model
class Attention(nn.Module):
def __init__(self, feature_dim, max_seq_len=70):
super().__init__()
self.attention_fc = nn.Linear(feature_dim, 1)
self.... |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Ansible Project
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
fro... |
# Generated by Django 2.1.4 on 2018-12-16 18:11
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Extractor',
fields=[
('id',... |
from settings import *
import pygame
import math
class Player:
def __init__(self):
self.x, self.y = player_pos
self.angle = player_angle
self.sensitivity = 0.004
@property
def pos(self):
return (self.x, self.y)
def movement(self):
self.keys_control()
se... |
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app,db
#app.config.from_object(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://genrichez:Kandra5moneR@localhost/Recommendations'
migrate = Migrate(app, db)
manager = Manager(a... |
from machine import I2C, Pin,RTC,WDT,reset
from ssd1306 import SSD1306_I2C
from font import Font
import time
i2c = I2C(scl=Pin(0), sda=Pin(2))
display= SSD1306_I2C(128, 32, i2c)
f=Font(display)
f.text("sdada",0,0,24)
f.show() |
try:
from ._version import version as __version__ # type: ignore[import]
except ImportError:
__version__ = "UNKNOWN"
from .core import *
from . import loss, enc, demo, data, image, pyramid, optim
import os
os.makedirs(home(), exist_ok=True)
|
import numpy as np
from ...sgmcmc_sampler import SGMCMCSampler, SeqSGMCMCSampler
from .parameters import SVMPrior, SVMParameters
from .helper import SVMHelper
class SVMSampler(SGMCMCSampler):
def __init__(self, n, m, observations=None, prior=None, parameters=None,
forward_message=None, name="SVMSampler... |
"""
API facade that allows interaction with the library with strings and vanilla Python objects.
Copyright 2021 InferStat Ltd
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.... |
from typing import Any, Dict, Type, TypeVar
from injector import Injector, Provider, Scope, ScopeDecorator
from appunit import context
__all__ = ["RequestScope", "request"]
T = TypeVar("T")
class CachedProviderWrapper(Provider):
def __init__(self, old_provider: Provider) -> None:
self._old_provider = ... |
import math
import datetime
import Config
import Math
import TargetNone
class TargetAvoid(TargetNone.TargetNone):
def __init__(self):
if 'avoid' not in Config.save_json:
Config.save_json['avoid'] = []
self.avoid_coordinate = Config.save_json['avoid']
self.vehicle_width = 1.3... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import sys
import datetime
message = "Hello, %s! Current time: %s." % (sys.argv[1], datetime.datetime.now())
# Print the message to stdout.
print(message)
# Append the message to the log file.
with open("/tmp/Green... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code, Day 12
======================
Author: hbldh <henrik.blidh@nedomkull.com>
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import re
with open('input_12.txt', 'r') as f:
instructions... |
"""Module that manages the testing states of the access ports"""
import threading
from forch.utils import get_logger
from forch.proto.shared_constants_pb2 import PortBehavior
from forch.proto.devices_state_pb2 import DeviceBehavior, DevicePlacement
from forch.proto.shared_constants_pb2 import DVAState
INVALID_VLAN ... |
#!/usr/bin/env python
#
# Copyright (c), 2021, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide ... |
import yaml
CONFIG_PATH = "./config.yml"
config = {}
with open(CONFIG_PATH, 'r') as f:
config = yaml.load(f)
|
from __future__ import print_function, division, absolute_import
import time
import multiprocessing
import pickle
from collections import defaultdict
import warnings
import sys
# unittest only added in 3.4 self.subTest()
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
import unittest2 as unittest
else:
... |
from lib.directives import DIRECTIVES
class Node:
def __init__(self, key=None):
self.key = key if key else ""
self.keysplit = []
self.raw = None
self.inner = None
self.directive = None
self.incontext = None
self.func = None
self... |
from enum import IntEnum;
class OgreMeshChunkID(IntEnum):
"""
Definition of the OGRE .mesh file format
.mesh files are binary files (for read efficiency at runtime) and are arranged into chunks
of data, very like 3D Studio's format.
A chunk always consists of:
unsigned short CHUNK_ID ... |
# -*- coding: UTF-8 -*-
"""
A set of tests for the vmware.py module
"""
import unittest
from unittest.mock import patch, MagicMock
from vlab_inventory_api.lib.worker import vmware
class TestVMware(unittest.TestCase):
"""A suite of test cases for the vmware.py module"""
@patch.object(vmware.virtual_machine, ... |
import os, json, re
import discord, asyncio
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from urllib import parse
from riot_api import *
app = discord.Client()
mstatus = 0
botid = ""
token = os.getenv("TOKEN")
lol_apikey = os.getenv("API_KEY")
if not token:
json_data = open(os.getcwd... |
from dart_version_manager.commands.build_command import app as build_app
from dart_version_manager.commands.major_command import app as major_app
from dart_version_manager.commands.minor_command import app as minor_app
from dart_version_manager.commands.patch_command import app as patch_app
from dart_version_manager.co... |
# -*- coding: utf-8 -*-
from flask_restful import Api
import resources
def create_api(app):
api = Api(app)
api.add_resource(resources.OndeRemar, '/api/onde-remar', '/api/onde-remar/<int:item_id>')
api.add_resource(resources.Produtos, '/api/produtos', '/api/produtos/<int:item_id>')
api.add_resource(re... |
from .map import MapFactory, Map, Graph
__all__ = ['MapFactory', 'Map', 'Graph']
|
from collections import defaultdict
count=0
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addNode(self, init, connect):
self.graph[init].append(connect)
def DFStrigger(self, index, visited, stack):
visited[index] =True
for ele in self.graph[index]:
... |
from __future__ import unicode_literals
import frappe
import erpnext
from frappe import auth
import datetime
import json, ast
from frappe.share import add
@frappe.whitelist()
def share_lead(doc, method=None):
'''
users = frappe.db.sql(""" select owner from `tabToDo` where reference_type = 'Lead' and reference_... |
import unittest
import unittest.mock
import ast
import io
from margate.parser import (Parser, parse_expression, IfNode, ForNode,
ExtendsNode)
from margate.code_generation import (Literal, Sequence, IfBlock,
ForBlock, ExtendsBlock, ReplaceableBlock,
... |
import ast
import json
import logging
import os.path
import re
from six.moves import urllib
from check_mk_web_api.activate_mode import ActivateMode
from check_mk_web_api.exception import CheckMkWebApiResponseException, CheckMkWebApiException, \
CheckMkWebApiAuthenticationException
from check_mk_web_api.no_none_va... |
import numpy as np
from .shader_program import ShaderProgram
STATIC_VERTEX_SHADER = """
#version 400 core
in vec3 position;
out vec3 color;
uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 vColor;
void main(void) {
gl_Position = projectionMatrix * viewMa... |
#!/usr/bin/env python
#
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.)
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file ex... |
def timemat(n,m):
import numpy
import time
t = time.time()
X = numpy.random.rand(m, n+1)
Y = numpy.random.rand(m, 1)
theta = numpy.linalg.inv(X.T @ X) @ X.T @ Y
return time.time() -t
if __name__ == '__main__':
import sys
n = 1000
m = 100
if len(sys.argv) > 2:
n = int(sys.argv[1])
m = int(sys.argv[2])... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A script for
"""
import os, sys
import zipfile
def toBytes(para):
return bytes(para, 'utf-8')
def getPass(para):
import getpass
return getpass.getpass(para)
def decompress(filename):
print("Archive: ", filename)
file = zipfile.ZipFile(filename, "r")
... |
from typing import List, Dict
from klgists.common import flatten
from klgists.common.exceptions import BadConfigException
class BoardLayout:
"""The pins and ports on an Arduino board.
Defines which correspond to input and output stimuli and sensors.
Does not know about sensors or stimuli themselves, only about t... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
import sys
import unittest
import numpy as np
import torch
import torch.nn.functional as F
import lava.lib.dl.slayer as slayer
verbose = True if (('-v' in sys.argv) or ('--verbose' in sys.argv)) else False
seed = np.random.randint(1000)... |
from time import sleep
from smbus import SMBus
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
bus = 0
class PiTouch:
def __init__(self):
if GPIO.RPI_REVISION == 1: # Although PiTouch doesn't fit, keep for compatibility
i2c_bus = 0
elif GPIO.RPI_REVISION == 2: # As well as the rev 2
i2c_bus = 1
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date
from psycopg2 import IntegrityError, ProgrammingError
import odoo
from odoo.exceptions import UserError, ValidationError, AccessError
from odoo.tools import mute_logger
from odoo.tests import c... |
import cv2
import time
cap = cv2.VideoCapture('C:/Users/Administrator/Documents/GOMCam/parking.mp4')
cap.set(3, 800)
cap.set(4, 448)
if not cap.read():
print("none")
if cap.read():
count_2 = 0
while True:
time.sleep(0.3)
count_2 +=1
ret, img = cap.read()
if img is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.