content stringlengths 5 1.05M |
|---|
import xml.etree.ElementTree as ET
import numpy as np
from gensim.models import Word2Vec
from utils.data_helper import clean_sentence
np.random.seed(26061997)
word_vector = Word2Vec.load('helper_files/word2vec/word2vec-dim300')
data = ET.parse('data/full.xml')
embedding_file_path = 'helper_files/embedding/generated... |
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from vaccine_scraper import VACCINE_COUNTRY_LIST
layout_vaccine = html.Div(className="data-page-container",
# id='output-layout',
children=[
html.Div(
... |
from django.shortcuts import redirect, render,HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth import logout,login
from django.contrib.auth.models import User
from django.contrib import messages
from .models import Message,Friend,Fileupload
from django.http import JsonResponse
# Creat... |
import csv
import json
with open("res/uiuc_demographics_2005_15.csv") as f:
reader = csv.DictReader(f)
data = [row for row in reader]
majors = {}
for row in data:
majorName = row["Major Name"].strip()
year = row["Fall"].strip()
degree = row["Degree"].strip()
# Skip empty rows
if majorName... |
from setuptools import setup
setup(
name="teapot",
version="0.0.1",
description="",
url="https://github.com/admiralobvious/teapot",
author="Alexandre Ferland",
author_email="aferlandqc@gmail.com",
license="MIT",
packages=["teapot"],
zip_safe=False,
install_requires=[
"ce... |
#Author: Gentry Atkinson
#Organization: Texas University
#Data: 10 December, 2020
#Just a toy file to figure out bokeh
from bokeh.plotting import figure, output_file, show, ColumnDataSource
import numpy as np
from bokeh.models import Button, CustomJS
from bokeh.layouts import column
from bokeh.io import curdoc
def bu... |
"""
Six namespaced tasks
"""
import os
from invoke import task
def get_six_path():
here = os.path.abspath(os.path.dirname(__file__))
return os.path.join(here, '..', 'six')
@task
def build(ctx, install_prefix=None, cmake_options=''):
six_path = get_six_path()
here = os.path.abspath(os.path.dirname(__... |
from decimal import Decimal
from typing import NamedTuple, Optional, Tuple, Union
BYTE = 1
# Binary
KIBIBYTE = BYTE * 1024
MEBIBYTE = KIBIBYTE * 1024
GIBIBYTE = MEBIBYTE * 1024
TEBIBYTE = GIBIBYTE * 1024
PEBIBYTE = TEBIBYTE * 1024
EXBIBYTE = PEBIBYTE * 1024
ZEBIBYTE = EXBIBYTE * 1024
YOBIBYTE = ZEBIBYTE * 1024
# SI
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: gtfs-realtime.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import List
import betterproto
class FeedHeaderIncrementality(betterproto.Enum):
FULL_DATASET = 0
DIFFERENTIAL = 1
class TripUpdateStopTimeUpd... |
from marshmallow import fields, Schema
class RunSchema(Schema):
id = fields.Int()
session = fields.Str(description='Session number')
acquisition = fields.Str(description='Acquisition')
subject = fields.Str(description='Subject id')
number = fields.Int(description='Run id')
duration = fields.Nu... |
import os
from datetime import timedelta
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secr... |
from xml.dom.minidom import Element
class Properties:
def __init__(self, testcase: Element):
self.__properties_tag_name = 'property'
self.__properties_iter = iter(testcase.getElementsByTagName(self.__properties_tag_name))
self.__current = None
print(f"INFO: Successfully extracted... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-20 11:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cadastro', '0006_evangelista_data_batismo_no_espirito_santo'),
]
operations = [
... |
#
# Copyright 2016 Quantopian, Inc.
#
# 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 in wr... |
from datetime import date
from layeredconfig import LayeredConfig, Defaults, Environment
from pypki.core.openssl_ca import run_cmd, run_cmd_pexpect, generate_password, opensslconfigfileparser, generate_certificate
from pypki.core.forms import config_form, usercert_form, servercert_form, bulkcert_form, revoke_form, repo... |
from flask import url_for
from app.db import Session
from app.models import User, ApiKey
def test_apple_process_payment(flask_client):
user = User.create(
email="a@b.c", password="password", name="Test User", activated=True
)
Session.commit()
# create api_key
api_key = ApiKey.create(user... |
# coding: utf-8
"""
Memsource REST API
Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis... |
import json
from argparse import Namespace
class Config(object):
'''创建一个配置类来管理系统的所有变量'''
def __init__(self, config_dict):
'''
Args:
config_dict: 配置文件转换生成的字典
'''
self.args = Namespace(**config_dict)
# 读取JSON格式的配置文件,并创建Config实例
@classmethod
def from_con... |
# Generated by Django 2.1.5 on 2019-02-01 12:18
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Productlar',
... |
"""A module for testing validator classes."""
import yaml
from tests import PROJECT_ROOT
from variation.tokenizers import Tokenize, GeneSymbol
from variation.tokenizers.caches import AminoAcidCache
from gene.query import QueryHandler as GeneQueryHandler
class ValidatorBase:
"""The validator base class."""
de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import torch
from torchknickknacks import metrics
model = torch.hub.load('pytorch/vision:v0.10.0', 'alexnet', pretrained = True)
data = torch.rand(64, 3, 224, 224)
output = model(data)
# This is just an example where class coded by 999 has more occure... |
import sys
from lib import is_palindrome
largest = 0
lx=0
ly=0
for x in range(100,999):
for y in range(100,999):
if(is_palindrome(int(x*y))):
if(largest< (int(x*y)) ):
largest = (int(x*y))
lx=x
ly=y
print(largest) |
from PIL import Image
try:
from io import BytesIO
except ImportError:
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
def resize_image(image, size, content_type, quality=98, file_path=None):
image.thumbnail(size, Image.ANTIAL... |
import os
import glob
import argparse
import configparser as confp
import ruamel.yaml as yaml
def parse_file(path):
"""Parse the INI file provided at the command line"""
parser = confp.ConfigParser(interpolation=None)
parser.optionxform = str
with open(path,'r') as config_file:
parser.rea... |
from __future__ import division
import numpy as np
array1= np.array([[1,2,3,4],[5,6,7,8]])
print array1
#multiplication
array2=array1*array1
print array2
#exp multiplication
array3=array1**3
print array3
#subtraction
array4=array1-array1
print array4
array5=array2 - array1
print array5
#reciprocal
print 1/arr... |
import cv2
from more_itertools import unique_everseen
import numpy as np
'''
##폴더 경로 설정
from tkinter import filedialog
from tkinter import *
root = Tk()
root.dirName = filedialog.askdirectory();
data_path = root.dirName
print(data_path)
### 폴더 열기
import os
path="D:\workspace\AceVision\Samsung\AAA"
path=os.path.rea... |
class DataGridViewBindingCompleteEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.DataBindingComplete event.
DataGridViewBindingCompleteEventArgs(listChangedType: ListChangedType)
"""
@staticmethod
def __new__(self, listChangedType):
""" __new__(cl... |
"""defines the MainWindow class"""
# coding: utf-8
# pylint: disable=C0111
# standard library
import sys
import os.path
import importlib
#import traceback
import webbrowser
#webbrowser.open("http://xkcd.com/353/")
from typing import Tuple, List, Optional
from pyNastran.gui.qt_version import qt_version
from qtpy impor... |
#Copyright 2010 Brian E. Chapman
#
#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 in writing, s... |
# MIT License
#
# Copyright (c) 2020 - Present nxtlo
#
# 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 use, copy, modify, mer... |
_SERVICES = {
"http": 80,
}
def get_port(scheme):
return _SERVICES[scheme]
if __name__ == '__main__':
import unittest
class Test(unittest.TestCase):
def test_http(self):
self.assertEqual(get_port("http"), 80)
def test_https(self):
self.assertEqual(get_port("ht... |
"""."""
import numpy as np
from ..optimization import PSO, SimulAnneal, GA
class SHBPSO(PSO):
"""."""
C = 299792458
E0 = 0.51099895e6
EMIN = E0 + 90e3
DRIFT = 615e-3
FREQUENCY = 499.658e6
WAVELEN = C/FREQUENCY
NPOINT = 51
BUN_LEN = np.pi
def initialization(self):
""... |
import os
import shutil
import json
import pytest
from archive import Archive
def test_archive_rar():
"""
Test extractall for rar arvhives
"""
path = os.getcwd()
file_path = 'tests/assets/rar.rar'
destination_path = ('tests/assets/extracted')
if not os.path.exists(destination_path):
... |
from django.core.management.base import BaseCommand
class BaseMonitorCommand(BaseCommand):
help = 'Base events, resource, and errors monitor.'
def add_arguments(self, parser):
parser.add_argument('--sleep_interval',
type=int,
default=1)
... |
#!/usr/bin/env python
#
# Code for dumping the bitcoin Berkeley db files in a human-readable format
#
from bsddb3.db import *
import logging
import sys
from address import dump_addresses
from wallet import dump_wallet, dump_accounts
from blkindex import dump_blkindex_summary
from transaction import dump_transaction
fr... |
# Stdlib imports
import os
import json
# Django imports
from django.conf import settings
from django.core.files import File
# Pip imports
from web3 import Web3
# App imports
from .contract import Contract
class VotingManagerContract(Contract):
def __init__(self, client, abi=None, address=None):
"""
... |
from unittest import TestCase
import pytest
from todo_sample.entities.todo import Todo
from todo_sample.use_cases.exceptions import TodoInvalidIdFormatException, TodoNotFoundException
from todo_sample.use_cases.get_todo import GetTodo
MODULE = "todo_sample.use_cases.get_todo"
class TestGetTodo(TestCase):
@pyte... |
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
import module
class Filters(commands.Cog):
def __init__(self, client):
self.client = client
self.bad_words = []
@commands.Cog.listener()
async def on_message(self,msg):
with open("src/b... |
from udp_server import UdpServer
def main():
server = UdpServer(5000)
server.startWork()
if __name__ == '__main__':
main()
|
from libs.config import alias, gget, gset, color
@alias(True, func_alias="sw")
def run():
"""
switch
(for input Non-ascii) Switch input between raw input and better input.
"""
switch = not gget("raw_input", default=False)
print(
f"\nRaw input: {color.green('On') if switch else color... |
import connexion
import six
from openapi_server import query_manager
from openapi_server.utils.vars import SOFTWARECONFIGURATION_TYPE_NAME, SOFTWARECONFIGURATION_TYPE_URI
from openapi_server.models.software_configuration import SoftwareConfiguration # noqa: E501
from openapi_server import util
def softwareconfigurat... |
import sqlite3
import os
FILE_PATH = os.path.abspath(os.path.join(os.getcwd(), "../.."))
DATA_PATH = os.path.join(FILE_PATH,'config')
async def connectDB(userid,uid = None,mys = None):
conn = sqlite3.connect('ID_DATA.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS UIDDATA
... |
import numpy as np
from dataset._shared import Dataset
def count(items, T=8, classes=5):
# Create initial value
X = np.random.uniform(0, classes, size=(items, 1))
# Create targe by incrementing
inc = np.tile(np.arange(0, T), (items, 1))
t = np.mod(X + inc, classes)
t = np.floor(t)
# add ... |
class Solution:
def toLowerCase(self, str: str) -> str:
string = ""
for idx in range(len(str)):
if str[idx].isupper():
string += str[idx].lower()
else:
string += str[idx]
return string
class Solution:
def toLowerCase(se... |
import os
import yaml
from env_alias.utils import logger
from env_alias.exceptions.EnvAliasException import EnvAliasException
class EnvAliasConfig:
debug = None
config = None
config_root = None
def __init__(self, config_root, debug=False):
self.debug = debug
self.config_root = conf... |
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com>
# ----------
#
# ----------
import typing
from .descriptors import Descriptor
class ServicesMap:
def __init__(self, services: typing.List[Descriptor]):
self._type_map: typing.Dict[type, typing.List[Des... |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import numpy as np
import matplotlib.pyplot as plt
from nn.module import Linear
from nn.loss import MSELoss
from tools.basic import *
a=50
b=10
x= np.random.uniform(-5,5,50).reshape((-1,1))
y = a * x + b +(... |
import pytest
from dagster import seven
@pytest.mark.skipif(seven.IS_WINDOWS, reason="docker doesn't work on windows tests")
def test_build_container(dagster_docker_image):
assert "buildkite-test-image-core" in dagster_docker_image
@pytest.mark.skipif(seven.IS_WINDOWS, reason="docker doesn't work on windows tes... |
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from .models import Book, Review
from .utils import average_rating
def book_list(request):
books = Book.objects.all()
book_list = []
for book in books:
reviews = book.review_set... |
import requests
import pandas as pd
import deepdish as dd
import os
import pickle
import warnings
from .analyze import analyze
from ..datageometry import DataGeometry
BASE_URL = 'https://docs.google.com/uc?export=download'
homedir = os.path.expanduser('~/')
datadir = os.path.join(homedir, 'hypertools_data')
datadict... |
# Copyright 2016-2020 Blue Marble Analytics LLC.
#
# 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 ag... |
import pandas as pd
import copy
from . import api
from datetime import datetime
from typing import Optional, List, Dict
class SearchAdsReporter:
api: api.SearchAdsAPI
verbose: bool = False
_date_format = '%Y-%m-%d'
def __init__(self, api):
self.api = api
def get_searchterms_report(self, start_date: da... |
__VERSION__ = '0.4.1'
|
{% extends 'estimation.py' %}
{% block estimation_method %}
model = smf.logit(formula="{{ formula }}", data=df).fit()
{% endblock %}
|
if __name__ == '__main__':
import keras as ks
import numpy as np
from agents.deep_sarsa import DeepSarsa
from environments.flappybird import FlappyBird
from q_network_sarsa_lambda import QNetworkSL
neural_network = ks.models.Sequential()
neural_network.add(ks.layers.Dense(150, activation='... |
import numpy as np
import cv2
import Person
import time
#Contadores de entrada y salida
cnt_up = 0
cnt_down = 0
#Fuente de video
#cap = cv2.VideoCapture(0)
cap = cv2.VideoCapture('peopleCounter.avi')
#Propiedades del video
##cap.set(3, 160) #Width
##cap.set(4, 120) #Height
# Imprime las propiedades de captura a con... |
import warnings
import locale
import re
import calendar
from contextlib import contextmanager, suppress
from datetime import datetime, timedelta
# from pipeline.util import Dimension
import urllib.parse
CIRCA = 5 # years
CIRCA_D = timedelta(days=365*CIRCA)
share_re = re.compile("([0-9]+)/([0-9]+)")
_COUNTRY_NAMES = ... |
import operator
import copy
from django.shortcuts import render, redirect
from django.views.generic.base import TemplateView
from .forms import SearchForm
from django.contrib.auth import get_user_model
from users.models import Speaker
from django.contrib.auth.decorators import login_required, user_passes_test
from pro... |
from django.conf.urls.defaults import *
local_media_url = 'statica'
urlpatterns = patterns('assetsy.django.views',
url(r'^%s/(?P<path>.*)$' % local_media_url, 'static_serve'),
) |
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from collections import defaultdict
from data import data_utils
parser = argparse.ArgumentParser(description=... |
# Generated by Django 3.2 on 2021-04-15 22:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_weathersource_name'),
]
operations = [
migrations.AddField(
model_name='newssource',
name='name',
... |
from cupy import zeros, dot, outer, array
from cupy.linalg import cholesky
def calculate_sigmas(x, dim_x, P, kappa):
sp = zeros((2*dim_x+1, dim_x))
sp[0] = array(x)
root = cholesky((dim_x+kappa)*P).T
sp[1:dim_x+1] = array(x) + root
sp[dim_x+1:2*dim_x+2] = array(x) - root
return sp
def unsce... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 14:46:37 2019
Vetor de cargas equivalentes a distrubuída da placa OK!
Carga de vento OK!!!
@author: markinho
"""
import sympy as sp
import numpy as np
from matplotlib import rcParams
rcParams['mathtext.fontset'] = 'stix'
rcParams['font.family'... |
def attach_callback(func, callback_name):
def notify(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
finally:
if callback_name == 'on_size_change':
self.on_size_change(self)
elif callback_name == 'on_item_change':
se... |
#
# This file is part of JKQ QMAP library which is released under the MIT license.
# See file README.md or go to http://iic.jku.at/eda/research/quantum_verification/ for more information.
#
import pickle
from pathlib import Path
from typing import Any, Dict, Union
from .pyqmap import map, Method, InitialLayoutStrategy,... |
# -*- coding: utf-8 -*-
"""Plugin for chaining Chrome downloads to filesystem and execution events."""
from timesketch.lib.analyzers.chain_plugins import interface
from timesketch.lib.analyzers.chain_plugins import manager
class ChromeDownloadFilesystemChainPlugin(interface.BaseChainPlugin):
"""A plugin to chain... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.core import signals
from indico.core.config import co... |
import numpy as np
from jina.executors.crafters import BaseCrafter
from jina.flow import Flow
from jina.proto import jina_pb2
class DummyCrafter(BaseCrafter):
def craft(self, *args, **kwargs):
return 1 / 0
def test_bad_flow(mocker):
def validate(req):
bad_routes = [r for r in req.routes if ... |
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from operators.load_dimension import LoadDimensionOperator
from helpers.sql_queries import SqlQueries
def loader_subdag(
parent_dag_name,
task_id,
redshift_conn_id,
table,
... |
# Copyright 2021 NREL
# 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 in writing, software
# distri... |
'''
Interpreters package contains classes of which instances are created for every
node in the document hierarchy.
@author: Teodor G Nistor
@copyright: 2018 Teodor G Nistor
@license: MIT License
'''
# Import interpreters from subpackages using specific names
from beamr.interpreters.textual import *
from bea... |
import torch.nn as nn
import torch
import math
from torch.nn import init
import torch.nn.functional as F
# 2D Conv
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes,
kernel_size=1, stride=stride, padding=0,
bias=False)
def conv2x2(in_pl... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import user_reco_pb2 as user__reco__pb2
class UserRecommendStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
chann... |
# settings.py
# Settings
# Author: Tim Schlottmann
from typing import Any
from .dicts import JsonDict
class Settings(JsonDict):
""" Settings of the app """
def __getitem__(self, setting_name) -> Any:
return super().__getitem__(setting_name)
def __setitem__(self, setting_name, setting):
super().__seti... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 08:54:59 2020
@author: Lucas
"""
print("Programa que calcula fatorial")
n = int(input("Digite o numero que quer saber o fatorial: "))
c = n
f=1
while c > 0:
print(f"{c}", end="")
print ("x" if c>1 else '=', end="")
f *= c
c -= 1
print (f"{f}") |
import collections
import itertools
import functools
import math
import re
import bisect
import random
rint = lambda: int(input())
rstr = lambda: input()
rints = lambda: list(map(int, input().split()))
rstrs = lambda: input().split()
wmat = lambda n, mat, sep: '{}\n{}'.format(n, '\n'.join(sep.join(map(str, row)) for r... |
from datetime import datetime
from tkinter.constants import *
from PIL import Image, ImageTk
from pyzbar.pyzbar import decode
from playsound import playsound
import sqlite3
import tkinter as tk
import argparse
import cv2
import os
import threading, time
class Application:
def __init__(self, output_path = "./"):
... |
"""Unit test helpers."""
# pylint: disable=too-few-public-methods
from functools import wraps
import gc
import os.path
from stenographer import CassetteAgent
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, maybeDeferred
from twisted.internet.task import Clock
from twisted.pyt... |
import requests
from bs4 import BeautifulSoup
YOUTUBE_TRENDING_URL = 'https://www.youtube.com/feed/trending'
# Doesnot execute Javascript and hence the data doesn't get loaded dynamically
response = requests.get(YOUTUBE_TRENDING_URL)
print('Status Code:', response.status_code)
#print('Output:', response.text[:1000... |
#!/usr/bin/env python3
import pandas as pd
import openpyxl
import re
df = pd.read_csv(snakemake.input.tsv,sep="\t",dtype=str)
c = pd.read_csv(snakemake.input.core_panel, header=None).iloc[:,0].to_list()
e = pd.read_csv(snakemake.input.extend_panel, header=None).iloc[:,0].to_list()
ped = pd.read_csv(snakemake.input.ped... |
from django.conf.urls import url
from cobra.core.application import Application
from cobra.core.loading import get_class
class SummaryApplication(Application):
name = 'summary'
def get_urls(self):
urls = [
]
return self.post_process_urls(urls)
application = SummaryApplication()
|
#!/usr/bin/env python
import pyami.fft.calc_fftw3
import fftw3
import numpy
import time
import os
import sys
timing = {'create':[], 'plan':[], 'init':[], 'run':[]}
def create(shape):
global timing
t0 = time.time()
a = numpy.empty(shape, numpy.float)
timing['create'].append(time.time() - t0)
return a
def make_p... |
"""
Name: job_base.py
Author: Charles Zhang <694556046@qq.com>
Propose: The main process of a grading.
Coding: UTF-8
"""
import json
import types
from pygrading.testcase import TestCases
from pygrading.exception import FunctionsTypeError, FieldMissingError, DataTypeError
class JobBase(object):
"... |
import os
from typing import Callable, List
import pickle
import multiprocessing as mp
from functools import partial
from .._logger import progress_bar
__all__ = [
'load_pickle',
'save_pickle',
]
def load_pickle(path: str):
"""
Load pickle from path.
Args:
path (str): Path to the pickle... |
#
# 1679. Max Number of K-Sum Pairs
#
# Q: https://leetcode.com/problems/max-number-of-k-sum-pairs/
# A: https://leetcode.com/problems/max-number-of-k-sum-pairs/discuss/962118/Kt-Js-Py3-Cpp-Map
#
from typing import List
class Solution:
def maxOperations(self, A: List[int], T: int, cnt = 0) -> int:
m = {}
... |
import random
from card import Card
class Deck:
def __init__(self):
self.cards = []
for number in range(1, 14):
for suit in '♣♦♥♠':
self.cards.append(
Card(
number=number,
suit=suit,
... |
from setuptools import setup
import sys
if sys.version_info < (3, 6):
print("Python 3.6 or higher required, please upgrade.")
sys.exit(1)
setup(
name="jaxfenics_adjoint",
version="1.0.0",
description="JAX-FEniCS interface using dolfin-adjoint",
url="https://github.com/IvanYashchuk/jax-fenics"... |
# -*- coding: utf-8 -*-
import pytest
from spectron import parse_date
@pytest.mark.parametrize("s, expected", [("", 0), ("a", 0), ("1", 1), ("a1b2", 2)])
def test_num_digits(s, expected):
assert parse_date.num_digits(s) == expected
@pytest.mark.parametrize(
"s, expected",
[
("test1digit", None... |
"""
Django settings for kboard project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
# 作者:longanyang
# 使用说明
# 1.终端安装python3和pandas库
# 2.将下载的csv文件命名为grafana_data_export.csv并放在此py同目录下 终端执行'python3 script.py'
# 3.已做去空处理
df = pd.read_csv('./grafana_data_export.csv', skiprows=[0]) # 忽略第一行
rows = df.shape[0]
while rows > 0:
... |
# modified file from
# https://github.com/nioinnovation/python-xbee/blob/master/xbee/ieee.py
import struct
from xbee.base import XBeeBase
from xbee.python2to3 import *
class XBeeWiFi(XBeeBase):
"""
Provides an implementation of the XBee API for IEEE 802.15.4 modules
with recent firmware.
Commands m... |
import unittest
import numpy as np
from scipy.integrate import cumtrapz
from skfda.datasets import make_gaussian, make_gaussian_process
from skfda.misc.covariances import Gaussian
from skfda.misc.operators import LinearDifferentialOperator
from skfda.misc.regularization import TikhonovRegularization
from skfda.ml.reg... |
#!/usr/bin/env python3
# This script generates radio/radio_446x_conf.h
#
# Silabs' WDS software allows to export a header file containing register values
# for a specific configuration of the radio. For our use we want to be able to
# switch between couple of those configurations. That's where this script comes in.
# ... |
"""
OpenVINO DL Workbench
Tool to reshape model to a new shape
Copyright (c) 2021 Intel Corporation
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/LICENS... |
## adopted from Aaron Sharp's code. Modified to work with tab delimited file.
import sys
if len(sys.argv) != 2:
print("USAGE: python revcomp_rdp_format.py RPD_MAPPING_FILE.txt > RPD_MAPPING_FILE_REV.txt")
sys.exit()
fh = open(sys.argv[1])
for lines in fh:
lines = lines.strip()
lexemes = lines.split('\t')
tags... |
import time
import model
from sqlalchemy import orm
from TrackedFile import *
class FilesDb(object):
def __init__(self, **kwargs):
self.dbfile = kwargs.get('dbfile', '.zeng.sqlite')
from sqlalchemy import create_engine
engine = 'sqlite:///' + self.dbfile
self.engine = create_en... |
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Timeline(models.Model):
RECEIVED = "RE"
TURNED_DOWN = "TU"
IN_EVALUATION = "EV"
REJECTED = "RJ"
IN_DEVELOPMENT = "DE"
DISCONTINUED = "DI"
COMPLETED = "CO"
STATUS_CHOICES = (
(RECEIVED, "Re... |
def filereader(filename):
hashes = {}
M = 0
f = open(filename)
N = int(f.readline())
imgs = {
'H': [],
'V': []
}
for i in range(N):
line = f.readline().split(" ")
n = int(line[1])
imgs[line[0]].append([None for _ in range(n+1)])
for j in rang... |
from ursina.application import pause, resume
from ursina.ursinastuff import destroy
from game import app
from ursina import *
from game import hand
from game.entities.menu import Menu, Exit, PlayGame
#from game.__init__ import voxel
its_menuopen = False
menu = None
exit = None
play = None
def update():
glob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.