content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python2
from sys import stdin
n = raw_input().split(' ')
k = int(n[1])
n = int(n[0])
ans = 0
for i in range(0, n):
t = int ( stdin.readline() )
if (t%k) == 0: ans += 1
print (ans)
|
"""
@Time : 2021/8/27 16:00
@Author : Haiyang Mei
@E-mail : mhy666@mail.dlut.edu.cn
@Project : CVPR2021_PDNet
@File : datasets.py
@Function:
"""
import os
import os.path
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch
import numpy as np
import torch.utils.data as d... |
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('conjuet/', include('account.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_UR... |
# coding: utf-8
from __future__ import absolute_import
import unittest
from flask import json
from openapi_server.dbmodels.organization import Organization as DbOrganization # noqa: E501
from openapi_server.test.integration import BaseTestCase
from openapi_server.test.integration import util
ID_QUERY = [("organiz... |
""" Finviz Comparison View """
__docformat__ = "numpy"
import logging
import os
from typing import List
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import export_data, print_rich_table
from openbb_terminal.rich_config import console
from openbb_terminal.stocks.comparison_ana... |
'''
A library for bringing together various components to interface with and analyze a "real" exported
safety project.
The function build_program_model() is the primary entry point to this module.
'''
from fbdplc.s7xml import parse_static_interface_from_file, parse_tags_from_file
from fbdplc.modeling import ProgramM... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author mybsdc <mybsdc@gmail.com>
@date 2020/10/12
@time 15:05
@issues
https://github.com/googleapis/python-firestore/issues/18
https://github.com/firebase/firebase-admin-python/issues/294
https://github.com/firebase/firebase-admin-python/issues/282
ht... |
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'user-name/$',
views.user_name,
name='user_name'),
url(r'approve/(?P<identifier>\w{10})/(?P<id>\d+)/$',
views.approve_immediately,
name='approve_immediately'),
url(r'remove/(... |
# Copyright (c) 2020, Zhouxing shi <zhouxingshichn@gmail.com>
# Licenced under the BSD 2-Clause License.
import os, json
res = {}
for dataset in ["yelp", "sst"]:
for num_layers in range(1, 4):
for ln in ["", "_no", "_standard"]:
dir = "model_{}_{}{}".format(dataset, num_layers, ln)
... |
# Copyright 2014-2019 The PySCF Developers. 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 appl... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
from django.urls import path
from .views import *
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('home',home, name="home"),
path('addproduct',addproduct, name="addproduct"),
path('productlist',ProductList.as_view(),name='productlist'),
path('edit/<pk>',... |
# Copyright 2016-2020 the GPflow 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 in ... |
"""
SOI Tax Data (soi_processing.py):
-------------------------------------------------------------------------------
Last updated: 6/29/2015.
This module creates functions for gathering and processing various SOI Tax
data into a NAICS tree.
"""
# Packages:
import os.path
import sys
import numpy as np
import pandas as... |
# ********************************************************************************** #
# #
# Project: FastClassAI workbecnch #
# ... |
# Copyright 2018 Google 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 writing, s... |
from typing import Dict
import pytest
import nest_asyncio
from mds.agg_mds import datastore
from unittest.mock import patch
from conftest import AsyncMock
# https://github.com/encode/starlette/issues/440
nest_asyncio.apply()
@pytest.mark.asyncio
async def test_aggregate_commons(client):
with patch.object(
... |
"""Bipartite.py
Two-color graphs and find related structures.
D. Eppstein, May 2004.
"""
import unittest
from sets import Set
from Biconnectivity import BiconnectedComponents
import Graphs
import DFS
class NonBipartite(Exception):
pass
def TwoColor(G):
"""
Find a bipartition of G, if one exists.
Rai... |
from bitmath import GiB
from bitmath import MiB
class Album:
def __init__(self,
artist,
album,
url,
band_url='',
slug_text='',
num_comments=0,
tralbum_id=0,
art_id=0,
... |
import calendar as cal
import os
import tempfile
import zipfile
import logging
import fiona
from shapely import geometry
import seaice.nasateam as nt
log = logging.getLogger(__name__)
OCEAN = 0
ICE = 1
COAST = nt.FLAGS['coast']
LAND = nt.FLAGS['land']
MISSING = nt.FLAGS['missing']
def _clim_string(range):
ret... |
from syft import node
from syft.message import execute_capability
import numpy as np
port = 50051
iface = "0.0.0.0"
target_addr = f"http://{iface}:{port}"
remote_caps = node.request_capabilities(target_addr)
print(f"Node at: {target_addr} has capabilities: {remote_caps}")
message = execute_capability(target_addr, "... |
string = "The b";
count = 0;
for i in range(0, len(string)):
if(string[i] != ' '):
count = count + 1;
print("Total number of characters in a string: ",count); |
import requests
import json
import config
class dns:
api_token: str
email : str
zoneid : str
dnsrecords : json
def __init__(self, API_TOKEN: str, EMAIL: str, ZONE_ID: str):
self.api_token = API_TOKEN
self.email = EMAIL
self.zoneid = ZONE_ID
def get_dnsrecords(self) -> None:
# Initialize your dns re... |
from .control import common_process, interactive_process, CommonProcess, InteractiveProcess, TimingContent, common_run, \
timing_run, mutual_run, ProcessResult, RunResult, RunResultStatus, ResourceLimit, Identification
from .entry import DispatchRunner, load_pji_script
from .service import DispatchTemplate, Dispatc... |
import boto3
from config.constants import DEFAULT_S3_RETRIES
from config.settings import (S3_BUCKET, BEIWE_SERVER_AWS_ACCESS_KEY_ID,
BEIWE_SERVER_AWS_SECRET_ACCESS_KEY, S3_REGION_NAME)
from libs import encryption
class S3VersionException(Exception): pass
conn = boto3.client('s3',
aws_access_k... |
coffee_src_type = [".coffee"]
cjsx_src_type = [".cjsx", ".coffee"]
def _cjsx_compile_dir(ctx, dir, srcs, generate_dts):
"""
Compiles a single directory of JSX/CoffeeScript files into JavaScript files.
"""
out_dir = ctx.configuration.bin_dir.path + "/" + dir
arguments = [out_dir]
outputs = []
... |
import docutils.frontend
import docutils.parsers.rst
import docutils.utils
import pyautogui
import pynput.keyboard as kb
import queue
import subprocess as sp
import threading
import time
slide = 0
slides = [
'''
# Give the Gift of Python
## Grant Jenks
# 1. Python trainer for Fortune 100 companies.
# 2. Married to ... |
"""
Test cases for the wiutils.summarizing.compute_count_summary function.
"""
import numpy as np
import pandas as pd
import pytest
from wiutils.summarizing import compute_count_summary
@pytest.fixture(scope="function")
def images():
return pd.DataFrame(
{
"deployment_id": [
"... |
import numpy as np
import pandas as pd
import json
import argparse
def convert_factors_to_numeric(dataset):
# DATASET
with open('../Configs/'+dataset+'.json') as config_file:
config = json.load(config_file)
dataset = pd.read_csv('../Data/'+config['filtered_data_with_headers'], header = 0)
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 15:22:29 2022
@author: tonifuc3m
"""
import argparse
import warnings
import livingner_app
import livingner_ner_norm
def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
return '%s:%s: %s: %s\n' % (filename, l... |
import os
import time
import json
import sys
import shutil
def write_file(base_dir, filename, text):
path = "{}/out/data/{}".format(base_dir, filename)
with open(path, "w") as out:
out.write(text)
def write_event(base_dir, filename, event):
path = "{}/out/events/{}".format(base_dir, filename)
... |
import contextlib
import sqlite3
from typing import Iterator
class RDB:
def __init__(self, database: str, table: str, schema: str):
self.con = sqlite3.connect(database)
self.table = table
self.schema = schema
self.initialize()
def initialize(self):
"""テーブルの初期化"""
... |
# Season - Fall 2016
# Week Date Time Ice Home Team Away Team Home Score Away Score Shootout Clock Operator Disc Jockey First Star Second Star Third Star
# Week 1 9/12/2016 09:00 PM Olympic North Stars Nordiques 1 2 False Todd ... |
import json
import numpy as np
from pypokerengine.players import BasePokerPlayer
from treys import Card
import os
from sample_player.tools.models import load
from sample_player.tools.utils import hand_strength_estimation, hand_strength_estimation_with_time
def save_board_in_tab_and_return_equity(nb_players, saved_ta... |
"""Displays the metrics of Keras History dictionaries in folder 'Data/NNResults'.
"""
import pickle
import matplotlib.pyplot as plt
# ************************* Config *************************************
# Choose wether custom metrics like TPR or MCC were calculated during training.
custom_metrics = False
# Set thi... |
'''
Joe Walter
difficulty: 20%
run time: 0:00
answer: 1322
***
064 Odd Period Square Roots
How many continued fractions of sqrt(n) for n≤10000 have an odd period?
'''
# https://en.wikipedia.org/wiki/Periodic_continued_fraction#Canonical_form_and_repetend
from math import isqrt
def nonsquare(m):
n = 2
wh... |
from django_filters import (
CharFilter,
FilterSet,
NumberFilter,
CharFilter,
OrderingFilter,
)
from graphene import relay, ObjectType
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from coordinator.api.models.task import Task
cla... |
from enum import Enum
class AdminOperation(Enum):
CREATE = 0
UPDATE = 1
DELETE = 2
class AdminItemType(Enum):
Announcement = "announcement"
QueryEngine = "query_engine"
QueryMetastore = "query_metastore"
Admin = "admin"
Environment = "environment"
Task = "task"
|
import torch
from torch.autograd import Variable
from .lazy_variable import LazyVariable
class ConstantMulLazyVariable(LazyVariable):
def __init__(self, lazy_var, constant):
if not isinstance(constant, Variable):
tensor_cls = lazy_var.tensor_cls
constant = Variable(tensor_cls(1).fi... |
from django.urls import reverse
from wagtail.images.views.serve import generate_signature
def generate_image_url(image, filter_spec='original'):
"""Return generated URL for image."""
signature = generate_signature(image.id, filter_spec)
url = reverse('wagtailimages_serve', urlconf='wagtail.images.urls', a... |
# this defines the input size of the images we will be feeding into our model
target_size = 28
# create an instance of a sequential model
model = models.Sequential()
# first block of convolutional layers
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(target_size, target_size, 1)))
model.a... |
from math import pi,sin,cos,acos
def dis(lat1,long1,lat2,long2):
'''Calculates the distance from a second airport and returns it as a float'''
r_earth=6378.1
theta1=long1*(2*pi)/360
theta2=long1*(2*pi)/360
phi1=(90-lat1)*(2*pi)/360
phi2=(90-lat2)*(2*pi)/360
... |
""" All command line related exceptions """
# standart python imports
import logging
import sys
# 3rd party imports
import click
# Creates a ClickLogger
logger = logging.getLogger(__name__)
class Two1Error(click.ClickException):
"""
A ClickException with customized formatting.
"""
def __init__(sel... |
#! /usr/bin/env python
"""
Variables that are shared between modules
"""
import sys
import codecs
version = ""
scriptPath = ""
scriptName = ""
mediaInfoExe = ""
mets_ns = ""
mods_ns = ""
premis_ns = ""
ebucore_ns = ""
xlink_ns = ""
xsi_ns = ""
isolyzer_ns = ""
cdInfo_ns = ""
dfxml_ns = ""
dc_ns = ""
hfs_ns = ""
metsS... |
import torch
def save_checkpoint(save_dir, model, optimizer):
torch.save({'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()}, save_dir)
return True
def load_checkpoint(load_dir):
checkpoint = torch.load(load_dir)
return checkpoint
|
from pyspark.mllib.feature import Word2Vec
from xframes.spark_context import CommonSparkContext
class TextModel(object):
def __init__(self, model):
self.model = model
def find_associations(self, word, num=10):
return self.model.findSynonyms(word, num)
class TextBuilder(object):
def __ini... |
print(int(5.5))
|
import numpy as np
import netCDF4 as nc
|
#!/usr/bin/env python3
def good(sol):
n = len(sol)
for i in range(n):
for j in range(i+1,n):
dy = sol[i]-sol[j]
dx = i-j
if dy==0: return False
if dy==dx or dy==-dx: return False
return True
def solve(n,m=3):
tot = n**n
sol = [0]*n
cnt = ... |
import os
class Config:
def __init__(self, recipe):
self.recipe = recipe
self.app_dir = os.path.abspath(self.recipe.get_item('AppDir/path'))
self.arch = self.recipe.get_item('AppDir/yum/arch')
self.include_list = self.recipe.get_item('AppDir/yum/include')
self.exclude_lis... |
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
import numpy as np
import collections, random
# Hyperparameters
lr_pi = 0.0005
lr_q = 0.001
init_alpha = 0.01
gamma = 0.98
batch_size = 32
buffer_limit = 50000
tau = 0.01 # ... |
def section1():
import dtlpy as dl
# Get project and dataset
project = dl.projects.get(project_name='project_name')
dataset = project.datasets.get(dataset_name='dataset_name')
def section2():
item.metadata['user']['MyKey'] = 'MyValue'
annotation.metadata['user']['MyKey'] = 'MyValue'
def sect... |
""" Serializers for the Transaction Logging API """
from rest_framework import serializers
from .models import TransactionRecord
class TransactionRecordSerializer(serializers.ModelSerializer):
""" Serializer for TransactionRecord objects """
class Meta:
""" TransactionRecordSerializer Django Metadata... |
import math
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, no):
return Points((self.x-no.x), (self.y-no.y), (self.z-no.z))
#dot product
def dot(self, no):
return (self.x*no.x)+(self.y*no.y)+(self.z*no.z)
... |
def test_range():
simple = list(range(0, 10))
results = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
assert simple == results
def test_range_with_steps():
with_steps = list(range(0, 10, 2))
results = [0, 2, 4, 6, 8]
assert with_steps == results
def test_range_with_negative_steps():
with_steps = list(r... |
import argparse
import os
import functools
import time
import subprocess
from augmentation.utilities.config import *
from augmentation.utilities.metrics import *
from augmentation.datasets.utils import get_processed_dataset_info, apply_modifier_to_dataset_payload, load_dataset
from augmentation.dataflows.utils import d... |
"""
Compile SMIv2 MIBs
++++++++++++++++++
Invoke user callback function to provide MIB text,
compile given text string into pysnmp MIB form and pass
results to another user callback function for storing.
Here we expect to deal only with SMIv2-valid MIBs.
We use noDeps flag to prevent MIB compiler from attemping
to c... |
import os
import queue
import cv2
import numpy as np
from PIL import Image, ImageDraw
import csv
import sys
try:
input_video_path = sys.argv[1]
input_csv_path = sys.argv[2]
#output_video_path = sys.argv[3]
if (not input_video_path) or (not input_csv_path):
raise ''
except:
print('usage: python3 show_trajectory.... |
"""tests/test_dataframe.py module."""
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
from talus_utils import dataframe
from talus_utils.fasta import parse_fasta_header_uniprot_protein
DATA_DIR = Path(__file__).resolve().parent.joinpath("d... |
##
# movie_reccomendation.py
# Created: 29.08.19
# Last edit: 06.09.19
# A program that reccommends movies based on an algorithm and other users
from tkinter import *
import tkinter as tk
class GUI:
def __init__(self, parent):
self.parent = parent
# Frames
self.search_fram... |
'''
Descripttion:
version:
Author: Jinlong Li CSU PhD
Date: 2022-01-04 10:58:11
LastEditors: Jinlong Li CSU PhD
LastEditTime: 2022-01-04 17:06:05
'''
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# from ._utils import _C
# from maskrcnn_benchmark import _C
from ._utils import _C
from apex i... |
# coding=utf-8
from random import randint
array = []
cont = 0
while cont <= 7:
array.append(randint(0,100))
cont += 1
else:
print("Numeros Gerados com sucesso! \n{} \nFim da execução!" .format(array))
|
# Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
#
# This file is part of Aspose.Words. The source code in this file
# is only intended as a supplement to the documentation, and is provided
# "as is", without warranty of any kind, either expressed or implied.
import aspose.words as aw
import aspose.pydra... |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
DataType,
FloatType,
)
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class RiskAssessment_PredictionSchema:
""... |
from gwa_framework.resource.base import BaseResource
from gwa_framework.utils.decorators import validate_schema
from common.models.goal import GoalModel
from common.repositories.goal import GoalRepository
from common.schemas.goal import GoalInputSchema, GoalOutputSchema
class GoalResource(BaseResource):
method_d... |
from schema import Schema, Optional, SchemaError
from exceptions import RoutificParamsError
"""
Defines and validates visits, which are locations that must be visited.
"""
VISIT_SCHEMA = Schema({
"location": {
"lat": float,
"lng": float,
Optional("name"): str
},
Optional("start... |
"""
TorchScript implementation of the low-level push/pull utilities.
The idea is to eventually have an alternate implementation that does not
require compiling C++/CUDA code. The compiled version could still be
installed [optionally] by the setup script, since it is expected to be
much faster than the TorchScript versi... |
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
import numpy as np
import pandas as pd
import os
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
fig_path = 'H:/py4fi/images/ch08/'
if not os.path.exists(fig_path):
os.makedirs(fig_path)
raw = pd.read_csv('tr_eikon_eod_data.csv', index_col=0, parse_dates=True)
data = raw... |
__author__ = "Rodrigo Yamamoto"
__date__ = "2021.Mar"
__credits__ = ["Rodrigo Yamamoto"]
__maintainer__ = "Rodrigo Yamamoto"
__email__ = "codes@rodrigoyamamoto.com"
__version__ = "version 0.1.8.9"
__license__ = "MIT"
__status__ = "development"
__description__ = "A simple and concise gridded data IO library for read mul... |
def jdt(i,alln):
ii=alln//10
if ii>0:
iii=i
iiii=alln
i=i//ii
alln=10
print("[%s>%s] %u/%u"%("="*i," "*(alln-1-i),iii,iiii-1) , end = '\r')
print("="*50)
print("made in china?")
print("="*50)
forcs = int(input("please tape the cishu"))
a = 0
b = 1
list = []
for i in range (forcs):
jdt(i,forcs)
a,b=b,a+b... |
from app.content.models.badge import Badge
from app.content.models.category import Category
from app.content.models.cheatsheet import Cheatsheet
from app.content.models.event import Event
from app.content.models.news import News
from app.content.models.user import User, UserManager
from app.content.models.user_badge im... |
from flask import Flask, request, Response
from flask_cors import CORS
import drone_awe
import json
import copy
import traceback
import utilities
'''
Notes:
- Need to disable plotting in the library
- if possible remove matplotlib entirely from the library
- if possible remove gekko object from a.output in... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
import unittest
from mbed_tools_lib.python_helpers import minimum_python_version, named_tuple_with_defaults
class TestPythonHelpers(unittest.TestCase):
def test_python_version(self):
# Tools only support Python>... |
import random
Column = []
for x in range(ord('A'),ord('I')+1):
Column.append(chr(x))
print(Column)
Rows = [None]*9
Game = [[0 for i in range(len(Column))] for j in range(len(Rows))]
print(Game,'\n')
mX = len(Game[0])
mY = len(Game)
print(mX)
print(mY,'\n')
Bombs = []
mB = _mB = 10
while mB>0:
ran = (... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-02 17:06
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import ... |
# https://www.shadertoy.com/view/stdGzH
import taichi as ti
ti.init()
res_x = 1024
res_y = 576
pixels = ti.Vector.field(3, ti.f32)
ti.root.dense(ti.i, res_x).dense(ti.j, res_y).place(pixels)
@ti.kernel
def render(t :ti.f32):
for i, j in pixels:
color = ti.Vector([0.0, 0.0, 0.0])
u... |
from collections import deque
from .tst import TernarySearchTree
from .corpustools import extract_fields, ContainsEverything
class LanguageModel():
"""N-gram (Markov) model that uses a ternary search tree.
Tracks frequencies and calculates probabilities.
Attributes
----------
n : int
Size... |
#!/usr/bin/env python
from __future__ import print_function, division
import argparse
import rospy
from tf import transformations
import tf2_ros
import numpy
from StringIO import StringIO
from std_msgs.msg import String
from visualization_msgs.msg import Marker, MarkerArray
from ihmc_msgs.msg import FootstepDataList... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 the AAS WorldWide Telescope project
# Licensed under the MIT License.
from __future__ import absolute_import, division, print_function
import pytest
from . import test_path
from .. import collection
try:
from astropy.io import fits
HAS_ASTRO = True
excep... |
import numpy as np
import time
from copy import deepcopy
from functools import partial, reduce
from itertools import product
from collections.abc import Mapping, Sequence, Iterable
import operator
from simulation.model.epidemic import Epidemic
class ParameterSearch:
"""Gradient-based search to estimate network ch... |
# inclass/elephant.py
# Not sure why, but the .env file dissapeared.
# I would recreate it, but I don't want to confuse
# Python when it goes to run the other files in the
# inclass folder.
import os
import psycopg2 as psycho
from dotenv import load_dotenv
load_dotenv()
DB_NAME = os.getenv("DB_NAME", "Invalid DB_NA... |
import uuid
from pprint import pformat
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import pandas as pd
from .utils import add_default_to_data
from .utils import create_db_folders
from .utils import dump_cached_schema
from .utils import dump_db
from .utils impor... |
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('after845'):
after845 = "Y"
else:
after845 = "N"
if form.getvalue('noisyCats'):
noisyCats = "Y"
else:
noisyCats = "N"
if form... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
from typing import final
from weakref import WeakKeyDictionary, WeakValueDictionary
_combined_metaclasses = WeakValueDictionary()
def combine(*classes: type):
# Order of bases matters
# (A, B) and (B, A) different base tuples which lead to different MRO
# So combined classes of these bases are different
... |
#MenuTitle: Tab with compound glyphs
# -*- coding: utf-8 -*-
__doc__="""
Based con mekablue's "New Edit tab with compound glyphs".
"""
import GlyphsApp
Doc = Glyphs.currentDocument
Font = Glyphs.font
FontMaster = Font.selectedFontMaster
selectedLayers = Font.selectedLayers
editString = ""
Output = ""
for thisLayer ... |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2020, Maximilian Köhl <koehl@cs.uni-saarland.de>
import dataclasses as d
import typing as t
import fractions
import pathlib
import subprocess
import tempfile
import re
from .. import model
from ..analysis import checkers
from ..jani import dump_model
from .errors import Tool... |
from . import generic
from .generic import *
from . import kafka
from .kafka import *
from . import csv
from .csv import *
from . import avro_file
from .avro_file import *
from . import json
from .json import *
|
import locale
import sys
from os.path import dirname, join, realpath
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.signal import resample
from base.config_loader import ConfigLoader
from base.data.dataloader import TuebingenDataloader
def alternate_signal_ww(signals, sample_left, sample... |
import simtk.openmm as mm
import simtk.unit as unit
import openmmnn as nn
import tensorflow as tf
import unittest
class TestNeuralNetworkForce(unittest.TestCase):
def testFreezeGraph(self):
graph = tf.Graph()
with graph.as_default():
positions = tf.placeholder(tf.float32, [None, 3], 'p... |
import typing
import pytest
from testsuite import annotations
from testsuite.mockserver import server
from testsuite.utils import callinfo
from testsuite.utils import http
TestpointHandler = typing.Callable[
[annotations.JsonAnyOptional],
annotations.MaybeAsyncResult[annotations.JsonAnyOptional],
]
Testpoin... |
#!/usr/bin/env python
# Copyright 2016 Melomap (www.melomap.com)
#
# 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 app... |
from numpy import tan, cos, sin, linspace
from scipy.optimize import root
def fun(x):
return tan(x) + 2*x
def jac(x):
return 1/cos(x)**2 + 2
sols = set()
for x0 in linspace(0, 1000, 1e6):
ans = root(fun, [x0], jac=jac, method='hybr')
sols.add(ans.x[0])
print(sorted(list(sols)))
|
# Generated by Django 2.1.4 on 2019-01-12 03:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parser_app', '0008_auto_20181230_0303'),
]
operations = [
migrations.AddField(
model_name='resume',
na... |
def list_join(list, conjunction_str, format_func=str, oxford_comma=True):
'''
Joins a list in a grammatically-correct fashion.
:param list:
the list to join.
:param conjunction_str:
the string to use as conjunction between two items.
:param format_func:
a function that takes... |
from _initdef import *
|
import os
import shutil
import numpy as np
import glob
import xml.etree.ElementTree as ET
import pandas as pd
def randCpFiles(src, destn, ratio=0.8, createDir=True, ext='', fileFilter=None):
# TODO - can let the user pass in the "ext" filter in the fileFilter too. THis will
# make the function more general.
... |
import os
from tabulate import tabulate
from transformers import AutoTokenizer, AutoConfig
class InputLM():
def __init__(self, lm_path, max_length) -> None:
self.max_length = max_length
self.tokenizer = AutoTokenizer.from_pretrained(
lm_path, model_max_length=max_length)
def __call... |
from keras.models import load_model
import signal_data
import tensorflow as tf
train, test = signal_data.load_data()
features, labels = train
featuresT, labelsT =test
featuresarr=featuresT.__array__(dtype=int);
model = tf.keras.models.load_model("keras_modelv3.h5")
pred = model.predict(featuresarr)
print(pred) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.