text stringlengths 1 927k |
|---|
import sys
import os
from PIL import Image
import struct
def writeu8(val, outf):
outf.write(struct.pack("B", val))
if __name__ == "__main__":
#print("ARGV: {}".format(sys.argv))
if len(sys.argv) < 2:
print("{}: Expected input file".format(sys.argv[0]))
exit
inName = sys.argv[1]
fSi... |
#!/usr/bin/python3
import os
import json
class Config:
def __init__(self, filename):
self.filename = filename
self.data = dict()
# read config file, return true when success
def success(self):
try:
with open(self.filename) as f:
self.data = json.load(f)... |
# -*- coding: utf-8 -*-
# Put in here all of some of your custom decorators |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v6/proto/common/metrics.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobu... |
# Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... |
"""
Usage::
import install_cmake
install_cmake.install()
"""
import os
import subprocess
import sys
import textwrap
from subprocess import CalledProcessError, check_output
DEFAULT_CMAKE_VERSION = "3.5.0"
def _log(*args):
script_name = os.path.basename(__file__)
print("[circle:%s] " % script_name ... |
#!/usr/bin/env python3
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
from . import ed25519 as ed25519_sha3
import nacl.signing as ed25519_sha2
import hashlib
import binascii
import grpc
import time
import re
import os
from . import commands_pb2
from . import endpoint_p... |
# NLP written by GAMS Convert at 04/21/18 13:52:27
#
# Equation counts
# Total E G L N X C B
# 52 40 0 12 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the aiida-jutools package. ... |
#!/usr/bin/env python
from builtins import map
import os, sys, json, re
from lxml.etree import parse
def create_met_json(xml_file, json_file, mis_char):
"""Write product metadata json."""
with open(xml_file) as f:
doc = parse(f)
coords = doc.xpath("//*[local-name() = 'coordinates']")[0].text ... |
"""
ASGI config for codezone project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETT... |
# Copyright (c) 2020 PaddlePaddle 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... |
import markdown
markdown.markdownFromFile(
input="resume.md",
output="index.html",
encoding="utf8"
) |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
"""foodfitnessProject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
... |
import base64
import json
import logging
import re
import traceback
from typing import Optional
from urllib.parse import urlparse
from moto.cloudformation import parsing
from moto.core import CloudFormationModel as MotoCloudFormationModel
from moto.ec2.utils import generate_route_id
from six import iteritems
from loc... |
import os
import errno
import shutil
import mimetypes
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
class StorageException(Exception):
pass
class PathNotFound(StorageException):
pass
class Storage(object):
def join_path(self, *args):
... |
import os
import traceback
from time import time, gmtime, strftime
from datetime import date
from commands import getstatusoutput, getoutput
from shutil import copy2
from PilotErrors import PilotErrors
from pUtil import tolog, readpar, timeStamp, getBatchSystemJobID, getCPUmodel, PFCxml, updateMetadata, addSkippedToPF... |
# 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... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2012-2021 Roel Derickx, Paul Norman <penorman@mac.com>,
Sebastiaan Couwenberg <sebastic@xs4all.nl>, The University of Vermont
<andrew.guertin@uvm.edu>, github contributors
Released under the MIT license, as given in the file LICENSE, which must
accompany any distribution of t... |
import tflearn
import math
import numpy as np
import tensorflow as tf
import os
import time
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
FEATURE_NUM = 128
EPS = 1e-4
GAMMA = 0.99
class Network():
def CreateNetwork(self, inputs):
with tf.variable_scope('actor'):
split_0 = tflearn.fully_connected(
... |
import psycopg2
import toml
import matplotlib.pyplot as plt
import numpy as np
from lib import node_time, node_uptime
config = toml.load("./db.toml")['psql']
conn = psycopg2.connect(
host=config['host'],
port=config['port'],
database=config['database'],
user=config['user'],
password=config['passwor... |
"""
link: https://leetcode.com/problems/integer-break
problem: 将n拆分成若干个整数之和,求这堆整数的最大积,2 <= n <= 58
solution: DP。dp[i] 为 n==i 时的最优解,遍历所有组合可能即可
"""
class Solution:
def integerBreak(self, n: int) -> int:
dp = [1 for _ in range(n + 1)]
for i in range(2, n + 1):
for j in range(1, i // 2 ... |
import pandas as pd
import psycopg2
import os
from dotenv import load_dotenv
load_dotenv()
# read in our data
df = pd.read_csv('./titanic.csv')
print(f"DF shape: {df.shape}")
# create connection to db we want to move the data to
conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
dbname=os.getenv('DB_USER')... |
""" Functions for parsing database and shell commands """
import shlex
from typing import Tuple, Callable, List, Dict, Generator
from .constants import SHELL_COMMAND_INDICATOR
from .exc import WrongNumberOfArgumentsError, UnknownCommandError
def parse(command_string: str, shell_command_lookup: Dict[str, dict]) -> ... |
# 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 ... |
# Generated by Django 2.2.7 on 2019-11-12 14:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
n... |
from .network import Person, Post, SocialNetwork
from dsa import Array, mergesort, Set
from typing import List
__all__ = [
"people_by_popularity",
"posts_by_popularity",
"read_event_file",
"read_network_file"
]
# Creates a network from a network file.
def read_network_file(file_path: str, **network... |
#!/usr/local/bin/python2.7
"""
Copyright (c) 2017 Ad Schellevis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright not... |
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
class InventoryManagementCommandsTest(TestCase):
def test_cleanup_inventory_history(self):
out = StringIO()
call_command('cleanup_inventory_history', stdout=out)
result = out.getvalue()... |
"""Module containing helper functions."""
from __future__ import annotations
import collections
import logging
import sys
import traceback
from prettyqt import qt, widgets
from prettyqt.qt import QtCore
logger = logging.getLogger(__name__)
LOG_MAP = {
QtCore.QtMsgType.QtInfoMsg: 20,
QtCore.QtMsgType.QtWar... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... |
import cv2
import numpy as np
import torch
from path import Path
from tqdm import tqdm
from dvmvs.config import Config
from dvmvs.dataset_loader import PreprocessImage, load_image
from dvmvs.pairnet.model import FeatureExtractor, FeatureShrinker, CostVolumeEncoder, CostVolumeDecoder
from dvmvs.utils import cost_volume... |
# Copyright (c) Alex Ellis 2017. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
from flask import Flask, request, jsonify
from function import handler
#from gevent.wsgi import WSGIServer
from gevent.pywsgi import WSGIServer
app = Flask(__name... |
#- * - encoding : utf - 8 - * -
"""
:copyright: 2017-2018 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
def import_data(data_path,
use_pandas=False,
intercept=True,
valid_fraction=0.2,
classification=True):
"""Impo... |
from regression_tests import *
class TestBase(Test):
def test_c_contains_for_or_while_loop(self):
assert self.out_c.contains(r'(for|while) \(')
def test_c_contains_no_gotos(self):
assert not self.out_c.contains(r'goto .*;')
def test_c_contains_all_strings(self):
assert self.out_c.... |
from typing import Optional
class Solution:
def search(self, node: Optional[TreeNode], target: int):
if target - node.val in self.set and target - node.val != node.val:
self.flag = True
return
self.set.add(node.val)
if node.left:
self.search(node.left, t... |
import os
import re
import ctypes
import zlib
import functools
from urllib.parse import urlparse
from collections import namedtuple
from copy import deepcopy
from datafaucet import metadata
from datafaucet.paths import rootdir
from datafaucet._utils import merge, to_ordered_dict
from datafaucet.yaml import YamlDict
... |
class DecryptError(Exception):
"""
Can't even decrypt the message. May be corrupt or keys may be out of step.
"""
pass |
"""converted from ..\fonts\BLADE3D_AGP__8x8.bin """
WIDTH = 8
HEIGHT = 8
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\
b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\
b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\
b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\
b'\x00\xc6\xcc\x18\x30\x66\x... |
from __future__ import annotations
import itertools
from dataclasses import dataclass
from typing import List, Optional
import heapq
import time
import cProfile
@dataclass
class Edge:
"""Not to be used directly - does not validate nodes build inverse relationships. Use the node methods."""
source: Node
... |
import spam
import glob
def precalibrater():
uvfits_files = glob.glob('*.UVFITS')
#flag_files = glob.glob('*.FLAGS*')
for i in range(0,len(uvfits_files)):
#if source_name in uvfits_files[i]:
#print source_name
spam.pre_calibrate_targets(uvfits_files[i]) |
import torch
from .observation_type import ObservationType
import torch.nn.qat as nnqat
def get_native_backend_config_dict():
""" Get backend for PyTorch Native backend_config_dict (fbgemm/qnnpack)
"""
# dtype configs
# weighted op int8 config
# activation: quint8, weight: qint8, bias: float
w... |
import os
import fastestimator as fe
import numpy as np
import sls
import torch
import torch.nn as nn
import wget
from fastestimator.op.numpyop import NumpyOp
from fastestimator.op.tensorop import TensorOp
from fastestimator.op.tensorop.loss import CrossEntropy
from fastestimator.op.tensorop.model import ModelOp, Upda... |
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Basic canvas")
self.canvas = tk.Canvas(self, bg="white")
self.label = tk.Label(self)
self.canvas.bind("<Motion>", self.mouse_motion)
self.canvas.pack()
self.label.pac... |
import pandas as pd
import matplotlib.pyplot as plt
from numpy.random import randn
from krg_utils import transform_normal_scores
r = randn(10000)
slip_sc = pd.read_csv('slip_nscore_transform_table.csv')
slip = transform_normal_scores(r, slip_sc)
avg_slip = slip_sc['x'].sum() / len(slip_sc['x'])
avg_score = slip_sc['... |
#!/usr/bin/python
import nslocalizer
def main():
nslocalizer.main()
if __name__ == "__main__":
main() |
def setup(B):
@B.listen()
async def on_message(M):"💀"in M.content and await M.channel.send("http://tenor.com/view/10107813") |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
UDP support for IOCP reactor
"""
import socket, operator, struct, warnings, errno
from zope.interface import implements
from twisted.internet import defer, address, error, interfaces
from twisted.internet.abstract import isIPAddress, isIPv6... |
from src.data.datasets import FlickrDataset
from src.config import config
import matplotlib.pyplot as plt
import torch
from PIL import Image
def display_img_FlickrDataset(dataset, index=0, predicted_caption=None):
image = Image.open(dataset.images_directory / dataset.image_ids[index])
caption_txt = "\n".... |
def generateMatrice(data, K_mer, k):
# Variables
X = []
# Generate K-mer dictionnary
X_dict = {}
for i, e in enumerate(K_mer): X_dict[e] = 0;
# Generates X (matrix attributes)
for d in data:
x = []
x_dict = X_dict.copy()
# Count K-mer occurences (with overlaping)
for i in range(0, len(d[1]) - k + 1... |
from django.conf.urls.defaults import patterns, include, url
from django.views.generic import RedirectView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin... |
from django.shortcuts import render
from django.http import HttpResponse
from .forms import CarForm
from .models import NewCar
# Creates form
def index(request):
form = CarForm() #asign model and form to a variable
NewCarModel = NewCar.objects.all()
if request.method == "POST":
form = CarForm(reque... |
from pyspark.mllib.common import _java2py, _py2java
from pyspark.mllib.linalg import Vectors
from _model import PyModel
"""
Fits an Exponentially Weight Moving Average model (EWMA) (aka. Simple Exponential Smoothing) to
a time series. The model is defined as S_t = (1 - a) * X_t + a * S_{t - 1}, where a is the
smooth... |
import time
from turtle import *
setup(800, 800, 0, 0)
speed(0)
penup()
seth(90)
fd(340)
seth(0)
pendown()
speed(2)
begin_fill()
fillcolor('red')
circle(50, 30)
for i in range(10):
fd(1)
left(10)
circle(40, 40)
for i in range(6):
fd(1)
left(3)
circle(80, 40)
for i in range(20):
fd(0.5)
le... |
import re
from enum import Enum
from typing import Union
from packaging.version import LegacyVersion, Version, parse as parse_version
from raiden.constants import (
HIGHEST_SUPPORTED_GETH_VERSION,
HIGHEST_SUPPORTED_PARITY_VERSION,
LOWEST_SUPPORTED_GETH_VERSION,
LOWEST_SUPPORTED_PARITY_VERSION,
Eth... |
from flask import render_template, Flask, request, redirect, flash
from app import app
from .forms import RequestForm
import requests
from twilio.rest import TwilioRestClient
import twilio.twiml
import urllib
import math
import sys
import urllib2
'''
@author Arjun Jain
@author Chris Bernt
@author Greg Lyons
@author We... |
import logging
LOGGER = logging.getLogger(__name__)
try:
# from .import stanford_tagger as postagger
# LOGGER.debug('Use stanford_tagger')
from . import perceptron_tagger as postagger
LOGGER.debug('Use perceptron_tagger')
except:
from . import nltk_tagger as postagger
LOGGER.debug('Use nltk_tagg... |
"""
sphinx.writers.manpage
~~~~~~~~~~~~~~~~~~~~~~
Manual page writer, extended for Sphinx custom nodes.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import warnings
from typing import Iterable, cast
from docutils import nodes
from d... |
# Possible future states (for internal use).
RUNNING = 'RUNNING'
# Task has set the return or exception and this future is filled
FINISHED = 'FINISHED'
_FUTURE_STATES = [
RUNNING,
FINISHED
]
class Error(Exception):
"""Base class for all future-related exceptions."""
# TODO: for review - user-defined... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
import requests
import os
from dotenv import load_dotenv
from pprint import pprint
load_dotenv()
URL = os.getenv("URL")
TOKEN = os.getenv("TOKEN")
headers={"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
"Accept": "application/vnd.heroku+json; version=3"}
class HerokuClient:
... |
from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from .models import Scale
from .serializers import ScaleSerializer
from rest_framework.decorators import api_view
APP_NAME="Scale"
@api_view(['GET', 'PO... |
from appium.webdriver.common.mobileby import MobileBy
from app_APPium_test.src.BasePage import BasePage
from app_APPium_test.src.Manual_add import Manual_add
class Add_Member(BasePage):
def go_to_Manual_add(self):
# self.driver.find_element(MobileBy.XPATH, '//*[@text="手动输入添加"]').click()
self.clic... |
"""Setup for Office Mix XBlock."""
import os
from setuptools import setup
def package_data(pkg, roots):
"""Generic function to find package_data.
All of the files under each of the `roots` will be declared as package
data for package `pkg`.
"""
data = []
for root in roots:
for dirnam... |
# any work with the data file
# make a nicer csv to pull from
import pandas as pd
import gsw
# all of the parameters from the full data: 'Longitude [degrees_east]', 'Latitude [degrees_north]',
# 'PRESSURE [dbar]', 'DEPTH [m]', 'CTDTMP [deg C]', 'CTDSAL', 'SALINITY_D_CONC_BOTTLE', 'SALINITY_D_CONC_PUMP',
# 'SALINITY_D... |
#!/usr/bin/env python
#
# Copyright (c) 2013 In-Q-Tel, Inc/Lab41, 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... |
from time import sleep, time
import pytest
from distributed import Client
from dask_jobqueue import SGECluster
import dask
from dask.utils import format_bytes, parse_bytes
from . import QUEUE_WAIT
@pytest.mark.env("sge")
def test_basic(loop):
with SGECluster(
walltime="00:02:00", cores=8, processes=4, ... |
test = {
'name': '6.1',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like you did not follow the format
>>> # given in the problem. Maybe there's a typo?
>>> 'new_letter' in vars()
True
"""
},
{
'code':... |
import sqlite3
import os
def sql_connection():
"""
Establishes a connection to the SQL file database
:return connection object:
"""
path = os.path.abspath('PlaystoreDatabase.db')
con = sqlite3.connect(path)
return con
def sql_fetcher(con):
"""
Fetches all the with the given quer... |
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np
import constants as ct
class ThreeBarPlot():
def __init__(self, canvas, bar_color):
self.bar_color = bar_color
self.prepare(canvas)
def update(self, values=None, xmax=None):
... |
from .delaymatch import LetterDelayMatch
from .physionet import PhysioNetMI |
"""Checks for obsolete messages in PO files.
Returns an error code if a PO file has an obsolete message.
"""
import argparse
import sys
def check_obsolete_messages(filenames, quiet=False):
"""Warns about all obsolete messages found in a set of PO files.
Parameters
----------
filenames : list
... |
from HLTriggerOffline.HeavyFlavor.heavyFlavorValidationHarvesting_cfi import *
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
baseFolderPath = 'HLT/BPH/HLT/'
hfv1 = heavyFlavorValidationHarvesting.clone(
MyDQMrootFolder = cms.untracked.string(baseFolderPath + 'HLT_DoubleMu4_3_Bs_v')
)
hfv2 = heavyFlavor... |
"""
Revision ID: 0122_add_service_letter_contact
Revises: 0121_nullable_logos
Create Date: 2017-09-21 12:16:02.975120
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0122_add_service_letter_contact"
down_revision = "0121_nullable_logos"
def upgrade():
o... |
#!/usr/bin/env python3
""" Output a colorized list of listening addresses with owners.
This tool parses the output of ``netstat`` directly to obtain the list
of IPv4 and IPv6 addresses listening on tcp, tcp6, udp, and udp6 ports
also with pids of processes responsible for the listening.
The downside here is to obtai... |
import time
import subprocess
from collections import namedtuple,defaultdict
import logging
import json
import os
import yaml
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import threading
import numpy as np
import gym
from collections import deque
import random
import... |
import nltk
from nltk.stem.lancaster import LancasterStemmer
from nltk.tokenize import word_tokenize
from tensorflow.python.ops.gen_array_ops import expand_dims_eager_fallback
stemmer = LancasterStemmer()
import numpy
import tflearn
import random
import json
import tensorflow as tf
import pickle
import discord
impor... |
#!/usr/bin/env python
"""
.. script::
:language: Python Version 3.7.4
:platform: Windows 10
:synopsis: build basic tables in Postgres
.. moduleauthor:: Maura Rowell <mkrowell@uw.edu>
"""
# ------------------------------------------------------------------------------
# IMPORTS
# -------------------------... |
import json
'''
crash course on APM & PX4 flight modes:
APM:
Stabilize
Alt Hold
Loiter
RTL (Return-to-Launch)
Auto
Additional flight modes:
Acro
AutoTune
Brake
Circle
Drift
Guided (and Guided_NoGPS)
Land
PosHold
Sport
Throw
Follow Me
Simple and Super Simple
Avoid_ADSB for ADS-B based avoidance of manned aircraft. Shou... |
from code import interact
import optparse
import sys
import textwrap
from pyramid.compat import configparser
from pyramid.util import DottedNameResolver
from pyramid.paster import bootstrap
from pyramid.paster import setup_logging
from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
... |
import re
import pycurl
import cStringIO
import argparse
import json
import yaml
import datetime
import time
import multiprocessing
import certifi
from multiprocessing import Lock, Manager
from bs4 import BeautifulSoup
CPU_CORES = multiprocessing.cpu_count()
USCIS_URL = "https://egov.uscis.gov/casestatus/mycasestatus.... |
#!/usr/bin/env python2
from __future__ import print_function
import heart
import datetime
import time
import sys
import numpy as np
import argparse
import os
import stat
class recorder(heart.Heart_Monitor):
"""Command line tool that records the Arduino heart beat data into timestamped file"""
def __init__(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import torch
import horovod.torch as hvd
def broadcast_optimizer_state(optimizer, root_rank):
"""
This function is copied from the new... |
import testing
from testing import divert_nexus,restore_nexus,clear_all_sims
from testing import failed,FailedTest
from testing import value_eq,object_eq,text_eq
def test_import():
from rmg import Rmg,generate_rmg
#end def test_import
def test_minimal_init():
from machines import job
from rmg import R... |
from ._help import HelpCommandFactory
from ._unknown import UnknownCommandFactory
from ._usage import UsageAction |
from python_speech_features import mfcc
import scipy.io.wavfile as wav
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import os
import random
def load_noise(path='dat/_background_noise_/'):
noise = []
files = os.listdir(path)
for f in files:
filename = f
if ('w... |
#!C:\Users\HARETH\Desktop\eye-blink-detection-demo-master\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'... |
from django.contrib import admin
from .models import Snack
# Register your models here.
admin.site.register(Snack) |
import sys
import os
import tempfile
from multiprocessing import Pool
import datetime
import numpy as np
import matplotlib.style
import matplotlib
matplotlib.use('Agg')
from matplotlib.figure import Figure
from mpl_toolkits.axes_grid1 import make_axes_locatable
# To revert back to matplotlib 1.0 style
matplotlib.style... |
# testing/exclusions.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import contextlib
import operator
import re
import sys
from . import config
... |
from looptools import Timer
from tqdm import tqdm
from mysql.toolkit.utils import wrap
# TODO: Organize methods into database and table classes
# TODO: Fix issue where primary and foreign keys are not being copied
# TODO: New functionality to allow for dumping to file
class CloneData:
def get_database_rows(self, ... |
def mpm_sample():
print("hello, I am 'mpm_sample.py'.") |
def encryped_text(first_text, second_text, third_text):
encryped_text = ""
for i in third_text:
if i in first_text:
encryped_text += second_text[first_text.index(i)]
else:
encryped_text += i
return encryped_text
first_text = input()
second_text = input()
print(seco... |
# Copyright 2017 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 logging
import zmq
import sys
import time
import uptime
import pickle
from datetime import datetime
from os import path
try:
from gps_config import (init, GPS_TOPIC)
except ImportError:
raise Exception('failed to import init method')
sys.exit(-1)
def gen_gps_message():
return [
time.t... |
import wavio
import torch
import numpy as np
from specaugment import spec_augment_pytorch, melscale_pytorch
import matplotlib.pyplot as plt
PAD = 0
N_FFT = 512
SAMPLE_RATE = 16000
def trim(data, threshold_attack=0.01, threshold_release=0.05, attack_margin=5000, release_margin=5000):
data_size = len(data)
cut_... |
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print("Yay! Printing.")
print("I'd much rather you 'not'.")
print('I "said" do not touch this.') |
from test_env import TestEnv
import sys
import unittest
from pythran.typing import List
@TestEnv.module
class TestItertools(TestEnv):
@unittest.skipIf(sys.version_info.major == 3, "not supported in pythran3")
def test_imap(self):
self.run_test("def imap_(l0,v): from itertools import imap; return su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.