text string | size int64 | token_count int64 |
|---|---|---|
"""
* Words.
*
* The text() function is used for writing words to the screen.
* The letters can be aligned left, center, or right with the
* textAlign() function.
"""
def setup():
size(640, 360)
# Create the font
printArray(PFont.list())
f = createFont("Georgia", 24)
textFont(f)
def d... | 708 | 312 |
#!/usr/bin/env python
# The app.page dict:
# 'title': '',
# 'url': '',
# 'description': '',
# 'author': '',
# 'datestamp': '',
# 'keywords': '',
# 'keywords_array': '',
# 'shareimg': '',
# 'shareimgdesc': '',
details = {
'base-unemployment': {
'title': '',
'description': ... | 1,892 | 610 |
from docutils import nodes
def no_needs_found_paragraph():
nothing_found = "No needs passed the filters"
para = nodes.line()
nothing_found_node = nodes.Text(nothing_found, nothing_found)
para += nothing_found_node
return para
def used_filter_paragraph(current_needfilter):
para = nodes.paragr... | 1,144 | 355 |
from django.db import models
from django.conf import settings
from datetime import datetime
User = settings.AUTH_USER_MODEL
# Technique
class Technique(models.Model):
name = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.name... | 2,905 | 935 |
# Generated by Django 2.1.5 on 2020-06-21 19:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20200621_1606'),
]
operations = [
migrations.AddField(
model_name='post',
name='height',
... | 743 | 236 |
from pyramid.view import view_config
# ################### INDEX #################################
@view_config(route_name='account_home',
renderer='pypi:templates/account/index.pt')
def index(request):
return {}
# ################### LOGIN #################################
@view_config(route_na... | 1,173 | 334 |
from django.apps import AppConfig
class MqttServicesConfig(AppConfig):
name = 'mqtt_services'
| 100 | 32 |
#!/usr/bin/env python
import docker
import logging
import sys
import web
from rest.create import CreateR
from rest.delete import DeleteR
from rest.nics import NICsR
from rest.nlist import ListR
from rest.start import StartR
from rest.stop import StopR
module_logger = logging.getLogger(__name__)
class NControlServe... | 1,469 | 455 |
import io
import sys
import tweepy
import time
def predict(request): # serve as api function
start = time.time()
info = request.split(":")
stockcode = info[0]
data_path = "/container/c2_Twitter_Collector/dataset/" + stockcode + ".txt"
with open(data_path, 'r', encoding='utf-8') as file:
result = file.read().rep... | 410 | 148 |
import pytest
from datacrunch.exceptions import APIException
ERROR_CODE = 'test_code'
ERROR_MESSAGE = "test message"
def test_api_exception_with_code():
# arrange
error_str = f'error code: {ERROR_CODE}\nmessage: {ERROR_MESSAGE}'
# act
with pytest.raises(APIException) as excinfo:
raise APIExc... | 891 | 285 |
from pathlib import Path
from io import BytesIO
import json
from contextlib import contextmanager
import tempfile
import shutil
from django.db import models, transaction
from django.contrib.postgres.fields import JSONField
from django.conf import settings
def cache(model, keyfunc):
def decorator(func):
i... | 5,686 | 1,664 |
__author__ = 'Jack'
| 20 | 9 |
"""
myOperations is a list wich memory all values and operators entered by the user before click on "="
"""
myOperations=[]
def put_in_myOperations(value):
#this function fill myOperations list
myOperations.append(value)
def clear_myOperations():
#this function delete all values in myOperations list
... | 1,643 | 474 |
# Utilities for dealing with AUTOSAR secure on-board communication.
# (SecOC, i.e., verification of the authenticity of the sender of
# messages.)
from cantools.database.can.message import Message
from cantools.errors import Error
from typing import (
Union,
List,
Optional,
)
from cantools.typechecking i... | 3,863 | 1,037 |
#!/usr/bin/python
import os.path, sys, glob, datetime, time, subprocess, shutil, re
import xml.sax.saxutils, csv, tempfile
import choraconfig
def usage() :
print "USAGE: testing.py --run <batchname>"
print " to start a new testing run"
print " OR testing.py --format <run_id>"
print " ... | 52,453 | 17,597 |
# -*- coding: utf-8 -*-
import crawler
import mongo
# in this module, data form model will be read and spec of each model is
# recorded int he database
# import mongo driver
from pymongo import MongoClient
client = MongoClient()
db = client['test_car']
# define base link
baselink = "http://newcar.xcar.com.cn"
# ... | 1,710 | 616 |
import os,sys
import csv
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn import svm
from sklearn import linear_model
from sklearn.metrics import matthews_corrcoef
from sklearn.feature_extraction.text import TfidfVectorizer
import re
import nltk
from coll... | 1,233 | 441 |
import json
import shutil
import tempfile
import traceback
from multiprocessing import Process
from subprocess import call, check_output, CalledProcessError
from api import swift
from utils import settings, delete_directory_tree
from deploy.deploy import Deployment
from deploy.deploy_status import DeploymentStatus
f... | 3,393 | 968 |
import random
import string
class Password:
"""
Password class takes care of:
- Checks for password strength.
- Generates strong random password that contains lower/upper/numbers,
random password length 16 bits.
"""
def __init__(self):
self._password_strength = 0
... | 2,344 | 648 |
# -*- coding: utf-8 -*-
########################################################################
# #
# Main router #
# #
# MI... | 849 | 162 |
"""
Schulze STV voting implementation.
See https://en.wikipedia.org/wiki/Schulze_method
"""
from collections import defaultdict, OrderedDict
import random
def compute_strongest_paths(preference, candidates):
"""
input: preference
p[i,j] = number of voters that prefer candidate i to candidate j
in... | 5,153 | 1,622 |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 19:42:57 2018
@author: kanav
"""
import logging
from pyscf import gto, scf, ao2mo
from pyscf.lib import param
from scipy import linalg as scila
from pyscf.lib import logger as pylogger
from qiskit.chemistry import QiskitChemistryError
# from qiskit.chemistr... | 5,308 | 2,337 |
import datetime
import json
import requests
# url = 'http://localhost:8080/antenna/simulate?phi1={}&theta1={}&phi2={}&theta2={}&phi3={}&theta3={}'
url = 'https://aydanomachado.com/mlclass/02_Optimization.php?phi1={}&theta1={}&phi2={}&theta2={}&phi3={}&theta3={}&dev_key=Dual Core'
angles = ['phi1', 'theta1', 'phi2', '... | 1,673 | 536 |
from db_file_storage.form_widgets import DBAdminClearableFileInput
from django import forms
from django.contrib import admin, messages
from django.db import transaction
from django.db.models import ProtectedError
from .models import CustomField, CustomFieldChoice, FileProxy, JobResult
def order_content_types(field):... | 4,511 | 1,227 |
from dataclasses import dataclass
@dataclass
class Config:
mutation_prob: float
crossover_prob: float
| 112 | 36 |
import json
from falsy.falsy import FALSY
class CustomException(Exception):
pass
def handle_custom(req, resp, e):
resp.body = json.dumps({'error': 'custom error catched'})
resp.content_type = 'application/json'
f = FALSY(static_path='test', static_dir='demo/catch/static')
f.swagger('demo/catch/spec.y... | 407 | 142 |
"""Show Posts Method."""
from django.core.cache import cache
from main.forms import CommentsForm
from main.models import Post
def post_all():
"""Post All."""
key = Post().__class__.cache_key()
if key in cache:
objects_all = cache.get(key)
else:
objects_all = Post.objects.all()
... | 1,125 | 327 |
import pytest
import torch
DEVICES = ["cpu"]
if torch.cuda.is_available():
DEVICES.append("cuda")
@pytest.fixture(params=DEVICES)
def device(request):
"""parametrized device function,
that returns string names of the devices
that ``torch`` considers "available".
causes any test using ``device`` ... | 470 | 151 |
# Autogenerated file.
from .client import HeartRateClient # type: ignore
| 73 | 21 |
import copy
import pytest
from ckan_api_client.exceptions import HTTPError
from ckan_api_client.tests.utils.strings import gen_random_id
from ckan_api_client.tests.utils.validation import check_group
@pytest.mark.xfail(run=False, reason='Work in progress')
def test_group_crud(ckan_client_ll):
client = ckan_clie... | 3,464 | 1,118 |
def grains(n):
return 2**(n**2)-1 | 37 | 19 |
# Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique
# o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será
# mostrado ou não na tela o processo de cálculo do fatorial.
def factorial(number, show=False):
"""
Calcula o f... | 749 | 232 |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour_datasets.loaders.kuopio` module.
"""
import numpy as np
import os
import unittest
from colour import SpectralShape
from colour_datasets.loaders.kuopio import (
MatFileMetadata_KuopioUniversity, read_sds_from_mat_file_KuopioUniversity)
from colour_da... | 208,496 | 76,586 |
import re
from django import template
from faq.models import QuestionCategory, QuestionAndAnswer
register = template.Library()
class QuestionsByCategories(template.Node):
def __init__(self, categories, var_name):
self.categories = categories
self.var_name = var_name
def render(self, contex... | 1,417 | 392 |
import json
import os
import pytest
import requests
from weather import api_connector, exceptions
def test_get_city_id_unknown_city(monkeypatch):
class MockResponse:
def json(self):
return []
def raise_for_status(self):
pass
class MockRequest:
@staticmethod
... | 3,387 | 1,036 |
import csv
from textblob import TextBlob as tb
if __name__ == "__main__":
analyse_data() | 93 | 33 |
from keras import backend as K
def dice_coef(y_true, y_pred):
"""
A simple dice metric over true and predicted tensors.
We do not calculate dice axis-based, instead of this we calculate total dice
for the whole batch. It is simpler, when the result is the same as after
'fair' calculation of dice f... | 928 | 311 |
import os
import os.path
import sys
import argparse
def list_all(args):
results = search_index(q='*', start=0, rows=2000000)
for result in results:
print result['id']
print
print 'Found %d results.' % len(results)
def update_all(args):
print 'Firing off task to update entire searc... | 1,932 | 635 |
from mmdet.apis import init_detector, inference_detector, show_result
import mmcv
import os
import cv2
import sys
from mmdet.datasets.pipelines.loading import LoadPolNPZImageFromFile
from mmdet.datasets.pipelines.loading import LoadPolSubImageFromFile
import numpy as np
def load_pol_sub_image(sample_file, div_num=655... | 5,145 | 2,056 |
"""
Faça um programa que receba 6 números inteiros e mostre:
- Os números pares digitados;
- A soma dos números pares digitados;
- Os números ímpares digitados;
- A quantidade de números ímpares digitados.
"""
from random import randint
vetor = []
pares = []
impares = []
for x in range(randint(6, 50)):... | 684 | 274 |
from __future__ import unicode_literals
from django.db import models
from django_evolution.errors import SimulationFailure
from django_evolution.mutations import RenameField
from django_evolution.signature import (AppSignature,
ModelSignature,
... | 20,793 | 5,797 |
#!/usr/bin/env python3
# *******************************************************
# Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved.
# SPDX-License-Identifier: MIT
# *******************************************************
# *
# * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
# * WARRANTIES OR CO... | 26,192 | 7,207 |
# coding: utf-8
from subprocess import run
import pathlib
import os
TEST_DIR = 'tests'
ROOT_PATH = pathlib.Path(__file__).parent.parent
TEST_MODULES = ['verr']
def get_modules():
global TEST_MODULES
result = ''
if len(TEST_MODULES) > 0:
result = ' --cov=' + ' --cov='.join(TEST_MODULES)
return ... | 810 | 306 |
from generativemagic.movement import Movement
DECK_TOP = 1
DECK_BOTTOM = 52
class Effect(Movement):
def apply(self, sequence, chosen=None):
raise Exception(f"Effect method not yet implemented for {self}")
| 220 | 75 |
from PyQt5 import QtCore, QtGui, QtWidgets # , uic
from sectograph import resources, widgets, entities, datetime as dt
from .edit_window_ui import Ui_EditEventForm
repeat = {
"None": None,
"Every Day": 1,
"Every Week": 7,
"Every 2 Weeks": 14,
"Every Month": 30, # actually not a month
"Every ... | 10,159 | 3,064 |
'''
You prefer a good old 12-hour time format. But the modern world we live in would rather use the 24-hour format and you see it everywhere. Your task is to convert the time from the 24-h format into 12-h format by following the next rules:
- the output format should be 'hh:mm a.m.' (for hours before midday) or 'hh:m... | 2,010 | 710 |
# Space Complexity O(1)
# Time Complexity O(log N)
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = left + right // 2
if target == nums[mid]:
return mid
... | 447 | 132 |
import numpy as np
class GailRiskCalculator:
NumCovPattInGailModel = 216
def __init__(self):
self.bet2 = np.zeros((8,12),dtype=np.float64)
self.bet = np.zeros(8,dtype=np.float64)
self.rf = np.zeros(2,dtype=np.float64)
self.abs = np.zeros(self.NumCovPattInGailModel,dtype=np.flo... | 57,494 | 26,231 |
from rest_framework import serializers
from pki_framework.models import AerobridgeCredential
from . import encrpytion_util
from django.conf import settings
class AerobridgeCredentialSerializer(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
token_type = serializers.SerializerMethodFie... | 1,170 | 347 |
import math
import random
import pygame
from utils import config
# Constants for state of movement and rotations
NO_WAYPOINT = 1
MOVE_WAYPOINT = 2
FIRE_WAYPOINT = 3
MOVE_AND_FIRE_WAYPOINT = 4
"""Represents a generic ship.
"""
class Ship:
random.seed()
"""Constructor to make the ship.
:param x: starti... | 8,777 | 2,715 |
import os
PROJECT_PATH = os.path.dirname(__file__)
PROJECT_NO = 3
ARCHITECTURE_TYPE = 'dense'
NUM_COLS = 10
NUM_ROWS = 10
TRAINED_MODEL_NUM_ROWS = 10
TRAINED_MODEL_NUM_COLS = 10
INF = 1e9
FILE_PREFIX = "10x10"
FILE_SUFFIX = "new"
TRAIN_DATA_PREFIX = "21_to_30_probability_and_1000_each"
VALIDATION_TEST_DATA_PREFIX =... | 1,827 | 804 |
import logging
import pytest
from ocs_ci.ocs import constants
from ocs_ci.ocs.resources import mcg
from tests import helpers
from tests.helpers import craft_s3_command, create_unique_resource_name
logger = logging.getLogger(__name__)
@pytest.fixture()
def mcg_obj():
"""
Returns an MCG resource that's conne... | 3,919 | 1,220 |
#!/usr/bin/env python3
import sys
import random
n = int(sys.argv[1])
max_w = int(sys.argv[2])
seed = int(sys.argv[3])
k = 3
random.seed(seed)
print(n)
for _ in range(k+1):
A = []
for i in range(n):
A.append(random.randint(1, max_w))
print(*A)
| 266 | 118 |
# -*- coding: utf-8 -*-
from .directives import automodule_bound, autodirective_bound
from .extractor import _get_roots
def setup(app):
app.add_config_value('js_roots', _get_roots, 'env')
modules = {}
app.add_directive_to_domain('js', 'automodule', automodule_bound(app, modules)
)
autodirective = ... | 488 | 180 |
from mjolnir.kafka import bulk_daemon
import pytest
def _mock_bulk_response(ok, action, status, result):
return ok, {
action: {
'status': status,
'result': result,
}
}
def _update_success(result, n=1):
return [_mock_bulk_response(True, 'update', 200, result) for _... | 1,867 | 669 |
#!/usr/bin/env python
import mirheo as mir
import numpy as np
import argparse
import trimesh
parser = argparse.ArgumentParser()
parser.add_argument("--restart", action='store_true', default=False)
parser.add_argument("--ranks", type=int, nargs=3)
args = parser.parse_args()
ranks = args.ranks
domain = (16, 16, 16)
d... | 2,248 | 984 |
from setuptools import setup, find_packages
setup(
name="analyze-shopify",
version="0.1.0",
description="Matatika datasets for tap-shopify",
packages=find_packages(),
package_data={
"bundle": [
"analyze/datasets/tap-shopify/*.yml",
]
},
)
| 292 | 96 |
#!/usr/bin/env python
import ROOT
import AtlasStyle
import os
import sys
import threading
import math
from array import array
ROOT.gROOT.SetBatch()
if not hasattr(ROOT, "loader"):
ROOT.gROOT.LoadMacro("/afs/cern.ch/user/x/xju/tool/loader.c")
ROOT.gROOT.LoadMacro(os.getenv("ROOTCOREBIN")+"/lib/x86_64-slc6-gcc49-... | 11,641 | 4,598 |
from django.urls import path
from user import views
app_name = 'user'
urlpatterns = [
path('', views.ListUserView.as_view(), name="list"),
path('detail/<int:pk>', views.RetrieveUserView.as_view(), name="detail"),
]
| 226 | 79 |
import time
import numpy as np
import tensorflow as tf
from my_logger import get_logger
from squeezenet.config import get_config
from squeezenet.inputs import get_input_pipeline
from squeezenet.networks.squeezenet import Squeezenet_Imagenet
from squeezenet import eval
from squeezenet.checkpoint_handler import Checkpo... | 11,588 | 3,463 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 17:14:12 2020
@author: Narjes Rohani
"""
#install subprocess, Pandas, biopython, and IntaRNA packages
import os
import subprocess
import pandas as pd
#Load file of miRNAs sequences that you want to canculate MFE to bind SARS-CoV-2
mRNAMicroRNA=pd... | 1,151 | 471 |
# -*- coding: utf-8 -*-
'''
python3 salt.py
'''
import time
import random
import hashlib
def all_ip_addresses():
''' Return all IPv4 addresses one by one '''
# IPv4 uses a 32-bit address space: 4,294,967,296 (2**32) unique addresses
for part1 in range(11, 256): # 11-255
for part2 in range(0, 256): ... | 3,229 | 1,226 |
import sys
import numpy as np
from keras_bert import load_vocabulary, load_trained_model_from_checkpoint, Tokenizer, get_checkpoint_paths
print('This demo demonstrates how to load the pre-trained model and check whether the two sentences are continuous')
if len(sys.argv) == 2:
model_path = sys.argv[1]
else:
f... | 2,025 | 848 |
#!/usr/bin/env python
import time,os,re,csv,sys,uuid,joblib
from datetime import date
import numpy as np
from sklearn import svm
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
def train_model(X,y,saved_model):
"""
function t... | 3,052 | 1,087 |
#coding=utf8
| 14 | 9 |
"""
Skip RNN cells that decide which timesteps should be attended.
"""
from __future__ import absolute_import
from __future__ import print_function
import collections
import tensorflow as tf
from rnn_cells import rnn_ops
from tensorflow.python.framework import ops
SkipLSTMStateTuple = collections.namedtuple("Skip... | 21,378 | 6,656 |
#
# @lc app=leetcode id=892 lang=python3
#
# [892] Surface Area of 3D Shapes
#
# https://leetcode.com/problems/surface-area-of-3d-shapes/description/
#
# algorithms
# Easy (57.01%)
# Likes: 209
# Dislikes: 270
# Total Accepted: 15.9K
# Total Submissions: 27.5K
# Testcase Example: '[[2]]'
#
# On a N * N grid, we ... | 1,601 | 788 |
import tensorflow as tf
import tensorflow_addons as tfa
class AFNO(tf.keras.layers.Layer):
"""
AFNO with adaptive weight sharing and adaptive masking.
"""
def __init__(self, k, *args, **kwargs):
self.k = k
super().__init__(*args, **kwargs)
def build(self, input_shape):
d ... | 1,147 | 409 |
"""AWS CDK module to create ECS infrastructure"""
import os
from typing import Optional
from aws_cdk import (
core,
aws_ecs as ecs,
aws_ec2 as ec2,
aws_iam as iam,
aws_ecr as ecr,
aws_elasticloadbalancingv2 as elbv2,
aws_route53 as route53,
aws_route53_targets as alias,
aws_certific... | 7,696 | 2,308 |
from django.urls import path
from django.contrib.sitemaps.views import sitemap
import hello.views
from hello.sitemaps import SubtitleSitemap, StaticSitemap
app_name = 'sirobutton'
sitemaps = {
'subtitles': SubtitleSitemap,
'static': StaticSitemap,
}
urlpatterns = [
path('', hello.views.SubtitleListView.... | 1,139 | 399 |
import os, tempfile
from PIL import Image
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import test, status
from rest_framework.test import APIClient
from core.models import Profile, Address, Gig, Education
from freelancer.serial... | 5,415 | 1,824 |
from bokeh.embed import components
from bokeh.plotting import figure, curdoc, ColumnDataSource
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8
from bokeh.models import CustomJS, LabelSet, Slider
from bokeh.models.widgets import Slider
from bokeh.models.layouts import WidgetBox, Row
from bok... | 5,106 | 1,995 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mailauth.models
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),... | 1,072 | 301 |
from torchvision import transforms as T
import torch
import random
class RandomApply(torch.nn.Module):
def __init__(self, fn, p):
super().__init__()
self.fn = fn
self.p = p
def forward(self, x):
if random.random() > self.p:
return x
return self.fn(x)
SimC... | 733 | 314 |
import boto3
import requests
def lambda_handler(event, context):
print(event)
object_get_context = event["getObjectContext"]
request_route = object_get_context["outputRoute"]
request_token = object_get_context["outputToken"]
s3_url = object_get_context["inputS3Url"]
# Get object from S3
... | 728 | 228 |
# -*- coding: utf-8 -*-
from django.db import DEFAULT_DB_ALIAS
from multidb import PinningReplicaRouter
class EdwReplicationRouter(PinningReplicaRouter):
def db_for_read(self, model, **hints):
if not hasattr(model, '_rest_meta'):
return DEFAULT_DB_ALIAS
db = model._rest_meta.db_for_rea... | 421 | 144 |
import os
libName = "cobalt"
distrib_path = os.path.normpath(os.path.abspath(os.path.join(os.pardir, 'Cobalt-Web'))) #../Cobalt-Web
web_sources_path = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__)))) #here
common_file_path= os.path.normpath(os.path.abspath(os.path.join(web_sources_path, 'comm... | 1,593 | 605 |
#!/usr/bin/env python
#
# License: BSD
# https://raw.github.com/yujinrobot/kobuki/hydro-devel/kobuki_testsuite/LICENSE
#
##############################################################################
# Imports
##############################################################################
import threading
impo... | 2,051 | 678 |
# -*- encoding: utf-8 -*-
#
# Copyright © 2020 Mergify SAS
#
# 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 applicabl... | 2,023 | 626 |
# Generated by Django 2.2.24 on 2021-07-30 13:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('assignment', '0001_initial'),
('submission', '0012_auto_20180501_0436'),
]
operations = [
migratio... | 692 | 233 |
__version__ = "0.3.2.dev0"
__title__ = "zs2decode"
__description__ = "read Zwick zs2 and zp2 files"
__uri__ = "https://zs2decode.readthedocs.org/"
__author__ = "Chris Petrich"
__email__ = "cpetrich@users.noreply.github.com"
__license__ = "MIT"
__copyright__ = "Copyright (C) 2015-2017 Chris Petrich"
| 304 | 133 |
##
# test-pokersim.py
#
# Tests
# check hand logic
# check readable_hand, hand_to_numeric
# check best_five
# valid_hand
import unittest
import pokersim
class TestPokerSim(unittest.TestCase):
def test_readable_hand(self):
self.assertEqual("Qd3c3d3h3s",
pokersim.readable_... | 10,158 | 4,161 |
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[i] for i in range(0,len(nums),2)) | 148 | 56 |
from django.shortcuts import render
def visual(requests):
return render(requests, 'visual/welcome.html')
def gapminder(requests):
return render(requests, 'visual/gapminder.html')
def multipleoutputs(requests):
return render(requests, 'visual/multipleoutputs.html')
def interactions(requests):
return ... | 446 | 128 |
"""fastai1 code, not yet converted"""
from ..label import *
from tqdm import tqdm
from fastai.vision import open_image
import os
from PIL import Image as PIL_Image
"""
# %%
from fastiqa.all import *
learn = RoIPoolLearner.from_cls(FLIVE, RoIPoolModel)
learn.path = Path('.')
learn.load('RoIPoolModel-fit(10,bs=120)')
l... | 2,170 | 758 |
# Generated by Django 2.2.2 on 2019-12-26 03:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('appointments', '0001_initial'),
]
operations = [
migrations.CreateModel(
na... | 687 | 225 |
# Codigo: Importa Modulos
# Autora: Carla Edila Silveira
# Finalidade: definir funcoes - curso Python Quick Start
# Data: 21/09/2021
# MODULO calendario do Python
import calendar # importa modulo de calendario
cal = calendar.month(2021, 9) # variavel recebe dados do calendario desejado
print(cal) # imprime o cale... | 2,264 | 825 |
# Copyright 2020 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... | 11,873 | 3,133 |
# DO NOT EDIT
# Autogenerated from the notebook plots_boxplots.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
#!/usr/bin/env python
# coding: utf-8
# # 箱线图
# 以下说明在 statsmodels 中的箱线图的一些选项。包括 `violin_plot` 和 `bean_plot`.
import numpy as np
import matplotlib.pyplot a... | 5,992 | 2,332 |
# -*- coding: utf-8 -*-
import os
from tempfile import mkstemp
from bs4 import BeautifulSoup
from git import Repo
from nose.tools import assert_equal, assert_in, assert_is, assert_is_not
from sphinx_git import GitCommitDetail
from . import MakeTestableMixin, TempDirTestCase
class TestableGitCommitDetail(MakeTestab... | 5,736 | 1,881 |
# -*- coding: utf-8 -*-
#################################################################
# File : pylibczirw_tools.py
# Version : 0.0.5
# Author : sebi06
# Date : 18.01.2022
#
# Disclaimer: This code is purely experimental. Feel free to
# use it at your own risk.
#
#############################... | 5,239 | 1,807 |
# Generated by Django 2.2.17 on 2021-07-28 10:09
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencies = [
("people", "0028_auto_20210604_1234"),
]
operations = [
migrations... | 1,316 | 338 |
"""Evaluate exported frame-level probabilities."""
from __future__ import division
import argparse
import csv
import glob
import numpy as np
import os
from scipy.special import softmax
import sys
CSV_SUFFIX = '*.csv'
np.set_printoptions(threshold=sys.maxsize)
def import_probs_and_labels(args):
"""Import probabili... | 10,395 | 3,980 |
"""
module to run with the -m flag
python -m async_sched.client.request_schedules
"""
import argparse
from async_sched.client.client import request_schedules
from async_sched.utils import DEFAULT_HOST, DEFAULT_PORT
__all__ = ['NAME', 'get_argparse', 'main']
NAME = 'request_schedules'
def get_argparse(host: str ... | 1,050 | 363 |
from .util import load_images_as_tensors
import torch
from diamond_square import functional_diamond_square
from .random import Uniform, Bernoulli, Categorical, Constant, Normal
from .base_augmentation import DeterministicImageAugmentation
class AbstractBackground(DeterministicImageAugmentation):
def blend_by_mask... | 3,775 | 1,280 |
from datetime import datetime
import logging
import os
from praw import Reddit as PrawReddit
from prawcore.exceptions import NotFound
import pytz
logger = logging.getLogger(__name__)
class Reddit:
def __init__(self, client_id=None, client_secret=None, user_agent=None):
self.client_id = client_id or os.ge... | 2,156 | 632 |
from PySide2.QtCore import Slot, Qt, QThreadPool, QCoreApplication, QSize
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import (
QDialog, QLabel, QLineEdit, QComboBox, QMainWindow, QMessageBox,
QWidget, QPushButton, QGridLayout, QDialogButtonBox, QTextEdit,
)
from pyside2_demo.utils import get_resourc... | 5,417 | 1,854 |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import unittest
import mock
from dashboard.pinpoint.models.quest import read_value
@mock.patch('dashboard.services.isolate_service.Retrieve')... | 3,329 | 1,103 |
import os.path
import pytest
from datasetloader import LSP
from datasetloader import LSPExtended
from . import DS_PATH
class TestLSP():
def test_LSP(self):
# test loading both, full sized and small images
folders = ("lsp", "lsp_small")
for ds in folders:
lsp = LSP(os.path.joi... | 1,736 | 568 |
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
users = [
{
"name": "Nicholas",
"age": 42,
"occupation": "Network Engineer"
},
{
"name": "Elvin",
"age": 32,
"occupation": "Doctor"
},
{
... | 1,173 | 450 |