content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
import base64
from Crypto.Cipher import AES
ciphertext = base64.b64decode("rW4q3swEuIOEy8RTIp/DCMdNPtdYopSRXKSLYnX9NQe8z+LMsZ6Mx/x8pwGwofdZ")
key = base64.b64decode("6v3TyEgjUcQRnWuIhjdTBA==")
aes_text = AES.new(key, AES.MODE_ECB)
print(aes_text.decrypt(ciphertext))
|
from heapq import heapify, heappop, heappush
import collections
'''
Time: O(n) + O(nlogk)
Space: O(n)
'''
class Solution:
def __init__(self, nums, k):
self.heap = []
self.k = k
self.nums = nums
def topk(self):
freq = collections.defaultdict(int)
for num in self.nu... |
import dj_database_url
from decouple import config
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
ADMINS = (('Neil', 'neil@neilmillard.com'),)
# Console will be picked up by gunicorn
LOGGING = {
'version': 1,... |
"""
python scripts/remote_capture.py
"""
import os
import subprocess
import click
import cv2
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
import rawpy
from diffcam.util import rgb2gray, print_image_info
from diffcam.plot import plot_image, pixel_histogram
from diffcam.io import load... |
"""Implements OA algorithm for convex problems"""
import copy
import logging
import time
from decogo.solver.settings import Settings
from decogo.util.block_vector import BlockVector
logger = logging.getLogger('decogo')
class OaSolver:
"""Class which implements OA method for convex problems
:param problem:... |
XXXXXXXX XXX XXX XXXXX
|
import asyncio
import math
import platform
import socket
from datetime import timedelta
import discord
import psutil
import uptime
from discord.ext import commands
class Admin:
"""
Bot owner and admin commands
"""
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=True)
... |
'''
Created on Oct 15, 2014
@author: stefan
'''
import ast
from pydron.translation.astwriter import mk_str, mk_num, mk_call, mk_None, mk_tuple, mk_assign, mk_attr, mk_name, mk_subscript_assign
from pydron.translation import transformer
class DeImport(transformer.AbstractTransformer):
"""
Replaces `import` an... |
from tatk.util.kb_query import KBquery |
from __future__ import annotations
from typing import overload
class Vector2:
def __init__(self, x: int = 0, y: int = 0) -> None:
self.x = x
self.y = y
def __mul__(self, other: Vector2 | int) -> Vector2:
if isinstance(other, Vector2):
return Vector2(self.x * other.x, self.y... |
import unittest
from bank import BankAccount
class BadTestBankAccount(unittest.TestCase):
def setUp(self):
self.account = BankAccount("TestName", 0)
self.account_1 = BankAccount('For testing', 100)
self.account_2 = BankAccount('In dollars', 10)
def test_deposit_positive_amount(sel... |
from logic.enums.card_type import CardType
class Card:
def __init__(self):
self.card_type = CardType.NONE
self.cost = 0
self.name = 'card'
self.actions = []
self.burnout = []
self.resistance = 3
self.fresh = True
def my_type(self):
return self.ca... |
"""Useful functions that don't fit anywhere else."""
def is_string(obj):
"""Python 2 and 3 compatible string determinor."""
try:
return isinstance(obj, basestring)
except NameError:
return isinstance(obj, str) |
import pytest
import receptor
from receptor.config import ReceptorConfig
from receptor import Receptor
from receptor.node import mainloop
import socket
import asyncio
from mock import patch
@pytest.fixture
def receptor_config(unused_tcp_port):
config = dict()
config.setdefault('server', {})['port'] = unused_t... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 5 22:44:32 2022
"""
from Wrapper import ModelWrapper
import numpy as np
from utils.ImageLoader import ImageLoader
from tensorflow import keras
from matplotlib import pyplot as plt
from tensorflow.keras.layers.experimental.preprocessing import Resizing
import pickle
'''
... |
from flask import Flask, jsonify
from flask_cors import CORS
from func import linearReg
app = Flask(__name__)
CORS(app)
@app.route('/predict', methods=['POST'])
def predict():
return jsonify({
'data': linearReg()
}) |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from timezones.fields import TimeZoneField
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], [r"^timezones\.fields\.TimeZoneField"])
CONFERENCE_CACHE = {}
class Conference(models.Model):
""... |
import pickle
import numpy as np
import pandas as pd
import argparse
def list_of_columns(pdata, rdata):
"""
Using R and Python files, make a list of columns that will be used
for comparison.
"""
r_cols = set(rdata.columns)
print('Number of columns in R file...{0}'.format(len(r_cols)))
p_c... |
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Yahoo! 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... |
#
# PySNMP MIB module ROUTER-OIDS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROUTER-OIDS
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
def linearsearch(arr, key):
for i in range(len(arr)):
if arr[i] == key:
return i
return -1
arr = [12,45,78,98,63,21,458,78,96,420,69,21,78,96,55,266,10,666,214,789,654,1,2,4,8,9,3,5,78]
key = 10
print("element found at index "+str(linearsearch(arr,key))) |
import unittest
from test.support import import_module, import_fresh_module
# Skip test if _thread or _tkinter wasn't built or idlelib was deleted.
import_module('threading') # imported by PyShell, imports _thread
tk = import_module('tkinter') # imports _tkinter
idletest = import_module('idlelib.idle_test')
# Make s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author = i@cdxy.me
# project = https://github.com/Xyntax/POC-T
"""
Open SSHD User Enumeration (CVE-2016-6210)
Usage:
python POC-T -T -m opensshd-user-enum --api --dork="port:22 country:cn"
"""
import paramiko
import time
from plugin.util import randomString
delay =... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-19 17:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetable', '0005_auto_20171007_1837'),
]
operations = [
migrations.CreateM... |
"""Given an array of integers, write a function to determine
whether the array could become non-decreasing by modifying at most 1 element.
For example, given the array [10, 5, 7], you should return true, since we
can modify the 10 into a 1 to make the array non-decreasing.
Given the array [10, 5, 1], you should ret... |
import pytest
from casparser.exceptions import HeaderParseError
from casparser.process import parse_header
class TestProcessClass:
def test_header_parser(self):
good_header = 'Consolidated Account Statement\n01-Apr-2018 To 31-Mar-2019'
bad_header = 'Consolidated Account Statement\n01-Apr-2018'
... |
"""This module provides functionality for wrapping key infrastructure components
from distutils and setuptools.
"""
from __future__ import print_function
import argparse
import copy
import json
import os
import os.path
import platform
import stat
import sys
import warnings
from contextlib import contextmanager
# pyl... |
def dailyTemperatures(T):
output = [0 for _ in T]
seen = []
for i in range(len(T)-1, -1, -1):
while seen and seen[-1][0] <= T[i]:
seen.pop()
if seen:
output[i] = seen[-1][1]-i
seen.append((T[i], i))
return output
print(dailyTemperatures([73, 74, 75, 71... |
import requests
import json
import urllib3
from robot.api.deco import keyword
from .version import VERSION
__version__ = VERSION
BASE_ENDPOINT = '{}://{}:{}@{}/'
GET_JOB = '{}/api/json'
GET_JOB_BUILD = '{}/{}/api/json'
BUILD_JOB_WITH_PARAMETERS = '{}/buildWithParameters'
class JenkinsFace(object):
def __init__... |
from jinjasql import JinjaSql
from typing import List
import os
import pandas as pd
import psycopg2
import streamlit as st # version 0.49
# Simple streamlit example to illustrate retrieving data from a database
# based on 2 inputs provided from the user. It also makes use of the
# JinjaSql library since in this vers... |
"""
Generates RASPA input file for given cif file and simulation parameters to calculate adsorption.
"""
# RASPA 2 input file generation for adsorption simulations
# Author: Kutay B. Sezginel
# Date: July 2017
def write_raspa_file(input_file, config):
"""
Writes RASPA input file for simulating gas adsorption.... |
# This init file seems necessary to have _cli.py:main as an entry point.
|
n = input()
for num in reversed(n):
num = int(num)
for pos in range(num):
if num != 0:
symbol = chr(num + 33)
print(symbol, end="")
if num == 0:
print("ZERO")
else:
print()
|
import json
#import the created helper functions
from operators import Ops
from memfuncs import MemFunc
class DecisionTree():
"""Takes in a json file of the tree structure then generates the tree"""
def __init__(self,filename):
#parse the json file into a data structure
with open... |
# Copyright (c) 2015 Rackspace, Inc.
#
# 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 wr... |
# -*- coding: utf-8 -*-
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import import_string
from django.utils.text import slugify
from crispy_forms.h... |
# Copyright 2018 The TensorFlow 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 applic... |
'''
判断一个数字是否可以表示成三的幂的和
给你一个整数 n ,如果你可以将 n 表示成若干个不同的三的幂之和,请你返回 true ,否则请返回 false 。
对于一个整数 y ,如果存在整数 x 满足 y == 3x ,我们称这个整数 y 是三的幂。
提示:
1 <= n <= 107
'''
'''
思路:数学
对于一个整数x,如果是3的幂的和,说明x=y*3 or x= y*3+1
也就是x是3的整数倍或整数倍+1
不对,是3个不同的幂之和如果是21,3^2+3^2+3^1
TODO
'''
|
from filterset import FilterSet
from filters import *
|
import os
import torch
from collections import OrderedDict
from . import networks
class BaseModel():
# modify parser to add command line options,
# and also change the default values if needed
@staticmethod
def modify_commandline_options(parser, is_train):
return parser
def name(self):
... |
# -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
from __future__ import absolute_import, print_function
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for... |
import os
import tempfile
import uuid
from typing import Generator, List
import pytest
from click.testing import CliRunner
from pytest_mock import MockFixture
from opta.amplitude import AmplitudeClient, amplitude_client
from opta.cli import cli
tmp_dir = ""
@pytest.fixture(autouse=True)
def run_before_and_after_te... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nicira Networks, 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.apach... |
import fbx
# I got these string from fbxio.h (which works in 2015)
# in FBX SDK Reference > Files > File List > fbxsdk > fileio > fbx
FBX_VERSION = {'2010': "FBX201000",
'2011': "FBX201100",
'2012': "FBX201200",
'2013': "FBX201300",
'2014': "FBX201400",
... |
import flask
import json
from flask import make_response, request, jsonify
from flask_cors import CORS, cross_origin
from flask_pymongo import PyMongo,ObjectId
from flask import render_template
from pytz import timezone
from datetime import datetime
import settings
IST = timezone('Asia/Kolkata')
# APP... |
from .Entity import Entity
from .ontologies import ODEUROPA
class Smell(Entity):
def __init__(self, seed):
super().__init__(seed)
self.setclass(ODEUROPA.L11_Smell)
|
#!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections in sample i... |
import sys
import csv
def add_freqs(infile, outfile):
myoutput = open(outfile, 'w')
csvwriter = csv.writer(myoutput, delimiter=';')
current_string = 'description_pair'
current_freq = 'joint freq'
with open(infile, 'r') as csvinput:
csvreader = csv.reader(csvinput, delimiter=';')
... |
import functools as func
import torch
import torch.distributed as dist
from torch import nn
from apex import check_cudnn_version_and_warn
import fast_bottleneck
import nccl_p2p_cuda as inc
assert check_cudnn_version_and_warn(__name__, 8400)
def kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu... |
"""AvailabilityTestCase class"""
from django.contrib.auth.models import User
from django.test import TestCase
from member_manager.models import Availability
from member_manager.models import Profile
class AvailabilityTestCase(TestCase):
"""AvailabilityTestCase to test availability periods."""
@classmethod
... |
from graphics.lib import *
from math import hypot
from random import randrange
import pyscreenshot as ImageGrab
#Returns true if the edge from u to v is directed
def is_directed(dir_G, u, v):
return not u in dir_G[v]
def simple(vertices,graph_name="graph"):
x_size, y_size = 0, 0
for vertex in vertices:
... |
'''
Print and text rendering utils for the CLI commands
Click library extension classes
'''
import dataclasses
import datetime
import decimal
import functools
import logging
from typing import Any, cast, Dict, Hashable, List, Optional, Set
import arrow
import click
import pandas as pd
from rich import box
from rich.ta... |
from itertools import permutations
# input
n, d = map(int, input().split())
# process
'''
n을 d진법으로 바꾼다.
문제의 조건에 맞추려면 무조건 d진법의 d자리 수여야 함.
val := n을 d진법으로 변환한 수. d^x의 자리는 val[x]로 찾을 수 있음.
조건을 만족하는 d진법 d자리 수 >> 순열로 구함.
'''
# n이 d진법으로 몇 자리 수인지 계산
i = 0
while d ** i <= n: i += 1
# 조건을 만족하는 d진법 d자리 수의 순열
special_val = per... |
from django.shortcuts import render
from .models import Post
from django.shortcuts import redirect
from bulletin_board.crawling_get_worldJob import *
from bulletin_board.crawling_get_kosaf import *
from bulletin_board.crawling_get_youthcenter import *
from bulletin_board.store_db import *
from bulletin_board.db_table i... |
from os import remove, path
from event_logger import event_log
#deletes a DB file given its name
def remf(dbname):
try:
try:
remove(dbname + ".hashdb")
except Exception as e:
event_log("There was an error destroying DB {} - {}".format(dbname, str(e)), dbname)
return (str(e))
except Exception as e:
e... |
# coding: utf-8
"""
FeersumNLU API
This is the HTTP API for Feersum NLU. See https://github.com/praekelt/feersum-nlu-api-wrappers for examples of how to use the API. # noqa: E501
OpenAPI spec version: 2.0.54.dev2
Contact: nlu@feersum.io
Generated by: https://github.com/swagger-api/swagger-codege... |
# Copyright 2020 by Aaron Baker.
# All rights reserved.
# This file is part of the Nightcap Project,
# and is released under the "MIT License Agreement". Please see the LICENSE
# file that should have been included as part of this package.
# region Imports
from nightcapserver.helpers.docker_configure import NightcapDoc... |
#coding=utf-8
from functools import wraps
from utils import *
from models import *
def top_add(func):
@wraps(func)
def with_logging(*args, **kwargs):
# size_list.append(args[1])
size = request2size(args[1])
content = args[2]
mem2chunk(size,content)
... |
import os
from datetime import datetime
from project_root import *
__par_cpp_dir__ = proot('..')
authors = 'tpyj'
author = 'x'
input_code = 'x'
def setAuthor(name):
assert name in authors
global author
author = name
def setInput(name):
global input_code
input_code = name
|
from django.db import models
from core.models import AbstractTimeStampModel
class Tag(AbstractTimeStampModel):
name=models.CharField(max_length=16, unique=True)
def __str__(self):
return self.name
|
import os
import sys
import h5py
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--root', help='path to root directory')
parser.add_argument('--seed', type=int, default=42, help='random number seed')
args = parser.parse_args()
root = args.root
seed = args.seed
np.random.seed(seed)
fname = ... |
"""
| Handle interaction with the mongodb database.
"""
# External modules
from pymongo import MongoClient
from asyncio import get_event_loop
from logging import getLogger
from typing import Callable
log = getLogger("pog_bot")
# dict for the collections
_collections = dict()
class DatabaseError(Exception):
"""... |
def check_schedule_vs_members(sch, members):
if len(members) != len(sch.divisions):
raise(ValueError('the members and schedule structures are inconsistent'))
for div_idx, teams in enumerate(members):
if len(teams) != len(sch.divisions[div_idx].teams):
raise(ValueError('the member... |
'''
This demo is used to validate the back-propagation of the torch implementation of oriented
2d box intersection.
This demo trains a network which takes N set of box corners and predicts the x, y, w, h and angle
of each rotated boxes. In order to do the back-prop, the prediected box parameters and GT are
converted... |
import FWCore.ParameterSet.Config as cms
from RecoTauTag.RecoTau.PFRecoTauQualityCuts_cfi import PFTauQualityCuts
pfTauEnergyRecoveryPlugin = cms.PSet(
qualityCuts = PFTauQualityCuts,
corrLevel = cms.uint32(3), # enable all corrections
lev1PhiWindow = cms.double(0.50),
lev1EtaWindow = cms.double(0.10)... |
"""EXCEPTIONS
Exception manager for Bus and Stop getters, returning custom exceptions depending on the response returned by the API.
"""
# # Native # #
import contextlib
# # Installed # #
import httpx
# # Project # #
from vigobusbot.exceptions import StopNotExist, GetterAPIException, GetterInternalException, GetterT... |
from collections import defaultdict
from re import compile, finditer, match, sub
from .ntheory import factors
_str_power = r'(?:[1-9][0-9]*(?: *\^ *[1-9][0-9]*)?)'
_str_product = r'(?:(?:%s *\* *)*%s)' % (_str_power, _str_power)
_str_integer = r'(%s|%s)' % (_str_product, _str_power)
_str_term = r'(\(%s\)|%s)' % (_str_... |
# [Shaolin Temple] Demon-iority Complex
GOBLIN_DEMON = 9310578
HUMAN_FACE_MASK = 4034664
sm.removeEscapeButton()
sm.setSpeakerID(GOBLIN_DEMON)
sm.setBoxChat()
sm.sendNext("You SURE I'll learn how to tolerate humans better if I wear this? Okaaay...")
sm.completeQuest(parentID)
sm.consumeItem(HUMAN_FACE_MASK)
sm.giveEx... |
import string
import sys
from google.protobuf import descriptor_pb2 as descriptor
from google.protobuf.compiler import plugin_pb2 as plugin
# Parameters:
# parser_functions
# The set of ParseMessage and ParseMessageImpl functions that actually do the parsing
FILE_TEMPLATE = """
package ca.isupeene.charactershee... |
default_app_config = 'demo.apps.ConcurrencyTestConfig'
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import copy
import json
import logging
import warnings
from collections import defaultdict
from six.moves.urllib.parse import urljoin
from six.moves.http_cookiejar import CookieJar
import scrapy
from scrapy.exceptions import NotConfigured
from scrapy.htt... |
#! /usr/bin/python
'''
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p... |
from libs import hub
hub.check()
hub.CONSTANTS.initialize_databases()
def create_account(email: str, password: str, username: str):
while True:
try:
string = username + ":" + email.replace(".", "DOT")
print(string, password, username)
hub.CONSTANTS.DATABASE.update("/us... |
import unittest
import githubParser.github_parser as g
from sof.sof_parser import SOFParser
from githubParser.github_parser import GITHUBParser
from utils import get_parser_of_link
from collections import OrderedDict
from result import Result
parsers = [SOFParser, GITHUBParser]
# ----------------------------------- G... |
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# 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/... |
from collections import deque
"""
Graph traversal
---------------
Since graphs don't necessarily have an ordered structure, traversing a graph can be more involving.
Traversal normally involves keeping track of which nodes or vertices have already been visited and which ones have not.
Strategies:
-> follow a path unt... |
#!/usr/bin/python
import time
import argparse
import os
import datetime
import numpy as np
import sys
import glob
import pytz
# argument parser
parser = argparse.ArgumentParser(description = "BirdCam summary script")
parser.add_argument("-p", "--path", type=str,help="Path to the output folder")
parser.add_argument("-... |
# coding: utf-8
"""
Grafeas API
An API to insert and retrieve annotations on cloud artifacts.
OpenAPI spec version: 0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in co... |
import sqlite3
import uuid
class AssetDBConnection:
def __init__(self, databasePath):
sqlite3.register_converter('BLOB', lambda b: uuid.UUID(bytes=b))
sqlite3.register_adapter(uuid.UUID, lambda u: buffer(u.bytes))
self.databasePath = databasePath.replace('\\', '/')
def __enter__(self)... |
import warnings
import textwrap
warnings.warn(textwrap.dedent("""\
The module 'sunpy.physics.transforms.differential_rotation.py' is deprecated and
will be removed in the future. Use 'sunpy.physics.differential_rotation.py' instead"""),
stacklevel=2)
from sunpy.physics... |
# coding: utf-8
"""
Tests for builders
"""
from datetime import datetime
from time import sleep
import pytest
from maggma.utils import Timeout # dt_to_isoformat_ceil_ms,; isostr_to_dt,
from maggma.utils import (
dynamic_import,
grouper,
primed,
recursive_update,
to_dt,
to_isoformat_ceil_ms,
)... |
#
# Copyright (c) 2015-2020 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRAN... |
'''
Description on how to produce metadata file.
'''
input_filter = None
treename = 'deepntuplizer/tree'
reweight_events = -1
reweight_bins = [list(range(200, 2051, 50)), [-10000, 10000]]
metadata_events = 1000000
selection = '''jet_tightId \
&& ( !label_H_cc )'''
# && ( (sample_isQCD && fj_isQCD) || (!sample_isQCD &&... |
from locale import getdefaultlocale
from os import getenv, path
HOME = getenv('HOME')
language = getdefaultlocale()[0].lower()
def validate_folder(list_of_folders):
for index in range(len(list_of_folders)):
if not path.isdir(list_of_folders[index]):
if list_of_folders[index][-1].lower() != 's... |
'''PyFastL2LiR: Fast L2-regularized Linear Regression.'''
import math
import sys
from time import time
import warnings
import numpy as np
from numpy.matlib import repmat
from tqdm import tqdm
pv = sys.version_info
python_version = float('{}.{}'.format(pv.major, pv.minor))
if python_version >= 3.5:
from threadp... |
from __future__ import absolute_import, print_function
from .ext import OARepoHealthCheck
from .version import __version__
__all__ = ('__version__', 'OARepoHealthCheck',) |
import six
import escpos.printer as printer
from escpos.constants import GS
def test_cut_without_feed():
"""Test cut without feeding paper"""
instance = printer.Dummy()
instance.cut(feed=False)
expected = GS + b'V' + six.int2byte(66) + b'\x00'
assert(instance.output == expected)
|
def profitableSchemes(n: int, minProfit: int, group: list[int], profit: list[int]) -> int:
total_schemes = len(group)
dp = [[[0] * (minProfit+1) for _ in range(n+1)] for _ in range(total_schemes+1)]
for members in range(n+1):
dp[0][members][0] = 1
for scheme in range(1, total_schem... |
from dall_e import map_pixels, unmap_pixels
import numpy as np
import torchvision
import tempfile
import imageio
import random
import kornia
import shutil
import torch
import time
import os
import re
def create_outputfolder():
outputfolder = os.path.join(os.getcwd(), 'output')
if os.path.exists... |
"""
This file has methods to be able to send emails from an API REST
And some specific methods from some typical emails.
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL, SMTPAuthenticationError, SMTPRecipientsRefused
from cornflow_core.exceptions im... |
from client.resource import Resource
class Entities(Resource):
def all(self, page=None, limit=100, **kwargs):
extra_params = {name: kwargs[name] for name in kwargs if kwargs[name] is not None}
params = {
'page': page,
'limit': limit,
**extra_params
}
... |
from ..hashing_helpers import hash_dictionary
class KeyValueHashableObject:
""" Objects can be hashed from the keys and values of their self.__dict__ """
def __hash__(self):
""" custom hash function that allows use in dictionary just based off of the values and not the object instance. """
... |
import collections.abc
import hashlib
import jwt
import uuid
import requests
from ratelimit import limits, RateLimitException
from backoff import on_exception, expo
from typing import Mapping, Sequence
from urllib.parse import urlencode
from .exceptions import APIException, RequestException
class UPBitClient:
A... |
"""
MassOpenCloud / Hardware Isolation Layer (HIL)
User Level Slurm Reservations (ULSR)
Infiniband Link Management
December 2017, Tim Donahue tdonahue@mit.edu
"""
import hostlist
import logging
import sys
IBLINKINFO_CMD = iblinkinfo.sh
IBPORTSTATE_CMD = ibportstate.sh
def main(argv=[]):
'''
'''
if ... |
import numpy as np
import os
import glob
import re
from .BaseDataset import BasePlainDataset, BaseImageDataset
class iLIDS(BasePlainDataset):
"""No Camera"""
dataset_dir = 'i-LIDS'
def __init__(self, store_dir, verbose=True, **kwargs):
super().__init__()
self.dataset_dir = ... |
from CodernityDB.hash_index import HashIndex
class MultiIndex(HashIndex):
def __init__(self, *args, **kwargs):
kwargs['key_format'] = 'I'
super(MultiIndex, self).__init__(*args, **kwargs)
def insert(self, doc_id, key, start, size, status='o'):
if isinstance(key, (list, tuple)):
... |
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from setuptools import setup
setup(name='snowflake-connector-python', version='9000', packages=['snowflake'])
|
# -*- coding: utf-8 -*-
"""testapp2 setup script."""
from setuptools import setup
if __name__ == "__main__":
setup(
name="testapp2",
description="Not a real package, just for testing GravityBee.",
package_dir={"": "src"},
)
|
import click
from . import Alebot
@click.command()
@click.option("--path", default=".",
help="Path in which confi.json and plugins are.")
def run(path):
alebot = Alebot(path)
alebot.connect()
|
# 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 th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.