text string | size int64 | token_count int64 |
|---|---|---|
from collections import defaultdict
from typing import Dict
from nonebot.log import logger
from peewee import JOIN
from .db import DB
from .tables import BilibiliUser, BilibiliUserStatus, FollowLink, Group
def log_sql(s):
# logger.debug(f"[DB:SQL] {s.sql()}")
return s
def get_all_groups():
yield from ... | 3,016 | 1,021 |
db = 'log.db'
import sqlite3
import time
dbc = sqlite3.connect(db, check_same_thread=False)
dbc.text_factory = str
c = dbc.cursor()
def key(obj):
return obj[2]
while True:
c.execute('SELECT userid, name, COUNT(`date`) FROM log WHERE `date` > \'' + time.strftime('%Y-%m-%d 00:00:00') + '\' AND result=1 GROUP BY use... | 1,536 | 678 |
#!/usr/bin/python3
#Copyright 2018 Jim Van Fleet
#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 ... | 1,949 | 594 |
import numpy as np
import torch
import torch.nn.functional as F
from TorchSUL import Model as M
from torch.nn.parameter import Parameter
import torch.nn.init as init
class PropLayer(M.Model):
def initialize(self, outdim, usebias=True):
self.outdim = outdim
self.act = torch.nn.ReLU()
self.act2 = torch.nn.Re... | 2,270 | 1,101 |
import pytest
import fast_carpenter.backends as backends
def test_get_backend():
coffea_back = backends.get_backend("coffea:dask")
assert hasattr(coffea_back, "execute")
with pytest.raises(ValueError) as e:
backends.get_backend("doesn't exist")
assert "Unknown backend" in str(e)
| 307 | 107 |
from typing import Dict
import logging
logger = logging.getLogger(__name__)
def path_builder(url: str, path: str) -> str:
if path == "" or path is None:
return url
if path.startswith("/"):
path = path[1:]
if url.endswith("/"):
url = f"{url}{path}"
else:
url = f"{url}/{... | 1,534 | 499 |
import typing
class NotRelativePrimeError(ValueError):
def __init__(self, a, b, d, msg=''):
super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d))
self.a = a
self.b = b
self.d = d
def bit_size(num: int) -> int:
try:
return num.bit_length... | 1,856 | 698 |
import datetime
import json
import os
from uuid import uuid4
import pytest
import numpy as np
from pandas import util
from whylogs.core.datasetprofile import DatasetProfile, array_profile, dataframe_profile
from whylogs.core.model_profile import ModelProfile
from whylogs.util import time
from whylogs.util.protobuf im... | 12,217 | 4,002 |
# coding: utf-8
'''
The CLI API definition, available to both the core and plugins.
'''
import sys
from ..exceptions import NotInstalled
from .. import __installed__
# Define the global name to launcher function map.
_launchers = dict()
# Define a single character to launcher function map.
_shortforms = dict()
def ... | 2,645 | 951 |
# Generated by Django 2.0 on 2017-12-10 16:10
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("gallery", "0005_auto_20170912_1708")]
operations = [
migrations.AlterField(
m... | 1,408 | 405 |
from os import unlink
from random import randint
import util
import tempfile
def config_setup(stack, *configs):
config_name = "tconfig" + str(randint(1000, 5000))
fp = tempfile.NamedTemporaryFile(delete=False)
for c in configs:
fp.write(bytes(c+"\n", 'utf8'))
fp.close()
util.run(f"rio ... | 1,898 | 721 |
from django.db import models
# Create your models here.
class Categoria(models.Model):
nombre = models.CharField(max_length=200)
pub_date = models.DateTimeField('Fecha Creación')
def __str__(self):
return self.nombre
class Product(models.Model):
categoria = models.ForeignKey(Categoria, on_del... | 1,090 | 360 |
a=input("a= ")
b=input("b= ")
aa=a
a=b
b=aa
print("a=",a)
print("b=",b) | 71 | 44 |
import os
import datetime
import csv
import time
import random
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementExceptio... | 5,548 | 1,595 |
# Copyright (c) 2012-2016 Seafile Ltd.
"""
The MIT License (MIT)
Copyright (c) 2013 Omar Bohsali
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 ... | 3,339 | 994 |
import data.make_stterror_data.utils as utils
import os
import sys
import subprocess
# TTS imports
from gtts import gTTS
import pyttsx3
# sys.path.append("~/PycharmProjects/pyfestival") # https://github.com/techiaith/pyfestival/pull/4
# import festival
__author__ = 'Gwena Cunha'
"""
Text-To-Speech Module
"""
... | 3,203 | 1,050 |
from year2019.intcode_v2 import Intcode
from common import input_integer_sep
def part_one(inp_list):
program1 = (
"NOT A J\n"
"NOT B T\n"
"OR T J\n"
"NOT C T\n"
"OR T J\n"
"AND D J\n"
"WALK\n"
)
p = Intcode(
inp_list,
[ord(char) for ch... | 1,047 | 417 |
import logging
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
from july.models import User
from july.people.models import Location
from july.utils import check_location
from optparse import make_option
class Command(BaseCommand):
help = 'fix locations'
... | 2,252 | 562 |
"""Tests for package name identifiers."""
| 42 | 11 |
# Copyright (c) 2018, MD2K Center of Excellence
# - Alina Zaman <azaman@memphis.edu>
# All rights reserved.
#
# 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 copy... | 6,338 | 1,918 |
rows, columns = [int(x) for x in input().split(", ")]
matrix = [[int(i) for i in input().split()] for _ in range(rows)]
for column in range(columns):
sum_column = 0
for row in range(rows):
sum_column += matrix[row][column]
print(sum_column)
| 263 | 90 |
import sys
import uuid
import psutil
import time
from datetime import datetime
# remove for production
from pprint import pprint
from functools import reduce
import function_lib as lib
class Invocation:
def __init__(self, exp_uuid: str, root: str, data: dict):
self.exp_id = exp_uuid
self.root_ide... | 2,939 | 910 |
from django import forms
from .models import News
class NewsForm(forms.ModelForm):
class Meta:
model = News
# fields = '__all__'
fields = ['title', 'content', 'is_published', 'category']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
... | 470 | 141 |
# This file is part of the pyMOR project (https://www.pymor.org).
# Copyright pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
from pymor.core.config import config
config.require('VTKIO')
from pathlib import Path
import meshio
fro... | 4,123 | 1,279 |
class MessageTypeNotExist(Exception):
"""
消息类型不存在
"""
pass
class TopicMessageTypeNotExist(Exception):
"""
主题消息类型不存在
"""
pass
| 161 | 65 |
from django.contrib import admin
from .models import Cart,CartItems
# Register your models here.
admin.site.register(CartItems)
admin.site.register(Cart)
| 159 | 45 |
import torch.nn as nn
from models.blocks import GlobalAvgPool2d
class _VanillaConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size):
super(_VanillaConvBlock, self).__init__()
self._block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size, str... | 1,887 | 651 |
"""Well known exceptions."""
from routemaster_sdk.types import LabelRef, StateMachine
class UnknownLabel(ValueError):
"""Represents a label unknown in the given state machine."""
deleted = False
def __init__(self, label: LabelRef) -> None:
self.label = label
def __str__(self):
retur... | 1,079 | 322 |
from platforms.models import PlatformGroup, Platform
from rest_framework import viewsets
from platforms.api.serializers import PlatformGroupSerializer, PlatformSerializer
class PlatformViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows tenants to be viewed or edited.
"""
queryset = Platform... | 604 | 150 |
import cv2
import numpy as np
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.interpolation import map_coordinates
def upsample(image, image_size_target):
padding0 = (image_size_target - image.shape[0]) / 2
padding1 = (image_size_target - image.shape[1]) / 2
padding_start0 = int(np.ce... | 5,528 | 2,132 |
from taskobra.orm import *
import platform
import cpuinfo
import subprocess
def create_system(args, database_engine):
system = System(name=platform.node())
cpu_info = cpuinfo.get_cpu_info()
system.add_component(OperatingSystem(
name=platform.system(),
version=platform.platform(),
))
... | 1,663 | 609 |
import unittest
from expression_builder.exceptions import ExpressionError
from expression_builder.expression_builder import ExpressionBuilder
class StringReplaceTests(unittest.TestCase):
# noinspection PyPep8Naming
def setUp(self):
self.exp = ExpressionBuilder()
self.exp.add_to_global("fred"... | 2,392 | 797 |
from flask import Flask, render_template
from flask_dummyimage import DummyImage
app = Flask(__name__)
dummyimage = DummyImage(app, url_prefix="/dm", endpoint="images", route="img")
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
| 309 | 105 |
from typing import Type, Any
class Typed:
"""A typed command line argument.
A typed command line argument is used for specifying the type
to convert the value to. For example, consider the following code:
@cli
def double(number: Opt[int]('A number to double.')):
print(number ... | 1,562 | 440 |
import json
import time
import cherrypy
class albums:
def __init__(self,artist,year,title,num):
self.artist=artist
self.year=year
self.title=title
self.N=num
class owner(albums):
def __init__(self,nome,date):
self.album_list=[]
self.nome=nome
self.last_... | 5,994 | 1,963 |
from django.conf.urls import url
from django.http import HttpResponse
urlpatterns = [
url(r'^$', lambda req: HttpResponse('OK')),
]
| 143 | 51 |
import random
from itertools import product
CS = 10 # cell size
W = 600 # width
H = 600 # height
COLS = W // CS
ROWS = H // CS
DENSITY = 0.35
dirs = list(product((-1, 0, 1), repeat=2))
dirs.remove((0, 0))
points = []
new_points = []
run = False
def xy2flat(x, y):
x = (x + COLS) % COLS
y = (y + ROWS) % RO... | 1,653 | 643 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
from conans import ConanFile, CMake, tools
class LibwebpConan(ConanFile):
name = "libwebp"
version = "1.0.0"
description = "library to encode and decode images in WebP format"
url = "http://github.com/bincrafters/conan-libwebp"
... | 5,064 | 1,741 |
# coding: utf-8
"""
Exposes several methods for transmitting cyclic messages.
The main entry point to these classes should be through
:meth:`can.BusABC.send_periodic`.
"""
import abc
import logging
import threading
import time
import warnings
log = logging.getLogger('can.bcm')
class CyclicTask(object):
"""
... | 5,184 | 1,404 |
from pywintypes import com_error
import win32com.client
from main import OutputError, BrailleOutput
class Virgo (BrailleOutput):
"""Braille output supporting the Virgo screen reader."""
name = 'Virgo'
def __init__(self, *args, **kwargs):
super (Virgo, self).__init__(*args, **kwargs)
try:
self.object = win... | 513 | 174 |
import pandas as pd
import numpy as np
from os import path
from path_service import LOG_DIR, DATA_DIR
from sklearn.metrics import log_loss
import re
prob_columns = list(map(lambda x: f"prob{x}", range(8)))
prob_columns_without_end = list(map(lambda x: f"prob{x}", range(7)))
def row_check(df: pd.DataFrame):
df.loc... | 3,050 | 1,167 |
import base64
# USER
post_user_data_200 = {
"username": "sbandera1",
"firstname": "Stepan",
"lastname": "Bandera",
"email": "stepanko@liamg.com",
"phone": "123",
"password": "supersecret"
}
post_user_alt_data_200 = {
"username": "ivanbahryanyi",
"firstname": "Ivan",
"lastname": "Bahryanyi",... | 1,255 | 576 |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CalendarConfig(AppConfig):
name = 'terrafirma.calendar'
label = 'terrafirma_calendar'
verbose_name = _('Terrafirma Calendar')
| 235 | 74 |
# Copyright 2019 https://github.com/kodi-addons
#
# 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 use, copy, modify, merge, p... | 6,466 | 2,067 |
import pickle
from flask import Flask, request, jsonify, session
from flask_cors import CORS, cross_origin
import sklearn
from sklearn.decomposition import TruncatedSVD
import pandas as pd
import numpy as np
ranks = []
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
class Model:
... | 3,440 | 1,469 |
from django.conf.urls import patterns,url
from ccr import views
urlpatterns=patterns(
'',
url(r'^$',views.main),
url(r'^save/',views.save),
url(r'^template/',views.template),
url(r'^compile/',views.compile),
url(r'^run/',views.run),
) | 235 | 95 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI/ModuleMgrDlg.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCo... | 9,354 | 3,184 |
"""Transmissivity classes
"""
import numpy as np
import scipy.integrate as integrate_mod
import spowtd.spline as spline_mod
def create_transmissivity_function(parameters):
"""Create a transmissivity function
Returns a callable object that returns transmissivity at a given
water level. The class of t... | 3,941 | 1,296 |
"""
category: Generate kinetics
name: Hill equations
description: automatically generate the equilibrium rate equation for transcription
icon: hillequation.png
menu: yes
specific for: Coding
tool: yes
"""
from tinkercell import *
from tc2py import *
items = tc_selectedItems();
genes = [];
for i in range(0,items.lengt... | 1,737 | 759 |
#encoding:utf-8
from setuptools import setup, find_packages
import sys, os
version = '0.4.3'
setup(name='ici',
version=version,
description="方便程序员在terminal查询生词的小工具",
long_description="""方便程序员在terminal查询生词的小工具""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_cla... | 795 | 291 |
"""
Copyright (c) 2015 SONATA-NFV
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 law or agreed to in... | 24,074 | 7,657 |
from datetime import datetime
from typing import Union
from discord import Member, User, Embed
from discord.ext import commands
from bot.main import NewCommand
class Avatar(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(
name='avatar',
cls=NewComman... | 2,246 | 773 |
class ProfileNotFound(Exception):
""" Exception if the linkedin url points to the linkedin not found page """
pass
class NotAProfile(Exception):
""" Exception raised if you pass a non linkedin profile as url """
pass
class ServerIpBlacklisted(Exception):
pass
class BadStatusCode(Exception):
p... | 323 | 83 |
print(isinstance(3, int))
lista = ['marina', 2, 'jujuba']
lista2 = []
for i in lista:
if isinstance(i, str):
lista2.append(i)
print(lista2)
myList = ['marina', 123, 9.5]
print(isinstance(9.5, int))
#strings
items = ['marina', 123, 9.5]
print(isinstance(9.5, float))
str_items = ['abc', 'Abc','def', 'BBBB','... | 810 | 351 |
import os
import logging
APP_NAME = 'psycopg3-connpool'
# Set to False to force reporting queries to share pool with non-reporting queries
REPORTING_POOL = True
POOL_MIN_SIZE = 1
POOL_MAX_SIZE = 10
POOL_MAX_IDLE = 60
POOL_STAT_SLEEP = 300
if not REPORTING_POOL:
pool_max_size += 5
CURR_PATH = os.path.abspath(... | 1,283 | 520 |
# coding: utf-8
class ObjectDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value | 247 | 72 |
import os
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.examples.tutorials.mnist import mnist
TRAIN_FILE = 'train.tfrecords'
VALIDATION_FILE = 'train.tfrecords'
def lenet(images):
net = slim.layers.conv2d(images, 20, [5,5], scope='conv1')
net = slim.layers.max_pool2d(net, [2,2... | 3,695 | 1,208 |
#!/usr/bin/env python
###############################################################################
# #
# Copyright 2017 - Ben Frankel #
# ... | 2,635 | 631 |
#!/usr/bin/python
from django.core.management import setup_environ
import sys
sys.path.append('/var/wsgi/maiznet')
sys.path.append('/var/wsgi')
from maiznet import settings
setup_environ(settings)
from maiznet.register.models import Presence
wfile_announces = open("/var/wsgi/maiznet/tools/ml/emails_announces","w"... | 605 | 237 |
# 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 t... | 1,368 | 430 |
import torch
import torch.nn as nn
from program.graph_utils import *
from helper import fc_block, LayerNormGRUCell
# helper class for GraphEncoder
class AttrProxy(object):
"""
Translates index lookups into attribute lookups.
To implement some trick which able to use list of nn.Module in a nn.Module
s... | 11,798 | 3,728 |
# check with status codes
# exceptions
# check 'error' and 'status'
from socket import inet_pton, inet_aton, AF_INET, error
def valid_ipv4(address: str):
"""
:param address: ip address string
:return: if the address is a valid dotted ipv4 address
"""
try:
inet_pton(AF_INET, address)
e... | 744 | 247 |
#!/bin/python
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author: wangms
# @Date : 2018/8/7
from flask import Blueprint
core = Blueprint('core', __name__)
from . import view | 182 | 76 |
# flake8: noqa
"""
This file holds code for the Pytorch Trainer creator signatures.
It ignores yapf because yapf doesn't allow comments right after code blocks,
but we put comments right after code blocks to prevent large white spaces
in the documentation.
"""
# yapf: disable
# __torch_model_start__
import torch.nn a... | 3,241 | 1,034 |
class Table(object):
def __init__(self, table, col, values):
self.table = table
self.col = col
self.values = values
| 144 | 42 |
import pytest
from baguette.app import Baguette
from baguette.httpexceptions import MethodNotAllowed
from baguette.responses import make_response
from baguette.view import View
@pytest.mark.asyncio
async def test_view_create():
class TestView(View):
async def get(self, request):
return "GET"
... | 2,185 | 667 |
# Copyright 2021 Blue Brain Project / EPFL
#
# 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... | 5,167 | 1,420 |
#
# Author: L. Salud, April 26.2018
#
import pandas as pd
import os
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
os.getcwd() # Get and place .py in same directory as .xls initially
os.chdir('./') # Path to .xls file
from pandas import read_ex... | 2,633 | 1,025 |
import re
def read_from_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read().splitlines()
return content
def write_to_file(corpus, dest_path):
with open(dest_path, 'w', encoding='utf-8') as f:
for item in corpus:
f.write("%s\n" % item)
def f... | 1,278 | 710 |
"""Classes to access the `cltk_data/` directory tree"""
__author__ = 'Stephen Margheim <stephen.margheim@gmail.com>'
__license__ = 'MIT License. See LICENSE.'
import os
import site
from cltk.cltk import CLTK_DATA_DIR
from cltk.cltk.corpus.wrappers.logger import logger
class CorpusError(Exception):
pass
class C... | 3,680 | 1,013 |
from .decommission import Decommission
from .release_resources import ReleaseResources
from .farewell import Farewell
| 118 | 29 |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# 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 copyright
# notice, this list of conditions a... | 3,482 | 1,112 |
import numpy as np
import torch
def fexp(x, p):
return torch.sign(x)*(torch.abs(x)**p)
def cuboid_inside_outside_function(X, shape_params, epsilon=0.25):
"""
Arguments:
----------
X: Tensor with size BxNxMx3, containing the 3D points, where B is the
batch size and N is the number... | 19,093 | 7,219 |
from PyQt5.QtOpenGL import *
from OpenGL.GL import *
from PyQt5 import QtWidgets, QtCore
class FigureWidget(QGLWidget):
""" Main OpenGL widget. """
def __init__(self, parent):
super(FigureWidget, self).__init__()
self.setMinimumSize(1280, 720)
self.__rotate_angle_y = 70
sel... | 6,206 | 2,756 |
"""
Submit a SIP archive to the digital preservation service
"""
from pathlib import Path
import click
from passari.config import CONFIG
from passari.dpres.package import MuseumObjectPackage
from passari.dpres.ssh import connect_dpres_sftp
from passari.utils import debugger_enabled
def submit_sip(package_dir, objec... | 2,485 | 780 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.IndirectIsvTerminalInfo import IndirectIsvTerminalInfo
class AlipayOfflineProviderIndirectisvActivityCreateModel(object):
def __init__(self):
self._ext_info = None
... | 2,931 | 969 |
import numpy
class Environment:
def __init__(self, params) -> None:
self.domain_value_labels = params["domain_value_labels"]
self.observation_dim = params["observation_dim"]
self.nr_agents = params["nr_agents"]
self.nr_actions = params["nr_actions"]
self.time_limit = params... | 4,220 | 1,279 |
import ast
from typing import Optional, Tuple, Union
from boa3.model.expression import IExpression
from boa3.model.imports.package import Package
from boa3.model.symbol import ISymbol
from boa3.model.type.classes.classtype import ClassType
from boa3.model.type.itype import IType
class Attribute(IExpression):
"""... | 1,651 | 493 |
import os
import os.path as osp
__all__ = [
'pack_images',
'plot_and_pack',
'save_images'
]
def pack_images(output, imgs, vmax=1024.0, archive=None, name="image_%d.png", **data):
from scipy.misc import toimage
try:
os.makedirs(output)
except:
pass
for i in range(imgs.shape[0]):
args = dict... | 2,409 | 1,001 |
import metrics
from metrics import timeit
from main import *
import os
class Shield(object):
def __init__(self, env, actor, model_path=None, force_learning=False, debug=False):
"""init
Args:
env (Environment): environment
actor (ActorNetwork): actor
force_learning (bool, option... | 34,085 | 11,934 |
class PalindromePartitioning:
"""
https://leetcode-cn.com/problems/palindrome-partitioning/
"""
def partition(self, s: str) -> List[List[str]]:
| 171 | 63 |
##Write a program that reads the contents of a text file. The program should create a diction-
##ary in which the key-value pairs are described as follows:
##• Key. The keys are the individual words found in the file.
##• Values. Each value is a list that contains the line numbers in the file where the word
##(the key)... | 3,922 | 1,051 |
file_input = open('stack.in', 'r')
file_output = open('stack.out', 'w')
def validate_stack(top_index):
return True if (top_index == -1) else False
class ImplementedStack(object):
def __init__(self):
self.stack = []
self.top = -1
def push_value(self, value):
self.top ... | 982 | 342 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import queue
import threading
import typing
from .constants import S_END_OF_CMD
import serial
class AbstractSerialNex(object):
INCOMING_BUFFER_SIZE = 1024 # Seems the Nextion buffer size, mentioned in official docs
MIN_SIZE_READ = len(S_END_... | 4,151 | 1,276 |
# -*- coding: utf-8 -*-
"""
Compute essential stats(freq/tf-idf) on a corpus
Dependencies:
pandas == 0.23
gensim == 3.8
"""
__author__ = "Mike Shuser"
import pickle
import numpy as np
import pandas as pd
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
DATA_SRC = "../processed_corp... | 1,762 | 637 |
import math
def print_matrix(matrix):
"""
Function to print a matrix
"""
for row in matrix:
for col in row:
print("%.3f" % col, end=" ")
print()
def rows(matrix):
"""
Returns the no. of rows of a matrix
"""
if type(matrix) != list:
return 1
r... | 2,937 | 943 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
... | 1,102 | 303 |
import hashlib
from datetime import datetime
def salsa_20_xor_bytes():
pass
def n_string(string, n):
hash = hashlib.sha512()
hash.update(string.encode('utf-8'))
return hash.digest()[:n]
def encryption(iv: str, key: str, filename: str) -> bool:
try:
iv = n_string(iv, 8)
key = n_... | 1,443 | 454 |
"""
This file contains tests on the creation of directories
"""
from __future__ import absolute_import, division, print_function
import time
import os
import shutil
import unittest
from fitbenchmarking.utils.create_dirs import (figures, group_results, results,
support_pa... | 3,747 | 1,088 |
import os
from urllib.parse import urlparse
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from typing import Optional
import api
app = FastAPI()
app.mount("/files", StaticFi... | 1,173 | 355 |
#!/usr/bin/env python
#
# Get alert notifications from Sysdig Cloud
#
import os
import sys
import time
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient
def print_notifications(notifications):
for notification in notifications:
values = ... | 1,976 | 678 |
from sqlalchemy import Column, Integer, String
from sqlalchemy import DateTime
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
class groupingDeviceMappingTable():
def __init__(self, metadata: MetaData):
self.groupingDeviceMappingTable = Table('GroupingDeviceMapping', metadata,
... | 791 | 170 |
import sys
import numpy
from distutils.version import LooseVersion
assert sys.version_info >= (3, 5)
assert LooseVersion(numpy.version.version) >= LooseVersion('1.16'), 'nutils requires numpy 1.16 or higher, got {}'.format(numpy.version.version)
version = '8.0a0'
version_name = None
long_version = ('{} "{}"' if versi... | 802 | 291 |
# The MIT License (MIT)
#
# Copyright (c) 2015 addfor s.r.l.
#
# 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 use, copy, m... | 4,871 | 1,388 |
from django.db import models
from django.utils import timezone
class Tag(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=200, null=True, blank=True, default='')
def __str__(self):
return self.name
class Post(models.Model):
author = models.Fore... | 720 | 221 |
# http://github.com/timestocome
# data
# https://www.cs.toronto.edu/~kriz/cifar.html
import numpy as np
import pickle
import matplotlib.pyplot as plt
###################################################################################
# read in data
###############################################################... | 1,710 | 611 |
from flask import render_template
from app.blueprints.seo_arizona.views import seo_arizona
@seo_arizona.app_errorhandler(403)
def forbidden(_):
return render_template('errors/403.html'), 403
@seo_arizona.app_errorhandler(404)
def page_not_found(_):
return render_template('errors/404.html'), 404
@seo_ariz... | 427 | 173 |
import flames
import unittest
class TestFlamesMethods(unittest.TestCase):
def test_flames_count(self):
self.assertEqual(flames.flames_count('abhi','abhi'),0)
self.assertEqual(flames.flames_count('abhi','a'),3)
self.assertEqual(flames.flames_count('abhi','asd'),5)
def test_flames... | 1,315 | 485 |
import traceback
from fastapi import Request
from fastapi.responses import PlainTextResponse
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
def internal_server_exception_handler(
_: Request,
exception: Exception
) -> PlainTextResponse:
""" Return the traceback of the internal server ... | 826 | 246 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
helper class that supports empty tensors on some nn functions.
Ideally, add support directly in PyTorch to empty tensors in
those functions.
This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""
import m... | 11,025 | 3,663 |