text
string
size
int64
token_count
int64
"""Abstract class for all toggle buttons""" # Standard library imports import logging from collections import OrderedDict # Third party imports import ipywidgets # Local imports from .abc_toggle_buttons import BaseToggleButtons from .layouts import DICT_LAYOUT_HBOX_ANY LOGGER = logging.getLogger(__name__) class Ba...
7,027
2,003
__author__ = 'Pat McClernan and Dan Wegmann' import Player import Message # input #0 for rock #1 for paper #2 for scissors # past move is array of numbers # our move followed by their move #Our strategy is to look at all past moves #In a large number of games, you would expect # each move to be seen an even amount ...
3,899
1,145
from age_and_gender import * from PIL import Image, ImageDraw, ImageFont data = AgeAndGender() data.load_shape_predictor('models/shape_predictor_5_face_landmarks.dat') data.load_dnn_gender_classifier('models/dnn_gender_classifier_v1.dat') data.load_dnn_age_predictor('models/dnn_age_predictor_v1.dat') filename = 'test...
1,023
382
from tictactoe import TicTacToe import random import csv import os gameNr = 1 gameLimit = 10000 lst_moves_1 = [] lst_moves_2 = [] while gameNr <= gameLimit: print("+++++++++++") print("Game#", gameNr) game = TicTacToe() tmp_moves_1 = [] tmp_moves_2 = [] while game.get_winner() == 0 and game....
1,463
588
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7 # TODO this should be implemented, see "kratos/utilities/interval_utility.h" class IntervalUtility(object): def __init__(self, settings): pass def IsInInterval(self, curr...
350
100
import bitstring import pytest from stixcore.data.test import test_data from stixcore.idb.manager import IDBManager from stixcore.tmtc.packets import ( SOURCE_PACKET_HEADER_STRUCTURE, TC_DATA_HEADER_STRUCTURE, TM_DATA_HEADER_STRUCTURE, SourcePacketHeader, TCPacket, TMDataHeader, TMPacket, ...
2,906
1,128
"""Provides SeriesLoader object and helpers, used to read Series data from disk or other filesystems. """ from collections import namedtuple import json from numpy import array, arange, frombuffer, load, ndarray, unravel_index, vstack from numpy import dtype as dtypeFunc from scipy.io import loadmat from cStringIO impo...
40,969
10,757
# run local models given a path, default to './mxnet_models/' import os import argparse import time import mxnet as mx import numpy as np file_path = os.path.realpath(__file__) dir_name = os.path.dirname(file_path) os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"] = "0" class cuda_profiler_start(): import numba.cuda ...
3,097
1,067
from lammps_data.angles import get_angles def test_separate_diatomic_molecules_should_have_no_angles(): bonds = [(0, 1), (2, 3)] assert get_angles(bonds) == [] def test_molecule_with_two_bonds_should_have_one_angle(): bonds = [(0, 1), (1, 2)] assert get_angles(bonds) == [(0, 1, 2)] def test_differ...
1,198
528
# Generated by Django 3.1.1 on 2020-12-16 03:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Scheduler', fields=[ ('id', models.AutoFiel...
491
153
from sklearn.preprocessing import StandardScaler from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split wine = load_wine() columns_names = wine.feature_names y = wine.target X = wine.data print('Pre scaling X') print(X) scaler = StandardScaler() scaler.fit(X) scaled_features = sc...
477
171
#!/usr/bin/env python # -*- coding: utf-8 -*- # Common Python library imports import os import pytest # Pip package imports from collections import namedtuple from flask import template_rendered from flask_security.signals import ( reset_password_instructions_sent, user_confirmed, user_registered, ) # In...
4,057
1,270
from setuptools import setup from nats.aio.client import __version__ EXTRAS = { 'nkeys': ['nkeys'], } setup( name='nats-py', version=__version__, description='NATS client for Python', long_description='Python client for NATS, a lightweight, high-performance cloud native messaging system', cla...
927
294
############################################################## #*** MagicDAQ USB DAQ and M&A Board General Demo Script *** ############################################################## #*** Websites *** # MagicDAQ Website: # https://www.magicdaq.com/ # API Docs Website: # https://magicdaq.github.io/magicdaq_docs/ #*...
12,844
4,015
from .results import (ArticleSearchResult, EmbeddingsResult, SearchResult, TagResult, ZoteroExtractionResult) __all__ = [ "TagResult", "EmbeddingsResult", "ZoteroExtractionResult", "SearchResult", "ArticleSearchResult" ]
252
76
from django.contrib.auth import get_user_model from rest_framework import serializers class UsersListSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = [ "id", "phone", "first_name", "last_name", "author", ] class U...
2,257
626
# Copyright 2022 IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # 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 ...
3,733
1,493
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: qgeddes # # Created: 25/04/2013 # Copyright: (c) qgeddes 2013 # Licence: <your licence> #------------------------------------------------------------------------------- import L7...
793
273
# -*- coding: utf-8 -*- from __future__ import absolute_import import six from sentry.api.serializers import serialize from sentry.models import SavedSearch from sentry.models.savedsearch import DEFAULT_SAVED_SEARCHES from sentry.testutils import TestCase class SavedSearchSerializerTest(TestCase): def test_sim...
1,676
453
""" #;+ #; NAME: #; general #; Version 1.0 #; #; PURPOSE: #; Module for monkeying with files and filenames #; 172Sep-2014 by JXP #;- #;------------------------------------------------------------------------------ """ # Import libraries import numpy as np from astropy.io import fits from astropy.io import as...
864
321
#!/usr/bin/env python try: from setuptools.core import setup except ImportError: from distutils.core import setup setup(name='genderizer', version='0.1.2.3', license='MIT', description='Genderizer tries to infer gender information looking at first name and/or making text analysis', lo...
655
200
# Copyright 2022 Collate # 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...
1,855
568
# -*- coding: utf-8 -*- from storyruntime.Containers import Containers from storyruntime.constants.ServiceConstants import ServiceConstants import storyscript def test_containers_format_command(story): """ Ensures a simple resolve can be performed """ story_text = 'alpine echo msg:"foo"\n' story....
1,285
379
from django.contrib import admin from django.shortcuts import redirect from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None, renderer=None): output = [] if value and ...
1,367
432
import os plane = [[0 for i in range(1000)] for j in range(1000)] count = [0] def overlapping_vents(): path = os.getcwd() file_path = os.path.join(path, 'vents.txt') file1 = open(file_path, 'r') Lines = file1.readlines() for line in Lines: input = line.strip() points = input.spli...
1,222
525
import unittest class Solution: def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ rows = [0] * len(matrix) cols = [0] * len(matrix[0]) for i, row in enumerate(matrix): ...
1,217
377
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2019, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWritePrintOptions(unittest.TestCase): """ ...
2,508
770
from neo4j.v1 import GraphDatabase #neo4j==1.7.0 uri="bolt://localhost:7687" driver=GraphDatabase.driver(uri, auth=("neo4j", "testneo4j")) def execute_queries(scripts,message=None): with driver.session() as session: tx=session.begin_transaction() res=tx.run(';'.join(scripts)) tx.commit() ...
1,011
334
import os import tempfile import mock from . import utils from hotsos.core.config import setup_config from hotsos.core.ycheck.scenarios import YScenarioChecker from hotsos.core.issues.utils import KnownBugsStore, IssuesStore from hotsos.plugin_extensions.juju import summary JOURNALCTL_CAPPEDPOSITIONLOST = """ Dec 2...
9,077
2,908
import argparse import collections import shutil import sys import time from datetime import timedelta from pathlib import Path import torch from torch.nn.parallel import DataParallel, DistributedDataParallel try: # PyTorch >= 1.6 supports mixed precision training from torch.cuda.amp import autocast amp_su...
9,626
3,315
import logging import requests import multiprocessing import pathlib from typing import List from typing import Optional from typing import Tuple from typing import Dict from joblib import delayed from joblib import Parallel from datetime import date from datetime import timedelta logger = logging.getLogger(__name__) ...
1,907
585
# -*- coding: utf-8 -*- """ Created on Wed Oct 21 19:52:22 2020 #Plan A @author: 18096 """ '''Defines the neural network, loss function and metrics''' #from functools import reduce import torch import torch.nn as nn from torch.nn.functional import pad from torch.autograd import Variable import logging ...
7,625
2,893
import pytest @pytest.mark.asyncio async def test_reinstall_if_needed(repository): repository.content.path.local = "/non/existing/dir" repository.data.installed = True await repository.async_reinstall_if_needed()
227
74
# Copyright (c) 2017 Yingxin Cheng # # 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...
11,124
3,175
"""Test suite for pylab_import_all magic Modified from the irunner module but using regex. """ # Global to make tests extra verbose and help debugging VERBOSE = True # stdlib imports import StringIO import sys import unittest import re # IPython imports from IPython.lib import irunner from IPython.testing import dec...
3,890
1,212
import logging import os import shutil import time import torch model_state = 'model_state.pt' trainer_state = 'trainer_state.pt' class Checkpoint(): def __init__(self, step, epoch, model, optim, path=None, opt=None): self.step = step self.epoch = epoch self.model = model self.o...
2,241
703
import numpy as np import torch import os import cv2 import importlib from dataset import * from PIL import Image from argparse import ArgumentParser from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision.transforms import Compose, CenterCrop, Normalize, Resize from torchvision.tr...
4,250
1,467
import pytest from pytest import raises from pydantic_jsonapi.resource_linkage import ResourceLinkage from pydantic import BaseModel, ValidationError class ThingWithLinkageData(BaseModel): data: ResourceLinkage class TestResourceLinks: @pytest.mark.parametrize( 'linkage, message', [ ...
2,440
677
import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD from keras.utils import np_utils import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf batch_size = 1...
2,046
813
#!/usr/bin/env python3 # Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. from dace.transformation.dataflow.streaming_memory import StreamingMemory from dace.transformation.interstate.sdfg_nesting import InlineSDFG from dace.transformation.interstate.fpga_transform_sdfg import FPGATransformSDF...
4,942
1,937
import math from typing import List, Union import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor @torch.jit.script def spatial_pyramid_pool( input: Tensor, bins: Union[int, List[int]], mode: str = "max" ) -> Tensor: """Spatial Pyramid Pooling: https://arxiv.org/pdf/1406....
1,925
689
""" usage requires these additional modules pip install azure-batch azure-storage-blob jsonschema pyyaml && pip install git+https://github.com/microsoft/SparseSC.git@ad4bf27edb28f517508f6934f21eb65d17fb6543 && scgrad start usage: from SparseSC import fit, aggregate_batch_results from SparseSC.utils.azure_batch_clie...
21,417
6,687
from .visual_entailment_dataset import VisualEntailmentDataset
63
18
# Basic Fantasy RPG Dungeoneer Suite # Copyright 2007-2012 Chris Gonnerman # 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 # no...
14,174
6,585
from flask import Flask, current_app from flask import render_template from flask import jsonify from jieba.analyse import extract_tags import string from DB import chinaSQL from DB import worldSQL app = Flask(__name__, template_folder='../../web', static_folder='../../static') @app.route('/', methods=["get", "post"...
20,773
7,034
# Generated by Django 2.0.2 on 2018-02-17 10:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('T2API', '0007_apiuser_deviceuser'), ] operations = [ migrations.AddField( model_name='product', name='weight', ...
396
134
#!/usr/bin/env python3 # Simple and dumb script to send a message to the #podman IRC channel on frenode # Based on example from: https://pythonspot.com/building-an-irc-bot/ import os import time import random import errno import socket import sys class IRC: response_timeout = 10 # seconds irc = socket.sock...
3,402
1,060
from changes.api.base import APIView from changes.lib.coverage import get_coverage_by_build_id, merged_coverage_data from changes.models.build import Build class BuildTestCoverageAPIView(APIView): def get(self, build_id): build = Build.query.get(build_id) if build is None: return '',...
441
141
"""Compliant mechanism synthesis problems using topology optimization.""" import numpy import scipy.sparse from ..problems import ElasticityProblem from .boundary_conditions import MechanismSynthesisBoundaryConditions from ..utils import deleterowcol class MechanismSynthesisProblem(ElasticityProblem): r""" ...
5,251
1,595
import unittest from flydenity import Parser class TestParseIcao24Bit(unittest.TestCase): def setUp(self): self.parser = Parser() def test_parse_simple(self): match = self.parser.parse("3D2591", icao24bit=True) self.assertEqual(match, {"nation": "Germany", "description": "general", ...
932
357
import os def create_project(path): dirs = ['configs', 'module', 'data'] dirs = [os.path.join(path, d) for d in dirs] for d in dirs: os.makedirs(d) train_script = r""" import ever as er def train(trainer_name): trainer = er.trainer.get_trainer(trainer_name)() trainer.run() ...
465
177
class MetricsService: def __init__(self, adc_data, metrics_data): self._adc_data = adc_data self._metrics_data = metrics_data @property def metrics_data(self): return self._metrics_data def update(self): self._metrics_data.is_new_data_available = False if self....
473
155
import unittest from resthelper.utils import build_restful_url class TestBuildUrl(unittest.TestCase): def test_is_restful_https_url(self): url = build_restful_url('https://jenkins1.tttech.com', 'testuser', '/rest/1.0/request') self.assertEqual(url, 'htt...
687
229
""" python-rq based backend This backend will send your messages asynchronously with python-rq. Before using this backend, make sure that django-rq is installed and configured. Usage ----- In settings.py SENDSMS_BACKEND = 'sendsms.backends.rq.SmsBackend' RQ_SENDSMS_BACKEND = 'actual.backend.to.use.SmsBack...
929
329
#Autogenerated schema from openpyxl.descriptors.serialisable import Serialisable from openpyxl.descriptors import ( Typed, String, Bool, Sequence, ) from openpyxl.descriptors.excel import CellRange class Extension(Serialisable): tagname = "extension" uri = String(allow_none=True) def __...
2,435
696
from kol.request.GenericRequest import GenericRequest from kol.manager import PatternManager import re class ItemDescriptionRequest(GenericRequest): "Gets the description of an item and then parses various information from the response." _itemIdPattern = re.compile(r'(?i)<!--\s*itemid:\s*(\d+)\s*-->') def...
2,918
820
import json import sys def compatible_loads(json_data): """ Function json.loads in python 3.0 - 3.5 can't handle bytes, so this function handle it. :param json_data: :return: unicode (str if it's python 3) """ if isinstance(json_data, bytes) and (3, 0) <= sys.version_info < (3, 6): ...
619
227
import sys,time def sprint(str): for c in str + '\n': sys.stdout.write(c) sys.stdout.flush() time.sleep(3./90) from colorama import Fore, Back, Style sprint (Fore.RED + "გამარჯობა. tool-ი შექმინლია ლევან ყიფიანი-DaduVoke-ის მიერ @2021") import socket import _thread im...
3,578
1,766
# This file is part of the clacks framework. # # http://clacks-project.org # # Copyright: # (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de # # License: # GPL-2: http://www.gnu.org/licenses/gpl-2.0.html # # See the LICENSE file in the project's top-level directory for details. """ The object base class. ...
53,296
14,638
""" Testing default benchmarks in single thred and parallel configuration Check whether it generates correct outputs and resulting values Copyright (C) 2017-2019 Jiri Borovec <jiri.borovec@fel.cvut.cz> """ import argparse import logging import os import shutil import sys import unittest try: # python 3 from uni...
8,752
2,821
from .errors_exception_handling import errors_exception_handling
65
17
#!/usr/bin/env python ################################################################################################## ## mtstub.py ## ## emulates rockblock api so I don't have to burn credits testing... ################################################################################################## import cgi #i...
470
119
#sum(iterable, start=0, /) #Return the sum of a 'start' value (default: 0) plus an iterable of numbers #When the iterable is empty, return the start value. '''This function is intended specifically for use with numeric values and may reject non-numeric types.''' a = [1,3,5,7,9,4,6,2,8] print(sum(a)) pr...
343
131
################################################################################# # 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...
10,926
3,813
# coding: utf8 """ Ortholog Based Bait Design Script for creating Elateridae ortholog based baits suitable submission to myBaits Compares t_coffee AA alignment scores with nucleotide tranalignments to find conserved blocks Author Jackson Eyres jackson.eyres@canada.ca License: MIT Copywright: Government of Canada """ i...
12,055
3,763
import sys import numpy as np sys.path.append("d:/data/annooptimize") import triangle import time tinternal = list() def labstart(): points,tri = triangle.gentri("d:/data/annooptimize/Annodata/200600/poise.shp") plabels = triangle.dynamicSize(points) conflictg = triangle.conflictgraphdy(points,...
1,361
550
from util.infinity import INFINITY from tc_python.arule import ARule from t_core.rollbacker import Rollbacker from t_core.resolver import Resolver class XRule(ARule): ''' Applies the transformation on one match with roll-back capability. ''' def __init__(self, LHS, RHS, max_iterations=...
5,091
1,469
from unittest import TestCase from propara.commonsense.semantic_lexicon_knowledge.ai2_lexicon import AI2Lexicon, AI2LexiconPredicate, AI2LexiconArg, AI2LexiconIndications, \ AI2LexiconPattern class TestAI2Lexicon(TestCase): def setUp(self): self.lexicon_fp = "tests/fixtures/ie/TheSemanticLexicon-v3.0...
5,266
1,839
# -*- coding: utf-8 -*- """ Fitbit API Library ------------------ :copyright: 2012-2015 ORCAS. :license: BSD, see LICENSE for more details. """ from .api import Fitbit, FitbitOauthClient, FitbitOauth2Client # Meta. __title__ = 'fitbit' __author__ = 'Issac Kelly and ORCAS' __author_email__ = 'bpitcher@orcasinc.com' ...
473
213
from django.urls import include, path from exchange.api.views import LatestOrdersListAPIView, OrderViewSet, ProfileAPIView from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'orders', OrderViewSet, basename='orders') urlpatterns = [ path('profile/', ProfileAPIView.as_view()...
468
137
def dbl(): return ( (a, a) for a in [])
52
22
from bs4 import BeautifulSoup import requests import re def retrieveText(): print("Parsing text from online target") url = "https://www.whitehouse.gov/the-press-office/2017/10/16/remarks-president-trump-and-senate-majority-leader-mitch-mcconnell-joint" response = requests.get(url) soup = BeautifulSoup(...
848
297
# -*- coding: utf-8 -*- from cfmacro.processors import SgProcessor from cfmacro.core.engine import ProcessorEngine from cfmacro.core.template import TemplateProcessor def lambda_handler(event, context): """ Implement a core handler for security groups ingress / egress :param event: :param context: ...
869
239
import torch import argparse from roberta_modeling import RobertaJointForLong from transformers.modeling_roberta import RobertaConfig, RobertaModel from torch.utils.data import TensorDataset, SequentialSampler, DataLoader import utils from tqdm import tqdm import os import json import collections import pickle import p...
8,038
2,654
""" Django settings for city-infrastructure-platform project. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import environ import sentry_sdk from djan...
9,385
3,524
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2021/7/25 19:30 # @author : Mo # @function: predict model, 预测模块-多类分类 # 适配linux import platform import json import sys import os path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) path_sys = os.path.join(path_root, "pytorch_nlu", "pyto...
1,184
700
import unittest from stringsheet.parser import create_spreadsheet_values from stringsheet.parser import create_language_sheet_values from stringsheet.parser import parse_resources class BaseTestCase(unittest.TestCase): def setUp(self): self.resources = parse_resources('test-resources/res') class Create...
5,645
1,718
import cv2 def img_path2array(path): return cv2.cvtColor(cv2.imread(path, 10), cv2.COLOR_BGR2RGB) def img_array2file(path, array): cv2.imwrite(path, cv2.cvtColor(array, cv2.COLOR_RGB2BGR))
195
91
import os, sys import numpy as np from sedflow import obs as Obs from sedflow import train as Train from provabgs import infer as Infer from provabgs import models as Models #################################################### # input #################################################### sample = sys.argv[1] itrain...
3,079
1,146
import json import time import re from .keyvalue_provider import KeyValueProvider from .gcloud_artifact_store import GCloudArtifactStore from .util import timeit class GSProvider(KeyValueProvider): def __init__(self, config, blocking_auth=True, verbose=10, store=None): self.config = config self.b...
2,709
739
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. 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 require...
46,830
15,892
# coding: utf-8 from __future__ import unicode_literals, print_function, division, absolute_import HOME_ACCESSED = "home-accessed"
131
43
import logging from urllib.parse import unquote, urlparse from pathlib import PurePosixPath import requests from requests.exceptions import ReadTimeout, ConnectionError, HTTPError from django.core.management.base import BaseCommand from django.core.files.base import ContentFile from places.models import Place, Image ...
2,217
567
# -*- coding: utf-8 -*- # Copyright 2014 Google Inc. 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 require...
18,227
5,577
''' Created on Dec 28, 2021 @author: Itay Abstracting the DB connection piece ''' import mysql.connector as My from app import logging as L from app import exceptions as exceptions class Connection(): ''' Abstracting the actions on a DB ''' def __init__(self, connection_config): self._debug_c...
2,250
645
import os from tqdm import tqdm import cv2 import numpy as np #pre process test data: path = "raw_test_data/" list_width = [] list_height = [] list_image = [] def pre_process(): print("analyze images") for Files in tqdm(os.listdir(path)): if "jpg" in Files: #print(Files) img = ...
1,527
485
# Copyright 2016 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...
4,934
1,646
import functools import glob import itertools import logging import os from progressbar import progressbar import re import requests from typing import List class ValueSingleDispatch: def __init__(self): self._handlers = dict() def register(self, key): def decorator(fn: callable): ...
3,218
994
#Copyright 2021 Neil Flood and Sam Gillingham. All rights reserved. # #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, cop...
1,637
557
import os import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder def read_dataset_from_npy(path): """ Read dataset from .npy file """ data = np.load(path, allow_pickle=True) return data[()]['X'], data[()]['y'], data[()]['train_idx'], data[()]['test_idx'] def read_dataset...
3,846
1,571
from __future__ import print_function, division, unicode_literals import os import warnings import numpy as np from scipy import interpolate import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from pymatgen.io.vasp.outputs import Vasprun from pymatgen.core.structure import Structure from pymatg...
17,458
6,431
from aiopylimit import AIOPyRateLimit from aiopylimit import AIOPyRateLimitException import asynctest import asyncio class TestPyLimit(asynctest.TestCase): async def test_exception(self): limit = AIOPyRateLimit(10, 10) await self.assertAsyncRaises(AIOPyRateLimitException, ...
1,380
433
# coding: utf-8 import sys import shutil import requests import wx from pathlib import Path from urllib.parse import urljoin, urlsplit from tempfile import TemporaryFile from zipfile import ZipFile from bookworm import typehints as t from bookworm import app from bookworm.http_tools import RemoteJsonResource, HttpReso...
5,772
1,945
# -*- coding: utf-8 -*- """ *************************************************************************** v_proj.py --------- Date : November 2017 Copyright : (C) 2017 by Médéric Ribreux Email : medspx at medspx dot fr ****************************************...
2,448
700
# Copyright 2013 Devsim 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 agreed to in writing, s...
1,919
695
from dataclasses import dataclass import os path_base_default = os.getenv('ASTRO_IMAGING_DATA_PATH', default='./') @dataclass class Paths: base: str = path_base_default catalogs: str = None images: str = None def __post_init__(self): if self.catalogs is None: self.catalogs = os.p...
470
156
#!/usr/bin/env python from typing import Tuple import argparse from src.loadopts import * METHOD = "RobOC-AT" SAVE_FREQ = 5 PRINT_FREQ = 20 FMT = "{description}={scale}-{leverage}" \ "={learning_policy}-{optimizer}-{lr}" \ "={attack}-{epsilon:.4f}-{stepsize}-{steps}" \ "={batch_size}={trans...
8,018
2,664
from django.db import models # Create your models here. class CommonFieldsMixin(models.Model): """Add created_at and updated_at fields.""" created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: """Define metadata options....
680
219
# seq2seq LSTM (no-convolutional model) for time series prediction import numpy as np import torch import torchvision import torch.utils.data as data import torchvision.transforms as transforms import pandas as pd import h5py import os import sys import json import time import pdb from jma_timeseries_dataset import...
8,534
2,506
import numpy as np class ProbAbsoluteShading(object): def __init__(self, params): self.params = params def cost(self, s_nz): if self.params.abs_shading_weight: if self.params.abs_shading_log: return self.params.abs_shading_weight * \ np.abs(np.l...
556
179