text
string
size
int64
token_count
int64
import pprint from typing import Optional, List, Tuple, Set, Dict import numpy as np from overrides import overrides from python.handwritten_baseline.pipeline.data.base import Dataset from python.handwritten_baseline.pipeline.model.feature_extr import DEBUG_EXTR from python.handwritten_baseline.pipeline.model.feature...
2,384
698
# -*- coding: utf-8 -*- # # Author: Tomi Jylhä-Ollila, Finland 2014 # # This file is part of Kunquat. # # CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/ # # To the extent possible under law, Kunquat Affirmers have waived all # copyright and related or neighboring rights to Kunquat. # from __futu...
1,253
443
import warnings import unittest from igraph import * class TestBase(unittest.TestCase): def testPageRank(self): for idx, g in enumerate(self.__class__.graphs): try: pr = g.pagerank() except Exception as ex: self.assertTrue(False, msg="PageRank calcu...
4,311
1,277
import dataclasses import enum class CLType(enum.Enum): """Enumeration over set of CL types. """ BOOL = 0 I32 = 1 I64 = 2 U8 = 3 U32 = 4 U64 = 5 U128 = 6 U256 = 7 U512 = 8 UNIT = 9 STRING = 10 KEY = 11 UREF = 12 OPTION = 13 LIST = 14 BYTE_A...
3,509
1,205
# -*- coding: utf-8 -*- # Copyright 2020 Google 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 o...
1,668
453
# Copyright (c) 2009 Bryan Cain ("Plombo") # Class and functions to read .PAK files. import struct from cStringIO import StringIO class PackFileReader(object): ''' Represents a BOR packfile. ''' files = dict() # the index holding the location of each file packfile = None # the file object def __in...
3,119
1,244
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Created by magus0219[magus0219@gmail.com] on 2020/3/23 from types import FunctionType from flask import ( Flask, redirect, url_for, ) import artascope.src.web.lib.filter as module_filter from artascope.src.web.lib.content_processor import inject_version d...
1,017
336
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
2,251
739
""" Utility functions and classes shared by multiple backends """ from collections import namedtuple import logging from . import symbols from . import types LOGGER = logging.getLogger('spc.backend_utils') # NameContexts encapsulate both the function stack (which holds values) and # the symbol table context (which b...
16,446
4,580
__version__ = "2021.0.6"
25
16
""" recommender_engine ----- recommender_engine is a recommendation application using either item-based or user-based approaches :copyright: (c) 2016 - 2019 by Tran Ly Vu. All Rights Reserved. :license: Apache License 2.0 """ from .cosine import cosine from .euclidean_distance import euclidean_distance from .p...
744
277
a,b=map(int,input().split()) print((a+b)%24)
44
24
class CheckType: r""" 8.9 创建新的类或实例属性 使用描述器,实现参数类型检查 >>> @ParamAssert(a=int, b=list) ... class A: ... def __init__(self, a, b): ... self.a = a ... self.b = b >>> a = A(1, []) """ def __init__(self, name, expected_type): self.name = name sel...
1,925
617
import math import torch import unittest import gpytorch from torch import optim from torch.autograd import Variable from gpytorch.kernels import RBFKernel from gpytorch.means import ConstantMean from gpytorch.likelihoods import GaussianLikelihood from gpytorch.random_variables import GaussianRandomVariable # Simple ...
7,306
2,320
from CyberSource import * import os import json from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() # To delete None values in Input Request Json body def del_none(d): for ke...
4,264
1,182
import numpy as np import random import math import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style angle = np.linspace( 0 , 2 * np.pi , 150) radius = 1 x = radius * np.cos(angle) y = radius * np.sin(angle) #prints the circle style.use('fivethirtyeight') fig = plt.f...
936
350
""" This is where the web application starts running """ from app.index import create_app app = create_app() if __name__ == "__main__": app.secret_key = 'mysecret' app.run(port=8080, host="0.0.0.0", debug=True)
219
81
class Proceso: def __init__(self,tiempo_de_llegada,t,id): self.t=t self.tiempo_de_llegada=tiempo_de_llegada self.id=id self.inicio=0 self.fin=0 self.T=0 self.E=0 self.P=0 self.tRestantes = t
267
111
# Time: sum(O(l * 2^l) for l in range(1, 11)) = O(20 * 2^10) = O(1) # Space: O(1) class Solution(object): def findInteger(self, k, digit1, digit2): """ :type k: int :type digit1: int :type digit2: int :rtype: int """ MAX_NUM_OF_DIGITS = 10 INT_MAX = ...
804
284
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: from django.core.urlresolvers import reverse except ImportError: # Django 2.0 from django.urls import reverse from django.utils.translation import force_text from cms import api from cms.utils.i18n import force_language from aldryn_peop...
7,875
2,368
# Copyright (C) 2020 THL A29 Limited, a Tencent company. # All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may # not use this file except in compliance with the License. You may # obtain a copy of the License at # https://opensource.org/licenses/BSD-3-Clause # Unless required by appl...
661
190
# This script contains the get_joke() function to generate a new dad joke import requests def get_joke(): """Return new joke string from icanhazdadjoke.com.""" url = "https://icanhazdadjoke.com/" response = requests.get(url, headers={'Accept': 'application/json'}) raw_joke = response.json() joke ...
355
122
from .test_commands import all_commands all_triggers = all_commands from .test_quack import TestQuack all_triggers.append(TestQuack)
136
48
from __future__ import print_function from crassus import Crassus from crassus.output_converter import OutputConverter def handler(event, context): crassus = Crassus(event, context) crassus.deploy() def cfn_output_converter(event, context): """ Convert an AWS CloudFormation output message to our def...
445
129
import sys success = False in_ironpython = "IronPython" in sys.version if in_ironpython: try: from ironpython_clipboard import GetClipboardText, SetClipboardText success = True except ImportError: pass else: try: from win32_clipboard import GetClipboardText, SetClipboardTex...
1,960
614
import logging logging.disable(logging.CRITICAL) import math from tabulate import tabulate from mjrl.utils.make_train_plots import make_train_plots from mjrl.utils.gym_env import GymEnv from mjrl.samplers.core import sample_paths import numpy as np import torch import pickle import imageio import time as timer import o...
17,634
6,085
import json from datetime import timedelta from decimal import Decimal import pytest from django.utils.timezone import now from pretix.base.models import Event, Order, OrderRefund, Organizer, Team, User from pretix.plugins.banktransfer.models import RefundExport from pretix.plugins.banktransfer.views import ( _ro...
4,499
1,747
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from django.conf.urls.defaults import patterns, url from datawinners.alldata.views import get_entity_list_by_type from datawinners.alldata.views import smart_phone_instruction from datawinners.alldata.views import index, reports from datawinners.alldata.views import failed_s...
872
311
from NewLifeUtils.ColorModule import ACC, MCC from NewLifeUtils.UtilsModule import hex_to_rgb from NewLifeUtils.FileModule import DataStorage, LogFile from NewLifeUtils.StringUtilModule import remove_csi from datetime import datetime import sys class Formatter(dict): def __init__(self, *args, date_format="%d-%m-%...
4,804
1,637
from rest_framework import routers from boards.api.viewsets import BoardViewSet from fleets.api.viewsets import FleetViewSet from missiles.api.viewsets import MissileViewSet app_name = 'api' router = routers.DefaultRouter() router.register(r'boards', BoardViewSet, base_name='board') router.register(r'fleets', FleetV...
440
144
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu Nguyen" at 14:22, 11/04/2020 % # ...
6,290
1,906
from estimagic.inference.ml_covs import cov_cluster_robust from estimagic.inference.ml_covs import cov_hessian from estimagic.inference.ml_covs import cov_jacobian from estimagic.inference.ml_covs import cov_robust from estimagic.inference.ml_covs import cov_strata_robust from estimagic.inference.shared import calculat...
16,106
4,157
import six import chainer import numpy as np import chainer.links as L import chainer.functions as F import nutszebra_chainer import functools from collections import defaultdict class Conv(nutszebra_chainer.Model): def __init__(self, in_channel, out_channel, filter_size=(3, 3), stride=(1, 1), pad=(1, 1)): ...
6,503
2,698
import pytest from abra import Experiment, HypothesisTest def test_large_proportions_delta_expermiment(proportions_data_large): exp = Experiment(proportions_data_large, name='proportions-test') # run 'A/A' test test_aa = HypothesisTest( metric='metric', control='A', variation='A', ...
2,945
976
# -*- coding: utf-8 -*- # pylint: disable= """ Tanuki Java Service Wrapper runtime environment. Debian JSW paths (Wheezy 3.5.3; Jessie 3.5.22):: /usr/sbin/wrapper – ELF executable /usr/share/wrapper/daemon.sh /usr/share/wrapper/make-wrapper-init.sh /usr/share/wrapper/wrapper.conf "...
1,441
441
import numpy as np class LinearRegression: def __init__(self, num_features): self.num_features = num_features self.W = np.zeros((self.num_features, 1)) def train(self, x, y, epochs, batch_size, lr, optim): final_loss = None # loss of final epoch # Training should b...
1,992
651
from copy import copy DEFAULT_SCHEDULE = {} for day in "lmwjvs": for mod in "12345678": DEFAULT_SCHEDULE[day + mod] = "'FREE'" def process_schedule(text_sc): """For a given schedule text in BC format, returns the SQL queries for inserting the full schedule and schedule info. Those queries have t...
1,655
560
# Copyright 2012 Nebula, 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 agree...
9,739
2,849
"""Tests for YesssSMS."""
26
12
# This is used by Environment to populate its env # Due to circular dependencies it cannot reference other parts of bldr import toml def default(dotbldr_path: str) -> dict: dep = { 'config': toml.load(f"{dotbldr_path}/dependency.toml"), 'lock': toml.load(f"{dotbldr_path}/dependency.lock.toml") ...
677
249
import re from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from rasa_sdk.events import SlotSet import lark_module class ActionHelloWorld(Action): state_map = {} def name(self) -> Text: return "action_hello_world" d...
5,382
1,551
from baseparser import BaseParser, grab_url, logger # Different versions of BeautifulSoup have different properties. # Some work with one site, some with another. # This is BeautifulSoup 3.2. from BeautifulSoup import BeautifulSoup # This is BeautifulSoup 4 import bs4 class PoliticoParser(BaseParser): domains = ...
1,557
496
import os import sys from queue import Queue from threading import Thread from helper.pytest import DoltConnection # Utility functions def print_err(e): print(e, file=sys.stderr) def query(dc, query_str): return dc.query(query_str, False) def query_with_expected_error(dc, non_error_msg , query_str): ...
6,535
2,345
from requests import get, post, exceptions from datetime import datetime from PyQt5 import QtWidgets, QtCore from PyQt5.QtWidgets import QMessageBox from PyQt5.QtGui import QFont from qtwidgets import PasswordEdit from client_commands import (help_client, online, status, myself, reg, role, ban, unban) from client_con...
24,598
6,878
from __future__ import unicode_literals import inspect import os import signal import sys import threading import weakref from wcwidth import wcwidth from six.moves import range __all__ = ( 'Event', 'DummyContext', 'get_cwidth', 'suspend_to_background_supported', 'is_conemu_ansi'...
6,599
2,040
# # Copyright 2013 The py-lmdb authors, all rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted only as authorized by the OpenLDAP # Public License. # # A copy of this license is available in the file LICENSE in the # top-level directory of the distribut...
92,209
28,581
# default_exp core #hide from nbdev.showdoc import * from fastcore.test import * # export import os import torch from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader import warnings import torchvision from torchvision.datasets import MNIST, ImageFolder from torchvision...
6,425
2,149
from seedwork.application.modules import BusinessModule from modules.iam.application.services import AuthenticationService class IdentityAndAccessModule(BusinessModule): def __init__(self, authentication_service: AuthenticationService): self.authentication_service = authentication_service # @staticm...
641
144
# Copyright 2015 Ufora 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 i...
2,030
650
import os import gc import random import numpy as np import torch def seed_everything(seed): os.environ['PYTHONHASHSEED'] = str(seed) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.be...
597
219
from conans import ConanFile, CMake, tools import os import shutil required_conan_version = ">=1.43.0" class FreeImageConan(ConanFile): name = "freeimage" description = "Open Source library project for developers who would like to support popular graphics image formats"\ "like PNG, BMP, JPE...
6,713
2,239
#!/usr/bin/env python # # Copyright 2007 Google 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...
110,180
33,498
# flake8: noqa import warnings import pytest import torch from sklearn.exceptions import UndefinedMetricWarning from sklearn.metrics import recall_score from torchflare.metrics.recall_meter import Recall from torchflare.metrics.meters import _BaseInputHandler torch.manual_seed(42) def test_binary_inputs(): def...
4,274
1,483
from __future__ import unicode_literals import unittest from ..utils import compose, flatten, truncate, join, unary, equals class TestEquals(unittest.TestCase): def test_it_should_return_a_function_that_compares_against_x(self): self.assertTrue(equals(234)(234)) self.assertFalse(equals(234)(123)...
1,785
662
from Utils.Array import input_array # Time : O(n2) # Space : O(1) Constant space """ Ill be having 2 pointers here one of them will move through the array looking for -ve numbers to operate on and another will be pointing to the correct location where i can put the -ve elements, after i find them also this same...
1,807
582
# coding=utf8 import socket import select from datetime import datetime from datetime import timedelta EOL = b'\n\n' response = b'HTTP/1.0 200 OK\nDate: Mon, 1 Jan 1996 01:01:01 GMT\n' response += b'Content-Type: text/plain\nContent-Length: 13\n\n' response += b'Hello, world!\n' # 创建套接字对象并绑定监听端口 servers...
2,786
1,023
import collections from pprint import pprint example1 = open("input.txt", "r").read() # grid = [[val for val in line] for line in example1.split("\n")] grid = example1.split("\n") length = 0 for line in grid: length = max(len(line), length) out = [] for line in grid: out.append(line[::-1].zfill(length)[::-1...
2,771
1,069
#!/usr/bin/env python """ test_history.py """ # Copyright (c) 2011 Paul Makepeace, Real Programmers. All rights reserved. import unittest from OR_Client_Library.openrefine_client.google.refine.history import * class HistoryTest(unittest.TestCase): def test_init(self): response = { u"code": ...
845
310
""" Provide tests for command line interface's get batch command. """ import json import pytest from click.testing import CliRunner from cli.constants import ( DEV_BRANCH_NODE_IP_ADDRESS_FOR_TESTING, FAILED_EXIT_FROM_COMMAND_CODE, PASSED_EXIT_FROM_COMMAND_CODE, ) from cli.entrypoint import cli from cli.ut...
6,160
2,609
import sys from gssl.datasets import load_dataset from gssl.inductive.datasets import load_ppi from gssl.utils import seed def main(): seed() # Read dataset name dataset_name = sys.argv[1] # Load dataset if dataset_name == "PPI": load_ppi() else: load_dataset(name=dataset_na...
364
124
# Generated by Django 2.2.16 on 2022-04-12 13:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.expressions import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('sales...
4,030
1,206
from flask.ext.wtf import Form from wtforms import StringField, BooleanField, PasswordField from wtforms.validators import InputRequired, Email, EqualTo, Length class LoginForm(Form): nickname = StringField('nickname', validators=[InputRequired()]) password = PasswordField('password', validators=[InputRequired...
881
226
from problem import Problem from typing import Any, Tuple from random import randint import ast import json def gen_num(): return str(randint(1, 9)) def gen_op(): return "+-*/"[randint(0, 3)] def gen_expr(depth): if randint(0, depth) == 0: l = gen_expr(depth + 1) r = gen_expr(depth + 1...
2,353
965
import numpy as np from .movement_matrix import movement_matrix from ..image import image_circles def movement_circles(n=50, duration=2, fps=30, width=500, height=500, **kwargs): """ >>> import pyllusion as ill >>> >>> images = ill.movement_circles(n=50, duration=4, fps=30, color="black", size=0.05) ...
690
257
#%% import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.naive_bayes import GaussianNB f...
6,853
2,733
import tensorflow as tf import numpy as np from graphsage.models import FCPartition from graphsage.partition_train import construct_placeholders from graphsage.utils import load_graph_data, load_embedded_data, load_embedded_idmap flags = tf.app.flags FLAGS = flags.FLAGS # flags.DEFINE_integer('dim_1', ...
1,876
712
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Copyright (c) 2015, Elham Abbasian <e_abbasian@yahoo.com>, Kersten Doering <kersten.doering@gmail.com> This parser reads annotated sentences (output from get_relations.py) in a tab-separated format to generate a unified XML format (Tikk et al., 2010. A compreh...
13,307
4,088
def test_add_contact(app, db, json_contacts, check_ui): contact = json_contacts list_before = db.get_contact_list() contact.id_contact = app.contact.get_next_id(list_before) app.contact.create(contact) assert len(list_before) + 1 == len(db.get_contact_list()) list_after = db.get_contact_list() ...
488
165
from django.conf import settings from django.conf.urls.static import static from django.urls import path from members import views urlpatterns = [ path('solicitud-alta/', views.signup_initial, name='signup'), path('solicitud-alta/persona/', views.signup_form_person, name='signup_person'), path('solicitud-...
1,182
394
# -*- coding: utf-8 -*- """ Created on Wed Jul 18 14:04:03 2018 @author: zyv57124 """ import scipy.io as sio import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib import matplotlib.pyplot as plt from tensorflow.python.training import gradient_descent from time import tim...
2,482
893
# Solution of Exercise 8 - Exercise_8.py # # Uploaded by Aurimas A. Nausedas on 11/23/20. # Updated by Aurimas A. Nausedas on 11/06/21. formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter,...
496
208
# solution 1: Brute Force # time complexity: O(n^2) # space complexity: O(1) def twoNumberSum(arr, n): for i in range(len(arr) - 1): firstNum = arr[i] for j in range(i + 1, len(arr)): secondNum = arr[j] if firstNum + secondNum == n: return [first...
402
148
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-28 17:32 from __future__ import unicode_literals import ckeditor.fields import destinations.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('destinati...
1,631
489
# Kontsioti, Maskell, Dutta & Pirmohamed, A reference set of clinically relevant # adverse drug-drug interactions (2021) # Code to extract single-drug side effect data from the BNF website from bs4 import BeautifulSoup import urllib import os, csv import numpy as np import pandas as pd import re from tqdm i...
8,448
2,965
from django import forms class BaseFileForm(forms.Form): # we try to minify the file to only submit the data points_file = forms.FileField( required=False, widget=forms.FileInput(attrs={'required': 'required'}), label="Location History File (.json)" ) points_data = forms.CharFi...
1,080
343
from django.utils import timezone from django.utils.text import slugify def generate_billed_document_path(instance, filename): cur_time = timezone.now() return f"{cur_time.strftime('%Y/%m')}/{slugify(instance.name)}-{cur_time.strftime('%d.%m.%Y %H:%M')}.csv"
270
101
# This Python program is used to create a plot displaying the sponge # function we use in the CASTRO hydrodynamics for the wdmerger problem. import numpy as np import matplotlib.pyplot as plt def sponge(r): sp rs = 0.75 rt = 0.85 r = np.linspace(0.0, 1.0, 1000) f = np.zeros(len(r)) idx = np.where(r < rs) f[id...
718
364
# 005 印出菱形 while(1): level = int(input()) if(level <= 0): break L = 2*level-1 mid = int((L - 1) / 2) inspa = mid * 2 - 1 for i in range(L): spa = level - i - 1 if spa >= 0: print(" " * spa, end='') print('*', end='') if spa < 0...
753
297
import numpy as np from ..tools.utils import update_dict from .utils import save_fig def plot_direct_graph(adata, layout=None, figsize=[6, 4], save_show_or_return='show', save_kwargs={}, ): df_mat = adata...
1,978
613
# Copyright 2018 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 import json import logging import os from collections import namedtuple import eth_account import eth_keys import eth_utils from eth_keys import KeyAPI from eth_utils import big_endian_to_int from ocean_lib.web3_internal.web3_provider i...
4,327
1,501
import autofront.autofront as autofront import autofront.utilities as utilities initialize = autofront.initialize add = autofront.add run = autofront.run get_display = utilities.get_display
192
62
# THIS IS A FILE TO TEST THE CODE. DO NOT USE IT AS PART OF THE CODE. import matplotlib.pyplot as plt import numpy as np from StochasticMechanics import Stochastic from scipy.optimize import minimize from Performance import PerformanceOpt from Hazards import Stationary from Building import * from BuildingProperties im...
8,444
3,743
from categorical_embedder.embedders.core.aux.custom_layers import get_custom_layer_class from categorical_embedder.embedders.core.aux.loss_factory import get_loss_function def prepare_custom_objects(custom_object_info): custom_objects = {} custom_objects.update(_prepare_custom_layers(custom_object_info["layer...
777
241
# Copyright 2014 Mirantis 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 required by...
10,406
2,769
"""Utilities.""" from functools import wraps import re from typing import Callable, List, Optional, TypeVar, Union from .data import ( all_classes, all_slots, ) def pascal_to_snake(s: str, sep: str = "_") -> str: """Convert Pascal case to snake case. Assumes that a) all words are either all-lowercas...
3,695
1,195
# # OMNIVORE CONFIDENTIAL # __________________ # # [2013] - [2019] Omnivore Technologies # All Rights Reserved. # # NOTICE: All information contained herein is, and remains # the property of Omnivore Technologies and its suppliers, # if any. The intellectual and technical concepts contained # herein are proprietary...
657
189
__author__ = ["Markus Löning"] __all__ = [ "compute_relative_to_n_timepoints", "time_series_slope", "fit_trend", "remove_trend", "add_trend" ] import numpy as np from sklearn.utils import check_array from sktime.utils.validation.forecasting import check_time_index def compute_relative_to_n_timep...
7,960
2,530
#!/usr/bin/env python from __future__ import print_function import os import sys import csv import numpy as np import math import random from collections import defaultdict import torch from torch.autograd import Variable from torch.nn.parameter import Parameter import torch.nn as nn import torch.nn.functional as F i...
2,061
809
from collections import namedtuple Accelerometer = namedtuple('Accelerometer', ["timestamp", "x", "y", "z"]) Magnetometer = namedtuple('Magnetometer', ['timestamp', 'x', 'y', 'z']) Gyroscope = namedtuple('Gyroscope', ['timestamp', 'x', 'y', 'z']) Euler = namedtuple('Euler', ['timestamp', 'x', 'y', 'z']) Quaternion = ...
1,089
284
from __future__ import print_function import os import string import argparse try: maketrans = string.maketrans # python2 except AttributeError: maketrans = str.maketrans # python3 def caeser_cipher(string_: str, offset: int, decode: bool, file_: string) -> None: """Caeser Cipher implementation, reads ...
2,847
878
from collections import defaultdict from django.contrib.contenttypes.models import ContentType from guardian.shortcuts import ( assign_perm, remove_perm, get_perms, get_users_with_perms) from onadata.apps.api.models import OrganizationProfile from onadata.apps.main.models.user_profile import UserProfi...
8,217
2,872
# Self-Driving Car Engineer Nanodegree # # ## Project: **Finding Lane Lines on the Road** # ## Import Packages #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import math import moviepy image = mpimg.imread('test_images/solidWhiteRight...
10,078
3,369
try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping import zipfile class Zip(MutableMapping): """Mutable Mapping interface to a Zip file Keys must be strings, values must be bytes Parameters ---------- filename: string mode: stri...
1,873
603
# Copyright 2014 A10 Networks # # 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 agree...
7,741
2,158
# [h] hTools2.modules.ftp """Tools to connect to a FTP server, upload files etc.""" # This module uses the `ftplib` library to handle FTP connection and upload. # http://docs.python.org/library/ftplib.html import os from ftplib import FTP def connect_to_server(url, login, password, folder, verbose=False): """Co...
1,207
372
import Net import configparser import torch from PIL import Image config = configparser.ConfigParser() config.read('./config.ini') MODEL = config.get("Network", "Model") transformations = Net.transformations net = Net.Net() net.eval() net.load_state_dict(torch.load(MODEL)) image = Image.open("./html/rwby.jpg") imag...
553
198
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RGridextra(RPackage): """Miscellaneous Functions for "Grid" Graphics. Provides a numb...
724
324
import torch from tuframework.network_architecture.generic_UNet import Generic_UNet from tuframework.network_architecture.initialization import InitWeights_He from tuframework.training.network_training.tuframework_variants.data_augmentation.tuframeworkTrainerV2_insaneDA import \ tuframeworkTrainerV2_insaneDA from t...
2,707
951
from typing import List from src.command.command import Command class Yum(Command): """ Interface for `yum` """ def __init__(self, retries: int): super().__init__('yum', retries) def update(self, enablerepo: str, package: str = None, disablerepo...
3,088
903
from build.chart_data_functions import get_confirmed_cases_by_county from build.chart_data_functions import get_county_by_day from build.constants import CONFIRMED_CASES_BY_COUNTIES_PATH from build.constants import COUNTY_MAPPING from build.constants import COUNTY_POPULATION from build.constants import DATE_SETTINGS fr...
1,819
604