text string | size int64 | token_count int64 |
|---|---|---|
print('Begin', __name__)
print('Defines fA')
def fA():
print('Inside fA')
if __name__ == "__main__":
print('Calls fA')
fA()
print('End', __name__)
| 165 | 72 |
import pytest
from rest_framework import status
pytestmark = pytest.mark.usefixtures(
"wdae_gpf_instance", "dae_calc_gene_sets", "use_common_reports"
)
def test_variant_reports(admin_client):
url = "/api/v3/common_reports/studies/study4"
response = admin_client.get(url)
assert response
assert r... | 2,238 | 774 |
'''Unit tests for ckan/logic/auth/create.py.
'''
from pylons import config
import mock
import nose.tools
import ckan.tests.helpers as helpers
import ckan.tests.factories as factories
import ckan.model as model
import ckan.logic as logic
import ckan.plugins as p
assert_equals = nose.tools.assert_equals
assert_raises... | 8,000 | 2,344 |
def find_missing_number(sequence):
try:
numbers = sorted(int(word) for word in sequence.split(" ") if word)
except ValueError:
return 1
return next((i + 1 for i, n in enumerate(numbers) if i + 1 != n), 0) | 232 | 75 |
import pandas as pd
import os
import sys
def main():
# Arguments not equal to 5
if len(sys.argv) != 5:
print("ERROR : NUMBER OF PARAMETERS")
print("USAGE : python topsis.py inputfile.csv '1,1,1,1' '+,+,-,+' result.csv ")
exit(1)
# File Not Found error
elif not os.pa... | 4,075 | 1,468 |
from ._base import BaseWeight
from ..exceptions import NotFittedError
from ..utils.functions import mean_log_beta
import numpy as np
from scipy.special import loggamma
class PitmanYorProcess(BaseWeight):
def __init__(self, pyd=0, alpha=1, truncation_length=-1, rng=None):
super().__init__(rng=rng)
... | 6,337 | 2,048 |
from __future__ import annotations
from typing import Dict, List, Optional, Union
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from nlp.nlp import Trainer
app = FastAPI()
trainer = Trainer()
#BaseModel is used as data validator when using fast api it cares all about exception handilng and ... | 2,259 | 669 |
# Copyright 2018 Alibaba Cloud Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 2,359 | 633 |
import pandas as pd
import numpy as np
import glob
import os
import global_config
import yaml
import time
import sys
import collections
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.Mut... | 1,891 | 610 |
from typing import Union, List
from lagoon import Stage, Task
from coord2vec.pipelines.lagoon_utils.lambda_task import LambdaTask
class AutoStage(Stage):
def __init__(self, name: str, **kwargs):
super().__init__(name, **kwargs)
self.output_param_to_task = dict()
def update_output_params(se... | 1,757 | 525 |
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 07/03/09
#version :2.6.1
"""
collections module's extras in python 2.6.1 were used in my program, DVMextrapolating
DVMgordonsModel and CAPM subclasses of n... | 19,045 | 6,433 |
import binascii
import csv
import io
import json
import logging
import os
import traceback
import urllib
from pathlib import Path
import openpyxl
import pandas as pd
import pyximport
import redis
# from flask import (jsonify, abort, redirect, url_for,
#
# )
from NamedAtomicLock import NamedAtomicLoc... | 141,262 | 44,646 |
import os
import shutil
import codecs
import logging
import zipfile
from django.template import Template, Context
from django.contrib.auth.models import SiteProfileNotAvailable
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from builds import utils as version_utils
from core.ut... | 3,198 | 884 |
#!/bin/env mayapy
# -- coding: utf-8 --
u"""Ce test vérifie que le transform [LEFT] a bien le même rotateOrder que le transform [RIGHT]
Les [does not exist] indique un problème dans la nomenclature des noms et donc qu'il ne peut tester la symétrie des rotateOrders"""
__author__ = "Adrien PARIS"
__email__ =... | 1,108 | 365 |
# Lucas Reicher Prompt #3 - Coding Journal #1
def main():
# Uses formatted strings to output the required info (result & type)
# Adds floats
x = 1.342 # float
y = 3.433 # float
z = x + y # float
float_sum_string = "Addition: {0} + {1} = {2} with type = {3}".format(str(x),str(y),str(z)... | 898 | 377 |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... | 7,575 | 2,546 |
import re, requests, bs4, unicodedata
from datetime import timedelta, date, datetime
from time import time
# Constants
root = 'https://www.fanfiction.net'
# REGEX MATCHES
# STORY REGEX
_STORYID_REGEX = r"var\s+storyid\s*=\s*(\d+);"
_CHAPTER_REGEX = r"var\s+chapter\s*=\s*(\d+);"
_CHAPTERS_REGEX = r"Chapters:\s*(\d+)\... | 21,504 | 6,713 |
import sqlite3
from datetime import datetime
import click
from flask import current_app, g
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy, Model
from sqlalchemy import Column, Integer, TIMESTAMP, Boolean
class Base(Model):
# this id implementation does not support inheritance
i... | 1,506 | 495 |
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
from torch import nn
from tqdm import tqdm
import numpy as np
from datasets.preprocess import DatasetWrapper
from utils import AverageMeter
class IOC_MLP(torch.nn.Module):
def __init__(self, input_features, out_classes):
super()._... | 5,667 | 1,685 |
import base64
import re
def base64ToString(base64):
reg = "\\x[a-z0-9][a-z0-9]"
base64.b64decode()
message_bytes = message.encode("ascii")
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode("ascii")
def shiftASCII(string, n):
r = ""
for i in string:
... | 485 | 220 |
from django import forms
class AddUrlForm(forms.Form):
"""Добавляем УРЛ для проверки
"""
url = forms.URLField(initial='https://', label='Введите ссылку для проверки')
class UploadHappinessIndex(forms.Form):
"""Форма для загрузки файла с кастомным индексом счастья
"""
name = forms.CharField(max... | 568 | 218 |
import time
from math import fabs
import putil.timer
from putil.testing import UtilTest
class TestTimer(UtilTest):
def setUp(self):
self.op1_times = iter([ .01, .02 ])
self.a1 = putil.timer.Accumulator()
self.op2_step1_times = iter([ .005, .015, .005, .005])
self.op2_step2_times ... | 2,264 | 828 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 o... | 5,122 | 1,684 |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('imdb_required')
class FilterImdbRequired(object):
"""
Rejects entries without imdb_url or imdb_id.
Makes imdb lookup / search if necessary... | 966 | 285 |
import os
import sys
import shutil
import re
def make_output_folder(folder_path, debug=False):
""" Make folder for output, checking for previous results """
# Skip if debug (avoids replace prompt)
if debug:
print "FolderSetup warning: Not creating directory because debug = True"
... | 1,795 | 445 |
"""
This code contains tasks for executing EMIT Level 3 PGEs and helper utilities.
Author: Philip G. Brodrick, philip.brodrick@jpl.nasa.gov
"""
import datetime
import logging
import os
import luigi
import spectral.io.envi as envi
from emit_main.workflow.output_targets import AcquisitionTarget
from emit_main.workflo... | 6,748 | 2,282 |
'''
Code to copy Curry expressions.
'''
from __future__ import absolute_import
from .....common import T_SETGRD, T_FWD
from copy import copy, deepcopy
from ..... import inspect
from . import node
__all__ = ['copygraph', 'copynode', 'GraphCopier', 'Skipper']
class GraphCopier(object):
'''
Deep-copies an expressio... | 2,843 | 940 |
import unittest
import os
import sys
file_dir = os.path.dirname(os.path.dirname(__file__))
sys.path.append(file_dir + "/src")
from coins import coin_change_basic, coin_change_memo, coin_change_tab
class TestCoinChangeBasic(unittest.TestCase):
def test_negative(self):
num = 0
coins = [3, 2, 1]
... | 1,325 | 501 |
"""
At infinite membrane resistance, the Neuron does not leak any current out,
and hence it starts firing with the slightest input current,
This shifts the transfer function towards 0, similar to ReLU activation (centered at 0).
Also, when there is minimal refractory time, the neuron can keep firing
at a high input cu... | 359 | 95 |
#
# Visualize the audio of an Elixoids game:
#
# pip3 install websocket-client
# python3 clients/listen.py --host example.com
#
import argparse
import sys
import websocket
try:
import thread
except ImportError:
import _thread as thread
import sound_pb2
def on_message(ws, message):
sound = sound_... | 1,377 | 445 |
# -*- coding: utf-8 -*-
"""
This script looks through the JSON files created by parse_LN_to_JSON.py and looks
for duplicates using the Jaccard Coefficient f k-grams of the article text (body).
It creates a CSV file with all of the cases listed and duplicates marked, and
optionally stores the same information in a JSO... | 12,915 | 3,915 |
from QAPUBSUB.consumer import subscriber
sub = subscriber(host='192.168.2.116',user='admin', password='admin' ,exchange= 'realtime_60min_rb1910')
sub.start() | 160 | 69 |
import pennylane as qml
import numpy as np
def algo(x, y, z):
qml.RZ(z, wires=[0])
qml.RY(y, wires=[0])
qml.RX(x, wires=[0])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(wires=1))
def run_algo(device, args):
print(args)
circuit = qml.QNode(algo, device)
result = circuit(float(args['X']), float(args['Y'... | 356 | 169 |
# **YD** the model to train deep-ed-global for entity disambiguation
import copy
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from deep_ed_PyTorch.utils import utils
from deep_ed_PyTorch.ed.args import arg_parse
class EntityContext(nn.Module):
def __init__(self, args):
... | 14,389 | 4,983 |
# this code use cnn with inception unit + softmax to predict handwriting 0-9
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
batch_size = 64
# download the dataset, don't need to construc... | 4,349 | 1,754 |
from flask import Blueprint, request, render_template, url_for
from LovelyFlask.App.models import HomeWheel, HomeNav, HomeMustBuy, HomeMainShow, HomeShop, FoodTypes, Goods, CartModel
blue = Blueprint("first_blue", __name__, url_prefix="/api/")
def init_first_blue(app):
app.register_blueprint(blueprint=blue)
A... | 2,842 | 1,220 |
import json
import yaml
from redisbench_admin.utils.benchmark_config import (
results_dict_kpi_check,
check_required_modules,
extract_redis_dbconfig_parameters,
)
def test_results_dict_kpi_check():
return_code = results_dict_kpi_check({}, {}, 0)
assert return_code == 0
return_code = results_... | 3,546 | 1,081 |
"""Miscellaneous tools.
"""
import os
import csv
from typing import Union
from subprocess import Popen
from pathlib import Path
from scipy.io import loadmat
import pandas as pd
def open_in_explorer(path : os.PathLike) -> None:
if Path(path).is_dir():
_ = Popen(f'explorer.exe /root,"{path}"')
elif Pat... | 4,982 | 1,471 |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 25,521 | 7,541 |
#!/usr/bin/python3
import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, FileType
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pyfsdb
def parse_args():
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter,
desc... | 4,591 | 1,394 |
import base64
import mimetypes
import os
from urllib.parse import unquote
import xml.etree.ElementTree as etree
from markdown.inlinepatterns import LinkInlineProcessor
from markdown.extensions import Extension
def remove_namespace(doc, namespace):
"""Remove namespace in the passed document in place."""
ns = u... | 1,912 | 595 |
class Solution:
"""
@param k: The k
@param a: The A
@param b: The B
@return: The answer
"""
def addition(self, k, a, b):
result = ""
i = len(a) - 1
j = len(b) - 1
carry = 0
while i >= 0 and j >= 0:
summ = carry + ord(a[i]) - ord('0') + ord(... | 1,000 | 343 |
import json
import argparse
def to_output(filepath, outpath):
with open(filepath, encoding='utf-8') as f:
data = json.load(f)
output = []
for d in data:
temp = {}
temp['id'] = d['id']
temp['labels'] = d['pred_labels']
output.append(temp)
with open(outpath, 'w+') ... | 675 | 226 |
import sys
if sys.version_info > (3,):
basestring = (str, bytes)
long = int
class DeprecatedCellMixin(object):
"""Deprecated Cell properties to preserve source compatibility with the 1.0.x releases."""
__slots__ = ()
@property
def r(self):
"""The row number of this cell.
..... | 2,886 | 862 |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 13:59:43 2018
@author: ofn77899
"""
import numpy
from ccpi.segmentation.SimpleflexSegmentor import SimpleflexSegmentor
from ccpi.viewer.CILViewer import CILViewer
from ccpi.viewer.CILViewer2D import CILViewer2D, Converter
import vtk
#Text-based input s... | 7,234 | 2,385 |
import json
def read_input():
file = open("Data/day12.json", "r")
return json.load(file)
def calculate_sum(accounts):
if type(accounts) == str:
return 0
elif type(accounts) == int:
return accounts
elif type(accounts) == list:
return sum(calculate_sum(i... | 1,081 | 366 |
from .text_component import TextComponentAdmin # noqa
from .text_description_component import TextDescriptionComponentAdmin # noqa
| 131 | 30 |
from .celeryapp import *
| 27 | 12 |
from page_scrapers.wikipedia.scrapers.film import WikipediaFilmScraper
query_1 = "hellraiser 2"
scraper_1 = WikipediaFilmScraper(query_1)
scraped_1 = scraper_1.scrape()
filtered_1 = scraper_1.filter()
print(filtered_1)
query_2 = "hellraiser judgement"
scraper_2 = WikipediaFilmScraper(query_2)
scraped_2 = scraper_2.sc... | 377 | 160 |
# Copyright (C) MindEarth <enrico.ubaldi@mindearth.org> @ Mindearth 2020-2021
#
# This file is part of mobilkit.
#
# mobilkit is distributed under the MIT license.
'''Tools and functions to analyze the data in time.
'''
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
impor... | 42,835 | 12,954 |
from easyvec import Mat2, Vec2
import numpy as np
from pytest import approx
def test_constructor1():
m = Mat2(1,2,3,4)
assert m is not None
assert m.m11 == approx(1)
assert m.m12 == approx(2)
assert m.m21 == approx(3)
assert m.m22 == approx(4)
def test_constructor2():
m = Mat2([1,2,3,4])
... | 5,591 | 2,513 |
import numpy as np
from two_d_nav.envs.static_maze import StaticMazeNavigation
def test_goal():
env = StaticMazeNavigation()
for i in range(60):
obs, reward, done, _ = env.step(np.array([1.0, -0.1]))
env.render()
for i in range(30):
obs, reward, done, _ = env.step(np.array([-1.0... | 1,664 | 650 |
# OpenWeatherMap API Key
weather_api_key = "e1067d92d6b631a16363bf4db3023b19"
# Google API Key
g_key = "AIzaSyA4RYdQ1nxoMTIW854C7wvVJMf0Qz5qjNk"
| 146 | 96 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Xia Bin
# 2011 ~ 2012 Wang Yong
#
# Author: Xia Bin <xiabin@linuxdeepin.com>
# Maintainer: Wang Yong <lazycat.manatee@gmail.com>
#
# This program is free software: you can redistribute ... | 13,099 | 4,256 |
import pytest
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
from sghymnal.players.api.views import PlayersViewSet
from sghymnal.players.models import Player
pytestmark = pytest.mark.django_db
class TestPlayerViewSet:
def test_get_queryset(self, player: Player, rf: R... | 801 | 241 |
"""Matplotlib separation plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_separation(
y,
y_hat,
y_hat_line,
label_y_hat,
expected_events,
figsize,
textsize,
... | 2,351 | 838 |
import argparse
import git
import github
import os.path
from mesonwrap import gitutils
from mesonwrap import tempfile
from mesonwrap import webapi
from mesonwrap import wrap
from mesonwrap.tools import environment
from retrying import retry
class Importer:
def __init__(self):
self._tmp = None
s... | 5,053 | 1,420 |
import os
from .Base import *
from discord.ext import commands
class GuideCog(commands.Cog, BaseTools):
def __init__(self, bot):
self.setup()
self.bot = bot
# self.bot.remove_command("help")
self.fotter = "Tip: Use \";g\" to summon a list of all guides.\nType `;bhelp` to summon a li... | 10,843 | 3,007 |
#!/usr/bin/env python
"""bulge_graph.py: A graph representation of RNA secondary structure based
on its decomposition into primitive structure types: stems, hairpins,
interior loops, multiloops, etc...
for eden and graphlearn we stripped forgi down to this single file.
forgi: https://github.com/pkerpedj... | 83,766 | 26,184 |
#!/usr/bin/env python
import _init_paths
from evb.test import test_net
from evb.config import cfg, cfg_from_file, cfg_from_list
from datasets.factory import get_imdb
import caffe
import argparse
import pprint
import time, os, sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.Argumen... | 3,215 | 1,034 |
# Generated by Django 3.2.6 on 2021-08-24 09:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... | 2,030 | 586 |
RECOGNIZER_SNOWBOY = 'snowboy'
RECOGNIZER_SPHINX = 'sphinx'
RECOGNIZER_WIT = 'wit.ai' | 85 | 54 |
# Processor for kompas-data-contents.txt
MIN_IDX = 100
contentfile = open('../data/kompas-data-contents.txt', 'r')
content_data = []
for line in contentfile:
content_data.append(line)
processed_contentfile = open('../data/kompas-data-contents-processed.txt', 'w+')
for id, content in enumerate(content_data):
... | 1,023 | 381 |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""
from app.home import blueprint
from flask import render_template, redirect, url_for, request, flash, send_file
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
i... | 10,296 | 3,426 |
import logging
from botocore.exceptions import ClientError
from aws_cloudformation_power_switch.power_switch import PowerSwitch
from aws_cloudformation_power_switch.tag import logical_id
class RDSClusterPowerSwitch(PowerSwitch):
def __init__(self):
super(RDSClusterPowerSwitch, self).__init__()
s... | 2,730 | 784 |
# Generated by Django 2.2.1 on 2019-05-09 21:08
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('matchapp', '0003_available_doctors'),
]
operations = [
... | 435 | 145 |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .account_lookup.action import AccountLookup
from .all_lookup.action import AllLookup
from .billing_lookup.action import BillingLookup
from .card_lookup.action import CardLookup
from .cart_lookup.action import CartLookup
from .device_lookup.action import DeviceLookup
from .em... | 547 | 155 |
#!/usr/bin/env python
import os, sys, argparse, errno, yaml, time, datetime
import rospy, rospkg
import torch, torchvision, cv2
import numpy as np
from rosky_msgs.msg import WheelsCmdStamped, Twist2DStamped
from img_recognition.msg import Inference
from cv_bridge import CvBridge, CvBridgeError
from jetcam_ros.utils imp... | 3,630 | 1,247 |
"""Loads CartPole-v1 demonstrations and trains BC, GAIL, and AIRL models on that data.
"""
import os
import pathlib
import pickle
import tempfile
import seals # noqa: F401
import stable_baselines3 as sb3
from imitation.algorithms import adversarial, bc
from imitation.data import rollout
from imitation.util import ... | 2,395 | 828 |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2017 Anler Hernández ... | 38,456 | 13,826 |
import os
DB_SERVER = os.getenv('WMT_DB_SERVER', 'localhost')
DB_NAME = os.getenv('WMT_DB_NAME', 'wmt_db')
DB_USERNAME = os.getenv('WMT_DB_USERNAME', 'wmt')
DB_PASSWORD = os.getenv('WMT_DB_PASSWORD', 'wmt')
| 208 | 94 |
# _*_ coding:utf-8 _*_
import xadmin
from .models import Teacheres
from courses.models import Courses
class AddCourses(object):
model = Courses
extra = 0
#培训师
class TeacheresAdmin(object):
list_display = ['name', 'username', 'email', 'phone', 'weixin', 'password']
search_fields = ['name']
list_fi... | 484 | 183 |
import os
import json
from .models import User
from flask import Blueprint, send_from_directory, redirect, url_for, current_app, request, jsonify
main = Blueprint('main', __name__)
@main.route('/join', methods=['GET', 'POST'])
def join():
params = request.get_json()['params']
params['ip'] = compute_ip()
u... | 1,710 | 541 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
import numpy as np
class ClassifyPointCloudAugment():
def __init__(self):
self.is_augment_rotate = True
self.is_augment_dropout = True
self.is_augment_scale = True
self.is_augment_shift = True
self.rotation = (0, 30)
... | 2,728 | 876 |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
from __future__ import print_function
import os, importlib, sys
from cntk_helpers i... | 2,436 | 754 |
from .standard import *
from .few_shot import *
| 48 | 16 |
import unittest
import numpy as np
from gradient_descent.Momentum import Momentum
class TestMomentumClass(unittest.TestCase):
def setUp(self):
"""Setting up requirements for test
Params:
None
Returns:
None
"""
def f(x):
"""Apply functio... | 3,756 | 1,066 |
#! /usr/bin/env python
"""Compute a (somewhat more) human readable format for message
digests. This is port of the perl module Digest-BubbleBabble-0.01
(http://search.cpan.org/~btrott/Digest-BubbleBabble-0.01/)
"""
vowels = "aeiouy"
consonants = "bcdfghklmnprstvzx"
def bubblebabble(digest):
"""compute bubblebabb... | 2,436 | 1,123 |
import graphene
import graphql_jwt
import works.schema
import users.schema
import works.schema_relay
import people.schema
class Query(
users.schema.Query,
works.schema.Query,
works.schema_relay.RelayQuery,
people.schema.Query,
graphene.ObjectType,
):
pass
class Mutation(
users.schema.Mut... | 657 | 227 |
import tensorflow as tf
from t3f.tensor_train_base import TensorTrainBase
from t3f.tensor_train_batch import TensorTrainBatch
from t3f import ops
def concat_along_batch_dim(tt_list):
"""Concat all TensorTrainBatch objects along batch dimension.
Args:
tt_list: a list of TensorTrainBatch objects.
Returns:
... | 7,497 | 2,766 |
""" Python 3 native (desktop/mobile) OAuth 2.0 example.
This example can be run from the command line and will show you how the
OAuth 2.0 flow should be handled if you are a web based application.
Prerequisites:
* Create an SSO application at developers.eveonline.com with the scope
"esi-characters.re... | 3,496 | 1,037 |
# Copyright © 2021 Province of British Columbia
#
# 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 agr... | 1,763 | 494 |
from __future__ import print_function
import sys
import random
import Pyro4
if sys.version_info < (3, 0):
input = raw_input
uri = input("Enter the URI of the server object: ")
with Pyro4.Proxy(uri) as proxy:
print("currently allocated resources:", proxy.list())
name1 = hex(random.randint(0, 999999))[-4... | 756 | 254 |
class DmsRequestError(Exception):
def __init__(self, error_message, status_code):
self.message = "Error requesting DMS API %s with code %s" \
% (error_message, status_code)
super(DmsRequestError, self).__init__(self.message)
| 259 | 77 |
import pathlib
import configparser
class ConfigManager:
DEFAULT_CONFIG_PATH = "~/.config/notify-sync.ini"
SETTING_NOTIFICATION_ICON = "icon"
SETTING_NOTIFICATION_TIMEOUT = "timeout" # in ms
# SETTING_NOTIFICATION_URGENCY = "urgency" # 0,1,2 low, avg, urgent
SETTING_NOTIFICATION_EXEC = "exec_on... | 1,843 | 524 |
from dataclasses import dataclass
from typing import Optional
from ass_tag_parser.common import Meta
@dataclass
class AssDrawPoint:
x: float
y: float
class AssDrawCmd:
meta: Optional[Meta] = None
@dataclass
class AssDrawCmdMove(AssDrawCmd):
pos: AssDrawPoint
close: bool
@dataclass
class Ass... | 714 | 241 |
class Keyword:
def __init__(self, keyword):
if keyword in ['add', 'find']:
self.value = keyword
else:
self.value = 'find'
| 166 | 48 |
# The JSON feed parser
# Copyright 2017 Beat Bolli
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above... | 4,710 | 1,514 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: Python -*-
#
# (C) Alain Lichnewsky, 2021
#
import os
import sys
import re
import unicodedata
import unittest
from hypothesis import given, assume, settings, HealthCheck
import hypothesis.strategies as st
# using a try block so that this makes sense if exp... | 4,211 | 1,459 |
"""
Pawlytics API retreival tool
Author: jess@menidae.com
Requires crontab to run tool hourly:
0 * * * * /path/to/python3 /path/to/file/pawlytics.py
"""
from urllib.request import Request
from urllib.request import urlopen
from typing import Dict
from urllib.request import HTTPError
import json
from json import dump... | 2,586 | 1,044 |
"""Vault update CLI"""
import sys
from argparse import ArgumentParser, FileType, _ArgumentGroup
from yaml import safe_load
from utils.log import log
from utils.vault import Vault
parser = ArgumentParser(description="Manual update of repositories Vault")
required: _ArgumentGroup = parser.add_argument_group("required... | 1,099 | 342 |
import os
import numpy as np
import tensorflow as tf
import cPickle
from utils import shared, get_name
from nn import HiddenLayer, EmbeddingLayer, LSTM, forward
class Model(object):
"""
Network architecture.
"""
def __init__(self, parameters=None, models_path=None, model_path=None):
"""
... | 13,004 | 4,307 |
from revolt.types.file import File
from revolt.embed import Embed
from revolt.message import Message
from typing import Optional
class Context:
def __init__(self, message, bot):
self.message = message
self.bot = bot
async def send(self, content: Optional[str] = None, embeds: Optional[list[Emb... | 1,076 | 281 |
"""Given a string containing only the characters x and y, find whether there are the same number of xs and ys.
balanced("xxxyyy") => true
balanced("yyyxxx") => true
balanced("xxxyyyy") => false
balanced("yyxyxxyxxyyyyxxxyxyx") => true
balanced("xyxxxxyyyxyxxyxxyy") => false
balanced("") => true
balanced("x") =... | 2,860 | 1,120 |
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import RandomSampler
from gnnff.data.keys import Keys
from gnnff.data.split import train_test_split
__all__ = ["get_loader"]
def get_loader(dataset, args, split_path, logging=None):
"""
Parameters
----... | 4,108 | 1,325 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import
from __future__ import print_function
from glob import glob
from os.path import basename
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
setup(
na... | 1,510 | 452 |
from cms.plugin_base import CMSPluginBase
from cms.models.pluginmodel import CMSPlugin
from cms.plugin_pool import plugin_pool
from fduser import models
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
class Users(CMSPluginBase):
model = CMSPlugin # Model where data ... | 747 | 210 |
# pyright: reportUnknownMemberType=false
import logging
import zipfile
from pathlib import Path
from typing import Dict
import requests
from us_pls._config import Config
from us_pls._download.interface import IDownloadService
from us_pls._download.models import DatafileType, DownloadType
from us_pls._logger.interfac... | 5,214 | 1,547 |
#!/usr/bin/env python
from dlbot import default_settings
from flask import Flask
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(default_settings)
app.config.from_pyfile('dlbot.cfg', silent=True)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
... | 332 | 116 |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 10:15:21 2021
@author: CC-SXF
"""
| 95 | 60 |