text stringlengths 1 927k |
|---|
import requests
import os
import json
import datetime
import boto3
import logging
import datetime
import urllib.request
import re
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logging.info(json.dumps(event))
## eventが発生したらDBに接続
dynamoDB = boto3.resour... |
#!/usr/bin/env python3
import sys
import json
import socket
def parse_url(url):
client_socket = socket.socket()
client_socket.connect(('localhost', 8090))
url = f'{url}\r\n'
client_socket.send(url.encode('utf8'))
data = b''
tmp = client_socket.recv(1024)
while tmp:
print(f'Rec... |
# coding: utf-8
# In[1]:
def hist(len):
no_intervals = 10 // len
if 10 % len != 0:
no_intervals += 1
for i in range(0, no_intervals):
c = 0
for j in range(len * i + 1, len * i + len + 1):
if j > max:
break
c += count[j]
s1 = str(len*i... |
from django.apps import AppConfig as BaseAppConfig
from django.utils.translation import gettext_lazy as _
class AppConfig(BaseAppConfig):
name = "pinax.badges"
label = "pinax_badges"
verbose_name = _("Pinax Badges") |
# vim: set fileencoding=utf-8 :
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import functools
import jwt
import logbook
import six
import werkzeug.exceptions
import stethoscope.configurator
logger = logbook.Logger(__name__)
class AuthProvider(stethoscope.configurator.... |
"""
Non-symmetric Macdonald Polynomials
"""
from sage.combinat.combinat import CombinatorialObject, CombinatorialClass
from sage.combinat.words.word import Word
from sage.combinat.combination import Combinations
from sage.combinat.permutation import Permutation
from sage.rings.all import QQ, PolynomialRing, prod
from s... |
#
# Copyright 2019 The FATE 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 appli... |
#!/usr/bin/env python
'''Test LA load using PyPNG. You should see the la.png image on
a checkboard background.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import unittest
import base_load
from pyglet.image.codecs.png import PNGImageDecoder
class TEST_PNG_LA_LOAD(base_load.TestLoad):
texture_f... |
"""
Policy class
"""
from marshmallow import Schema, fields, post_load, ValidationError, validate
from .rules import Rules, RulesSchema
from .targets import Targets, TargetsSchema
from ..context import EvaluationContext
from ..exceptions import PolicyCreateError
# Access decisions
DENY_ACCESS = "deny"
ALLOW_ACCE... |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.centralnic.com/se.com/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser... |
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import permission_required
from django.contrib import messages
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.resp... |
from .inventory_loans import *
from .loans import * |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C3ub')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Mo... |
# -*- coding: utf-8 -*-
#
# discord.py documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 21 05:43:30 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... |
import lightbulb
import hikari
import datetime
ping_plugin = lightbulb.Plugin("ping")
@ping_plugin.command()
@lightbulb.command("ping", "measure the ping of the bot", auto_defer=True, aliases=["pong"])
@lightbulb.implements(lightbulb.PrefixCommand)
async def ping(ctx: lightbulb.Context) -> None:
heartbeat = ctx.b... |
# Monotonic array optimised solution
# Time complexity = O(n) | Space Complexity : O(1)
# method to check if the direction breaks
def directionChanged(direction, previous, current) :
difference = current - previous
if direction > 0 :
return difference < 0
return difference > 0... |
#Import required libraries
import textwrap, time
from django.utils.text import slugify
from quotes.admin.wpmodels import Images
from quotes.admin import utils
def updateQuotesImage(quotesObj):
for obj in quotesObj:
if not obj.quotesTxt:
obj.quotesTxt = obj.quotes
imgText = tex... |
# Generated by Django 2.2.5 on 2020-02-10 04:58
from django.db import migrations, models
import django.db.models.deletion
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('interfacemanagement', '0001_initial'),
('projectmanagent', '0001_initial... |
#!/usr/bin/env python
### command line options helper
from __future__ import print_function
import six
from Options import Options
options = Options()
## imports
import sys
from Mixins import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Lab... |
# nyokaUtilities.py
import numpy as np
from random import choice
from string import ascii_uppercase
import copy,json
import ast,pathlib
import traceback
from nyoka import PMML43Ext as ny
global MEMORY_DICT_ARCHITECTURE,MEMORY_OF_LAYERS
settingFilePath='./settingFiles/'
savedModels='./SavedModels/'
MEMORY_OF_LAYERS={}
... |
import datetime
from django.db.models import Q
from django.db.models.query import QuerySet
from django.utils import timezone
class JobTypeQuerySet(QuerySet):
def active(self):
""" active Job Types """
return self.filter(active=True)
def with_active_jobs(self):
""" JobTypes with acti... |
# coding=utf-8
from ..base import BitbucketCloudBase
class Issues(BitbucketCloudBase):
def __init__(self, url, *args, **kwargs):
super(Issues, self).__init__(url, *args, **kwargs)
def __get_object(self, data):
if "errors" in data:
return
return Issue(data, **self._new_ses... |
# decorators/time.measure.arguments.py
from time import sleep, time
def f(sleep_time=0.1):
sleep(sleep_time)
def measure(func, *args, **kwargs):
t = time()
func(*args, **kwargs)
print(func.__name__, 'took:', time() - t)
measure(f, sleep_time=0.3) # f took: 0.30056095123291016
measure(f, 0.2) # f t... |
# Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
# Based on
# https://medium.com/datadriveninvestor/mutable-and-immutable-python-2093deeac8d9 |
# -*- coding: utf-8 -*-
"""
asyncio-server.py
~~~~~~~~~~~~~~~~~
A fully-functional WSGI server, written using hyper-h2. Requires asyncio.
To test it, try installing httpin from pip (``pip install httpbin``) and then
running the server (``python asyncio-server.py httpbin:app``).
This server does not support HTTP/1.1:... |
import os
import os.path
from unittest.mock import MagicMock, patch
from ichnaea.models.content import (
DataMap,
)
from ichnaea.scripts import datamap
from ichnaea.scripts.datamap import (
encode_file,
export_file,
main,
merge_files,
render_tiles,
)
from ichnaea import util
class TestMap(obj... |
import pytest
import re
from pycolog.log_entry import LogEntry
@pytest.mark.parametrize('chars,expected', [
(4, 'S...'),
(8, 'Short...'),
(9, 'ShortLine'),
(12, 'ShortLine'),
])
def test_truncate(chars, expected):
assert LogEntry('ShortLine').truncate(chars) == expected
def test_fields_as_attri... |
#! /usr/bin/python3
import socket
import getpass
user = str(getpass.getuser())
out = 'error'
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.sendto(user.encode('utf-8'), ('127.0.0.1',40069))
date, addr = sock.recvfrom(1024)
if date:
out = date.decode('utf-8')
print(user + ", Ваш вариант № " + ... |
import asyncio
import time
import yaml,sys
#%%
from gremlin_python.driver import client, serializer, protocol
from gremlin_python.driver.protocol import GremlinServerError
import sys
import traceback
#%%
#Connection config
config = yaml.safe_load(open('configure.yaml'))
endpoint = config['endpoint']
username = con... |
"""Implementation of Layout Denoise model."""
# pylint: disable=not-callable
from typing import Any, Dict, List, Tuple, Optional
import flax.linen as nn
import jax.numpy as jnp
import ml_collections
from scenic.projects.baselines import resnet
from scenic.projects.layout_denoise import base_model
from scenic.project... |
x = ['apple', 'bob', 'cat', 'drone']
y = x
x[0] = 'qqrq'
print(x) # ['qqrq', 'bob', 'cat', 'drone']
print(y) # ['qqrq', 'bob', 'cat', 'drone']
# • There is one list in the memory and two pointers to it.
# • If you really want to make a copy the pythonic way is to use the slice syntax.
# • It creates a shallow copy
fro... |
import os
import pytest
import sys
class TestUpload:
@pytest.mark.parametrize("file_type", ["reference", "reads", "hmm", "subtraction"])
async def test(self, file_type, tmpdir, spawn_client, static_time, test_random_alphanumeric):
client = await spawn_client(authorize=True, permissions=["upload_file"... |
import os
import copy
import ray
import argparse
import tqdm
import logging
import pandas as pd
from pathlib import Path
from datetime import datetime
import shutil
import uuid as uu_id
from typing import ClassVar, Dict, Generator, Tuple, List, Any
from proseco.evaluator.remote import run
from proseco.evaluator.progre... |
# coding=utf-8
import argparse
import ipaddress
import time
import logging
from lib.common import start
from lib.cli_output import start_out
from plugins.ActiveReconnaissance.active import ActiveCheck
from report import gener
def read_file(file, dbname):
hosts = []
try:
with open(file, 'rt') as f:
... |
# -*- coding: utf-8 -*-
__author__ = "苦叶子"
"""
公众号: 开源优测
Email: lymking@foxmail.com
"""
from flask import current_app, session, request, send_file
from flask_restful import Resource, reqparse
import werkzeug
from utils.file import exists_path, rename_file, make_nod, remove_file, write_file, read_file
class Cas... |
import tikzplotlib
import matplotlib
import matplotlib.pyplot as plt
import os
import torch
import pickle
import json
from pytracking.evaluation.environment import env_settings
from pytracking.analysis.extract_results import extract_results
def get_plot_draw_styles():
plot_draw_style = [{'color': (1.0, 0.0, 0.0),... |
# crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-o (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se aposentar.
from datetime... |
from citlab_python_util.geometry.polygon import string_to_poly
from citlab_python_util.io.file_loader import load_text_file
from citlab_python_util.parser.xml.page.page import Page
def get_article_polys_from_file(poly_file_name):
""" Load polygons from a txt file or a PageXml file `poly_file_name`, split them up ... |
from setuptools import setup
package_name = 'tutorial'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
instal... |
__all__ = ["int_to_bytes", "bytes_to_int"]
def int_to_bytes(value: int):
byte_length = (value.bit_length() + 7) // 8
byte_length = (byte_length + 3) // 4 * 4
byte_length = 4 if byte_length == 0 else byte_length
return value.to_bytes(byte_length, "big")
def bytes_to_int(data: bytes):
return int.f... |
# encoding: UTF-8
import psutil
import traceback
from vnpy.trader.vtFunction import loadIconPath
from vnpy.trader.vtGlobal import globalSetting
from vnpy.trader.uiBasicWidget import *
from .vtEngine import DataEngine
from PyQt5 import Qt
########################################################################
class ... |
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, create_refresh_token
from .model import User
from .serializer import UserSchema
from datetime import timedelta
blue_print_login = Blueprint("login", __name__)
@blue_print_login.route("/login", methods=["POST"])
def logi... |
"""
lakeFS API
lakeFS HTTP API # noqa: E501
The version of the OpenAPI document: 0.1.0
Contact: services@treeverse.io
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import lakefs_client
from lakefs_client.model.stage_range_creation import StageRangeCreation
class... |
"""Unit test package for tagupy.""" |
#!/usr/bin/python3
"""
__reference:
"""
from tkinter import *
import tabs
import guideInfoStrings as gis
import outputFunctions
import menubar
def updateVariableText(thisTab, returnString):
""" This function updates the label when called """
change = StringVar(thisTab)
change.set(returnString)
... |
import datetime
## LOCAL POSTGRESQL DEFINITION
pg_items = {
'serial': 'serial',
'text': str,
'integer': int,
'real': float,
'boolean': bool,
'timestamp with time zone': datetime.datetime,
}
pg_items_str = {
'serial': 'serial',
'text': 'str',
'integer': 'int',
'real': 'float',
... |
import discord
import random
from helpers import get_gif
commands = ["gigawackelarm"]
requires_mention = False
accepts_mention = True
description = "*waves fouriouslyer*"
async def execute(message):
await message.channel.send("<a:wackelarm:721807816221786323>"*9) |
import argparse
import contextlib
import collections
import enum
import errno
import grp
import hashlib
import logging
import io
import json
import os
import os.path
import platform
import pwd
import re
import shlex
import signal
import socket
import stat
import subprocess
import sys
import textwrap
import time
import ... |
import json
import os
import confuse
import boto3
from botocore.exceptions import ClientError
from cachetools import Cache
class MissingCredentials(Exception):
"""
Credentials are missing, see the error output to find possible causes
"""
pass
class CredentialProvider:
credentials = None
cach... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# author: wangfeng19950315@163.com
import numpy as np
import torch
class CenterNetGT(object):
@staticmethod
def generate(config, batched_input):
box_scale = 1 / config.MODEL.CENTERNET.DOWN_SCALE
num_classes = config.MODEL.CENTERNET.NUM_CLASSES
... |
#
# Required by Cython to build Hiredis extensions
#
import os
import sys
from distutils.extension import Extension
from distutils.command.build_ext import build_ext
from distutils.errors import (CCompilerError, DistutilsExecError,
DistutilsPlatformError)
path = os.path.join('extensions',... |
data = {
"superfolia":
("grass weed moss root natural organic deep dark",
[(0.57, 0.57, 0.44, 1.00),
(0.29, 0.27, 0.08, 1.00),
(0.16, 0.16, 0.05, 1.00),
(0.00, 0.00, 0.00, 1.00),
]),
"evolution":
("sea underwater intelligent subtle soft",
... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Copyright (c) 2017 The Raven Core developers
# Copyright (c) 2018 The Colombo Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the imp... |
"""
Unittest for the bidding module.
"""
import logging
import unittest
import networkx as nx
from stitcher import bidding
FORMAT = "%(asctime)s - %(filename)s - %(lineno)s - " \
"%(levelname)s - %(message)s"
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
class EntityTest(unittest.TestCase):
... |
# Return the array names for a mesh.
#
import pyvista
mesh = pyvista.Sphere()
mesh.point_data['my_array'] = range(mesh.n_points)
mesh.array_names
# Expected:
## ['my_array', 'Normals'] |
import io
import os
from setuptools import setup, find_packages
def parse_requirements(file):
required_packages = []
with open(os.path.join(os.path.dirname(__file__), file)) as req_file:
for line in req_file:
if '/' not in line:
required_packages.append(line.strip())
re... |
"""Support for the Netatmo cameras."""
import logging
import aiohttp
import pyatmo
import voluptuous as vol
from openpeerpower.components.camera import SUPPORT_STREAM, Camera
from openpeerpower.core import callback
from openpeerpower.exceptions import PlatformNotReady
from openpeerpower.helpers import config_validati... |
import crcmod
from Crypto.Cipher import AES
import binascii
def lsfr(buf, feedback):
new_buf = ''
buf_len = len(buf)
if((ord(buf[buf_len - 1]) & 0x01) == 1):
feedback = True
for i in range(buf_len - 1, -1, -1):
tmp = ord(buf[i]) >> 1
if(i>0):
if((ord(buf[i-1]) & 0x01) == 1):
tmp = ... |
import collections
import numpy as np
import pandas as pd
import pymysql
import pytest
from pydantic import ValidationError
from pytest_mock import MockerFixture
from toucan_connectors.common import ConnectorStatus
from toucan_connectors.mysql.mysql_connector import MySQLConnector, MySQLDataSource, handle_date_0
@p... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for terracashd node under test"""
import decimal
import errno
import http.client
import json
import l... |
from collections import namedtuple
import logging
import random
from Items import ItemFactory
from Fill import FillError, fill_restrictive
#This file sets the item pools for various modes. Timed modes and triforce hunt are enforced first, and then extra items are specified per mode to fill in the remaining space.
#So... |
from __future__ import print_function
import numpy as np
import os
import sys
import cv2
import random
import pickle
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.optim as optim
from torch.optim import lr_scheduler
import torch.utils.data as data
import torch.nn.ini... |
"""
Script that creates a visual map in browser based off of world
GDP data based on year given by user.
"""
import csv
import math
import pygal
def read_csv_as_nested_dict(filename, keyfield, separator, quote):
"""
Inputs:
filename - Name of CSV file
keyfield - Field to use as key for rows
... |
from typing import NoReturn
from Recorder.BaseRecorder import BaseRecorder
from Config.const import BillStatus
from Models.AlipayBill import AlipayBill
class AlipayRecorder(BaseRecorder):
def __init__(self, rows):
super(AlipayRecorder, self).__init__(rows, AlipayBill)
@classmethod
def update_sa... |
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
str = type('')
class GPIOZeroError(Exception):
"Base class for all exceptions in GPIO Zero"
class DeviceClosed(GPIOZeroError):
"Error raised when an operation is attempted on a closed device"
class BadEve... |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_impor... |
PST = 0.07
GST = 0.06
price = float(input("what is the price of the item: "))
taxable = input("is this item taxable? ")
if taxable == "yes":
pst = PST * price
gst = GST * price
print(f"the price is {price}")
print(f"the pst of this item is {pst:.2f}")
print(f"the gst of this item is {gst:.2f}")
print(f"th... |
from django.apps import AppConfig
class ClassificationConfig(AppConfig):
name = 'classification' |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# !/user/bin/python
# coding=utf-8
from __future__ import print_function
import urllib
import time
import os
import re
try:
from my_net import net
except ImportError:
raise ImportError('Sorry, can not find \'my_net\' .\nPlease view https://github.com/WuJunkai2004/Pyself/blob/master/my_net/my_net.py to downlo... |
import _plotly_utils.basevalidators
class ShowValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="show", parent_name="scatter3d.projection.y", **kwargs
):
super(ShowValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pa... |
"""
Write a function:
def solution(A)
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.
For example, given:
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2
the function should return 5.
Assume that:
N is an i... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2019 Intel Corporation
import asyncio
import unittest
from unittest.mock import patch
from dffml.feature import Data, Feature, Features, LoggingDict, DefFeature
from dffml.util.asynctestcase import AsyncTestCase
class SingleFeature(Feature):
def dtype(self):
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
"""
The wntr.scenario.earthquake module includes methods to
define an earthquake location, magnitude and depth, and
compute PGA, PGV, and repair rate.
"""
from __future__ import print_function
import wntr
import numpy as np
import pandas as pd
from scipy.spatial import distance
class Earthquake(object):
"""
Ea... |
'''
Created on Feb 28, 2017
@author: kidane
'''
from os import path
from optparse import OptionParser
from utils import feed_utils, args_utils,ssh_utils, run_utils
from api import storage, job
import config
def test_move(nels_id):
feed_utils.heading("move use case. nels_id: %s" % nels_id)
credentail = ... |
# Copyright 2016 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.
# Recipe module for Skia Swarming calmbench.
DEPS = [
'core',
'flavor',
'recipe_engine/context',
'recipe_engine/file',
'recipe_engine/path',
'r... |
import itertools
fp = open('/code/input01.txt', 'r')
content = fp.readlines()
lines = [x.strip() for x in content]
numbers = [int(x) for x in lines]
divided = [int(x/3) for x in numbers]
subs = [int(x-2) for x in divided]
sum(subs)
#part2
def calc_fuel(x):
fuel = int(x/3) - 2
if fuel > 0:
return fuel + calc_fu... |
# qubit number=2
# total number=11
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
# -*- coding: utf-8 -*-
"""
sphinx.writers.websupport
~~~~~~~~~~~~~~~~~~~~~~~~~
sphinx.websupport writer that adds comment-related annotations.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinx.writers.html import HTMLTranslat... |
import numpy as np
import numpy as np
from matplotlib import pyplot as plt
from scipy import fftpack as fp
def cross_correlation(q):
ind = np.argmin(np.abs(q - 0.6))
inten = I2d[:, ind]
print("Found %d angles" % len(inten))
phi = chi.copy()
N = len(inten)
lags = np.arange(-N + 1, N)
inte... |
#Cory Mavis
import cv2
import numpy
import sys
import subprocess
import os
import statistics
cv2.namedWindow("LiveFeed")
def callback (event,x,y,flags,params):
global blueMark #update the position of the blue point
global greenMark #update the position of the green point
global redMark #update the positio... |
"""
Experimental video player using pyglet.
This requires that you have ffmpeg installed
and you might need to tell pyglet where it's located.
"""
# import sys
import pyglet
import arcade
class VideoPlayer(arcade.Window):
def __init__(self) -> None:
super().__init__(800, 600, "Video Player", resizable=T... |
#!/usr/bin/python
# Ingmar Steen, 2016
# This is to test label addressing on X86_64
# Github issue: #34
# Author: Ingmar Steen
from keystone import *
import regress
class TestX64NasmLabel(regress.RegressTest):
def runTest(self):
# Initialize Keystone engine
ks = Ks(KS_ARCH_X86, KS_MODE_64)
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# 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.apac... |
import datetime
from typing import TYPE_CHECKING, Iterable, Optional, Union
from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.aggregates import StringAgg
from django.db import models
from django.db.models import Case, Count, F, FilteredRelation, Q, Sum, Value, When
from django.db.mod... |
# Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class GetDriveFolderChildrenReq(object):
types: typing.List[str] = attr.ib(
factor... |
"""Implementation of JSONEncoder
"""
import re
try:
from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError:
c_encode_basestring_ascii = None
try:
from simplejson._speedups import make_encoder as c_make_encoder
except ImportError:
c_make_encoder = None
... |
import numpy as np
import random
from numpy.core.fromnumeric import clip
from numpy.lib.shape_base import vsplit
import tensorflow as tf
from tensorflow.python.ops.gen_linalg_ops import self_adjoint_eig_eager_fallback
import common.tf_util as U
from common.distributions import make_pdtype
import tensorflow.contrib.lay... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
"""Utilities for turning a string list of plugins into a usable list of BlockSet and PluginCommand objects."""
from typing import Dict, Generator, List, Optional, Tuple, Union
import click
import structlog
from meltano.core.plugin import PluginType
from meltano.core.plugin.error import PluginNotFoundError
from meltan... |
from typing import List, Dict, Iterable, Optional, Tuple, NamedTuple
import os
import json
from qanta.util import QANTA_MAPPED_DATASET_PATH
# from util import QANTA_MAPPED_DATASET_PATH
GUESSER_TRAIN_FOLD = 'guesstrain'
BUZZER_TRAIN_FOLD = 'buzztrain'
TRAIN_FOLDS = {GUESSER_TRAIN_FOLD, BUZZER_TRAIN_FOLD}
# Guesser an... |
import argparse
import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from mmpose.models import build_posenet
try:
import onnx
import onnxruntime as rt
except ImportError as e:
raise ImportError(f'Please install onnx and onnxruntime first. {e}')
try:
from mmcv.onnx.symb... |
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from enum import Enum, unique
from functools import singledispatch
from typing import Any, Collection, Dict, List, Optional, Set, Type, Union
import dateutil
import sqlalchemy as sa
from abilian.app import db
from email... |
from collections import Counter
from typing import List
import re
import random
class NgramLM(object):
"""N-Gram Language Model
:param n: Size of the n-gram, e.g., n=2 bigrams
:type n: int
:param nlp: Tokenizer, default spacy.lang.en.English
"""
def __init__(self, n: int=2, nlp: object=None)... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mymap.settings')
try:
from django.core.management import execute_from_command_line
except Import... |
from mlagents.trainers.policy.tf_policy import TFPolicy
from mlagents_envs.base_env import BatchedStepResult, AgentGroupSpec
from mlagents.trainers.action_info import ActionInfo
from unittest.mock import MagicMock
import numpy as np
def basic_mock_brain():
mock_brain = MagicMock()
mock_brain.vector_action_spa... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.