text string | size int64 | token_count int64 |
|---|---|---|
from api_discovery.modules import logging
from api_discovery.modules import api
from api_discovery.modules import database
from api_discovery.modules import task
log = logging.Logging()
discovery_api = api.DiscoveryAPI()
db = database.Database()
taskhub = task.TaskHub()
def init_app(app):
for module in [log, dis... | 375 | 123 |
"""A Controller class for composable things controlling robots, plus utility stuff.
An important abstraction here is Command: a function that returns immediately.
It may issue sub-Commands to motors and such, and do quick calculations, but
it must be fast. It must not block, ever. It will be called often enough to
saf... | 3,053 | 804 |
import pandas as pd
import constants as const
data = pd.read_csv('data/data_with_headers.csv')
data_class_1 = data[data.diagnosis==1]
for name,grouped_data in data[data.diagnosis!=1].groupby(const.LABEL):
data_class =grouped_data.append(data_class_1)
#print(data_class.head())
#print(data_class.tail())
d... | 437 | 161 |
# -*- coding: utf-8 -*-
from pprint import pprint # noqa
from ..support import TestCase
class DirectoryTest(TestCase):
def test_normal_directory(self):
fixture_path = self.fixture('testdir')
result = self.manager.ingest(fixture_path)
self.assertEqual(result.status, result.STATUS_SUCCESS... | 662 | 205 |
import math
import heapq
# Time: O(n * log n); Space: O(n)
# MinHeap
def k_closest(points, k):
distances = {} # O(n) space
h = [] # O(n) space
for point in points:
distance = math.sqrt(point[0] ** 2 + point[1] ** 2)
if distance not in distances:
distances[distance] = []
... | 1,224 | 501 |
from session import Session
from index import Index
from column import *
from document import make_base
import converters
| 122 | 27 |
#-*- coding: utf-8 -*-
from threading import Thread
class Receiver(Thread):
def __init__(self, queue):
super().__init__()
self.daemon = True
self.queue = queue
def run(self):
while True:
num = self.queue.get()
print("[<==] received {0}".format(num))
| 270 | 111 |
import noir.router as router
import noir.rule as rule
class HelloWorldV2(router.ServiceHandler):
async def process(self, args, context):
return 'Hello world V2 from HelloWorldV2', None
router.register_service_handler('/api/hello/v2', HelloWorldV2()) | 263 | 79 |
#!/usr/bin/python
# This is to tell python that this is a package
__version__ = '1.0'
# __path__ = __import__('pkgutil').extend_path(__path__, __name__)
__all__ = ['facebook', 'gmail', 'hangouts', 'nlp', 'quora', 'twitter', 'whatsapp', 'youtube', 'instagram'] | 260 | 92 |
#!/usr/bin/env python3
# day062.py
# By Sebastian Raaphorst, 2019.
from math import factorial
def num_paths(n: int, m: int) -> int:
"""
Calculate the number of paths in a rectangle of dimensions n x m from the top left to the bottom right.
This is incredibly easy: we have to make n - 1 moves to the righ... | 819 | 278 |
"""Tests for IOException."""
from raspy.io.io_exception import IOException
class TestIOException(object):
"""Test methods for IOException."""
def test_io_exception(self):
"""Test the exception."""
caught = None
try:
raise IOException("This is a test.")
except Exc... | 406 | 102 |
from django.contrib import admin
from django.db.models import Count
from django.utils.translation import gettext_lazy as _
from parler.admin import TranslatableAdmin
from parler.utils.context import switch_language
from .models import Language
@admin.register(Language)
class LanguageAdmin(TranslatableAdmin):
lis... | 1,634 | 523 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | 5,507 | 1,692 |
# Gearshift.py - monitors the rFactor 2 shared memory values for the shifter
# and clutch and if a gear change is not done properly it repeatedly sends a
# "Neutral" key press to prevent the gear being selected.
#
# Inspired by http://www.richardjackett.com/grindingtranny
# I borrowed Grind_default.wav from there to ma... | 13,656 | 4,024 |
from concurrent import futures
with futures.ProcessPoolExecutor() as executor:
_ = list(executor.map(print, 'Enjoy Rosetta Code'.split()))
| 144 | 46 |
from core.management.commands.custom_command import CustomCommand
from rooms.models import Amenity
class Command(CustomCommand):
help = "Automatically create amenities"
def handle(self, *args, **options):
try:
amenities = [
"Air conditioning",
"Alarm Clock"... | 2,225 | 569 |
"""MobileNet model for Keras.
Related papers
- https://arxiv.org/abs/1704.04861
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.keras import backend
from tensorflow.keras import models
from tensorflow.keras import layers
def _conv_bl... | 7,898 | 2,562 |
import pytest
import securemailbox
from securemailbox.models import Message, Mailbox
@pytest.fixture
def client():
securemailbox.app.config["TESTING"] = True
with securemailbox.app.test_client() as client:
yield client
# Force fixture to be used if not explicitly imported
@pytest.fixture(autouse=T... | 506 | 151 |
import unittest
from hostphot.cutouts import download_images
from hostphot.coadd import coadd_images
from hostphot.image_masking import create_mask
class TestHostPhot(unittest.TestCase):
def test_preprocessing(self):
coadd_filters = 'riz'
survey = 'PS1'
name = 'SN2004eo'
host_ra, h... | 943 | 313 |
import dbus
from module.EventBus import EventBus, mainEventBus
from bluetooth.objects.Player import Player
class Device:
event_bus: EventBus
__path: str
__dbus_obj: dbus.proxies.ProxyObject
__dbus_iface: dbus.proxies.Interface
__dbus_props_iface: dbus.proxies.Interface
__player_path: str = No... | 4,395 | 1,352 |
#!/usr/bin/env python
import sys
import subprocess
import re
import os.path
def main():
if len(sys.argv) < 2:
print('Missing argument')
sys.exit(-1)
exe = sys.argv[1]
if not os.path.isfile(exe):
print('Not a file, sir.')
exit(-2)
o = subprocess.check_output(['objd... | 2,213 | 805 |
''' Count number of declines with uncertain dates.
'''
import os
import pandas as pd
import numpy as np
input_path="output/cohort.pickle"
output_path="output/cohort_pickle_checks.csv"
backend = os.getenv("OPENSAFELY_BACKEND", "expectations")
cohort = pd.read_pickle(input_path)
cohort = cohort.loc[pd.notnull(cohort... | 641 | 259 |
#!/usr/bin/env python3
import unittest
if __name__ == '__main__':
testsuite = unittest.TestLoader().discover('./tests')
unittest.TextTestRunner(verbosity=1).run(testsuite) | 180 | 62 |
import gym
import numpy as np
from stable_baselines.common.policies import MlpPolicy as common_MlpPolicy
from stable_baselines.ddpg.policies import MlpPolicy as DDPG_MlpPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines.ddpg.noise import NormalActionNoise, OrnsteinUhlenbeckActionNoise... | 2,794 | 1,081 |
from lib import util
def test_cachedproperty():
class Target:
CALL_COUNT = 0
def __init__(self):
self.call_count = 0
@util.cachedproperty
def prop(self):
self.call_count += 1
return self.call_count
@util.cachedproperty
def cls... | 1,248 | 486 |
#
# Django Development
# ..........................
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#
# Developper additions
# ..........................
INSTALLED_APPS = (
'django_extensions',
'debug_toolbar',
'drf_yasg',
) + INSTALLED_APPS
INTERNAL_IPS = type(str('c'), (... | 605 | 224 |
import os
import pandas as pd
from datetime import datetime as dt
# Read raw data in
root = os.path.expanduser('../data/')
files = [root + f for f in os.listdir(root) if f.endswith('.csv') and f != 'addresses.csv']
dfs = [pd.read_csv(f, header=0, index_col='ID', parse_dates=['Date/Time']) for f in files]
df = pd.conc... | 1,629 | 536 |
class SemaphoreOfSpeaking():
class __Singleton():
def __init__(self):
self._is_instantiated = False
self._instance = None
self.is_speaking = False
def get_instance(self):
if(self._is_instantiated == False):
self._instance = SemaphoreO... | 738 | 202 |
from max7219 import Matrix8x8
from machine import Pin, SPI
from utime import sleep
if __name__ == '__main__':
CS = Pin(5, Pin.OUT) # GPIO5 pin 7
CLK = Pin(6) # GPIO6 pin 9
DIN = Pin(7) # GPIO7 pin 10
BRIGHTNESS = 3 # from 0 to 15
text1 = "Hello World!"
text2 = "PICO PI"
# C... | 1,007 | 399 |
"""
Tests the table print extra module
"""
import unittest
from unittest import mock
import pandas as pd
from dynamictableprint.dynamicprinter import DynamicTablePrint
def mock_terminal_size(_):
"""
Does what it says
"""
return [80]
class TestDynamicTablePrint(unittest.TestCase):
"""
Tests t... | 3,319 | 988 |
# Copyright 2019 Ali (@bincyber)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 1,778 | 566 |
# Generated by Django 3.2.11 on 2022-02-06 16:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import timezone_field.fields
import uuid
class Migration(migrations.Migration):
dependencies = [
... | 1,846 | 553 |
from django.conf.urls import url
from cmdbox.scaffold_templates import views
urlpatterns = [
url(r'^$', views.scaffold_templates, name='list'),
url(r'^(?P<slug>[^/]+)/$', views.details, name='details'),
url(r'^(?P<slug>[^/]+)/add-file/$', views.add_file, name='add_file'),
url(r'^(?P<slug>[^/]+)/add-f... | 1,115 | 469 |
import time
import socket
import random
import sys
def usage():
print "dP dP dP a88888b. dP 888888ba dP dP"
print "88 88 88 d8' `88 88 ... | 2,036 | 971 |
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
# Entry : a tkinter.Entry override which is more practical to use
# There is a label to the left and a button to the right (optionnals) :
#
# ----------------------------------------------
# | | | |
# | Label | Entry(redim) | Butto... | 2,653 | 1,118 |
# TODO: RENAME MODULE!
import logging
from miniworld.log import get_logger
from miniworld.util import PathUtil
_logger = None
# TODO: BETTER WAY THAN LOG FUNCTION?
def logger():
global _logger
if _logger is None:
_logger = get_logger("Spatial Backend")
_logger.addHandler(logging.FileHandler... | 392 | 133 |
#!/usr/bin/env python3
"""Bulk deletion of files on your Slack workspace
Requires a valid token from:
https://api.slack.com/custom-integrations/legacy-tokens
"""
import os
import sys
import json
import urllib.parse
import http.client
import calendar
import argparse
import time
from datetime import datetime, t... | 4,756 | 1,470 |
import main
def test_convert_case_error():
assert main.convert("error case", "error case") == main.validation_error
def test_convert_camel_case():
assert main.convert("camelCase", "my own camel case") == "myOwnCamelCase"
assert main.convert("camelCase", "camel") == "camel"
assert main.convert("camel... | 1,982 | 717 |
import json
import math
import os
import pathlib
import re
import socket
import ssl
import sys
import urllib.error
import urllib.request
import webbrowser
from difflib import SequenceMatcher
from typing import NoReturn, Tuple, Union
import certifi
import yaml
from geopy.distance import geodesic
from geopy.exc import G... | 22,030 | 6,264 |
import pytest
from vkbottle import CodeException, ErrorHandler, swear
def test_code_error():
class CodeError(CodeException):
pass
try:
raise CodeError[1]()
except CodeError[2]:
assert False
except CodeError[3, 4]: # type: ignore
assert False
except CodeError[1, 2... | 1,713 | 549 |
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# This file contains a simple testcase, that defines a table and runs a selection query on it.
import ibis
import os
import sys
import p... | 1,269 | 447 |
class RecentCounter:
def __init__(self):
self.record = []
def ping(self, t: int) -> int:
self.record.append(t)
record = self.record.copy()
count = 0
rm_list = []
for i in record:
if i in range(t-3000, t+1):
count += 1
else... | 381 | 120 |
"""
Write a program to solve a classic ancient Chinese puzzle:
"""
"""Question:
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Hint:
Use for loop to iterate all possible solutions.
... | 324 | 95 |
from django.test import TestCase
from example_app.views import ChatterBotApiView
class MockResponse(object):
def __init__(self, pk):
self.session = {'conversation_id': pk}
class ViewTestCase(TestCase):
def setUp(self):
super(ViewTestCase, self).setUp()
self.view = ChatterBotApiView... | 1,072 | 335 |
"""Entry point for our twitoff flask app"""
from .app import create_app
# This is a global variable
APP = create_app()
| 121 | 38 |
import os
import turtle
import time
t = turtle.Pen()
t.shape("turtle")
t.width(10)
t.forward(100)
t.left(90)
time.sleep(1)
t.forward(100)
os.system("Pause") | 160 | 83 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 1,746 | 469 |
# Generated by Django 3.1.13 on 2021-09-05 01:20
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),
('cars', '0028_auto_20210... | 819 | 278 |
"""
lokalise.endpoints.translation_providers_endpoint
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module containing translation providers endpoint.
"""
from .base_endpoint import BaseEndpoint
class TranslationProvidersEndpoint(BaseEndpoint):
"""Describes translation providers endpoint.
"""
PATH = "t... | 372 | 95 |
from PySide2.QtWidgets import (QWidget,
QGridLayout,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QLabel,
QInputDialog,
... | 10,597 | 3,074 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class HelperEndpointsConfig(AppConfig):
name = 'vm_helpers'
| 165 | 57 |
'''OpenGL extension EXT.multiview_draw_buffers
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.multiview_draw_buffers to provide a more
Python-friendly API
Overview (from the spec)
This extension allows selecting among draw buffers as the
rendering target. This may be among multiple primary buf... | 2,556 | 707 |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 23:08:27 2016
@author: eikes
"""
class Node(object):
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
def has_next(self):
return self.next_node is not None
def __repr__(self):
vals =... | 1,097 | 370 |
# -*- coding: utf-8 -*-
# msh-python/release/api/views.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import mixins
from rest_framework import ... | 1,793 | 641 |
__version__ = '0.3.2'
import sys
import os
import pwd
from pathlib import Path
import click
import crayons
def update_symlink(directory, filename, force=None):
force = False if force is None else force
home = str(Path.home())
try:
os.symlink(f'{home}/{directory}/{filename}', f'{home}/{filename}'... | 2,878 | 914 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-29 11:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('team', '0078_auto_20180328_1204'),
]
operations = [
migrations.RenameModel(
... | 753 | 258 |
import v6wos
class ErrorHandler(v6wos.ErrorHandler):
def initialize(self):
super().initialize(404)
| 114 | 40 |
import os
import uuid
from tempfile import SpooledTemporaryFile
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
from sqlalchemy.orm.session import Session
from quetz import authorization, dao
from quetz.config import Config
from quetz.deps import get_dao, get_db, get_rules
from .db_mo... | 4,312 | 1,389 |
from tests.unit.dataactcore.factories.staging import AppropriationFactory
from tests.unit.dataactcore.factories.domain import SF133Factory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'a26_appropriations'
_TAS = 'a26_appropriations_tas'
def test_column_headers(database):
... | 1,546 | 565 |
from fabric.api import abort, env, hide, run, settings, task
from fabric.operations import prompt
def run_mysql_command(cmd):
run('sudo -i mysql -e "{}"'.format(cmd))
def switch_slow_query_log(value):
run_mysql_command('SET GLOBAL slow_query_log = "{}"'.format(value))
@task
def stop_slow_query_log(*args):... | 5,334 | 1,750 |
from pyOpenBCI import OpenBCIGanglion
from pylsl import StreamInfo, StreamOutlet
import numpy as np
import argparse
import json
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--config_path', type=str, default='config/board_config.json')
return parser.parse_args()
SCALE_FACTOR_EE... | 1,158 | 453 |
import keras
# build VGG16 Place365 net based on the weight value and net architecture accessed from https://github.com/CSAILVision/places365
# the weight value is for caffe model and are parsed to npy files, the sequence are kept unchanged (channel first, BGR)
def _build_net():
model = keras.Sequential()
# ... | 9,486 | 2,950 |
import time
import yaml
from selenium import webdriver
def main():
conf = yaml.safe_load(open('config.yml'))
USERNAME: str = conf['USERNAME']
PASSWORD: str = conf['PASSWORD']
BROWSER: str = conf['BROWSER']
if USERNAME == 'yourusername' or PASSWORD == 'yourpassword':
print('Set y... | 1,313 | 532 |
print("FINDING Square OF a MATRIX")
print(" ")
order=int(input("enter order of square matrix="))
if (order==2):
a11=int(input("enter a11="))
print(" ")
a12=int(input("enter a12="))
print(" ")
a21=int(input("enter a21="))
print(" ")
a22=int(input("enter a22="))
print(" ")
... | 516 | 264 |
# This is a working model for converting python scripts to .cpp files
print("\nHello World!") # comment 1
print("\nThis is Bhasha") # comment 2
| 147 | 45 |
from pymongo import MongoClient
from pymongo import ReadPreference
import json as _json
import os
import mysql.connector as mysql
import requests
requests.packages.urllib3.disable_warnings()
# NOTE get_user_info_from_auth2 sets up the initial dict.
#The following functions update certain fields in the dict.
# So get_... | 17,672 | 5,072 |
from evm import constants
def blockhash(computation):
block_number = computation.stack_pop(type_hint=constants.UINT256)
block_hash = computation.vm_state.get_ancestor_hash(block_number)
computation.stack_push(block_hash)
def coinbase(computation):
computation.stack_push(computation.vm_state.coinba... | 681 | 221 |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from.models import Profile
from allauth.account.forms import SignupForm
from django.urls import reverse
class ProfileModelTest(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
em... | 1,096 | 331 |
from django.template import RequestContext
from django.shortcuts import render_to_response
def test_yui_include(request):
return render_to_response(
'yui/tests/test-yui-include.html',
{},
RequestContext(request))
| 243 | 71 |
#!/usr/bin/env python
# ##################################################################################
# MG ILLUMINATION #
# Author : cPOTTIER #
# Date : 07-07-2016 ... | 53,246 | 21,936 |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import itertools
from abc import ABCMeta, abstractmethod
from collections import OrderedDict, defaultdict
from contextlib import ExitStack
from types import SimpleNamespace
from typing import Callable, Dict, Optional, Set, Tuple, Union... | 26,013 | 8,016 |
from django.contrib import admin
from django.core.exceptions import ValidationError
from django.db import models
class Excursion(models.Model):
title = models.CharField(max_length=200)
desc = models.TextField('description', blank=True)
date = models.DateField()
seats = models.PositiveSmallIntegerField... | 2,367 | 748 |
import re
import sys
import os
'''
# TODO: tripartite verbs (verb is third node) in files:
1659.pislarsaga.bio-aut.conllu (3)
1745.klim.nar-fic.conllu (2)
1790.fimmbraedra.nar-sag.conllu (1)
1791.jonsteingrims.bio-aut.conllu (1)
1985.sagan.nar-fic.conllu (1)
Hinrik Hafsteinsson 2019
Part of UniTre... | 15,989 | 5,795 |
def main():
# input
N = int(input())
ss = [int(input()) for _ in range(N)]
# compute
ans = sum(ss)
for s in sorted(ss):
if ans%10==0 and s%10!=0:
ans -= s
# output
if ans%10 == 0:
print(0)
else:
print(ans)
if __name__ == '__main__':
main()
| 320 | 126 |
from construct import *
from construct.lib import *
nav_parent_switch_cast__foo__zero = Struct(
'branch' / LazyBound(lambda: nav_parent_switch_cast__foo__common),
)
nav_parent_switch_cast__foo__one = Struct(
'branch' / LazyBound(lambda: nav_parent_switch_cast__foo__common),
)
nav_parent_switch_cast__foo__common = ... | 802 | 302 |
import re
from collections import defaultdict
from typing import DefaultDict, Dict, List
from ja_timex.number_normalizer import NumberNormalizer
from ja_timex.tag import TIMEX
from ja_timex.tagger import AbstimeTagger, DurationTagger, ReltimeTagger, SetTagger
from ja_timex.util import is_parial_pattern_of_number_expre... | 4,711 | 1,526 |
import math
from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import QDesktopWidget
# pyqt5 version of matlab tilefigs function
def tileFigs(stackWindows):
# Filter out only open windows:
stackWindows = [w for w in stackWindows if w is not None]
assert len(stackWindows) > 0
hspc = 10 # Horisontal... | 1,481 | 520 |
from datetime import datetime
from django.db.models import Avg
from rest_framework.relations import SlugRelatedField
from rest_framework.serializers import (CurrentUserDefault, ModelSerializer,
SerializerMethodField, ValidationError)
from reviews.models import Comment, Rev... | 2,313 | 678 |
import logging
import numpy as np
from .base import Policy
logger_name, *_ = __name__.split(".")
logger = logging.getLogger(logger_name)
class BasePredictionPolicy(Policy):
def __init__(self, *args, **kwargs):
super(BasePredictionPolicy, self).__init__(*args, **kwargs)
def predict(self, ... | 2,126 | 729 |
"""
问题描述:给定一个有序数组sortArr,已知其中没有重复值,用这个有序数组生成一棵平衡二叉搜索树,并且该搜索二叉树
中序遍历结果与sortArr一致。
"""
from binarytree.toolcls import Node
from binarytree.q3 import PrintTree
class ReconstructBalancedBST:
@classmethod
def reconstruct(cls, arr):
if len(arr) == 0 or arr is None:
return None
return ... | 818 | 359 |
"""
Copyright 2018 ACV Auctions
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
di... | 1,988 | 683 |
import csv
import json
import os
import shutil
from collections import OrderedDict
from time import time
import numpy
import redis
from sklearn import model_selection
from MLLogger import BaseMLLogger
from exception_handler import MLExceptionHandler
from general_helper import (
get_oauth, make_stream_from_sdf, ma... | 21,562 | 6,666 |
"""
Global field power peaks extraction
===================================
This example demonstrates how to extract global field power (gfp) peaks for an eeg recording.
"""
#%%
# We start by loading some example data:
import mne
from mne.io import read_raw_eeglab
from pycrostates.datasets import lemon
raw_fname =... | 1,415 | 486 |
from ._randomsubgroups import SubgroupPredictorBase
from ._randomsubgroups import RandomSubgroupClassifier
from ._randomsubgroups import RandomSubgroupRegressor
from ._version import __version__
__all__ = ['SubgroupPredictorBase', 'RandomSubgroupClassifier', 'RandomSubgroupRegressor',
'__version__']
| 314 | 88 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.utils import timezone
from clock.forms import SignUpForm, ProjectForm
from clock.models import Project... | 2,643 | 995 |
#!/usr/bin/python
import re
import random
import urllib
import operator
from util import scanTokens, scanNgrams
from Levenshtein import distance
from random import choice
LEXER_TOKENS = "TOKENS"
LEXER_NGRAMS = "NGRAMS"
OFS_TRANSITION = 3
def pickIndex(counts):
total = sum(counts)
dice = random.randint(1, t... | 41,794 | 11,282 |
'''
Given a non-negative integer n, count all numbers with unique digits, x, where 0 < x < 10^n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 < x < 100, excluding [11,22,33,44,55,66,77,88,99])
'''
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
... | 610 | 287 |
from setuptools import setup, find_packages
import sys
import os
version = '1.3.2.dev0'
shortdesc = \
"Plone Souper Integration: Container for many lightweight queryable Records"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), '... | 2,284 | 711 |
import snapshot_queries.optional_dependencies
if snapshot_queries.optional_dependencies.SNAPSHOTTEST_INSTALLED:
from contextlib import contextmanager
import pytest
from snapshottest.pytest import PyTestSnapshotTest
from .assert_queries_match_mixin import AssertQueriesMatchMixin
class PyTestQuer... | 949 | 260 |
import pandas as pd
df = pd.read_csv('data/tweets.csv')
df = df[~df['full_text'].str.contains('RT|\@|»|https')]
df.to_csv('data/tweets_processed.csv', encoding='utf_8_sig')
| 174 | 75 |
from django.conf import settings
from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.views.generic import TemplateView
from django.urls import include, path
from service.views import ServiceList
from service.views import ServiceDetail
from django.utils import translation
from ... | 1,074 | 323 |
import uuid
import pytest
from asociate.entities.association import Association
from asociate.entities.member import Member
pytestmark = [
pytest.mark.entities,
]
def test_member_init():
member = Member(
first_name="Arthur",
last_name="Dent",
email="arthur.dent@deepthought.com",
... | 3,118 | 1,097 |
import numpy as np
import torch
import torchvision
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms, models, datasets
import matplotlib.pyplot as plt
%matplotlib inline
# Implementation of the ResNet-50 Architecture
class ResidualBlock(torch.nn.Modu... | 4,194 | 1,714 |
# -*- coding: utf-8 -*-
from datetime import datetime
class Unit:
def __init__(self, element):
self.annotations = element['annotationsGroup']['annotations']
self.id = element['id']
self.parentId = element['parentId']
self.title = element['title'] if 'title' in element else ''
... | 2,256 | 703 |
# Copyright (c) OpenMMLab. All rights reserved.
import numbers
import os.path as osp
import mmcv
import numpy as np
import torch
from mmcv.runner import auto_fp16
from mmedit.core import tensor2img
from mmedit.models.base import BaseModel
from mmedit.models.builder import build_backbone, build_component, build_loss
f... | 11,447 | 3,339 |
from aoi_envs.MultiAgent import MultiAgentEnv
from aoi_envs.Mobile import MobileEnv
from gym.envs.registration import register
MAX_EPISODE_STEPS = 10000
register(
id='StationaryEnv-v0',
entry_point='aoi_envs:MultiAgentEnv',
max_episode_steps=MAX_EPISODE_STEPS,
)
##########################################... | 8,240 | 3,669 |
# Copyright (c) 2013 Alan McIntyre
import urllib
import hashlib
import hmac
import warnings
from datetime import datetime
from btceapi import common
from btceapi import keyhandler
class InvalidNonceException(Exception):
def __init__(self, method, expectedNonce, actualNonce):
Exception.__init__(self)
... | 9,631 | 2,731 |
import numpy as np
class Forecaster:
def __init__(self, c, m, sigma):
self.c = c
self.m = m
self.sigma = sigma
def predict(self, Y0, T):
Yhat = np.zeros((T+self.m))
Yhat[:self.m] = Y0
for i in range(self.m,T+self.m):
Yhat[i] = self.c + Yhat[... | 776 | 357 |
"""This module runs a distributed hyperparameter tuning job on Google Cloud AI Platform."""
from pathlib import Path
import numpy as np
import chillpill
from chillpill import packages, params, search
from chillpill_examples.cloud_hp_tuning_from_train_fn import train
if __name__ == '__main__':
# Create a Cloud A... | 1,388 | 461 |
"""Tests timing of encoding classes
"""
import time
import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
from dsutils.encoding import MultiTargetEncoderLOO
def test_timing_MultiTargetEncoderLOO():
"""Tests timing of encoding.MultiTargetEncoderLOO"""
# Dummy data
N = 10000
Nc = ... | 858 | 344 |