text
string
size
int64
token_count
int64
from typing import List class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: l,r=0,len(nums)-1 ans = -1 while l<r: m = (l+r)//2 if nums[m] < target: l = m+1 else: r = m if nums[r] != tar...
834
347
#!/usr/bin/python3 import cartinit from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager, SlideTransition from kivy.lang import Builder from buttons import RoundedButton cartinit.init() # create ScreenManager as root, put all screens into sm = ScreenManager() sm.transition = SlideTransiti...
770
239
from CompartmentalSystems import smooth_reservoir_model from CompartmentalSystems import smooth_model_run from CompartmentalSystems import start_distributions
160
42
import numpy as np import re """ """ OCC_LIMIT = 10 def load_and_parse(filepath, verbose=True, pad_to_tweets=False, tweet_length=280): """ Le nom est plutot equivoque. Charge le fichier txt de chemin 'filepath' et retire les artefacts de parsing :param filepath: chemin d'acces vers le fichier (.tx...
6,482
2,160
from . import _tsp_c from .tsp_c import solve_greedy from .tsp_c import solve_SA from .tsp_c import set_param_SA from .tsp_c import solve_PSO
141
57
""" Data model for results of test cases :Author: Jonathan Karr <karr@mssm.edu> :Date: 2021-01-01 :Copyright: 2021, Center for Reproducible Biomedical Modeling :License: MIT """ from .._version import __version__ from ..warnings import TestCaseWarning # noqa: F401 import enum __all__ = [ 'TestCaseResultType', ...
4,496
1,193
# The MIT License (MIT) # # Copyright © 2021 Fridtjof Gjengset, Adele Zaini, Gaute Holen # # 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 ...
8,834
3,521
import json import shelve import sys import os import click from prettytable import PrettyTable import app_config as conf import analytics def get_json_out(raw_text): """Convert input raw text and return JSON.""" return json.dumps(raw_text, indent=4, sort_keys=False) def get_human_out(raw...
3,521
1,047
# Copyright (C) 2020 Zurich Instruments # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import numpy as np class SHFWaveform(object): """Implements a waveform for single channel. The 'data' attribute holds the waveform samples with th...
4,065
1,128
# from django.utils.translation import ugettext_lazy as _ # from django import forms # from django.contrib.auth.forms import ReadOnlyPasswordHashField # # from mongoengine.django.auth import User # # from mongodbforms import DocumentForm # # class UserCreationForm(DocumentForm): # """ # A form that creates a us...
3,905
1,110
""" Runs tests for Ptyhon Odin SDK """ import unittest from os import environ import random from pymongo import MongoClient import pyodin as odin class OdinSdkTest(unittest.TestCase): """ Establish OdinSdkTest object """ def setUp(self): client = MongoClient(environ.get('ODIN_MONGODB')) mongo...
2,554
829
from artemis.general.dict_ops import cross_dict_dicts, merge_dicts __author__ = 'peter' def test_cross_dict_dicts(): assert cross_dict_dicts({'a':{'aa': 1}, 'b':{'bb': 2}}, {'c': {'cc': 3}, 'd': {'dd': 4}}) == { ('a','c'):{'aa':1, 'cc':3}, ('a','d'):{'aa':1, 'dd':4}, ('b','c'):{'bb':2, 'c...
657
304
# Copyright 2021 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 agreed to in writing, ...
1,317
407
class Solution: def paintHouse(self, cost:list, houses:int, colors:int)->int: if houses == 0: # no houses to paint return 0 if colors == 0: # no colors to paint houses return 0 dp = [[0]*colors for _ in range(houses)] dp[0] = cost[0]...
908
373
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, division, print_function, absolute_import import sys import os import threading import warnings import locale import logging import win32api import win32con import win32gui import win32ts PY2 = sys.version_info < (3,) if PY2: ...
6,445
2,316
# * coding:utf-8 * # Author : Lucy Cai # Create Time : 2019/4/12 # IDE : PyCharm # Copyright(C) 2019 Lucy Cai/plumefox (LucysTime@outlook.com) # Github:https://github.com/plumefox/BiliTrend/ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
7,893
2,639
import numpy as np import pandas as pd import os.path as path import abydos.distance as abd import abydos.phonetic as abp import pytest from scipy.sparse import csc_matrix from sklearn.feature_extraction.text import TfidfVectorizer import name_matching.name_matcher as nm @pytest.fixture def name_match(): package...
29,914
10,138
''' Created on Dec 21, 2014 @author: Ben ''' def create_new_default(directory: str, dest: dict, param: dict): ''' Creates new default parameter file based on parameter settings ''' with open(directory, 'w') as new_default: new_default.write( '''TARGET DESTINATION = {} SAVE DESTINATION = {}...
645
233
import numpy as np import math import ROOT import sys class DistrReader: def __init__(self, dataset): self.stat_error = 0 self.sys_error = 0 self.plambda = 0 self.dataset = str(dataset) self.hist = ROOT.TH1D('','', 100, -0.2, 0.2) self.distr = ROOT.TH1D('','', 64, 0,...
4,129
1,595
""" Bad Apps Blog Author: Brandon Eskridge (a.k.a. 7UR7L3) (Initial commit is based on the official Flask tutorial) About: This app began as an (essentially) exact copy of the official Flask tutorial (linke below). It is intented as an opportunity to practice application security, secure design, and secure coding t...
2,364
722
from django.conf.urls import patterns, url from status import views urlpatterns = patterns('', url(r'^ups$', views.ups_status, name='ups_status'), url(r'^tor$', views.tor_status, name='tor_status'), )
204
72
import os import json from common import update_json_file, get_logger, exec_cmd from yamlparser import Parser from pathlib import Path logger = get_logger("update-image") # Functions that work to update gluu_versions.json def determine_final_official_and_dev_version(tag_list): """ Determine official version...
9,100
3,002
from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.lib.pagesizes import A3 from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle from reportlab.lib.enums import TA_CENTER import datetime class Crea...
2,767
949
from jax import config config.update("jax_enable_x64", True) from jax import custom_jvp, numpy as np from timemachine.lib.potentials import SummedPotential def _make_selection_mask(compute_du_dx=False, compute_du_dp=False, compute_du_dl=False, compute_u=False): return (compute_du_dx, compute_du_dp, compute_du_...
2,958
1,029
from bs4 import BeautifulSoup as soup from urllib.request import Request, urlopen from datetime import date import math import openpyxl import pandas as pd fname = 'https://www.governing.com/gov-data/census/state-minority-population-data-estimates.html' req = Request(fname, headers={'User-Agent': 'Mozilla/5.0'}) webpa...
996
382
from django.core.exceptions import FieldError from staff.models import Staff import re def get_choices(): # choices in a seperated funtion to change it easier STATUS_CHOICES = ( ('', ''), ('Test', 'Test'), ('Fertig', 'Fertig'), ('Löschen', 'Löschen'), ('Vertrieb', 'Vert...
7,601
2,332
from pydantic import BaseModel from app.orm_models.phone import Phone from tortoise.contrib.pydantic import pydantic_model_creator Phone_Pydantic = pydantic_model_creator(Phone, name="Phone") PhoneIn_Pydantic = pydantic_model_creator( Phone, name="PhoneIn", exclude_readonly=True)
287
97
# Need this to fix types from __future__ import annotations import tempfile import threading from typing import Union, Iterable, Dict, Tuple from suls.sul import SUL from graphviz import Digraph import random from itertools import product class MealyState: def __init__(self, name: str, edges: Dict[str, Tuple[M...
6,403
1,809
from threading import Thread from flask import current_app,render_template from flask_mail import Message from . import mail def send_async_email(app,msg): with app.app_context(): mail.send(msg) def send_email(to,subject,template,**kwargs): app=current_app._get_current_object() msg=Message(app.con...
636
210
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 10 18:30:46 2021 @author: fearthekraken """ import AS import pwaves import sleepy import pandas as pd #%% ### FIGURE 1C - example EEGs for NREM, IS, and REM ### ppath = '/home/fearthekraken/Documents/Data/photometry' AS.plot_example(ppath, 'ha...
29,708
13,256
from .filter_service import FilterService
42
10
import pickle from copy import deepcopy from graphviz import Digraph from torch.nn import Conv2d, MaxPool2d, ELU, Dropout, BatchNorm2d import pandas as pd from EEGNAS.model_generation.abstract_layers import IdentityLayer, ConvLayer, PoolingLayer, ActivationLayer from EEGNAS.model_generation.custom_modules import Ident...
4,177
1,495
from requests.auth import AuthBase import hmac import base64 import hashlib import urlparse import urllib #add your custom auth handler class to this module class MyEncryptedCredentialsAuthHAndler(AuthBase): def __init__(self,**args): # setup any auth-related data here #self.username = args['usern...
3,910
1,136
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE.txt in the project root for # license information. # -------------------------------------------------------------------------- from azure...
1,515
384
from .trial import Trial, NoTrial from .member import Member from .population import Population __all__ = ['Trial', 'NoTrial', 'Member', 'Population']
152
48
import multiprocessing from tqdm import tqdm import os import gdal from .downloader import downloader from .obsclient import bucket from .vector import Vector def Process( VectorDataSource, WgsCord, Class_key, DataSourcesType='Google China', DataSetName="DataSet", Remote_dataset_root="DataS...
7,003
2,104
import sys from setuptools import setup required_packages = ["boombox", "Pillow", "PyYAML", "rich"] win_packages = ["keyboard"] unix_packages = ["pynput"] WIN = "win32" LINUX = "linux" MACOS = "darwin" if sys.platform == WIN: required_packages += win_packages elif sys.platform in (LINUX, MACOS): required_pa...
1,016
362
from zipcodes import is_valid from random import randint from all_lunch_locs import call_lunch_api default_max = 30 default_range = 20 def random_zip(): # because what matters is good food, not close food. random_zip = 0 # because strings are required for this module while not is_valid(str(random_zip...
2,609
874
""" # -*- coding: utf-8 -*- __author__ = "Trakos" __email__ = "mhdeiimhdeiika@gmail.com" __version__ = 1.0.0" __copyright__ = "Copyright (c) 2019 -2021 Leonard Richardson" # Use of this source code is governed by the MIT license. __license__ = "MIT" Description: py-Insta Is A Python Library ...
1,414
425
from pyopenproject.api_connection.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.post_request import PostRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.membership.membership_command import Member...
1,182
278
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from lottery.branch import base import models.registry from pruning.mask import Mask from pruning.pruned_model import PrunedModel...
5,783
1,887
#!/usr/bin/env python # -*- coding: UTF-8 -*- from collections import OrderedDict from decimal import Decimal from parser_data import InlineList, DuplicationList from state import State, StateMachine from type_check import is_int, is_float, is_sci_notation from format import format from error import DMPException cl...
6,400
1,939
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project # root for license information. from typing import List from pathlib import Path from azure.storage.blob import ContainerClient from redact.types.file_bundle import FileBundle class BlobRead...
1,795
525
import torch import math from .grids import * from .conversions import * # ============================================================================= # Equirectangular mapping functions # ============================================================================= # # Note that there is no concept of padding for ...
8,111
2,685
import json from typing import Any, Callable, Dict, Optional import attr from .interfaces import Event, Router @attr.s(kw_only=True) class SingleRoute(Router): """ Routes to a single defined route without any conditions. :param route: The single defined route. Only set via ``add_route``. """ ...
8,164
2,357
"""autogenerated by genpy from multi_map_server/VerticalOccupancyGridList.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class VerticalOccupancyGridList(genpy.Message): _md5sum = "7ef85cc95b82747f51eb01a16bd7c795" _type = "multi_map_server/Verti...
6,026
2,007
""" ============== GLVQ Benchmark ============== This example shows the differences between the 4 different GLVQ implementations and LMNN. The Image Segmentation dataset is used for training and test. Each plot shows the projection and classification from each implementation. Because Glvq can't project the data on its ...
2,718
1,247
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2020 Nathaniel Fitzenrider <https://github.com/nfitzen> # # SPDX-License-Identifier: CC0-1.0 # Jesus Christ this was overengineered to Hell and back. from typing import List, Tuple, Union with open('input.txt') as f: instructions = f.readlines() class Console(): ...
2,662
834
from flask import Flask, request, jsonify from flask_restful import Api, Resource from flask_cors import CORS import json, os from models import db, User from UserList import UserList from PicturesList import Picture, PicturesList, Uploader basedir = os.path.dirname(os.path.abspath(__file__)) SQLALCHEMY_DATABASE_URI ...
1,010
377
# Ying Tung Lau - sharonlau@brandeis.edu # Jiaying Yan - jiayingyan@brandeis.edu # <editor-fold desc="import modules"> import pandas as pd import numpy as np import json import os import re import dash import dash_table import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_compon...
40,518
12,455
import scipy.signal as sig import numpy as np from qm.qua import * import matplotlib.pyplot as plt import warnings from qm.QuantumMachinesManager import ( SimulationConfig, QuantumMachinesManager, LoopbackInterface, ) ntaps = 40 delays = [0, 22, 22.25, 22.35] def delay_gaussian(delay, ntap...
2,888
1,012
#!/usr/bin/env python import sys class message(object): def add(self, idx, b): self.message[idx] = b if (b == '\x04') and self.is_complete(): self.print_message() def get_eom_idx(self): for i in sorted(self.message.keys()): if self.message[i] == '\x04': ...
1,696
572
class Solution(object): def intToRoman(self, num): """ 数字到罗马数字的转换 :type num: int :rtype: str """ dic = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]#两个数组,从高到低 res = "" ...
478
253
def setopts(defaults, given): """Override default keyword dictionary options. kwargs = setopts(defaults, kwargs) A warning is shown if kwargs contains a key not found in default. """ # Override defaults for key, value in given.items(): if type(given[key]) == dict: setopts(...
12,780
3,773
"""Convert file format.""" import fire import fromconfig def convert(path_input, path_output): """Convert input into output with load and dump.""" fromconfig.dump(fromconfig.load(path_input), path_output) if __name__ == "__main__": fire.Fire(convert)
269
85
from __future__ import unicode_literals, print_function, division import feedparser import dataset from twisted.internet.reactor import callLater from threading import Thread import twisted.internet.error import logging logger = logging.getLogger('module_rss') DATABASE = None updater = None botref = None config = {} ...
11,257
3,391
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os, ops, utils # Standard Imports from absl import flags import absl.logging as _logging # pylint: disable=unused-import import numpy as np import tensorflow as tf from PIL import Image import input_pi...
15,335
5,110
from nameko.timer import timer class Service: name ="service" @timer(interval=1) def ping(self): # method executed every second print("pong")
172
51
from .. import bp from flask import request, render_template, flash, redirect, url_for from flask_login import current_user, login_required from app.lib.base.provider import Provider from app.lib.base.decorators import admin_required @bp.route('/slack', methods=['GET']) @login_required @admin_required def slack(): ...
752
233
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='FarasaPy3', version='3.0.0', packages=find_packages(exclude=['tests*']), license='MIT', description='Farasa (which means “insight” in Arabic), is a fast and accurate te...
845
288
import ase from ase.spacegroup import crystal from ase.units import kB,mol,kJ import spglib import pyxtal from pyxtal.symmetry import Group import numpy # arrays import math # log import os.path # isfile, isdir import copy # copy dictionary imp...
45,026
13,871
__author__ = "Laurence Elliott - 16600748" from capstone import * import pefile, os # samplePaths = ["testSamples/" + sample for sample in os.listdir("testSamples")] samplePaths = ["../bin-utf8-vec/benignSamples/" + sample for sample in os.listdir("../bin-utf8-vec/benignSamples")] + \ ["../bin-utf8-vec/malwareSamples...
2,166
810
from django.apps import AppConfig class MessagingConfig(AppConfig): name = 'chat.messaging' def ready(self): try: import chat.messaging.signals # noqa F401 except ImportError: pass
233
69
import unittest import os import sys import StringIO path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lvsm'))) from lvsm.modules import keepalived class Keepalived(unittest.TestCase): """Tests for the functionality of the keepalive...
2,051
567
""" Copyright 2014-2018 University of Illinois 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 writ...
1,416
495
""" Cache abstractions for use with API resources. """ from abc import ABC, abstractmethod class CacheBase(ABC): """ A simple key-value cache interface. """ @abstractmethod def get(self, key): pass @abstractmethod def set(self, key, value, ttl=None): """ Set a ke...
912
268
#!/usr/bin/env python2.7 import time from http_request_randomizer.requests.proxy.requestProxy import RequestProxy if __name__ == '__main__': start = time.time() req_proxy = RequestProxy() print "Initialization took: {0} sec".format((time.time() - start)) print "Size : ", len(req_proxy.get_proxy_list()...
876
290
#!/usr/bin/env python """ data.py """ import itertools def loopy_wrapper(gen): while True: for x in gen: yield x class ZipDataloader: def __init__(self, dataloaders): self.dataloaders = dataloaders self._len = len(dataloaders[0]) def __len__(self): return...
555
189
# Copyright (c) 2013, masonarmani38@gmail.com and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(filters=None): columns, data = ["Sales Person: Link/Sales Person200", "Item:Link/Item:200","Item Name:Data:200","Qty:Float:200","Amount:Cu...
1,180
454
import shutil import sys def check_disk_usage(disk, min_absolute, min_percent): '''return true if there is enough free disk space, else false''' du = shutil.disk_usage(disk) percent_free= 100*du.free/du.total gigabytes_free = du.free/2**30 if percent_free<min_percent or gigabytes_free < min_absolut...
484
166
"""Test.""" import os import unittest import pytest from utils import www TEST_JSON_URL = os.path.join( 'https://raw.githubusercontent.com', 'nuuuwan/misc-sl-data/master', 'sl_power_station_info.json', ) TEST_TSV_URL = os.path.join( 'https://raw.githubusercontent.com', 'nuuuwan/gig-data/master',...
1,796
651
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. from typing import Optional from statistics import median import functools from google.protobuf.json_format import MessageToJson, Parse from pyqrllib.pyqrllib import b...
19,511
5,640
import os.path from timeit import default_timer as timer import data.make_stterror_data.utils as utils from data.make_stterror_data.handler import HandlerIntent from data.make_stterror_data.parser import snips_parser __author__ = "Gwena Cunha" """ Main module for Snips text -> TTS -> STT -> wrong text """ def ...
2,670
949
import tkinter as tk from PIL import Image, ImageTk from cv2 import cv2 import numpy as np import mediapipe as mp from keyboard import press_and_release as press from json import load from data_preprocessor import DataGenerator from gestures import GESTURES import tensorflow as tf TARGET_FRAMERATE...
5,591
1,906
import logging from typing import Dict, List from wykop.api.api_const import PAGE_NAMED_ARG, BODY_NAMED_ARG, FILE_POST_NAME from wykop.core.credentials import Credentials from wykop.core.requestor import Requestor log = logging.getLogger(__name__) class WykopAPI: """Wykop API version 2.""" def __init__(se...
12,761
3,670
from brainbox.singlecell import acorr, calculate_peths import unittest import numpy as np class TestPopulation(unittest.TestCase): def test_acorr_0(self): spike_times = np.array([0, 10, 10, 20]) bin_size = 1 winsize_bins = 2 * 3 + 1 c_expected = np.zeros(7, dtype=np.int32) ...
1,461
577
import pytest import re import unittest import metric_learn import numpy as np from sklearn import clone from test.test_utils import ids_metric_learners, metric_learners, remove_y from metric_learn.sklearn_shims import set_random_state, SKLEARN_AT_LEAST_0_22 def remove_spaces(s): return re.sub(r'\s+', '', s) def ...
11,958
4,162
#!/usr/bin/env python ''' Optimize molecular geometry within the environment of QM/MM charges. ''' from pyscf import gto, scf from pyscf.geomopt import berny_solver from pyscf.geomopt import geometric_solver mol = gto.M(atom=''' C 0.000000 0.000000 -0.542500 O 0.000000 0.000000 ...
881
397
import numpy as np import pandas as pd import scipy as sc from scipy.stats import randint, norm, multivariate_normal, ortho_group from scipy import linalg from scipy.linalg import subspace_angles, orth from scipy.optimize import fmin import math from statistics import mean import seaborn as sns from sklearn.cluster imp...
8,251
3,218
from sqlite3 import Row from fastapi.param_functions import Query from pydantic import BaseModel from typing import Optional class CreateUserData(BaseModel): user_name: str = Query(...) wallet_name: str = Query(...) admin_id: str = Query(...) email: str = Query("") password: str = Query("") cla...
793
257
import numba as nb import numpy as np import torch from torch.autograd import Function from Constants import MPS_KERNEL as w from Constants import BASE_RADIUS, ND_RAIUS, GRAD_RADIUS, LAP_RADIUS class DivOp(Function): """Compute the divergence of a given physics value. Implement in terms of pytorch autogra...
3,215
1,162
# LinearRegression.py # March 2018 # # This script builds a Linear regression class to analyse data. # It supports a continuous response and several continuous features. # The class has a constructor building and fitting the model, and # a plotting method for residuals. # # Dependencies: # # Usage: # from pythia.Li...
5,274
1,527
"""Exceptions for Renault API.""" class RenaultException(Exception): # noqa: N818 """Base exception for Renault API errors.""" pass class NotAuthenticatedException(RenaultException): # noqa: N818 """You are not authenticated, or authentication has expired.""" pass
289
90
def grayscale(image): for row in range(image.shape[0]): for col in range(image.shape[1]): avg = sum(image[row][col][i] for i in range(3)) // 3 image[row][col] = [avg for _ in range(3)]
203
80
''' ============================= EM for Linear-Gaussian Models ============================= This example shows how one may use the EM algorithm to estimate model parameters with a Kalman Filter. The EM algorithm is a meta-algorithm for learning parameters in probabilistic models. The algorithm works by first fixing t...
5,945
1,940
# encoding: UTF-8 """Physics Applications Utility""" __copyright__ = "Copyright (c) 2015, Facility for Rare Isotope Beams" __author__ = "Dylan Maxwell" __version__ = "0.0.1" import logging import phylib import machine from machine import * from phylib.libCore import * # configure the root logger logging.basicConfi...
382
144
#!python3 # # Copyright (C) 2014-2015 Julius Susanto. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """ PYPOWER-Dynamics Functions for standard blocks (solves a step) """ import numpy as np # Gain block # yo = p * yi # p is a scalar gain c...
1,902
876
# -*- coding: utf-8 -*- # Generated by Django 1.11.25 on 2019-11-13 21:50 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('river', '0011_auto_20191110_1411'), ] operations =...
2,151
669
from collections import namedtuple import pytest from nesta.packages.examples.example_package import some_func @pytest.fixture def mocked_row(): def _mocked_row(*, id, name): Row = namedtuple('Row', ['id', 'name']) return Row(id=id, name=name) return _mocked_row class TestSomeFunc: def...
929
339
import asyncio import unittest import unittest.mock import shc.misc from test._helper import ExampleSubscribable, ExampleWritable, async_test, ExampleReadable class MiscTests(unittest.TestCase): @async_test async def test_two_way_pipe(self) -> None: pipe = shc.misc.TwoWayPipe(float) pub_lef...
6,408
2,220
# -*- coding: utf-8 -*- """Supports F10.7 index values. Downloads data from LASP and the SWPC. Properties ---------- platform 'sw' name 'f107' tag - 'historic' LASP F10.7 data (downloads by month, loads by day) - 'prelim' Preliminary SWPC daily solar indices - 'daily' Daily SWPC solar indices (cont...
27,709
8,126
# Generated by Django 3.0.5 on 2020-08-13 19:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0003_auto_20200813_1943'), ] operations = [ migrations.AlterField( model_name='user', name='emailConfirmToke...
486
193
import glfw import OpenGL.GL as gl import imgui from imgui.integrations.glfw import GlfwRenderer def app(render): imgui.create_context() window = impl_glfw_init() impl = GlfwRenderer(window) while not glfw.window_should_close(window): glfw.poll_events() impl.process_inputs() gl...
1,394
499
from __future__ import absolute_import import locale import os from rabbitvcs.util.log import Log import rabbitvcs.util.settings import rabbitvcs.util.helper log = Log("rabbitvcs.util.locale") def initialize_locale(): try: settings = rabbitvcs.util.settings.SettingsManager() sane_default = local...
1,472
428
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Usage: %(scriptName) <bug_report_file> <data_prefix> """ import json from timeit import default_timer import datetime import numpy as np import pickle import sys from multiprocessing import Pool from operator import itemgetter from scipy import sparse from sklearn.fe...
7,378
2,575
import argparse import os import sys from lib.graph import Graph from lib.types import BeaverException, Uri from lib.command import OutCommand import sys reload(sys) sys.setdefaultencoding('utf8') from __init__ import __version__ arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--version', help='print ...
4,270
1,155
def get_cross_sum(n): start = 1 total = 1 for i in range(1, n): step = i * 2 start = start + step total += start * 4 + step * 6 start = start + step * 3 return total print(get_cross_sum(501))
242
91
import typing as T from dataclasses import dataclass, field from moonleap import Resource from titan.react_pkg.component import Component class Router(Component): pass @dataclass class RouterConfig(Resource): component: Component url: str params: T.List[str] = field(default_factory=list) wraps:...
1,509
420
import numpy as np from collections import defaultdict class Agent: def __init__(self, nA=6): """ Initialize agent. Params ====== - nA: number of actions available to the agent """ self.nA = nA self.actions = list(range(nA)) self.Q = defaultdict(lam...
2,119
629
# -*- coding: utf-8 -*- """ /*************************************************************************** VisicomReverseGeocoder A QGIS plugin plugin for reverse geocoding from visicom api Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ...
11,271
3,245