text stringlengths 957 885k |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
"""
Chat program
ROSPEEXから
入力された文章を使い、DoCoMoAPIで会話する
The project is hosted on GitHub where your could fork the project or report
issues. Visit https://github.com/roboworks/
:copyright: (c) 2015 by Hiroyuki Okada, All rights reserv... |
import sys
import os
import logging
import matplotlib.pyplot as plt
from numpy import median, zeros, nan, nanmedian, sqrt, mean, std, loadtxt, linspace, \
zeros_like, divide, asarray
from astropy.constants import G, R_sun, M_sun, R_jup, M_jup, R_earth, M_earth
from astropy.coordinates import SkyCoord
from pathlib i... |
<filename>src/args.py
import os
import re
import argparse
import json
import pydash as _
import fs
import handlebars
from configure import fake_config
def parse():
# Instantiate the parser
parser = argparse.ArgumentParser(description='savetube: apply your youtube metadata to id3 tags')
parser.add_argument(
... |
import re, sys, numpy, math
from collections import Counter
from scipy.sparse import lil_matrix
import scipy.sparse.linalg
doc_counters = []
corpus_counts = Counter()
doc_text = []
print ("reading")
# for TF-IDF
document_frequency = Counter()
with open(sys.argv[1], encoding="utf-8") as reader:
for line in reade... |
import copy
import pickle
import os
DEBUG = False
MIN_PROB = 1e-12#float('-inf')
# amount the value is allowed to be off for convergence
# the smaller the longer the training takes
EPSILON = 1.0e-9
# test if the two sets are equivalent
def is_converged(t, last_t):
for (e_j, f_i) in t.keys():
if abs(t[(e_j, f_i)] ... |
<filename>src/mainwindow/__init__.py
from PyQt4 import QtGui
from ags_service_publisher.runner import Runner, root_logger
from ags_service_publisher.logging_io import setup_logger
from aboutdialog import AboutDialog
from helpers.arcpyhelpers import get_install_info
from helpers.pathhelpers import get_app_path, get_con... |
<gh_stars>0
import hashlib
import multiprocessing
import os
import platform
import psutil
import socket
import subprocess
import sys
def collect_ci_info():
d = dict()
# Test for jenkins
if "BUILD_NUMBER" in os.environ:
if "BRANCH_NAME" in os.environ or "JOB_NAME" in os.environ:
br = os... |
import logging
import datetime
import json
logger = logging.getLogger(__name__)
from stix2patterns_translator.pattern_objects import ObservationExpression, ComparisonExpression, \
ComparisonExpressionOperators, ComparisonComparators, Pattern, \
CombinedComparisonExpression, CombinedObservationExpression, Obse... |
from . import abbr_patterns as ap
area_ptrn = r"\b(ha|(f(er)?|rúm)[pnµmcsdk]?m\b\.?)|[pnµmcsdk]?m[²2³3]"
def make_area_dict():
area_dict = {"((\W|^)(" + ap.accdatgen_words_comb + ") ((\d{1,2}\.)?(\d{3}\.?)*(\d*1|\d,\d*1))) ha\.?(\W|$)": "\g<1> hektara\g<14>",
"((\W|^)(" + ap.accgen_words + ") ((\d... |
import os
import lib.warning as warning
from amino.socket import Callbacks
from lib.logger import log
from lib.obscene import Obscene
import time
import datetime
import random
class MessageHandler(Callbacks):
def __init__(self, client, selected_chats):
"""
Build the callback handler.
This... |
<filename>EU_Open_Spending_Visualization/data/datacleaning.py
import csv
import json
data = []
delimiter = ','
# for each year the same procedure applies:
# remove rows with data that we will not use (for now)
# check each cell if it is empty or only a space > return "missing"
# check each cell if it is multiline, mer... |
"""
Tools for running CMake in setup phase
"""
__all__ = [
"CMakeExtension",
"CMakeBuild",
"find_package",
"WITH_CMAKE",
]
import argparse
import os
import subprocess
from tempfile import TemporaryDirectory
from setuptools import Extension
from setuptools.command.build_ext import build_ext
from .raise... |
<reponame>baishancloud/mysql-devops
#!/usr/bin/env python2
# coding: utf-8
import copy
import unittest
from pykit import utfjson
from pykit import ututil
from pykit.ectypes import (
BlockDesc,
BlockExists,
BlockGroup,
BlockGroupID,
BlockID,
BlockNotFoundError,
BlockTypeNotSupportReplica,
... |
<filename>paprika/actions/tripolis/SendEmail.py
from paprika.actions.Actionable import Actionable
from paprika.repositories.ProcessActionPropertyRepository import ProcessActionPropertyRepository
from paprika.repositories.ProcessPropertyRepository import ProcessPropertyRepository
from paprika.repositories.ProcessReposit... |
<gh_stars>0
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.signal import find_peaks
import csv
import os
def find_vel(i,x_list,y_list):
if i < 1 or i >= len(x_list):
return 0
if (x_list[i-1] == 0 and y_list[i-1] == 0) or (x_list[i] == 0 and y_list[i] == 0):
return 0
... |
# USAGE
# python neural_style_transfer_video.py
# during the process :
# press 'q' to quit
# press 'n' for next model
# press 'a' for auto models rotation switch (on/off)
# press 'l' to hide/display the legend
# press 's' to save the picture
# import the necessary packages
from helpers import SimpleDatasetRe... |
<filename>custom_widgets/navigation/navbutton/navbutton.py
from enum import Enum
from PySide2.QtGui import QPainter, QColor, QPixmap, QPen, QPolygon, QBrush
from PySide2.QtCore import QEnum, QSize, Qt, QRect, QPoint, QEvent
from PySide2.QtWidgets import QApplication, QPushButton
class NavButton(QPushButton):
"""... |
<filename>arosics/CoReg_local.py
# -*- coding: utf-8 -*-
# AROSICS - Automated and Robust Open-Source Image Co-Registration Software
#
# Copyright (C) 2017-2021
# - <NAME> (GFZ Potsdam, <EMAIL>)
# - Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences Potsdam,
# Germany (https://www.gfz-potsdam.de/)... |
<filename>square/api/v1_items_api.py
# -*- coding: utf-8 -*-
from deprecation import deprecated
from square.api_helper import APIHelper
from square.http.api_response import ApiResponse
from square.api.base_api import BaseApi
from square.http.auth.o_auth_2 import OAuth2
class V1ItemsApi(BaseApi):
"""A Controller... |
<reponame>robmarkcole/London-Air-Quality<gh_stars>1-10
from datetime import timedelta
import requests
from typing import List, Dict
AUTHORITIES = [
"<NAME>",
"Barnet",
"Bexley",
"Brent",
"Bromley",
"Camden",
"City of London",
"Croydon",
"Ealing",
"Enfield",
"Greenwich",
... |
<filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by <NAME> (http://www.dwerg.n... |
<reponame>DrackThor/artifactory-cleanup
import importlib
import logging
import sys
from datetime import timedelta, date
import requests
from hurry.filesize import size
from plumbum import cli
from prettytable import PrettyTable
from requests.auth import HTTPBasicAuth
from artifactory_cleanup.context_managers import ge... |
<reponame>simonchuth/patentAI
import datetime
from tqdm import tqdm
import pickle
import requests
import PyPDF2
import io
from os import listdir
from os.path import join
def generate_datelist(numdays=3650, date_list=None):
if date_list is None:
base = datetime.datetime.today()
date_list = [base - ... |
import re
import options
from utils import basetypes
import sys
import collections
from enum import IntEnum
from exprs import exprs
from exprs import exprtypes
import math
import heapq
import functools
from core import grammars
from enumerators import enumerators
from parsers import parser
from semantics import semanti... |
import ckan.model as model
from ckan.tests import *
from ckan.lib.base import *
import ckan.authz as authz
from test_edit_authz import check_and_set_checkbox
class TestPackageEditAuthz(TestController):
@classmethod
def setup_class(self):
# for the authorization editing tests we set up test data so:
... |
import random
from typing import Type, Dict, Tuple
import cv2
import numpy as np
import pytest
from albumentations import (
RandomCrop,
PadIfNeeded,
VerticalFlip,
HorizontalFlip,
Flip,
Transpose,
RandomRotate90,
Rotate,
ShiftScaleRotate,
CenterCrop,
OpticalDistortion,
G... |
<gh_stars>0
'''
File to store the Crystal class
Attributes
- molecules; list; list of all of the molecule objects in the crystal
Methods
- add_molecule(Molecule); return None; appends a Molecule object to molecules list
- add_molecules(list); return None; iterates through list of Molecule objects and appends them to mo... |
try:
import mysql.connector
from mysql.connector import Error
from zcrmsdk.src.com.zoho.api.authenticator.store.token_store import TokenStore
from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken
from zcrmsdk.src.com.zoho.crm.api.util.constants import Constants
from zcrmsdk.... |
from PIL import Image
from collections import namedtuple
from datetime import datetime, timedelta
from io import BytesIO
import json
import logging
import os
# logging
logger = logging.getLogger('epaper')
class EPaper:
'''Manages data that is pulled from SITE_ARCHIVE to enable selection of a specific
publication... |
import json
import yaml
import pprint
import unittest
import orthauth as oa
from orthauth import exceptions as exc
from .common import test_folder
class TestFormats(unittest.TestCase):
def _config(self, name):
path = test_folder / name
return oa.AuthConfig(path)
def _do_test(self, auth):
... |
#! /usr/bin/env python
'''
Brian2 setup script
'''
import io
import sys
import os
import platform
from pkg_resources import parse_version
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
from distutils.errors import CompileError, DistutilsPlatformError
REQUIRED... |
<filename>gluoncv/utils/metrics/tracking.py
""" SiamRPN metrics """
import numpy as np
from colorama import Style, Fore
def overlap_ratio(rect1, rect2):
"""Compute overlap ratio between two rects
Parameters
----------
rect1 : nd.array
2d array of N x [x,y,w,h]
rect2 : nd.array... |
<reponame>dperl-sol/cctbx_project
from __future__ import absolute_import, division, print_function
import iotbx.pdb
from libtbx.str_utils import split_keeping_spaces
import sys
import six
trans_dict = {}
for k,v in six.iteritems(iotbx.pdb.rna_dna_atom_names_reference_to_mon_lib_translation_dict):
trans_dict[k.strip(... |
<filename>vespa/analysis/block_raw.py
# Python modules
# 3rd party modules
from xml.etree.cElementTree import Element
# Our modules
import vespa.analysis.chain_raw as chain_raw
import vespa.analysis.block as block
import vespa.common.mrs_data_raw as mrs_data_raw
import vespa.common.util.xml_ as util_xml
from vespa.co... |
<reponame>paulhoule/tentacruel
# pylint: disable=missing-docstring
import datetime
import json
import os
import re
import sys
from email.utils import parsedate_to_datetime, format_datetime
from logging import getLogger
from shutil import copyfile
from uuid import uuid4, NAMESPACE_URL, uuid5
from hashlib import sha384
... |
<gh_stars>1-10
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import abc
from typing import NamedTuple
import numpy as np
from caffe2.python import core
class OutputTransformerNet(NamedTuple):
net: core.Net
init_net: core.Net
class OutputTransformerBase(obje... |
from src.tasks.visualization import Graph
from src.tasks.pdf_to_txt import PdfToTxt
from src.tasks.merge_relations import MergeRelation
from src.tasks.graph_visualization import GraphVisualization
from nltk import word_tokenize
from src.BioBERT_NER_RE import ner_lib,re_lib
import glob,os,re,time
import pandas as pd
d... |
<reponame>xdzkl/deep-learning-with-python-notebooks
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 4 15:52:14 2019
@author: Administrator
"""
# 导入imdb数据集,imdb数据集有5万条来自网络电影数据库的评论,电影评论转换成了一系列数字,每个数字代表字典汇总的一个单词,下载后放到~/.keras/datasets/目录下,即可正常运行。)中找到下载,下载后放到~/.keras/datasets/目录下,即可正常运行。
from tensorflow.keras.datasets imp... |
<reponame>TMillross/green_curriculum
"""
Created on Sun Nov 26 12:54:22 2017
@author: tom
Performs a keyword-based analysis of curriculum data from studiegids
Built for TU Delft to analyse the sustainability content of the education
With minor modifications, will work for any data with similar format
Outputs:
A rank... |
#!/usr/bin/env python
import sys, time, os
import logging
import RPi.GPIO as GPIO
import pyownet
from influxdb import InfluxDBClient
# change this to the pin used to monitor the rain sensor
rain_sensor_pin = 5
# database engine host
host = os.getenv('INFLUXDB_HOST', 'localhost')
# database engine port
port = 8086
# ... |
import matplotlib.pyplot as plt
import numpy as np
# Displays the probability that the current trajectory matches the stored trajectores at every instant in time.
def plot_distribution(dof_names, mean, upper_bound, lower_bound):
"""Plots a given probability distribution.
"""
figures_per_plot = np.min([4, m... |
"""
The :mod:`pyfan.devel.flog.logsupport` initiates logging and set logging options, output log path
points.
This is imported into other programs as *import pyfan.devel.flog.logsupport as pyfan_logsup*
Includes method :func:`log_vig_start`, :func:`log_format`
"""
import logging
import pyfan.util.path.getfiles as py... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
def get_config_schema():
from aksetup_helper import ConfigSchema, Option, \
IncludeDir, LibraryDir, Libraries, BoostLibraries, \
Switch, StringListOption, make_boost_base_options
import sys
if 'darwin' in sys.platform:
import... |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------\n
# Original Authors: BARC Project, Berkely MPC Laboratory -> https://github.com/MPC-Berkeley/barc
# Modified by: <NAME>, Graduate Student, Clemson University
# Date Create: 20/5/2016, Last Modified: 20/5/201... |
<filename>python/lib/packet/signed_util.py
# Copyright 2018 ETH Zurich
#
# 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 ... |
<reponame>nikifkon/ChatApp<filename>backend/socket_chat/tests/group_consumer/conftest.py
from datetime import datetime
import pytest
from django.contrib.auth import get_user_model
from channels.testing import WebsocketCommunicator
from backend.groups.models import ChatGroup, GroupMessage
User = get_user_model()
@... |
"""
Helper functions
"""
import os
import time
from os.path import join
from pathlib import Path
from typing import Callable
from colorama import Fore, Style
from pytorch_lightning import seed_everything
from torch import Tensor
from torch.nn import Module
VERBOSITY = 3
TIMESTAMPED = True
DATA_DIR = join(Path(os.pat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File coupling.py created on 20:47 2018/1/1
@author: <NAME>
@version: 1.0
"""
import matplotlib.cm
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import time
import logging
from interfaces import *
from tree_search import *
from lispy import sta... |
<gh_stars>0
from numpy.lib.function_base import _piecewise_dispatcher
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#define a class Team, which takes team name and performes the analysis
class Team():
def __init__(self, team_name):
self.team_name = team_name
self.team_row... |
import tkinter as tk
import tkinter.messagebox
from enums import CamperType, CampRegion
import csv, os, classBooking, random
import tkBooking
from datetime import date
class AdvisorWindow:
def __init__(self, root):
self.window = tk.Toplevel(root)
self.window.grab_set()
label1 = tk.Label(se... |
#!/usr/bin/env python3
import sys, math, numpy, os.path, collections, argparse
def parse_args(arglist):
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Path/prefix for SNP file, and maybe coverage and output files")
parser.add_argument("--coverfile", help="Coverage file, if different from <pa... |
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_daq as daq
from dash.dependencies import Input, Output, State
from datetime import date, datetime, timedelta
import plotly.express as px
import pandas as pd
import requests
import base64
from utili... |
<reponame>codacy-badger/prototorch
"""ProtoTorch GLVQ example using 2D Iris data."""
import numpy as np
import torch
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from prototorch.functions.distances import euclidean_distance
from prototorc... |
<reponame>HungYangChang/HAET-2021-competition
import torch
import sys
import os
from utils import *
import os.path
import torchvision
total_class = 10
# load data
def Data_load(root='./data'):
# CIFAR10
download = lambda train: torchvision.datasets.CIFAR10(root=root, train=train, download=True)
return {k: {'d... |
<gh_stars>1-10
import pe
from random import randint, choice
import pytest
import os
import itertools
import inspect
from pe_core import pe_core_genesis2
import glob
import fault
# PECore uses it's own tester rather than a functional tester because the pe.py
# functional model doesn't match the new garnet functional m... |
<filename>examples/dry_bf_bubble.py
from gusto import *
from firedrake import (IntervalMesh, ExtrudedMesh,
SpatialCoordinate, conditional, cos, pi, sqrt,
TestFunction, dx, TrialFunction, Constant, Function,
LinearVariationalProblem, LinearVariationalS... |
<reponame>alfredoosauce/quant-trading
# coding: utf-8
# In[1]:
# i call it oil money
# cuz its a statistical arbitrage on crude benchmark and petrocurrency
# the inspiration came from an article i read
# it suggested to trade on petrocurrency when the oil price went uprising
# plus overall volatility for forex marke... |
# This file is part of the History Store (histore).
#
# Copyright (C) 2018-2021 New York University.
#
# The History Store (histore) is released under the Revised BSD License. See
# file LICENSE for full license details.
"""unit tests for snapshot descriptors and snapshot descriptor listings."""
import pytest
from h... |
# All Rights Reserved.
# Copyright 2013 SolidFire 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 ... |
<reponame>lessss4/oil-and-rope
import random
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext as _
class SheetHeader(models.Model):
"""
Sheet
Parameters
----------
name: class:`str`
game: :class:`Game`... |
import pickle
from typing import Tuple, Optional, Any, Dict
import torch
import torch.nn as nn
from torch.autograd.function import once_differentiable
from hivemind.proto import runtime_pb2, runtime_pb2_grpc as runtime_grpc
from hivemind.utils import nested_flatten, nested_pack, nested_compare, Endpoint
from hivemind... |
<reponame>james-guevara/synthdnm
import pandas as pd
from sklearn.externals import joblib
from Backend import get_path
import os,sys
import numpy as np
def classify_dataframe(df, clf, ofh,pyDNM_header=False, mode="a",keep_fp=True):
pd.options.mode.chained_assignment = None
df = df.replace([np.inf, -np.inf], np... |
#! /usr/bin/env python
"""Tests of finite differencing module."""
from __future__ import division
import sys
import unittest
from indiff import FiniteDiff, FwdDiff, BwdDiff, CenDiff
import numpy as np
import xarray as xr
from . import InfiniteDiffTestCase
class DiffSharedTests(object):
def test_slice_arr_dim(s... |
<reponame>ubirch/elevate-research
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import pytz
from datetime import datetime
import sensor as sensor
USED_TIMEZONE = pytz.timezone('Europe/Berlin')#pytz.utc
def convert_timestamps(timestamps_in):
return [datetime.fromtimestamp(ts,USED_TIME... |
<reponame>ArenaNetworks/dto-digitalmarketplace-api
from datetime import date, timedelta
import pytest
import pendulum
from app.api.services import suppliers
from app.models import Supplier, User, db, utcnow
from tests.app.helpers import BaseApplicationTest
class TestSuppliersService(BaseApplicationTest):
def se... |
<filename>code/linear_bias.py
import numpy as np
import os
import pyccl as ccl
import h5py
import pandas as pd
from scipy.interpolate import CubicSpline
from scipy.interpolate import interp1d
from astropy.cosmology import LambdaCDM
def shear_extractor(zmin = 1.0, incomp = True, shape_noise = 0.3):
"""
extract ... |
<gh_stars>0
import tempfile
import os
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from core.models import Recipe, Tag, Ingredient
from rest_framework import status
from recipe.serialisers import RecipeSerialize... |
import io
import extractseqs
import inserthdr
last_output_text = """\
# LAST version 833
#
# a=7 b=1 A=7 B=1 e=34 d=-1 x=33 y=9 z=33 D=1e+06 E=22.3617
# R=01 u=2 s=2 S=0 M=0 T=0 m=10 l=1 n=10 k=1 w=1000 t=0.910239 j=3 Q=0
# /work/04658/jklynch/ohana/last/HOT_genes
# Reference sequences=42682828 normal letters=223596... |
<gh_stars>10-100
import os
import subprocess
import numpy as np
import skimage.io
from datasets.base import BaseDataset
from utils.boxes import generate_anchors
class KITTI(BaseDataset):
def __init__(self, phase, cfg):
super(KITTI, self).__init__(phase, cfg)
self.input_size = (384, 1248) # (he... |
# Copyright 2019 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 applicabl... |
<gh_stars>1-10
import unittest
import os
import shutil
import json
import glob
import logging
from math import floor
from easysquid.toolbox import logger
from easysquid.simulations.single_simulation_run_methods import SimulationParameters
from simulations import _get_configs_from_easysquid
from easysquid.simulations im... |
## @package twitter.bots
# coding: UTF-8
import logging
import json
from typing import Dict, List
from pyrabbit2.http import NetworkError
from pyrabbit2.api import Client
from bots.utils import current_time, from_json
logger = logging.getLogger("rabbit-messaging")
logger.setLevel(logging.DEBUG)
handler = logging.Str... |
<gh_stars>0
import cv2
import numpy as np
from . import border_utils
from . import layer_utils
from .frame import Frame
from .cv2_utils import cv2_estimateRigidTransform
def build_transformation_matrix(transform):
"""Convert transform list to transformation matrix
:param transform: transform list as [dx, dy,... |
<gh_stars>0
from copy import copy
from collections import OrderedDict, defaultdict
import six
from bpmappers.utils import sort_dict_with_keys
from bpmappers.fields import Field, BaseField
from bpmappers.exceptions import DataError
class Options(object):
"""Meta data of Mapper.
"""
def __init__(self, *ar... |
import json
import shutil
from pathlib import Path
from unittest import mock
from aiounittest import AsyncTestCase
from crawler.crawlers import Crawler
from crawler.scrapers import URLScraper
class CrawlerTest(AsyncTestCase):
def setUp(self) -> None:
self.crawler = Crawler(
initial_url='htt... |
<filename>www/apps/social/providers/base/oauth2base.py
import cgi, urllib, urllib2, json, base64
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, load_backend
from django.contrib.auth.models import User
from django.contr... |
from unittest.mock import Mock
import pytest
from empresa import Pessoa, Funcionario, Programador, Estagiario, Vendedor, Empresa, EmpresaCreationError
# -----------------------
# Testes da classe Pessoa
# -----------------------
def test_cria_pessoa():
try:
p = Pessoa("João", 20)
except:
rais... |
<reponame>CrazyBunQnQ/12306-ocr<gh_stars>100-1000
# coding: utf-8
import cv2
import tensorflow as tf
import numpy as np
from keras import models
from config import Logger, Config
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
class ShareInstance():
__session = None
@classmethod
def shar... |
<filename>Dimensionality-Reduction/src/main.py
import numpy as np
import os
from sklearn.decomposition import IncrementalPCA
from os import listdir
from os.path import isfile, join
import copy
import torch
import time
def get_PCA(src_dir, tar_dir, k):
'''
Assuming IPCA object hasn't been trained yet.
src_... |
"""
test nieghbors
"""
import pytest
@pytest.mark.skip(reason="This test documents an example, but is redundant. Skipped in the interest of CI time.")
def test_current_example():
import os
import pandas as pd
import numpy as np
from tcrdist.repertoire import TCRrep
from tcrdist.neighbors import compute_ecdf, bkg... |
<reponame>Bugnon/oc-2018
import turtle
bob = turtle.Turtle()
def lettre_a(t):
t.lt(75)
t.fd(170)
t.rt(150)
t.fd(170)
t.rt(180)
t.fd(70)
t.lt(75)
t.fd(55)
t.bk(55)
t.rt(75)
t.bk(70)
t.rt(105)
def lettre_b(t):
t.lt(90)
t.fd(200)
t.rt(180)
t.fd(200)
... |
import bpy
from mathutils import Vector, Euler
from mathutils.geometry import intersect_line_plane
from .functions_modal import *
from .classes_tool import *
def setup_tools(modal):
modal.tools = GEN_Modal_Container()
modal.tools.set_cancel_keys(['Cancel Tool 1', 'Cancel Tool 2'])
modal.tools.set_confirm_... |
from typing import List
import numpy as np
from pyNastran.utils.numpy_utils import integer_types
from pyNastran.op2.result_objects.op2_objects import ScalarObject
from pyNastran.f06.f06_formatting import write_floats_13e, write_imag_floats_13e
class AppliedLoadsVectorArray(ScalarObject):
def __init__(self, data_c... |
import sys
import os
import argparse
import torch
import time
import datetime
import pytz
#----------------------------------------------------------
def add_if_absent_(opt,names,val):
for name in names:
if not hasattr(opt,name):
setattr(opt,name,val)
#-----------------------------------------------... |
from itertools import chain
import json
import re
import time
from common.logging import get_logger
from common.utils import retry
from exceptions import ScrappingError
from scrapper.scripts import xhr_intercept_response
from scrapper.driver import forced_click
from selenium.common.exceptions import (
TimeoutExc... |
<reponame>nephomaniac/nephoria
# Software License Agreement (BSD License)
#
# Copyright (c) 2009-2014, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#... |
# SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
import logging
from datetime import datetime
from typi... |
<filename>custom_components/ecowitt/__init__.py
"""The Ecowitt Weather Station Component."""
import asyncio
import logging
import time
from pyecowitt import (
EcoWittListener,
WINDCHILL_OLD,
WINDCHILL_NEW,
WINDCHILL_HYBRID,
)
import voluptuous as vol
import homeassistant.helpers.config_validation as c... |
<filename>steem/markets.py
import time
from decimal import Decimal
from operator import mul
from pprint import pprint
from statistics import mean
import grequests
import steem as stm
from steem.amount import Amount
class Tickers(object):
@staticmethod
def btc_usd_ticker(verbose=False):
prices = {}
... |
<reponame>ratelang/pytest-ratl
import pytest
def _compile(
source_code,
*,
lark_grammar,
vyper_interface_codes=None,
evm_version=None,
vyper_output_formats=("abi", "bytecode"),
mpc_output_formats=None
):
from ratl import RatelCompiler
ratel_compiler = RatelCompiler()
output = ... |
<filename>apluslms_file_transfer/client/fileinfo.py
import os
import json
import requests
from io import BytesIO
from hashlib import sha256
import logging
from apluslms_file_transfer.exceptions import GetFileUpdateError
from apluslms_file_transfer.color_print import PrintColor
logger = logging.getLogger(__name__)
d... |
<reponame>rogue26/processy.io
from django.conf import settings
from django.http import HttpResponseRedirect
from bootstrap_modal_forms.generic import BSModalFormView
from projects.models import Project, Workstream, WorkstreamType, Deliverable, DeliverableType, Task, TaskType, \
TeamMember, Specification, Condition... |
# coding: utf-8
"""
Fulfillment API
Use the Fulfillment API to complete the process of packaging, addressing, handling, and shipping each order on behalf of the seller, in accordance with the payment method and timing specified at checkout. # noqa: E501
OpenAPI spec version: v1.19.9
Generated b... |
import hashlib
import settings
import os
import converter
import shutil
class MediaTask:
def __init__(self, filepath_in):
self.filepath_in = filepath_in
self._prepare_filepaths_out(filepath_in)
def _prepare_filepaths_out(self, filepath_in):
self.filename_out = hashlib.md5(filepath_in.... |
from .nn import NN
from .. import activations
from .. import initializers
from .. import regularizers
from ... import config
from ...backend import tf
from ...utils import timing
class MfNN(NN):
"""Multifidelity neural networks."""
def __init__(
self,
layer_sizes_low_fidelity,
layer_s... |
import matplotlib
matplotlib.use('Agg')
import os
from utils import check_dir
import numpy as np
import scipy
import matplotlib.pyplot as plt
from time import time
from models import BIVA
class DeepVAEEvaluator(object):
def __init__(self, images, n_images=5, iw_samples=1000, eval_every=1, preprocess_batch=lambda... |
"""
Copy files for all finished simulations to a new directory, change seed number and job name.
python add_run.py RUN1 RUN1-2
"""
import os
import sys
import glob
import shutil
def check_finished(sim_dir, file_name='lammps_out.txt'):
finished = False
dir_list = os.listdir(sim_dir)
if file_name in dir_li... |
"""CmdStan method variational tests"""
import os
import unittest
from math import fabs
import pytest
from testfixtures import LogCapture
from cmdstanpy.cmdstan_args import CmdStanArgs, VariationalArgs
from cmdstanpy.model import CmdStanModel
from cmdstanpy.stanfit import CmdStanVB, RunSet, from_csv
HERE = os.path.d... |
"""
This script contains a function that trains a model with given parameters and saves it.
"""
import os
import pickle
import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard, CSVLogger, ModelCheckpoint
from src.BRAVENET import bravenet_config
from src.BRAVENET.utils.architectures.bravenet import ... |
<filename>predict.py<gh_stars>0
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Activation, Dropout, Dense, Lambda
from tensorflow.keras.layers import BatchNormalization as BatchNorm
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.utils import to_cat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.