text string | size int64 | token_count int64 |
|---|---|---|
"""
You have been employed by the Japanese government to write a function that tests
whether or not a building is strong enough to withstand a simulated earthquake.
A building will fall if the magnitude of the earthquake is greater than the
strength of the building.
An earthquake takes the form of a 2D-Array. Each ... | 1,675 | 594 |
"""TODO: write docstring"""
from __future__ import annotations
from dataclasses import astuple
from difflib import unified_diff
from functools import update_wrapper
from pathlib import Path
import sys
import tempfile
from typing import TYPE_CHECKING
import click
from . import __version__, __repo__
from .base import ... | 20,186 | 5,928 |
#validate.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2018 NV Access Limited, Babbage B.V., Joseph Lee
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""
Module to provide backwards compatibility with add-ons that use the configobj validate modu... | 580 | 164 |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/5/14 21:42
# @author : Mo
# @function: nlg-yongzhuo
from macropodus.summarize.yongzhuo_nlg import *
doc = """PageRank算法简介。" \
"是上世纪90年代末提出的一种计算网页权重的算法! " \
"当时,互联网技术突飞猛进,各种网页网站爆炸式增长。 " \
"业界急需一种相对比较准确的网页重要性计算方法。 "... | 5,237 | 3,922 |
import glob
from PIL import Image
from functools import partial
# read in metadata file entries to a list of lists
print("Loading simulation metadata...")
fname = "./outfiles/metadata.txt"
file = open(fname, "r")
metadata = []
for line in file:
line = line.split()
metadata.append(line)
# parse metadata variab... | 1,240 | 442 |
from dataclasses import dataclass
from enum import Enum, auto
from typing import List
from ..exceptions import Unreachable
from ..utils import detect
from .tape import Tape, TMConfiguration
class Direction(Enum):
LEFT = auto()
RIGHT = auto()
@dataclass
class TMRule:
state: int
character: str
ne... | 2,363 | 645 |
import System
pf_path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86)
import sys
sys.path.append('%s\IronPython 2.7\Lib' %pf_path)
import random
def tolist(x):
if hasattr(x,'__iter__'): return x
else : return [x]
l1, rat, seed = IN
l1 = tolist(l1)
r = random.Random()
r.seed(seed... | 659 | 299 |
import dearpygui.dearpygui as dpg
from helpers.logger import Logger
from gui.utils import SaveInit
class EditMenu:
def __init__(self):
self.log = Logger("Aural.GUI.Menus.Edit", "gui.log")
with dpg.menu(label="Edit"):
dpg.add_menu_item(label="Save Window Configuration", callback=SaveIn... | 380 | 118 |
"""
Using pandas library, move data from John Hopkin's github repo to AWS S3
Data source: https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series
"""
import pandas as pd
import numpy as np
import re
from random import randint
import s3fs
class CovidDF():
def __init__(s... | 9,621 | 3,282 |
# Generated by Django 3.0.9 on 2020-08-18 18:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0005_userdetail_mobile'),
]
operations = [
migrations.AddField(
model_name='userdetail',
name='image',
... | 429 | 143 |
"""
This file will run REINFORCE or PPO code
with the input seed and environment.
"""
import gym
import os
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import ppo files
from ppo.ppo import PPO
from ppo.reinforce import REINFORCE
from ppo.network import FeedForwardN... | 4,754 | 1,736 |
import discord
from discord.ext import commands
from helpers.getWeather import getWeather
class Weather(commands.Cog):
"""
Weather Module
"""
def __init__(self, bot):
self.bot = bot
@commands.command(help="Get Tempurature of Specified Location")
async def weather(self, ... | 595 | 206 |
# -*- coding: utf-8 -*-
from copy import deepcopy
import pytz
def dict_merge(master, merge):
"""Recursively merge dicts
(originally found at https://www.xormedia.com/recursively-merge-dictionaries-in-python/)
Args:
master (dict): base dictionary
merge (dict): dictionary with entries to ... | 1,584 | 517 |
from django.urls import path, include
from .views import *
app_name = 'backoffice'
urlpatterns = [
path('', BackofficeIndexView.as_view(), name='index'),
path('product_handout/', ProductHandoutView.as_view(), name='product_handout'),
path('badge_handout/', BadgeHandoutView.as_view(), name='badge_handout'... | 1,182 | 413 |
class Solution:
# Recursion Approach
def countOfSubsetsWithSumEqualToX(self, arr, X):
def helper(arr, X, idx):
if idx== len(arr):
if X ==0:
return 1
else :
return 0
res = helper(arr, X-arr[idx], idx+1)+ helper(arr, X, idx+1)
return res
return helper(arr, X, 0)
#... | 1,451 | 755 |
from flask import Blueprint
bp = Blueprint('devices', __name__)
from . import emqx # noqa: E402
from . import devices # noqa: E402
from . import select_options # noqa: E402
from . import groups # noqa: E402
from . import security # noqa: E402
__all__ = [
'bp', 'emqx', 'devices', 'groups', 'security', 'sele... | 334 | 131 |
from flask import Flask, request, send_file
from main_controller import MainController
app = Flask(__name__)
@app.route('/generate', methods=['POST'])
def generate():
image_src = MainController().generate_image(request)
return send_file(image_src)
@app.route('/ping', methods=['GET'])
def ping():
... | 398 | 141 |
n = int(input())
cow1 = []
cow2 = []
combinations = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
results = []
for i in range(0, n):
temp1, temp2 = map(int, input().split())
cow1.append(temp1)
cow2.append(temp2)
# print(cow1)
# print(cow2)
for j in range(0, 6):
result = 0
for k in range(0, n)... | 656 | 313 |
"""
registerSegments.py
---------------
Main Function for registering (aligning) colored point clouds with ICP/feature
matching as well as pose graph optimizating
"""
# import png
from PIL import Image
import csv
import open3d as o3d
import pymeshlab
import numpy as np
import cv2
import os
import glob
from utils.ply... | 22,348 | 7,243 |
import pandas
from uuid import uuid4
import requests
import boto3
def download_file(file_url):
'''
'''
pass
def upload_file(file, dest):
'''
'''
pass
def create_file_name(filename):
'''
'''
pass
| 236 | 82 |
class NumArray:
def __init__(self, nums: List[int]):
self.nums_sum = [0]*len(nums)
for i, _ in enumerate(nums):
self.nums_sum[i] = self.nums_sum[i-1] + (nums[i] if i > 0 else nums[i])
def sumRange(self, left: int, right: int) -> int:
return self.nums_sum[right] - self.nums_... | 397 | 167 |
import sys
def inject_default_settings(name):
'''
Inject application default settings into config if not
already defined.
'''
try:
__import__('%s.settings' % name)
# Import this app defaults
app_settings = sys.modules['%s.settings' % name]
default_settings = sys.mod... | 874 | 233 |
import heapq
with open("day-15.txt") as f:
lines = [line for line in f.read().rstrip().splitlines()]
graph = {}
for i, row in enumerate(lines):
for j, n in enumerate(row):
graph[i, j] = int(n)
DELTAS = (
(0, 1),
(1, 0),
(-1, 0),
(0, -1),
)
def find_lowest_risk(graph, start, end):
... | 803 | 322 |
from .report import Report
from . import videos
| 48 | 12 |
class NXAPIError(Exception):
"""Generic NXAPI exception."""
pass
class NXAPICommandError(NXAPIError):
def __init__(self, command, message):
self.command = command
self.message = message
def __repr__(self):
return 'The command "{}" gave the error "{}".'.format(
sel... | 770 | 241 |
import logging
import pytest
from . import dcos_version
from .. import http, VERSION as SHAKEDOWN_VERSION
from ..clients import dcos_url_path
from ..clients.mesos import DCOSClient
from distutils.version import LooseVersion
logger = logging.getLogger(__name__)
dcos_1_12 = pytest.mark.skipif('dcos_version_less_than(... | 8,223 | 2,587 |
from django.db import models
class Hello(models.Model):
your_name = models.CharField(max_length=15)
def __str__(self):
return "<{0}>".format(self.your_name)
class Qiu(models.Model):
qiu_name = models.CharField(max_length=15)
def __str__(self):
return self.qiu_name
class Hello1(mo... | 567 | 206 |
def delete_navi_bar(driver):
"""Delete navigation of page for capturing clear image.
"""
js_string = """
function f() {
var x = document.getElementsByClassName("manga-bottom-navi");
for(var i = x.length - 1; i >= 0; i--) {
x[i].parentNode.removeChild(x[i]);
}
}
f();
... | 766 | 255 |
import re
from mydeploy import (
get_file_objects,
S3Util,
)
from environment_config import (
AWS_CONFIG_PATH,
AWS_PROFILE,
CSS_BUCKET,
IMAGE_BUCKET,
JS_BUCKET,
CSS_PREFIX,
IMAGE_PREFIX,
JS_PREFIX,
XML_PATH
)
def cleanup_main():
c = S3Util.create_connection_... | 1,621 | 553 |
import sys
class DirEntity:
def __init__(self, type_char, user_name, selector, host, port):
self.type = type_char
self.user_name = user_name
self.selector = selector
self.host = host
self.port = port
def __eq__(self, other):
if type(other) != type(sel... | 4,276 | 1,381 |
#!/usr/bin/env python
__author__ = 'rohe0002'
#from idp_test import saml2base
from idp_test import SAML2client
from idp_test.check import factory
cli = SAML2client(factory)
cli.run() | 184 | 71 |
import os
import gzip
import json
import numpy
import urllib.request
from nltk.sentiment.util import mark_negation
from nltk.corpus import stopwords, opinion_lexicon
from nltk.tokenize import sent_tokenize, word_tokenize
def download_data(dataset_name, directory_name):
"""
Download a given dataset name into a... | 5,265 | 1,566 |
#! python3
# coding: utf-8
KLX_CMT = '#'
KLX_NL = '\n'
KW_LBL = ':'
KW_SPL = '/'
KW_BR1 = '('
KW_BR2 = ')'
PRMTCH = lambda s, d: len(s) >= len(d) and s[:len(d)] == d
class err_lexer(Exception):
pass
class err_syntax(Exception):
pass
class c_lexer:
def __init__(self, raw):
self.raw = raw
... | 12,698 | 4,343 |
# coding=utf-8
#
# @lc app=leetcode id=965 lang=python
#
# [965] Univalued Binary Tree
#
# https://leetcode.com/problems/univalued-binary-tree/description/
#
# algorithms
# Easy (66.96%)
# Likes: 222
# Dislikes: 36
# Total Accepted: 43.7K
# Total Submissions: 65.3K
# Testcase Example: '[1,1,1,1,1,null,1]'
#
# A ... | 1,373 | 536 |
#! /usr/bin/env python3
""" Standalone script for evaluating a dataset.
Calculates measures of label quality and tries to spot outliers.
Usage:
python3 investigate.py <filename>"""
import argparse
import pandas as pd
import numpy as np
import math
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkit... | 4,501 | 1,586 |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
"""
@license
Copyright (c) Daniel Pauli <dapaulid@gmail.com>
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
#------------... | 1,571 | 345 |
import json
import os
from collections import Counter
import numpy as np
import tensorflow as tf
from tensorflow.python.keras import models
from tensorflow.python.keras.layers import Embedding, Bidirectional, LSTM
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras import layers
from io... | 4,241 | 1,523 |
class DIRECTIONS:
UP = (0, 1) # North UP South DOWN West LEFT EAST RIGHT
DOWN = (0, -1)
RIGHT = (1, 0)
LEFT = (-1, 0)
NORTH = (0, 1)
SOUTH = (0, -1)
EAST = (1, 0)
WEST = (-1, 0)
l_directions = [UP, DOWN, RIGHT, LEFT]
LM_DIRECTIONS = [NORTH, SOUTH, EAST, WEST]
| 302 | 158 |
import aiohttp
import asyncio
import json
from typing import Dict, List, Union
async def json_print(thing):
print(json.dumps(thing, indent=2, default=lambda o: o.to_json()))
async def json_apfell_obj(thing):
return json.loads(json.dumps(thing, default=lambda o: o.to_json()))
class APIToken:
def __init... | 100,345 | 27,551 |
#Author: David Zhen Yin
#Contact: yinzhen@stanford.edu
#Date: September 11, 2018
import numpy as np
import matplotlib.pyplot as plt
def scree_plot(input_data, data_name, keep_info_prcnt, plotORnot):
'''This is the PCA scree plot function,
This function also report the number of PCs that preserves the assig... | 1,932 | 712 |
# Copyright (c) 2013 Yubico AB
# 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 conditi... | 2,281 | 797 |
t=int(input("Enter the number of test cases:"))
temp=''
msg=input("Enter your message:")
print(len(msg))
ss=list(msg)
if ss%2==0:
for i in range(len(ss)):
if i%2==0:
temp+=ss[i].upper()
else:
temp+=ss[i].lower()
else:
for i in range(len(ss)):
if
print(temp) | 286 | 135 |
"""
Example file for the senstivity_analyzer package. The usage of modules and classes inside
the senanalyzer package should be clear when looking at the examples.
If not, please raise an issue.
Goals of this part of the examples:
1. Learn how to execute a sensitivity analysis
2. Learn how to automatically select sens... | 2,395 | 696 |
# coding: utf-8
import os
import re
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Elasticsearch ODM... | 1,985 | 717 |
#!/usr/bin/env runpipenv
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import xml.etree.ElementTree as ET
import sys
import csv
import re
import argparse
import os.path
NO_LICENSE = 'No license information available'
... | 9,350 | 2,832 |
from __future__ import unicode_literals
from django.apps import AppConfig
class CommunicationConfig(AppConfig):
name = 'communication'
| 142 | 40 |
from __future__ import annotations
import typing
from ctc import evm
from ctc import spec
from .. import rpc_constructors
from .. import rpc_digestors
from .. import rpc_request
async def async_eth_call(
to_address: spec.Address,
from_address: spec.BinaryData | None = None,
gas: spec.BinaryData | None ... | 4,930 | 1,522 |
import ffmpeg
from datetime import timedelta
class Media:
def __init__(self, path):
self.path = path
self._metadata = ffmpeg.probe(path)['format']
@property
def duration(self):
return timedelta(seconds=float(self._metadata['duration']))
@property
def media_type(self):
... | 939 | 411 |
"""cogeo_mosaic.backends."""
from typing import Any
from urllib.parse import urlparse
from cogeo_mosaic.backends.base import BaseBackend
from cogeo_mosaic.backends.dynamodb import DynamoDBBackend
from cogeo_mosaic.backends.file import FileBackend
from cogeo_mosaic.backends.memory import MemoryBackend
from cogeo_mosai... | 1,731 | 601 |
import logging
from poetics.lookups import get_pronunciations, check_onomatopoetic
from poetics.classes.pronunciation import Pronunciation
from poetics.stemmer import stem
class Word:
def __init__(self, word, user_pronunciation=None, parent=None):
self.parent = parent
self.token = word
se... | 2,791 | 842 |
"""This module regroups preset patterns related to schools in order to quickly
create emails using the NamesAlgorithm
Description
-----------
You can either subclass an already defined school or
create a new school by subclass NamePatterns.
For instance, improving a school would look like this:
class EDHEC2(EDHE... | 2,708 | 863 |
from typing import Any
from wav2vec_toolkit.text_preprocessing.normalizers import NormalizerOperation
def is_upper_vowel(letter):
return letter in ["A", "E", "I", "O", "U", "Á", "É", "Í", "Ó", "Ú"]
def irish_lower_word(word):
if len(word) > 1 and word[0] in ["n", "t"] and is_upper_vowel(word[1]):
r... | 821 | 303 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nullabletypes.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as ... | 6,077 | 2,436 |
# runall.py
from collections import OrderedDict
from sklearn.ensemble import RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.model_selection import ShuffleSplit
from sklearn.pipeline import Pipeline
from sklearn.pipeline import make_pipeline, FeatureUnion
from sklearn.preprocessing import O... | 4,584 | 1,693 |
DOMAIN = "{{ cookiecutter.domain }}"
| 37 | 14 |
import sys
import threading
import time
class Bullets:
@staticmethod
def spinning_cursor():
c = [
"[- ]",
"[ - ]",
"[ - ]",
"[ - ]",
"[ -]",
"[ - ]",
"[ - ]",
"[ - ]"
]
wh... | 1,235 | 379 |
from ..score_request import ScoreRequest
def test_score_request():
sr = ScoreRequest("foo", [1, 2, 3], ["bar", "baz"])
assert sr.context_name == "foo"
assert sr.rev_ids == {1, 2, 3}
assert sr.model_names == {"bar", "baz"}
assert sr.precache is False
assert sr.include_features is False
ass... | 346 | 121 |
from fs.fs_exceptions import NoSuchIndex
def restrictRange(min, max, keyword):
def decorator(function):
def check(*args, **kwargs):
if min <= kwargs[keyword] < max:
return function(*args, **kwargs)
raise NoSuchIndex()
return check
return decorator
"arr... | 613 | 199 |
"""
Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import os
import glob
import argparse
import time
import numpy as np
import caffe
import splatnet.configs
from splatnet.utils import modify_blob_... | 9,785 | 3,203 |
import numpy as np
import pandas as pd
import theano
import theano.tensor as T
import gc
import time
from theano_utils import floatX
from ops import euclidean, cosine
from sklearn import metrics
from sklearn.linear_model import LogisticRegression as LR
def cv_reg_lr(trX, trY, vaX, vaY, Cs=[0.01, 0.05, 0.1, 0.5, 1., ... | 3,284 | 1,317 |
from typing import List
from injector import inject, singleton
from .coordinator import Coordinator
from backup.time import Time
from backup.worker import Worker, Trigger
from backup.logger import getLogger
from backup.exceptions import PleaseWait
logger = getLogger(__name__)
@singleton
class Scyncer(Worker):
... | 1,130 | 300 |
/anaconda/lib/python3.6/tempfile.py | 35 | 16 |
# search backend
from momo.core import Node
from momo.plugins.flask.filters import get_attr
from momo.plugins.flask.utils import str_to_bool, split_by
from momo.utils import txt_type, bin_type
class SearchError(Exception):
pass
def join_terms(*args):
res = []
for arg in args:
res.append(arg.str... | 6,832 | 1,894 |
from flask import request
def get_real_ip():
return request.environ.get('HTTP_X_REAL_IP', request.remote_addr) | 116 | 39 |
import logging
from functools import wraps
from itertools import groupby
from multiprocessing import Process
from threading import Lock, Thread
import arrow
from rdflib import Graph, Literal, URIRef
from rdflib.namespace import XSD
from lakesuperior.config_parser import config
from lakesuperior.exceptions import (
... | 10,877 | 3,620 |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from .external import ExternalLink
| 110 | 39 |
import time
from tqdm import tqdm
from src.data.download.utils.tqdm_write import (
tqdm_print,
tqdm_printer,
tqdm_run_parallel,
)
def func0(tqdm_name, tqdm_idx):
N = 100
with tqdm(desc=tqdm_name, total=N, position=tqdm_idx, leave=False) as pbar:
for i in range(N):
pbar.update(... | 1,212 | 524 |
from subprocess import Popen, PIPE
import shlex
def pipe_commands(commands):
first_proc = None
last_proc = None
for command in commands:
args = shlex.split(command)
if first_proc is None:
first_proc = last_proc = Popen(args, stdout=PIPE, stderr=PIPE)
else:
l... | 515 | 169 |
# Generated by Django 2.2.12 on 2020-05-14 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields... | 2,248 | 645 |
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>,
# Apoorv Vyas <avyas@idiap.ch>
#
"""Implement the typical softmax attention as a recurrent module to speed up
autoregressive inference. See fast_transformers.attention.full_attenti... | 1,946 | 617 |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import os
f... | 2,797 | 667 |
from django import template
register = template.Library()
def is_authenticated(session):
return 'user' in session and 'is_authenticated' in session
def is_admin(session):
return 'user' in session and 'is_admin' in session and session['is_admin'] is True
register.filter('is_authenticated', is_authenticate... | 361 | 107 |
# Generated by Django 3.0.5 on 2020-04-07 22:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('urlshortener', '0002_auto_20200405_1734'),
]
operations = [
migrations.AlterModelOptions(
name='urlshortener',
options={'ver... | 409 | 154 |
# Generated by Django 3.2.5 on 2021-07-23 17:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualapp', '0002_assignment_assignmentno'),
]
operations = [
migrations.CreateModel(
name='Submission',
fields=[
... | 704 | 204 |
"""
Package contains datasets.
"""
from .dataset import (
Dataset,
DatasetBase,
DatasetConcatView,
DatasetIndexedView,
DatasetSlicedView,
concat,
create_view,
rationed_split,
stratified_split,
)
from .example_factory import Example, ExampleFactory, ExampleFormat
from .hierarhical_da... | 903 | 296 |
# 1) find contours of the receipt
# 2) if there are more than 4 vertices, find those which
# are the most likely to be receipt vertices, mark and show them
import cv2
import numpy as np
import imutils
from transform import four_point_transform
from skimage.filter import threshold_adaptive
font = cv2.FONT_HERSHEY_SIM... | 7,263 | 2,476 |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from time import time
from collections import deque
from threading import RLock, Thread
from random import Random
from httplib import HTTPConnection, responses
from argparse import ArgumentParser
class RWF:
def __init__(self, num_threads=30, conn_timeout=1,
... | 8,549 | 2,464 |
import argparse
from prettytable import PrettyTable
from prettytable import from_html_one
from worker import Worker
from config import login, password, folder_path
def initialize_parser():
"""Initialize parser for CLI."""
parser = argparse.ArgumentParser(
usage='acm [command] [parameters]',
)
... | 1,856 | 620 |
# 最終手段ハンドラを確認するためのモジュール
import logging
logger=logging.getLogger(__name__)
# Note
# any Handler is not added to logger
def func0():
logger.error("module0 : without_handler") | 184 | 79 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#...the usual suspects.
import os, inspect
#...for the unit testing.
import unittest
#...for the logging.
import logging as lg
# The wrapper class to test.
from nor import NOR
class TestNOR(unittest.TestCase):
def setUp(self):
pass
def tearDown(self)... | 1,169 | 403 |
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df) | 73 | 34 |
class Behaviour:
def __init__(self, unit):
self.game = unit.game
self.unit = unit
self.complete_init()
def complete_init(self):
pass
def process(self, dt):
pass
| 216 | 68 |
import avl
import random
import sys
import coverage
import time
import numpy
start = time.time()
branchesHit = set()
maxval = int(sys.argv[1])
testlen = int(sys.argv[2])
numtests = int(sys.argv[3])
cov = coverage.coverage(branch=True, source=["avl.py"])
cov.start()
for t in xrange(0,numtests):
a = avl.AVLTree... | 1,506 | 492 |
# -*- coding: utf-8 -*-
import os
from os import chdir
from os import path
from os import sep
import pupy.utils
from pupy import dirs_gen
from pupy import files_gen
PWD = path.split(path.realpath(__file__))[0]
def test_mkdirs():
dirs = [("something",), ("something", "else")]
expected = [path.join(*route) f... | 2,160 | 771 |
class Scenario:
timeLimit = 5
type = 'orbit'
def __init__(self, title, *kwargs):
self.title = title
| 121 | 42 |
import inspect
import string
from django import forms
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.template.engine import Engine
from django.template.exceptions import TemplateDoesNotExist
class QuestionTypeRegistry:
"""Registry for question type classes."""
_reg... | 8,527 | 2,278 |
import sys
import os
from tests.test_single_file import SingleFile
from .rootpath import Rootpath
from .report_file import RowCSV
from .report_file import RowDuplicated
class Report:
"""
@overview: this class print the report of a list of files in CSV format
"""
def __init__(self, new_report_name):... | 3,504 | 1,008 |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScCunhaPoraSpider(FecamGazetteSpider):
name = "sc_cunha_pora"
FECAM_QUERY = "cod_entidade:80"
TERRITORY_ID = "4204707"
| 197 | 95 |
numeros = list()
while True:
n = (int(input('Digite um valor:')))
if n not in numeros:
numeros.append(n)
else:
print('Valor duplicado!')
escolha = str(input('Deseja continuar? [S/N]')).upper().strip()[0]
if escolha in 'N':
break
numeros.sort()
print(f'Você digitou {numeros}') | 320 | 120 |
"""
OpenVINO DL Workbench
Test image explainer
Copyright (c) 2021 Intel Corporation
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 re... | 3,228 | 1,009 |
import sys
s = sys.stdin.read().split()
def main():
ans = "YES" if s[0] == s[1][::-1] else "NO"
print(ans)
if __name__ == "__main__":
main()
| 170 | 79 |
#!/usr/bin/env python
#
# MIT License
#
# Copyright The SCons Foundation
#
# 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 us... | 2,540 | 933 |
# pylint: disable=missing-function-docstring, missing-module-docstring/
from mpi4py import MPI
from numpy import zeros
# we need to declare these variables somehow,
# since we are calling mpi subroutines
if __name__ == '__main__':
size = -1
rank = -1
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
siz... | 1,943 | 771 |
# 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
# distributed under the Li... | 1,196 | 366 |
'''
1. Load and normalizeing the CIFAR10 training and test datasets using torchvision
2. Define a Convolutional Neural Network
3. Define a loss function
4. Train the network on the training data
5. Test the network on the test data
'''
# Reference: Pytorch Tutorial 60 minute Blitz, Training a classifier
# Link: https:... | 1,061 | 370 |
test_cases = int(input().strip())
def bubble_sort(lst):
nums = lst[:]
swap = True
for i in range(len(nums) - 1, -1, -1):
if not swap:
break
swap = False
for j in range(i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]... | 637 | 240 |
# Generated by Django 3.1.3 on 2021-01-04 01:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('dualtext_api', '0012_aut... | 883 | 301 |
from os import path
import codecs
from setuptools import setup, find_packages
with codecs.open('README.md', 'r', 'utf8') as reader:
long_description = reader.read()
with codecs.open('requirements.txt', 'r', 'utf8') as reader:
install_requires = list(map(lambda x: x.strip(), reader.readlines()))
setup(
... | 1,166 | 367 |
import matplotlib.pyplot as plt
import os
import numpy as np
import cv2
from skimage.metrics import structural_similarity as ssim
from USRNet.utils import utils_image as util
SMALL_SIZE = 24
MEDIUM_SIZE = 24
BIGGER_SIZE = 24
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titles... | 1,418 | 580 |
#!/usr/bin/env python
"""
Copyright 2015 ARC Centre of Excellence for Climate Systems Science
author: Scott Wales <scott.wales@unimelb.edu.au>
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
h... | 1,955 | 577 |