text
string
size
int64
token_count
int64
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): sorted_arr = sorted(arr) min_sum = sum(sorted_arr[:-1]) max_sum = sum(sorted_arr[1:]) print(min_sum, max_sum) if __name__ == '__main__': arr = list(map(int, input...
364
133
# -*- coding: utf-8 -*- import json import math import random import time import requests import scrapy from scrapy.http import HtmlResponse from scrapy import Request from spiders.common import OTA from spiders.items.spot import spot from spiders.items.price import price class QunarSpider(scrapy.Spider): # 标签 ...
15,322
5,458
#!/usr/bin/env python3 import argparse import os import sys import random import math from tqdm import tqdm from collections import Counter import operator import numpy as np FLAGS = None next_random = 1 def subsampling_bool(freq, sampling): global next_random next_random = (next_random * 25214903917 + 11)...
5,941
1,874
import pandas as pd # Read the Hofstede indices into a pandas dataframe data = pd.read_csv("..\\data\\Hofstede Insights - Manual 2021-05-13.csv", delimiter=",", index_col="country") # Transform all data in the dataframe to strings data["pdi"] = data["pdi"].astype(str) data["idv"] = data["idv"].astype(str) dat...
819
286
# pylint: disable="import-error" from command_line_creator import CommandLineCreator from current_cmd_b import CurrentCMD_B class CmdCreatorB(CommandLineCreator): def create_cmd(self): current_cmd = CurrentCMD_B(self.output) return current_cmd
269
85
from utils import _conv2d, _bn, _block import tensorflow as tf def WideResNet(x, dropout, phase, layers, kval, scope, n_classes = 10): # Wide residual network # 1 conv + 3 convblocks*(3 conv layers *1 group for each block + 2 conv layers*(N-1) groups for each block [total 1+N-1 = N groups]) = layers # 3*2*(N...
1,744
740
# -*- coding: utf-8 -*- """ Created on Sun Mar 06 00:27:21 2016 @author: maheshwa """ from __future__ import print_function import requests import time import binascii import hashlib import json # Authentication class AdobeAnalytics: def __init__(self, user_name, shared_secret, endpoint='', debug=False): ...
21,700
6,046
import logging import functools import mock from testify import TestCase, setup from testify import class_setup, class_teardown from testify import teardown import time from tron.utils import timeutils log = logging.getLogger(__name__) # TODO: remove when replaced with tron.eventloop class MockReactorTestCase(Test...
2,750
855
from classes.Display import Display from classes.FinalScoreboard import FinalScoreboard from classes.Sounds import Sounds from classes.TargetArea import TargetArea from classes.Target import Target from classes.Text import Text from classes.Timer import Timer from time import time import pygame class App(object): ...
10,397
3,450
"""Provide test fixtures""" import logging import os import pytest import vcd @pytest.fixture def dummy_vcd_file(tmpdir): """Create vcd file with random data""" filename = os.path.sep.join([str(tmpdir), 'test.vcd']) with open(filename, 'w+') as fptr: with vcd.VCDWriter(fptr, timescale=(10, 'ns'),...
3,501
1,130
import discord, os from discord.ext import commands from discord.ext.commands import has_permissions, bot_has_permissions from dotenv import load_dotenv client = commands.Bot(command_prefix='-') client.remove_command('help') client.remove_command('reload') # Loads a cog @client.command() @has_permissions(administrato...
1,408
503
import sys from setuptools import setup from setuptools.extension import Extension ### unit tests for this package import topicmodel_tests ### set include dirs for numpy try: import numpy except ImportError: numpy_already_installed = False from distutils.sysconfig import get_python_lib include_numpy_...
2,177
705
import datetime from unittest import mock import pytz from django.core.exceptions import ValidationError from django.db import IntegrityError from django.test import TestCase from game.models import Ownership, Game, Player, RealEstate from game.tests.factories.ownership import OwnershipFactory from game.tests.factori...
3,311
979
# from constraint.node.SubstitutorVisitor import SubstitutorVisitor from enum import Enum class Node(object): def __init__(self): self.children = list() self.node_type = NodeType.NODE def get_vars(self, vars = set()): # recursively crawls tree and writes down all the variables ...
4,637
1,620
# Generated by Django 3.1.7 on 2021-03-28 20:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0003_auto_20210328_2029'), ] operations = [ migrations.AlterField( model_name='order', name='shipped_date',...
464
162
from .snippets import ( remove_repeating, flare, list_appending_long, level_off, ) import itertools import copy from core.models import RotatorAdminPanel class PageLoad(object): """Zwraca tyle języków ile mamy zainstalowane w ustawieniach w zakładce LANGUAGES w formacie naprzemiennym p...
12,327
4,311
import copy import math import random import numpy as np import torch from game.Player import Player class RLPlayer(Player): def __init__(self, name, game_state, action_space, parameters={}): super().__init__(name) print(f"Player {name} parameters: {parameters}") self.action_space = acti...
11,972
3,948
from functools import partial from typing import Tuple import covasim as cv import matplotlib.pyplot as plt import numpy as np import scipy.stats as st def get_current_infected_ratio(): # Returns the current ratio of infected people in germany number_infected = 651500 # https://www.deutschland.de/de/topic/p...
4,761
1,713
# -*- coding: utf-8 -*- """ Created on Wed Jun 16 11:45:09 2021 @author: Michael ODonnell @purpose: scrape NBA draft picks by year """ # import needed libraries import requests from bs4 import BeautifulSoup import pandas as pd import time # function to scrape a list of years of NBA Drafts def scrape_draft_data(star...
25,812
7,804
import urlparse,urllib2,re import datetime,logging from marcbots import MARCImportBot from pymarc import Field class AlexanderStreetPressBaseBot(MARCImportBot): """ `AlexanderStreetPressBaseBot` encapsulates the basic MARC record changes used by child classes. """ def __init__(self,ma...
19,651
6,013
class TestGetter: """ Interface for getting tests. Useful because I'd like to both be able to evolve a next test as well as play a normal game of chess with the user """ #I thought about using abstract base class for this but it feels like overkill def getNextTest(self, opponents, previousTest): raise NotI...
335
85
from sqlalchemy import mapper, util, Query, exceptions import types def monkeypatch_query_method(ctx, class_, name): def do(self, *args, **kwargs): query = Query(class_, session=ctx.current) return getattr(query, name)(*args, **kwargs) setattr(class_, name, classmethod(do)) def monkeypatch_obj...
1,915
575
UNDO_EMPTY = 'undostack-empty' UNDO_NOT_EMPTY = 'undostack-not-empty' REDO_EMPTY = 'redostack-empty' REDO_NOT_EMPTY = 'redostack-not-empty' UNDO_CHANGED = 'undostack-changed' REDO_CHANGED = 'redostack-changed'
210
100
import discord from discord.ext import commands from os import system class Mod: def __init__(self, client): self.client = client # ------------------------------- COMMANDS ------------------------------- # # Commands need to have the @commands.command decorator @commands.command(hidden=True, pass_co...
3,564
1,094
""" Example showing use of the jsgf.ext DictationGrammar class for matching and compiling rules that use regular JSGF expansions like Literal and Sequence as well as Dictation expansions. """ from jsgf import PublicRule, Sequence from jsgf.ext import Dictation, DictationGrammar def main(): # Create a simple rule...
1,316
398
"""! @brief Integration-tests for Hierarchical Sync (HSyncNet) algorithm. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest; import matplotlib; matplotlib.use('Agg'); from pyclustering.cluster.tests.hsyncnet_templates import HsyncnetTestT...
2,534
1,006
import common.assertions as assertions def run(cfg): assertions.validateAdminPassword(cfg)
92
27
lista = [[], []] valor = 0 for c in range(1, 8): valor = int(input(f'Digite o {c}o. valor: ')) if valor % 2 == 0: lista[0].append(valor) else: lista[1].append(valor) print('-=' * 30) print(f'Os valores pares digitados foram: {sorted(lista[0])}') print(f'Os valores ímpres digitados foram: {so...
758
314
'''Top-k kendall-tau distance. This module generalise kendall-tau as defined in [1]. It returns a distance: 0 for identical (in the sense of top-k) lists and 1 if completely different. Example: Simply call kendall_top_k with two same-length arrays of ratings (or also rankings), length of the top elements k (defau...
3,216
1,222
import unittest import numpy as np import bayesnet as bn class TestMatMul(unittest.TestCase): def test_matmul(self): x = np.random.rand(10, 3) y = np.random.rand(3, 5) g = np.random.rand(10, 5) xp = bn.Parameter(x) z = xp @ y self.assertTrue((z.value == x @ y).all(...
619
242
class char: def __init__(self): self.str = 15 self.dex = 15 self.con = 14 self.wis = 15 self.int = 15 self.cha = 15 def raise_stat(self): stats = [self.str, self.dex, self.con, self.int, self.wis, self.cha] min_stat = min(stats) for ind...
2,387
851
from kivy.app import App from kivy.config import Config Config.set('graphics', 'width', '500') Config.set('graphics', 'height', '640') Config.set('graphics', 'resizable', False) Config.set('kivy','window_icon','data/friday/res/icon.ico') #from kivy.core.window import Window from kivy.uix.screenmanager import ScreenMana...
4,519
1,844
fig, ax = plt.subplots() # Add a bar for the rowing "Height" column mean/std ax.bar("Rowing", mens_rowing["Height"].mean(), yerr=mens_rowing["Height"].std()) # Add a bar for the gymnastics "Height" column mean/std ax.bar("Gymnastics", mens_gymnastics["Height"].mean(), yerr=mens_gymnastics["Height"].std()) # ...
380
149
from __future__ import annotations from itests.pages.base import BaseModal, BasePage class RoleUserViewPage(BasePage): def click_disable_button(self) -> None: button = self.find_element_by_id("disable-role-user") button.click() def get_disable_modal(self) -> DisableRoleUserModal: ele...
503
152
import tensorflow as tf import numpy as np import parse def lstm_cell(size_layer, state_is_tuple = True): return tf.nn.rnn_cell.LSTMCell(size_layer, state_is_tuple = state_is_tuple) def generate(sess, sequence, noise, model, tag, length_sentence, text_vocab): sentence_generated = [] onehot = parse.embed_to_onehot(...
6,141
2,412
from mmr2web.models import * import datetime def get_payments_file(nok_per_usd=9.1412): """Default exchange rate taken from Norges Bank, Nov 22, 2019.""" payments_out = open("payments_mmrisk.csv", "w") payments_out.write("amount,message\n") total_payment = 0 for s in Situation.objects.filter(selec...
987
327
# Test Event class try: import uasyncio as asyncio except ImportError: print("SKIP") raise SystemExit import micropython try: micropython.schedule except AttributeError: print("SKIP") raise SystemExit try: # Unix port can't select/poll on user-defined types. import uselect as selec...
1,488
521
import unittest from ortec.scientific.benchmarks.loadbuilding.instance.ThreeDitemkind import ThreeDitemkind class TestItemkind(unittest.TestCase): def setUp(self): self.item_kind = ThreeDitemkind() self.item_kind.id = 1 self.item_kind.quantity = 10 self.item_kind.boundingBox...
2,861
1,019
from .structs import GameNode
30
9
import socket import ipaddress def net_family(net): if isinstance(ipaddress.ip_network(net, strict=False), ipaddress.IPv6Network): return socket.AF_INET6 return socket.AF_INET def flag6(net): return '-6' if net_family(net) == socket.AF_INET6 else ''
292
99
# # Copyright John Reid 2006 # from _biopsy import * def _hit_str( hit ): return ",".join( [ hit.binder, str( hit.location.position ), str( hit.location.positive_strand ), str( hit.p_binding ) ] ) Hit.__str__ = _hit_str def _location_start( location ): re...
4,370
1,268
# -*- coding: utf-8 -*- import click from github import Github from github.GithubException import RateLimitExceededException def main(): cli(obj={}) def get_repos(key, org, repo, url): if url: g = Github(key, base_url=url) else: g = Github(key) if org: g_org = g.get_organizat...
8,384
2,482
import numpy as np def normalize(matrix, nh=1, nl=0): """Normalizes each column in a matrix by calculating its maximum and minimum values, the parameters nh and nl specify the final range of the normalized values""" return (matrix - matrix.min(0)) * ((nh - nl) / matrix.ptp(0)) + nl def one_hot_encod...
1,876
588
from pyimagesearch.searcher import Searcher from pyimagesearch.utils import * import pytest indexPath = "D:/APP/cbis/" verbose = True #test Search class @pytest.fixture def searcher(): return Searcher(indexPath, verbose) pred_file = "D://APP//cbis//tests//out//predictions_test.csv" top_k = 20 def test_search_g...
1,304
486
""" Provides functions for working with NTFS volumes Author: Harel Segev 05/16/2020 """ from construct import Struct, Padding, Computed, IfThenElse, BytesInteger, Const, Enum, Array, FlagsEnum, Switch, Tell from construct import PaddedString, Pointer, Seek, Optional, StopIf, RepeatUntil, Padded fro...
9,484
3,446
from ortools.linear_solver import pywraplp from ortools.sat.python import cp_model my_program = [ ["inp", "w"], ["mul", "x", "0"], ["add", "x", "z"], ["mod", "x", "26"], ["div", "z", "1"], ["add", "x", "12"], ["eql", "x", "w"], ["eql", "x", "0"], ["mul", "y", "0"], ["add", "y", ...
7,130
3,300
import xlsxwriter from slugify import slugify import os def write_to_xlsx(filename, title="Worksheet", data=None): directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) workbook = xlsxwriter.Workbook(filename) worksheet = workbook.add_worksheet(slugify(title)[:28]) row_...
486
189
import numpy as np def sisEcua(mat_A, mat_B): a_inv = np.linalg.inv(mat_A) C = a_inv.dot(mat_B.T) return C def matrices(sm, smm, smy, smn, datos, cant_datos): dimension = datos+1 s = (dimension, dimension) mat_A = np.zeros(s) mat_B = np.matrix(smy) # contadores n = len(smn) ...
4,251
1,983
#Para mostra qualquer coisa na tela, Você usa o print() print('Alesson', 'Sousa', sep='_')# O função sep='-' fala para o print o que colocar para separa os nome print('Alesson', 'Sousa', sep='_', end='\n')#esse end='' é para fala o que vc quer no final da linha do print #Exemplo #123.456.789-00 print('123','456','7...
354
154
# 闭包 def func(): a = 1 b = 2 return a + b def sum(a): def add(b): return a + b return add # add 函数名或函数的引用 # add() 函数的调用 num1 = func() num2 = sum(2) print(num2(5)) print(type(num1)) print(type(num2))
232
119
"""About tags inherited from standard mode Attributes BASE_GRAMMAR: The base grammar for python mode tag_manager: The tag manager for python mode """ from pathlib import Path from ...tags.manager import TagManager as TagManagerStandard from ...tags.grammar import Grammar from ...tags.tag import Tag as TagStand...
728
218
# data_loader # __init__.py from data_loader.image_data_loader import ImageDataLoader from data_loader.coco_data_loader import COCODataLoader from data_loader.tf_example_loader import TFExampleLoader
201
61
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-02-25 11:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cms_articles', '0007_plugins'), ] operations = [ ...
2,131
663
from time import sleep import pytest import torch from torchvision.ops import roi_align class TestTorchvision: @pytest.fixture(scope="class", params=[3, 17]) def num_points(self, request): return request.param @pytest.fixture(scope="class", params=[10, 64]) def width(self, request): ...
1,561
560
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Ardalan Naseri # Created Date: Mon September 21 2020 # ============================================================================= """The module is a VCF reader to parse input...
3,550
1,078
""" Layout definitions """ from libqtile import layout from .settings import COLS from libqtile.config import Match _layout_common_settings = dict( border_focus=COLS['purple_4'], border_normal=COLS['dark_1'], single_border_width=0, ) _max_layout_settings = { **_layout_common_settings, "border_focu...
899
320
from django.test import TestCase from django.contrib.auth.models import User from .models import Profile, Neighbourhood, Post, Business # Create your tests here. class ProfileTestClass(TestCase): ''' Test case for the Profile class ''' def setUp(self): ''' Method that creates an inst...
2,865
803
from rest_framework.routers import SimpleRouter from api.suids import views router = SimpleRouter() router.register(r'suids', views.SuidViewSet, basename='suid') urlpatterns = router.urls
190
59
""" Copyright (C) 2020 Nederlandse Organisatie voor Toegepast Natuur- wetenschappelijk Onderzoek TNO / TNO, Netherlands Organisation for applied scientific research Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You...
13,944
4,661
# -*- coding: utf-8 -*- from __future__ import unicode_literals from celery import Celery, platforms app = Celery("task") app.config_from_object('celery_task.celery_config') platforms.C_FORCE_ROOT = True
208
77
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Optional, Union import numpy as np from .builder import NODES from .node import MultiInputNode, Node try: from mmdet.apis import inference_detector, init_detector has_mmdet = True except (ImportError, ModuleNotFoundError): has_mmdet...
4,677
1,386
class HaltSignal(Exception): def __init__(self): super().__init__() class Machine: def __init__(self, initial_state, possible_states): self.history = [initial_state.name] self.possible_states = possible_states self.current_state = initial_state def find_state_by_name(se...
1,325
372
from .array import Array from .grid import Grid class Cube(object): """three-dimensional array""" def __init__(self, nrows, ncols, deep, value=None) -> None: """Initializes the Cube with nrows, ncols, deep and optional value""" self.data = Array(deep) for i in range(deep): ...
708
217
import os import sys import unittest import uuid from nanome import PluginInstance from nanome.api.plugin_instance import _DefaultPlugin from nanome.api import structure, ui from nanome.util import enums, Vector3, Quaternion, config if sys.version_info.major >= 3: from unittest.mock import MagicMock e...
8,015
2,562
""" Tests of bandits. """ import numpy as np import pytest from unittest import TestCase from bandit.bandit import ( CustomBandit, EpsGreedyBandit, GreedyBandit, RandomBandit, ) from bandit.environment import Environment from bandit.reward import GaussianReward class BanditTestCase(TestCase): de...
3,175
1,104
from .release import __version__ from .generate import generate, mark_dirty, dirty, clean from .exceptions import ParsimonyException from . import generators from . import configuration from . import persistence from .defaults import set_defaults set_defaults()
265
70
from pyrecard.utils.pyrequest import pyrequest PLAN_PATH = '/assinaturas/v1/plans' def create(json): return pyrequest('POST', PLAN_PATH, json) def alter(plan_code, json): return pyrequest('PUT', f'{PLAN_PATH}/{plan_code}', json) def activate(plan_code): return pyrequest('PUT', f'{PLAN_PATH}/{plan_co...
569
218
try: from setuptools import setup, find_packages from pkg_resources import Requirement, resource_filename except ImportError: from distutils.core import setup, find_packages setup( name='Aptly-Api-Cli', version='0.1', url='https://github.com/TimSusa/aptly_api_cli', license='MIT', keywor...
1,126
393
class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.email = first+last+'@123.com' self.pay = pay def fullname(self): return('{} {}'.format(self.first,self.last)) emp_1 = Employee('hello','world',1900) emp_2 = Employee(...
417
159
""" PASSENGERS """ numPassengers = 2290 passenger_arriving = ( (0, 5, 9, 3, 0, 0, 3, 7, 5, 2, 1, 0), # 0 (2, 4, 10, 6, 0, 0, 2, 3, 4, 2, 4, 0), # 1 (4, 9, 7, 4, 2, 0, 4, 5, 7, 4, 6, 0), # 2 (9, 9, 6, 4, 1, 0, 9, 8, 2, 5, 3, 0), # 3 (4, 6, 4, 8, 2, 0, 5, 6, 7, 3, 3, 0), # 4 (4, 3, 5, 3, 1, 0, 5, 8, 2, 2, 0...
37,697
36,553
import plotly.express as px from preprocess import PreprocessHeatmap def get_figure(df): pp = PreprocessHeatmap() heatmap_df = pp.preprocess_heatmap(df) hover_template = \ ''' <b style="font-size: 20px;>%{x}, %{y}h00</b> <br> <span style="font-size: 16px;>%{z:.0f} likes générés</span> ...
658
268
from dom import e, Div, TextInput, Button, TextArea from basicboard import BasicBoard from connection import getconn from utils import queryparams, random, setseed mainseed = 80 class Forumnode(e): def __init__(self, root, args = {}): super().__init__("div") self.root = root ...
13,985
4,291
#!/usr/bin/python # -*- coding: utf-8 -*- from include import * from timecat import detect_file_format from timecat import detect_datetime_format case_num = 0 def dofo(f, start, end, regex_format_info): global case_num case_num += 1 print("case {}".format(case_num)) res = detect_file_format(f, start, ...
1,783
796
"""This file contains code for use with "Think Bayes", by Allen B. Downey, available from greenteapress.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from thinkbayes import Pmf from bowl import Bowl class Cookie(Pmf): """A map from string bowl ID to probablity."""...
1,642
580
import unittest from models import settings from models.mathbot import * from models.settings import U238_DECAY_CONSTANT, U238_DECAY_CONSTANT_ERROR, TH232_DECAY_CONSTANT, \ TH232_DECAY_CONSTANT_ERROR class MathbotTests(unittest.TestCase): ######################################## ### Outlier resistant me...
6,513
2,529
from .abstract import AbstractAuthProvider, AbstractUnauthenticatedEntity from .utils import _context_processor from flask import _request_ctx_stack, has_request_context class AuthManager: def __init__(self, app=None, unauthorized_callback=None, unauthenticated_entity_class=None): self._auth_providers = [...
2,748
696
from threading import Lock import pytest from elmo.api.decorators import require_lock, require_session from elmo.api.exceptions import LockNotAcquired, PermissionDenied def test_require_session_present(): """Should succeed if a session ID is available.""" class TestClient(object): def __init__(self...
1,659
459
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from net_utils.nn_distance import nn_distance from net_utils.relation_tool import PositionalEmbedding from models.registers import MODULES from models.iscnet.modules.proposal_module import decode_scores from configs.scannet_config...
13,400
4,647
from enum import Enum, auto from typing import List, Union, Callable from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_network, ip_address from warnings import warn class Order(Enum): HEADER_APPENDED = auto() HEADER_PREPENDED = auto() class Header: def __init__(self, ...
1,760
507
from torch import nn import torch.nn.functional as F from locs.models.activations import ACTIVATIONS class AnisotropicEdgeFilter(nn.Module): def __init__(self, in_size, pos_size, hidden_size, dummy_size, out_size, act='elu', **kwargs): super().__init__() self.num_relative_feature...
2,333
802
#! /usr/bin/env python """ Daniel Gorrie Large dataset sampler """ import random import os from os import listdir from os.path import isfile, join # Constants INPUT_FILE = 'train.features' INPUT_FILE_SIZE = 8352136 OUTPUT_FILE = 'train_small.features' SAMPLE_SIZE = 110000 INPUT_LABEL_DIR = 'labels/' OUTPUT_LABEL_DIR...
1,798
601
import re import urllib.request """ Collection of handy functions related to uniprot. Potential reimplementations of code that would be available in various packages with the goal of keeping dependencies at a minimum. """ def valid_uniprot_ac_pattern(uniprot_ac): """ Checks whether Uniprot AC is formally cor...
1,581
541
from typing import Dict, Union, Optional from uuid import UUID import requests from requests.auth import HTTPBasicAuth from yarl import URL class BaseAdapter: """Default handlers for a given node connection. Methods should be overridden for each team, as needed.""" def __init__(self) -> None: super(...
7,414
2,331
#!/usr/bin/env python ''' Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Stroh Daniel, Trautmann Jeremias All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the follo...
2,672
902
from .auth import login_required
33
9
from geom2d import Segment, make_vector_between from structures.model.bar import StrBar from .node import StrNodeSolution class StrBarSolution: """ A truss structure bar with the solution values included. This class is a decorator of the original `StrBar` class that's linked to the solution nodes, th...
5,643
1,530
import pytest pytestmark = pytest.mark.forked from unladenchant.resourcecheck import MetaMixinResourceChecker class MetaClassTest(MetaMixinResourceChecker, type): pass class BaseClass(metaclass=MetaClassTest): pass ## Testing pass and failure def rescheckPassed(): return True def rescheckFailed(): r...
1,631
544
import sys input = lambda: sys.stdin.readline().rstrip() n = int(input()) i = 666 c = 0 while True: if str(i).find("666") != -1: c += 1 if c == n: print(i) break i += 1
219
90
from peitho.errors_and_parsers.abc_sysbio.abcsysbio_parser.ODEPythonWriter import ODEPythonWriter from peitho.errors_and_parsers.abc_sysbio.abcsysbio_parser.GillespiePythonWriter import GillespiePythonWriter from peitho.errors_and_parsers.abc_sysbio.abcsysbio_parser.SDEPythonWriter import SDEPythonWriter from peitho.er...
6,419
1,740
import unittest import os import sys class ArgCatUnitTest(unittest.TestCase): def __init__(self, methodName: str) -> None: super().__init__(methodName=methodName) self._cur_path = os.path.dirname(os.path.abspath(sys.modules[self.__module__].__file__)) def abs_path_of_test_file(self, file_name:...
390
134
year= int(input("Give the value of year:")) if((year%4==0 and year%100==0) or (Year%400==0)): print("This is a leap year") else: print("This is not leap year")
173
73
from __future__ import absolute_import # -- IMPORT -- # from ..utils.interfaces import Method class PatternAttribution(Method): """CLASS::PatternAttribution: --- Description: --- > Gets the attribution using patterns. Arguments: --- Link: --- >- http://arxiv.org/abs/1705.05598.""" def __init__(sel...
535
224
def align(value, alignment=0x1000): if value % alignment == 0: return value return value + (alignment - (value % alignment))
140
43
# stdlib modules try: from urllib.response import addinfourl from urllib.error import HTTPError from urllib.request import HTTPHandler from io import StringIO except ImportError: from urllib2 import addinfourl, HTTPError, HTTPHandler from StringIO import StringIO def mock_response(req): ur...
988
301
'''Slickbird collection handler''' import logging import json from tornado.web import URLSpec import tornado.web from slickbird import datparse import slickbird.orm as orm import slickbird from slickbird.web import hbase def _log(): if not _log.logger: _log.logger = logging.getLogger(__name__) ret...
2,192
617
import pydbus bus = pydbus.SystemBus() adapter = bus.get('org.bluez', '/org/bluez/hci0') mngr = bus.get('org.bluez', '/') def list_connected_devices(): connected = [] mngd_objs = mngr.GetManagedObjects() for path in mngd_objs: con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connecte...
715
255
# -*- coding: utf-8 -*- # # 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 ...
5,079
1,507
import numpy as np import PIL.ImageColor, PIL.ImageFont from .rescale import rescale def _rgb(x): """Convert 0-1 values to RGB 0-255 values. """ return rescale(x, to=[0, 255], scale=[0, 1]) def _color(color="black", alpha=1, mode="RGB"): """Sanitize color to RGB(A) format. """ if isinstance...
7,052
2,695
import sys import argparse import fnmatch import os import re import shutil import glob import logging import multiprocessing from copy_reg import pickle from types import MethodType _logger = logging.getLogger('default') _logger.addHandler(logging.StreamHandler()) _logger.setLevel(logging.CRITICAL) def _pickle_meth...
6,971
2,241
from balldontlie import balldontlie, player, stats from matplotlib import pyplot as plt '''This function gets more information about the player by inputting their name and dataset to search''' def getplayer(firstname, lastname, datalist): for players in datalist: for info in players.data: ...
1,325
452