text
string
size
int64
token_count
int64
#!_PYTHONLOC # # (C) COPYRIGHT 2004-2021 Al von Ruff and Ahasuerus # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from isfdblib import * from isfdblib_help import * fr...
1,944
672
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from dispatch.database.core import get_db from dispatch.database.service import common_parameters, search_filter_sort_paginate from dispatch.auth.permissions import SensitiveProjectActionPermission, PermissionsDependency from .mo...
2,988
916
import os from urllib.parse import urlparse, parse_qs from builtins import str from tests import PMGLiveServerTestCase from pmg.models import db, Committee, CommitteeQuestion from tests.fixtures import dbfixture, UserData, CommitteeData, MembershipData from flask import escape from io import BytesIO class TestAdminCo...
8,479
2,405
import sys, wave import AudioAnalysis FILE_NAME = "snippet.wav" def testWavWrite(): try: f = wave.open(FILE_NAME, "rb") except Exception, e: print e print "File type is not wav!" return c = wave.open("cnv_" + FILE_NAME, "wb") print f.getnchannels() print ...
2,907
1,048
from syloga.core.map_expression_args import map_expression_args from syloga.utils.identity import identity from syloga.ast.BooleanNot import BooleanNot from syloga.ast.BooleanValue import BooleanValue from syloga.ast.BooleanOr import BooleanOr from syloga.ast.BooleanAnd import BooleanAnd from syloga.ast.BooleanNand i...
4,866
1,491
from django.conf import settings from django.contrib.auth import authenticate, login as auth_login from django.contrib.sites.models import get_current_site from django.db.models import get_model from oscar.apps.customer.signals import user_registered from oscar.core.loading import get_class from oscar.core.compat impor...
2,753
747
from parameters import * from library_time import * from paths import * import numpy as np import pylab as plt import matplotlib.pyplot as mplt mplt.rc('text', usetex=True) mplt.rcParams.update({'font.size': 16}) import logging, getopt, sys import time import os #####################################################...
2,421
899
from helper import * def doTest(): msg = doCssFileCompress('_test.css') equal(msg, '@import (url-here);.test,.test2,.test3,.test4,.test5{_width:100px;*height:100px}.test6{display:none;_width:100px;*height:100px}', 'totally compressed') msg = doCssFileCompress('_test_different_order.css') equal(msg, '....
1,196
502
import sys, os sys.path.append("C:/Users/Delgado/Documents/Research/rheology-data-toolkit/rheodata/extractors") import h5py import pandas as pd from antonpaar import AntonPaarExtractor as APE from ARES_G2 import ARES_G2Extractor # %% sys.path.append("C:/Users/Delgado/Documents/Research/rheology-data-toolkit/rheodata"...
2,728
923
from ...models.models import Topic from ..default_schema import DefaultSchema from ..generics import DeleteAction from ..register import register_action @register_action("topic.delete") class TopicDelete(DeleteAction): """ Action to delete simple topics that can be shown in the agenda. """ model = To...
382
102
from core import file_handling as file_h, driver_handling as driver_h from website_handling import website_check as wc from cookie_handling import cookie_compare websites = file_h.website_reader() driver = driver_h.webdriver_setup() try: wc.load_with_addon(driver, websites) except: print('ERROR: IN FIREFO...
686
229
import numpy as np from scipy import constants as sc from scipy.interpolate import interp1d from pathlib import Path from scipy.special import erf as Erf import pandas as pd import sys import os import csv class OpticalMedium(): available_media = list() available_media.append("Rhodamine6G") def __init__(self, opt...
4,788
2,036
from django.conf.urls.defaults import url, include, patterns from corehq.apps.appstore.dispatcher import AppstoreDispatcher store_urls = patterns('corehq.apps.appstore.views', url(r'^$', 'appstore_default', name="appstore_interfaces_default"), AppstoreDispatcher.url_pattern(), ) urlpatterns = patterns('corehq...
1,251
467
from __future__ import absolute_import import torch from torch.nn import functional class FPN(torch.nn.Module): def __init__(self, out_channels): super(FPN, self).__init__() self.out_channels = out_channels self.P5 = torch.nn.MaxPool2d(kernel_size=1, stride=2, padding=0) self.P4_c...
2,667
1,074
import unittest from biicode.common.settings.version import Version from mock import patch from biicode.client.setups.finders.finders import gnu_version from biicode.client.setups.rpi_cross_compiler import find_gnu_arm from biicode.client.workspace.bii_paths import get_biicode_env_folder_path GCC_VERSION_MAC = '''Con...
2,314
841
from distutils.core import setup setup( name="arweave-python-client", packages = ['arweave'], # this must be the same as the name above version="1.0.15.dev0", description="Client interface for sending transactions on the Arweave permaweb", author="Mike Hibbert", author_email="mike@hibbertitsolutions.co.uk"...
784
275
""" Last update: 2018-10-26 """ from exchange_calendars.extensions.calendar_extension import ExtendedExchangeCalendar from pandas import ( Timestamp, ) from pandas.tseries.holiday import ( Holiday, previous_friday, ) from exchange_calendars.exchange_calendar import HolidayCalendar from datetime import tim...
18,195
9,315
import random import numpy #import tensorflow as tf #import torch from abc import abstractmethod from sklearn.decomposition import PCA from aggregators import FedAvg, MultiKrum, AlignedAvg, TrimmedMean, Median, StratifiedAggr class SelectionStrategy: # Unchanged from original work @abstractmethod def select_ro...
5,152
1,599
from sprites import PlayerSprite import time class Player(object): def __init__(self, name, game): self.name = name self.pos = [50, 50] self.do_blit = False self.game = game self.surf = game.SCREEN self.lastMove = 99999999999 self.velo_def = [0, 0] ...
1,301
482
from typing import Sequence import torch from torch import nn class MaxPool2d(nn.Module): def __init__(self, kernel_size, **kwargs): super().__init__() stride = kwargs.setdefault('stride', kernel_size) padding = kwargs.setdefault('padding', 0) dilation = kwargs.setdefault('dilatio...
1,019
348
from gi.repository import Gtk from masterdata_abstract_window import MasterdataAbstractWindow from person_add_mask import PersonAddMask from person_list_mask import PersonListMask class PersonWindow(MasterdataAbstractWindow): def __init__(self, main_window): super(PersonWindow, self).__init__(main_windo...
433
116
import torch.nn as nn from .efficientnet import EfficientNet_B4, EfficientNet_B0 from .mobilenetv3 import MobileNetV3_Large, MobileNetV3_Small def get_trunk(trunk_name): """Retrieve the pretrained network trunk and channel counts""" if trunk_name == 'efficientnet_b4': backbone = EfficientNet_B4(pretra...
1,792
689
import module from types import ModuleType def foo(m: ModuleType): pass def bar(m): return m.__name__ foo(module) bar(module)
136
47
from unittest.mock import patch, MagicMock from pdchaosazure.webapp.actions import stop, restart, delete from tests.data import config_provider, secrets_provider, webapp_provider @patch('pdchaosazure.webapp.actions.fetch_webapps', autospec=True) @patch('pdchaosazure.webapp.actions.client.init', autospec=True) def te...
2,151
717
def stringifySong(song): return f"<'{song['title']}' by '{song['artist']}' in '{song['album']}'>"
102
39
""" echopype data model that keeps tracks of echo data and its connection to data files. """ import os import warnings import datetime as dt from echopype.utils import uwa import numpy as np import xarray as xr class ModelBase(object): """Class for manipulating echo data that is already converted to netCDF.""" ...
30,091
9,021
import cv2 import numpy as np import time class CaptureManager(object): def __init__(self, capture, preview_window_manager=None, should_mirror_preview = False): self.preview_window_manager = preview_window_manager self.should_mirror_preview = should_mirror_preview self._capture = capture...
2,755
807
""" Alpha version of a version of ELLA that plays nicely with sklearn @author: Paul Ruvolo """ from math import log import numpy as np from scipy.special import logsumexp from scipy.linalg import sqrtm, inv, norm from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression, Lasso import matplotlib.pyp...
6,937
2,158
""" MIT License Copyright (c) 2020-present phenom4n4n 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, copy, modify, merge, pub...
1,970
674
__author__ = 'katharine' import csv import struct import time import datetime def generate_files(source_dir, target_dir): stops_txt = [x for x in csv.DictReader(open("%s/stops.txt" % source_dir, 'rb')) if x['location_type'] == '0'] print "%d stops" % len(stops_txt) name_replacements = ( ('Caltra...
6,736
2,427
from PHPUnitKit.tests import unittest from PHPUnitKit.plugin import is_valid_php_version_file_version class TestIsValidPhpVersionFileVersion(unittest.TestCase): def test_invalid_values(self): self.assertFalse(is_valid_php_version_file_version('')) self.assertFalse(is_valid_php_version_file_versi...
3,218
1,114
import pytest from feed.consts import FeedVersion from feed.utils import randomize_case from feed.errors import FeedVersionError # FeedVersion.supported def test_feed_version_supported(): assert FeedVersion.supported() == { FeedVersion.RSS_2_0, FeedVersion.ATOM_1_0, } # FeedVersion.get ...
3,554
1,310
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cmsplugin_cascade', '0006_bootstrapgallerypluginmodel'), ] operations = [ ]
203
64
Credits = [ ('Bootstrap', 'https://getbootstrap.com', 'The Bootstrap team', 'MIT'), ('Bottle', 'http://bottlepy.org', 'Marcel Hellkamp', 'MIT'), ('Cheroot', 'https://github.com/cherrypy/cheroot', 'CherryPy Team', 'BSD 3-Clause "New" or "Revised" License'), ('Click', 'https://github.com/pallets/click', '...
1,380
542
#---------------- # 01_02 文本分类 #---------------- # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt # TensorFlow's version : 1.12.0 print('TensorFlow\'s version : ', tf.__version__) #---------------- # 1 下载 IMDB 数据集 #-...
3,953
1,444
from django.urls import include, path from .views import (annotation, auto_labeling, comment, example, example_state, health, label, project, tag, task) from .views.tasks import category, relation, span, text urlpatterns_project = [ path( route='category-types', view=label.Cate...
6,134
1,917
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pynwb import TimeSeries from datetime import datetime from dateutil.tz import tzlocal from pynwb import NWBFile from ipywidgets import widgets from pynwb.core import DynamicTable from pynwb.file import Subject from nwbwidgets.view import defaul...
4,855
1,654
# -*- coding: utf-8 -*- from __future__ import division from datetime import datetime, timedelta import logging import os from guessit import guessit logger = logging.getLogger(__name__) #: Video extensions VIDEO_EXTENSIONS = ('.3g2', '.3gp', '.3gp2', '.3gpp', '.60d', '.ajp', '.asf', '.asx', '.avchd', '.avi', '.bik'...
7,987
2,573
# Generated by Django 3.2.7 on 2021-10-18 23:21 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
2,756
803
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli...
4,291
1,420
""" @author: tyrantlucifer @contact: tyrantlucifer@gmail.com @blog: https://tyrantlucifer.com @file: main.py @time: 2021/2/18 21:36 @desc: shadowsocksr-cli入口函数 """ import argparse import traceback from shadowsocksr_cli.functions import * def get_parser(): parser = argparse.ArgumentParser(description=color.blue(...
7,097
2,295
import zlib import zmq import simplejson import sys, os, datetime, time """ " Configuration """ __relayEDDN = 'tcp://eddn.edcd.io:9500' #__timeoutEDDN = 600000 # 10 minuts __timeoutEDDN = 60000 # 1 minut # Set False to listen to production stream; True to listen to debug stream __deb...
9,321
2,528
def repleace_pattern(t,s,r): assert len(t) > 0 assert len(s) > 0 assert len(r) > 0 assert len(t) >= len(s) n = len(t) m = len(s) k = len(r) idx = -1 for i in range(0, n): if t[i] == s[0]: pattern = True for j in range(1,m): ...
672
289
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
2,249
675
"""Unit tests for image iteration """ import logging import unittest import numpy from data_models.polarisation import PolarisationFrame from processing_components.image.iterators import image_raster_iter, image_channel_iter, image_null_iter from processing_components.image.operations import create_empty_image_li...
6,698
2,160
import cv2 import numpy as np from scipy import ndimage def compute_motion_boudary(flow_clip): mx = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) my = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) dx_all = [] dy_all = [] mb_x = 0 mb_y = 0 for flow_img in flow_clip: d_x = ndimage...
1,501
634
import os import sys import pytest from msl.qt import convert, Button, QtWidgets, QtCore, Qt def test_text(): b = Button(text='hello') assert b.text() == 'hello' assert b.icon().isNull() assert b.toolButtonStyle() == Qt.ToolButtonTextOnly def test_icon(): path = os.path.dirname(__file__) + '/g...
3,618
1,367
from random import randint from time import sleep computador = randint(0, 5) # Faz o computador "PENSAR" print('-=-' * 20) print('Vou Pensar em Um Número Entre 0 e 5. Tente Adivinhar Paçoca...') print('-=-' * 20) jogador = int(input('Em que Número eu Pensei? ')) # Jogador tenta Adivinhar print('PROCESSANDO........') sl...
499
202
from tkinter import* import tkinter.font as font import sqlite3 name2='' regis2='' branch2='' def main(): inp=Tk() inp.geometry("430x300") inp.title("Enter The Details") inp.iconbitmap("logo/spectrumlogo.ico") f=font.Font(family='Bookman Old Style',size=15,weight='bold') f1=f...
2,691
1,019
import unittest import time import logging logging.basicConfig() from intelhex import IntelHex import Adafruit_GPIO.I2C as i2c from gpiozero import OutputDevice from gpiozero import DigitalInputDevice from ctypes import c_uint8, c_uint16, c_uint32, cast, pointer, POINTER from ctypes import create_string_buffer, Struct...
16,036
5,425
import threading class RWLock: """Synchronization object used in a solution of so-called second readers-writers problem. In this problem, many readers can simultaneously access a share, and a writer has an exclusive access to this share. Additionally, the following constraints should be met: 1) no reader should b...
2,322
837
from .fmodobject import * from .globalvars import dll as _dll from .globalvars import get_class class ChannelGroup(FmodObject): def add_dsp(self, dsp): check_type(dsp, get_class("DSP")) c_ptr = c_void_p() self._call_fmod("FMOD_ChannelGroup_AddDSP", d._ptr, byref(c_ptr)) return get_...
5,627
1,958
import sqlite3 from bottle import route, run,debug,template,request,redirect @route('/todo') def todo_list(): conn = sqlite3.connect('todo.db') c = conn.cursor() c.execute("SELECT id, task FROM todo WHERE status LIKE '1'") result = c.fetchall() c.close() output = template('make_table', rows=res...
2,214
724
"""Module to initialize Maxmind databases and lookup IP metadata.""" import logging import os from typing import Optional, Tuple, NamedTuple import geoip2.database from pipeline.metadata.mmdb_reader import mmdb_reader MAXMIND_CITY = 'GeoLite2-City.mmdb' MAXMIND_ASN = 'GeoLite2-ASN.mmdb' # Tuple(netblock, asn, as_n...
3,246
1,135
from __future__ import print_function """ This example generates random data and plots a graph in the browser. Run it using Gevent directly using: $ python plot_graph.py Or with an Gunicorn wrapper: $ gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" \ plot_graph:resource """ impo...
1,105
353
import os import numpy as np import tensorflow as tf from nas_big_data.combo.load_data import load_data_npz_gz from deephyper.nas.run.util import create_dir from deephyper.nas.train_utils import selectMetric os.environ["CUDA_VISIBLE_DEVICES"] = ",".join([str(i) for i in range(4)]) HERE = os.path.dirname(os.path.absp...
844
340
""" Summary: Utility Functions that could be helpful in any part of the API. All functions that are likely to be called across a number of classes and Functions in the API should be grouped here for convenience. Author: Duncan Runnacles Created: 01 Apr 2016 Copyri...
14,744
4,591
"""Definitions of UI content objects.""" from dataclasses import asdict from dataclasses import dataclass from enum import Enum from typing import Dict from typing import Generic from typing import TypeVar from ..utils.compatibility import TypeAlias from ..utils.serialize import SerializationFormat class ContentVie...
3,636
1,009
# u28_cerr_cfg.py: # # Non-regression test configuration file for MessageLogger service: # distinct threshold level for linked destination, where # import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") import FWCore.Framework.test.cmsExceptionsFatal_cff process.options = FWCore.Framework.test.cmsExc...
1,244
436
""" Created:04 Mar. 2020 Author: Jordan Prechac """ from revibe._helpers import const from administration.utils import retrieve_variable from content.models import Song, Album, Artist from content.serializers import v1 as cnt_ser_v1 # ----------------------------------------------------------------------------- # _...
2,001
628
""" Authors: Elena Vasileva, Zoran Ivanovski E-mail: elenavasileva95@gmail.com, mars@feit.ukim.edu.mk Course: Mashinski vid, FEEIT, Spring 2021 Date: 09.03.2021 Description: function library model operations: construction, loading, saving Python version: 3.6 """ # python imports from keras.layers import ...
4,433
1,611
#!/usr/bin/env python3 #-*- coding: utf-8 -*- from itertools import combinations def solve(packages, groups): total = sum(packages) result = 9999999999999999 # we should use `for i in range(1, len(packages) - 2)` but it would # make the computation significantly slower for i in range(1, 7): ...
631
210
import configparser import math import re import urllib from pathlib import Path from PIL import Image def get_images(image_directory, thumbnail_directory, thumbnail_size): thumbnail_directory = Path(thumbnail_directory) for file in [file for file in thumbnail_directory.glob('*')]: file.unlink() ...
5,921
2,081
""" Unit tests for SNIa truth catalog code. """ import os import unittest import sqlite3 import numpy as np import pandas as pd from desc.sims_truthcatalog import SNeTruthWriter, SNSynthPhotFactory class SNSynthPhotFactoryTestCase(unittest.TestCase): """ Test case class for SNIa synthetic photometry factory c...
4,385
1,565
# Copyright (c) 2018, DjaoDjin inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
10,053
3,009
import sys import struct def save_sf_model(model): name_dicts = {'encoder.word_lut.weight': 'SrcWordEmbed_Embed_W', 'encoder.forward_gru.linear_input.weight': 'EncGRUL2R_GRU_W', 'encoder.forward_gru.linear_input.bias': 'EncGRUL2R_GRU_B', 'encoder.forward_gru.l...
2,801
998
# Copyright 2017 Novartis Institutes for BioMedical Research 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 agre...
4,219
1,138
from binance.client import Client import PySimpleGUI as sg api_key = "your_binance_apikey" secret_key = "your_binance_secretkey" client = Client(api_key=api_key, api_secret=secret_key) # price def get_price(coin): return round(float(client.get_symbol_ticker(symbol=f"{coin}USDT")['price']), 5) def colu...
3,196
1,336
import graphene from ...unurshop.ushop import models from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation class UshopBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( graphene.ID, required=True, description="List of ushop IDs to delete." ) ...
1,026
310
import os, sys, re import json import pandas as pd import pymongo from main.LOADERS.publication_loader import PublicationLoader from main.MONGODB_PUSHERS.mongodb_pusher import MongoDbPusher from main.NLP.PREPROCESSING.preprocessor import Preprocessor class ScopusStringMatch_HAmodule(): def __ini...
3,180
947
# _ # /\ | | # / \ _ __ ___| |__ ___ _ __ _ _ # / /\ \ | '__/ __| '_ \ / _ \ '__| | | | # / ____ \| | | (__| | | | __/ | | |_| | # /_/ \_\_| \___|_| |_|\___|_| \__, | # __/ | # |___/ # Copyright (C) 20...
642
247
from core.celery.config import ERIGONES_TASK_USER from que.tasks import execute, get_task_logger from vms.models import SnapshotDefine, Snapshot, BackupDefine, Backup, IPAddress logger = get_task_logger(__name__) def is_vm_missing(vm, msg): """ Check failed command output and return True if VM is not on comp...
7,484
2,458
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: x_depth = None x_parent = None...
1,133
351
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2016 Anler Hernández ...
5,433
1,814
import torch class ClsPostProcess(object): """ Convert between text-label and text-index """ def __init__(self, label_list, **kwargs): super(ClsPostProcess, self).__init__() self.label_list = label_list def __call__(self, preds, label=None, *args, **kwargs): if isinstance(preds, ...
679
215
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import os import argparse import logging import numpy as np from PIL import Image import matplotlib import matplotlib.pyplot as plt import torch import torch.nn as nn from torchvision import transforms import cv2 import tqdm from net.pspnet import PSPNet models = { ...
5,717
2,339
from src.gridworld_mdp import GridWorld class EquiprobableRandomPolicy: def __init__(self): self.world_model = GridWorld() def get_prob(self, selected_action, state): assert state in self.world_model.states assert selected_action in self.world_model.actions num_all_possible_a...
870
247
# -*- coding: utf-8 -*- """Summary Classifier. Pipeline classifier using the basic summary statistics and an estimator. """ __author__ = ["MatthewMiddlehurst"] __all__ = ["SummaryClassifier"] import numpy as np from sklearn.ensemble import RandomForestClassifier from sktime.base._base import _clone_estimator from s...
6,013
1,855
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n):
107
34
from django.shortcuts import redirect from django.views import View class TodoView(View): all_todos = [] def post(self, request, *args, **kwargs): todo = request.POST.get("todo") important = request.POST.get("important") if todo not in self.all_todos: if important: ...
461
138
import typing as tp from unittest import TestCase import hypothesis as hp from hypothesis import strategies as st import pypeln as pl import cytoolz as cz MAX_EXAMPLES = 10 T = tp.TypeVar("T") @hp.given(nums=st.lists(st.integers())) @hp.settings(max_examples=MAX_EXAMPLES) def test_from_to_iterable(nums: tp.List[int...
705
305
import json from app.model import TrainMetrics, TrainPlots class DatastoreTest: def getRuns(self): return [ "20211210T132017", "20211209T132017", "20211208T132017" ] def getEvals(self, run): return [40, 30, 20, 10] def getHyperparameters(self, ...
410,082
333,534
import logging from collections import namedtuple logger = logging.getLogger("pybinsim.Pose") class Orientation(namedtuple('Orientation', ['yaw', 'pitch', 'roll'])): pass class Position(namedtuple('Position', ['x', 'y', 'z'])): pass class Custom(namedtuple('CustomValues', ['a', 'b', 'c'])): pass cl...
1,614
487
from flask_sqlalchemy import SQLAlchemy from flask_redis import FlaskRedis from flask_migrate import Migrate # from flask_rq2 import RQ from rq import Queue from morphocut_server.worker import redis_conn database = SQLAlchemy() redis_store = FlaskRedis() migrate = Migrate() redis_queue = Queue(connection=redis_conn)...
337
121
from __future__ import print_function """ Low-level serial communication for Trinamic TMCM-140-42-SE controller (used internally for the Thorlabs MFC1) """ import serial, struct, time, collections try: # this is nicer because it provides deadlock debugging information from acq4.util.Mutex import RecursiveMut...
12,881
4,428
import unittest from signals.generators.ios.core_data import get_current_version, get_core_data_from_folder class CoreDataTestCase(unittest.TestCase): def test_get_current_version(self): version_name = get_current_version('./tests/files/doubledummy.xcdatamodeld') self.assertEqual(version_name, 'du...
981
348
# commend the lines for plotting using import matplotlib.pyplot as plt import networkx as nx def plot_graph(G, N, time_point, posi): #setting up for graph plotting #setting the positions for all nodes pos = {} for ii in range(N): pos[ii] = posi[ii] # plt.figure(time_point + 1) elarge=[(...
848
357
from sys import stdin input = stdin.readline N = int(input()) primes = [1]*(N+1) primes[0] = 0 primes[1] = 0 for i in range(2,int(N**0.5)+1): if primes[i]: for j in range(i*i,N+1,i): primes[j] = 0 for i in range(N+1): if primes[i]: print(i,end = " ")
293
139
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, absolute_import, print_function) __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import sys import os import errno from time import sleep from powerline.lib.monotonic import monotonic from powe...
6,118
2,545
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Fake Interact """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import...
3,642
1,009
#!/usr/bin/python import sys import argparse class main: def __init__(self): parser = argparse.ArgumentParser( description='Python package for streaming, recording, and visualizing EEG data from the Muse 2016 headset.', usage='''muselsl <command> [<args>] Available commands: ...
7,727
2,002
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2021- QuOCS Team # # 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://ww...
2,420
772
from datadog_checks.base import ConfigurationError, OpenMetricsBaseCheck EVENT_TYPE = SOURCE_TYPE_NAME = 'pulsar' class PulsarCheck(OpenMetricsBaseCheck): """ PulsarCheck derives from AgentCheck that provides the required check method """ def __init__(self, name, init_config, instances=None): ...
5,803
2,024
import ipfsapi c = ipfsapi.connect() peer_id = c.key_list()['Keys'][1]['Id'] c.name_publish('QmYjYGKXqo36GDt6f6qvp9qKAsrc72R9y88mQSLvogu8Ub', key='another_key') result = c.cat('/ipns/' + peer_id) print(result)
214
115
import pygame class Window: def __init__(self, title: str, dimension: tuple): self.surface = None self.initial_title = title self.initial_dimension = dimension @property def title(self) -> str: """Returns the title of the window.""" return pygame.disp...
1,756
566
from hypothesis import given, assume, settings from hypothesis.strategies import floats from numpy import cos from pytest import approx from fastats.optimise.newton_raphson import newton_raphson def func(x): return x**3 - x - 1 def less_or_equal(x, compared_to, rel=1e-6): return ((x < compared_to) ...
1,179
479
import cv2 import os import numpy as np # This module contains all common functions that are called in tester.py file # Given an image below function returns rectangle for face detected alongwith gray scale image def faceDetection(test_img): gray_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY) # convert color...
2,701
819
import argparse from os import listdir, mkdir from os.path import join, isdir from subprocess import call import sys import datasets from shutil import which """ Script to use pdftoppm to turn the pdfs into single images per page """ def get_images(pdf_dir, output_dir, dpi, mono=True): if which("pdftoppm") is N...
2,704
872
""" A module that helps solving problems in physics. """ from . import units from .matrices import mgamma, msigma, minkowski_tensor, mdft __all__ = [ 'units', 'mgamma', 'msigma', 'minkowski_tensor', 'mdft', ]
220
79
printf("Hello world")
23
8