content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
if __name__ == '__main__':
data = open('input').read().splitlines()
grid = []
for row in data:
newrow = []
for column in row:
newrow += [int(column)]
grid += [newrow]
low_points = []
for i,row in enumerate(grid):
for j,val in enu... |
#!/usr/bin/env python3
import numpy as np
import os
import sys
from scipy.stats import norm
##SOME CONSTANTS##############################################
epsilon0 = 8.854187817e-12 #F/m
hbar = 6.582119514e-16 #eV s
hbar2 = 1.054571800e-34 #J s
mass = 9.10938356e-31 #kg
c = 299792458 ... |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.properties import ListProperty
from kivy.core.window import Window
from random import random,randrange
from kivy.graphics import Color, Rectang... |
import os
os.environ["OMP_NUM_THREADS"]= '1'
os.environ["OMP_THREAD_LIMIT"] = '1'
os.environ["MKL_NUM_THREADS"] = '1'
os.environ["NUMEXPR_NUM_THREADS"] = '1'
os.environ["OMP_NUM_THREADS"] = '1'
os.environ["PAPERLESS_AVX2_AVAILABLE"]="false"
os.environ["OCR_THREADS"] = '1'
import poppler
import pytesseract
from pdf2im... |
import redis
from random import choice
from Proxypool.proxypool.error import PoolEmptyError
MAX_SCORE = 100
MIN_SCORE = 0
INITIAL_SCORE = 10
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_PASSWORD = None
REDIS_KEY = 'proxies'
class RedisClient(object):
def __init__(self, host=REDIS_HOST, port=REDIS_PORT, passw... |
import numpy as np
from divide import Predicate
from node import Node
class DecisionTree:
def build(self, X, y):
self.root = self.build_subtree(X, y)
return self
def build_subtree(self, X, y):
predicate = DecisionTree.get_best_predicate(X, y)
if predicate:
X1, y1, ... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to non-... |
from flask_sqlalchemy import SQLAlchemy
class Repository:
def __init__(self):
pass
db = SQLAlchemy
|
class SarsaAgent(acme.Actor):
def __init__(self,
environment_spec: specs.EnvironmentSpec,
epsilon: float,
step_size: float = 0.1
):
# Get number of states and actions from the environment spec.
self._num_states = environment_spec.observations.num_v... |
from typing import Tuple
from ..gameModel import GameModel
def putChess(cls: GameModel, pos: Tuple[int]):
"""
make in-place operation for both boards
and switch player.
Used in playing and test (pretend user and computer)
"""
cls.last_pos = pos
r, c = pos
cls.board_for_calc[r... |
#coding:utf-8
import os
import shutil
import tempfile
import unittest2 as unittest
import time
from replmon import Replmon
class StatusFileTestCase(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp()
self.status_file = os.path.join(self.test_dir, "replmon.status")
se... |
# This class parses a gtfs text file
class Reader:
def __init__(self, file):
self.fields = []
self.fp = open(file, "r")
self.fields.extend(self.fp.readline().rstrip().split(","))
def get_line(self):
data = {}
line = self.fp.readline().rstrip().split(",")
for e... |
from Classes.Logic.LogicCommandManager import LogicCommandManager
from Classes.Messaging import Messaging
from Classes.Packets.PiranhaMessage import PiranhaMessage
class EndClientTurnMessage(PiranhaMessage):
def __init__(self, messageData):
super().__init__(messageData)
self.messageVersion = 0
... |
from setuptools import setup
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name="reagan",
version="2.3.0",
description="Package for streamlining credentials, connections, and data flow",
url="https://github.com/schustda/reagan",
author="Douglas Schuster",
... |
from urlparse import urlparse
import logging
import requests
logger = logging.getLogger('solr_detective.app')
class BaseDao(object):
def __init__(self):
pass
class HttpBaseDao(BaseDao):
PROXIES = None
def parse_url_data(self, url):
result = urlparse(url)
return {
... |
from django.db import models
from django.db.models.deletion import CASCADE
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class BaseMeaning(models.Model):
global_id = models.CharField(max_length=50)
part_of_speech = models.CharF... |
from .. import paths
MODELS_PATH = paths.ROOT_PATH.joinpath('models')
def imagenet():
path = MODELS_PATH.joinpath('nin_imagenet')
return path
def regnet_tf():
path = MODELS_PATH.joinpath('regnet-tf')
return path
def multimodal():
path = MODELS_PATH.joinpath('multimodal')
return path
|
"""PgQ ticker.
It will also launch maintenance job.
"""
import sys, os, time, threading
import skytools
from maint import MaintenanceJob
__all__ = ['SmallTicker']
class SmallTicker(skytools.DBScript):
"""Ticker that periodically calls pgq.ticker()."""
tick_count = 0
maint_thread = None
def __init_... |
__author__ = 'feurerm'
import copy
import unittest
import numpy as np
import sklearn.datasets
import sklearn.metrics
from autosklearn.pipeline.components.data_preprocessing.balancing.balancing \
import Balancing
from autosklearn.pipeline.classification import SimpleClassificationPipeline
from autosklearn.pipelin... |
import time
from kivy.animation import Animation
from kivy.lang.builder import Builder
from kivy.properties import BooleanProperty, NumericProperty, StringProperty
Builder.load_string(
"""
<AKAnimationBehaviorBase>:
canvas.before:
PushMatrix
Rotate:
angle: root._angle
o... |
from ariadne import MutationType
from .users import resolve_login, get_user, modify_user
from .guilds import get_guild, modify_guild
mutation = MutationType()
mutation.set_field("login", resolve_login)
mutation.set_field("user", get_user)
mutation.set_field("get_guild", get_guild)
mutation.set_field("modify_guild", mo... |
# Copyright 2021 Waseda Geophysics Laboratory
#
# 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... |
# Generated by Django 3.1.14 on 2021-12-17 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log', '0008_workouttype_user'),
]
operations = [
migrations.AlterField(
model_name='workouttype',
name='icon',
... |
# -*- coding:utf-8 -*-
import json
import sys
from atp.utils.remoteBridge import RemoteBridge
from atp.api.comm_log import logger
class Encryption(RemoteBridge):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def map_to_sign(self, params):
if isinstance(params, str):
p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import gensim
import itertools
import os
import shutil
import sys
import yaml
from dnnwsd.pipeline import supervised
def run_pipeline(corpus_dir, results_dir, experiments, configuration):
pipeline = supervised.SupervisedPipeline(
corpus_dir, ... |
import pathlib
import ssl
import os
import datetime
import json
import pywhatkit
import sys
import time
import urllib.request
import twilio
print("Check completed, All required modules are found - you can run : cowin_crawler_wraper.ksh | Windows users : A "
"direct run of cowin_slot_search.py <path> should be do... |
# Use setuptools if we can
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_ballads'
VERSION = '0.3'
setup(
name=PACKAGE, version=VERSION,
description="Django library for coordinating multi-system transactions (eg database, filesystem, remot... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 11:23:22 2020
@author: Admin
"""
import IPython
import matplotlib.pyplot as plt
import numpy as np
import soundfile as sf
from tqdm import tqdm
import pathlib
import os
from wpe import wpe
from wpe import get_power
from utils import stft, istft, get_stft_center_frequ... |
# BlueGraph: unifying Python framework for graph analytics and co-occurrence analysis.
# Copyright 2020-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 a... |
import sys
import random
from itertools import product
import pygame
from pygame.sprite import Sprite, Group
GRID_SIZE = 30
WIN_WIDTH = 1020
WIN_HEIGHT = 620
BG = 0, 0, 0
class Walls():
"""Class to manage the walls."""
def __init__(self, screen):
"""Initialise the game walls"""
self.screen = s... |
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import log_loss
np.random.seed(0)
# Generate data
X, y = make_blobs(n_samples=1000, n_features=2, random_state=42,
... |
# Copyright 2018 Alexandru Catrina
#
# 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, publish, distr... |
# -*- coding: utf-8 -*-
"""Python 2/3 compatibility wrappers.
This module contains imports and functions that help mask Python 2/3
compatibility issues.
"""
import tempfile
# UserDict
try:
# pylint: disable-next=unused-import
from collections import UserDict
except ImportError:
from UserDict import UserD... |
"""
BIBLIOTECA DO BOT IMPERATOR!
lista de todos os comandos:
"""
import os
from random import shuffle, choice
# Lista de interação:
# Lista de comprimentos do usuario/ Bot
user_comp = ["Ola", "ola", "Oi", "oi", "Hey"]
bot_res = ["Olá, como vai? ", "Oi, Tudo bem? ", "Tudo bem? "]
# Resposta do usuario e pergunta;
... |
""" Python script to train HRNet + shiftNet for multi frame super resolution (MFSR) """
import json
import os
import datetime
import numpy as np
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import torch
import torch.optim as optim
import argparse
from torch import nn
from torch.utils.dat... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Intel Corporation, 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.or... |
import collections
import unittest
from typing import List
import utils
from tree import TreeNode
# O(n) time. O(number of groups) space. Hash table.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
group_size_to_people = collections.defaultdict(list)
for perso... |
import pymunk
from enum import Enum
class Game:
types = {"player": 1, "zombie": 2}
MAX_VELOCITY = 100
ACCELERATION = 1
INTERNAL_TICK_TIME = 0.01
EXTERNAL_TICK_TIME = 0.01
MAX_TICKS = 60
def __init__(self, max_players = 8, min_players = 4, width = 1300.0, height = 700.0):
self.star... |
import os
import h5py
import numpy as np
from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain, CMakeDeps
from pathlib import Path
class Hdf5TestConan(ConanFile):
name = "Hdf5PackageTest"
settings = "os", "compiler", "build_type", "arch"
generators = "CMakeDeps"
requi... |
from gym.envs.registration import register
name = 'gym_flp'
register(id='qap-v0',
entry_point='gym_flp.envs:qapEnv')
register(id='fbs-v0', entry_point='gym_flp.envs:fbsEnv')
register(id='ofp-v0', entry_point='gym_flp.envs:ofpEnv')
register(id='sts-v0', entry_point='gym_flp.envs:stsEnv')
|
import pytchat,discord,asyncio,csv,os
from modules import settings
from logging import basicConfig, getLogger
from pytchat import LiveChatAsync
from os.path import join, dirname
basicConfig(level=settings.LOG_LEVEL)
LOG = getLogger(__name__)
bot = discord.Client(intents=discord.Intents.default())
async def main():
... |
# CC0 - free software.
# To the extent possible under law, all copyright and related or neighboring
# rights to this work are waived.
'''
2D, 3D and 4D point classes with various basic operators and operations
defined. Operators accept not only Point objects but any list-like object with
values.
>>> p1 = Point2d(x=4, ... |
# Generated by Django 3.1.7 on 2021-03-20 07:18
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stories', '0003_auto_20210319_1019'),
]
operations = [
migrations.AlterField(
model_name='story',
... |
def sortByHeight(a):
heights = []
tree_trakcer_index = set()
for number in range(0, len(a)):
if a[number] == -1:
tree_trakcer_index.add(number)
else:
heights.append(a[number])
final = []
heights.sort()
for num in... |
import boto3
import json
import os
import subprocess
import sys
import tempfile
FUNCTION_NAME = os.environ['FUNCTION_NAME']
ssm_client = boto3.client('ssm')
def get_ssm_param_name(key_group):
return '/{}/{}'.format(FUNCTION_NAME, key_group)
def install_paramiko(python_dir):
cmd = [
'pip', 'insta... |
from target.telegram import Telegram
|
'''
9-16. Text Processing. You are tired of seeing lines on your e-mail wrap because people type
lines that are too long for your mail reader application. Create a program to scan a
text file for all lines longer than 80 characters. For each of the offending lines, find the
closest word before 80 characters and break t... |
from abc import ABC, abstractmethod
class BrokerProvider(ABC):
@abstractmethod
def declare_queues(self, channel_names):
pass
@abstractmethod
def disconnect(self):
pass
@abstractmethod
def get_next_message(self, queue_name, max_retry=5):
pass
@abstractmethod
... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import Dict, List # noqa: F401
from congress_api import util
from congress_api.models.base_model_ import Model
from congress_api.models.bill_text_content import BillTextContent # noqa: E501
class ... |
# coding=utf-8
# Copyright 2022 The Pix2Seq Authors.
#
# 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... |
from discord.ext import commands
from discord import Member, Embed, Colour
from discord.utils import find
from typing import Optional
from difflib import get_close_matches
class Immagini(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
... |
import argparse
import re
class ParseError(Exception):
pass
def parse_register(rs):
if rs[0] != 'r':
raise ParseError(f'{rs} is not Register')
register_num = int(rs[1:])
if register_num < 0 or 32 <= register_num:
raise ParseError(f'{rs} needs to be more than 0 and less than ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
import seaborn as sns
def get_quick_sample(num_samples):
df = pd.DataFrame(columns=["Y", "D", "X"])
for i in range(num_samples):
x = np.random.normal()
d = (x + np.random.normal()) >... |
from typing import TYPE_CHECKING
from ..validation import Validator
if TYPE_CHECKING:
from ..validation import RuleEnclosure, MessageBag
class ValidatesRequest:
"""Request mixin to add inputs validation to requests."""
def validate(self, *rules: "str|dict|RuleEnclosure") -> "MessageBag":
"""Vali... |
s = pd.Series(
data=np.random.randn(100),
index=pd.date_range('2000-01-01', freq='D', periods=100))
result = {
'2000-02-29': s['2000-02-29'],
'first': s[0],
'last': s[-1],
'middle': s[s.size // 2],
}
|
#!/usr/bin/env python
#
# Test cases for tournament.py
from tournament_extra import *
import os
def clearScreen():
os.system('cls' if os.name == 'nt' else 'clear')
def testDeleteTournaments():
deleteMatches()
print "1. Tournaments can be deleted."
def testDeleteMatches():
deleteMatches()
prin... |
import warnings
import os
import unittest
from test import test_support
# The warnings module isn't easily tested, because it relies on module
# globals to store configuration information. setUp() and tearDown()
# preserve the current settings to avoid bashing them while running tests.
# To capture the warning messa... |
# -*- coding: utf-8 -*-
import pytest
from processing import *
class GildedRose(object):
def __init__(self, items):
self.items = items
def update_quality(self):
for item in self.items:
update_item(item)
def update_item(item):
process_standard(item)
if itemIsConjuredChec... |
from django import forms
from base_app.models import Referral
from auth_app.models import BusinessOwner, Contest
from django.core.validators import RegexValidator
from django.forms import ValidationError
from tempus_dominus.widgets import DateTimePicker
class BusinessRegistrationForm(forms.ModelForm):
class Meta:... |
# 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 ... |
from .node_encoder import *
from .edge_encoder import *
from .graph_encoder import * |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def get_reverse_complement(s):
complements = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C'
}
result = ''.join(reversed([complements[x] for x in s]))
return result
if __name__ == "__main__":
import unittest
class Reve... |
"""Unit test package for player_tech_assignment."""
|
# coding: utf-8
from enum import Enum
from datetime import datetime
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
import pprint
import six
class PlayerLicense(BitmovinResponse):
@poscheck_... |
import datetime
import tzlocal
import pytz
import json
import zlib
class TimezoneAwarenessException(Exception):
pass
class ScalingException(Exception):
pass
MINUTES_IN_A_DAY = 1440
MINUTES_IN_A_WEEK = 7 * MINUTES_IN_A_DAY
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in r... |
from __future__ import absolute_import, division, print_function
from iotbx.cns.crystal_symmetry_utils import crystal_symmetry_as_sg_uc
from cctbx.array_family import flex
from six.moves import range
from six.moves import zip
def crystal_symmetry_as_cns_comments(crystal_symmetry, out):
if ( crystal_symmetry.unit_c... |
import sys
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
import matplotlib.pyplot as plot
from sklearn.svm import SVC
from sklearn.model_selection impo... |
'''
`Op` `Archive` `Ls`
`col2str` `fastlog`
>>> Op.enc(
x:all,
indent=_Default,
ensure_ascii=False,
sort_keys=False,
)->bytes
>>> Op.w(
x:all,
pth:str,
indent:Union=_Default,
ensure_ascii=Fal... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import logging
import os
import util
import tempfile
MODULE_NAME = __name__
MODULE_DESCRIPTION = '''Run analysis of code bui... |
import os
import sys
from string import Template
import flickrapi
import yaml
import micawber
import urllib2
import socket
providers = micawber.bootstrap_basic()
api = yaml.load(open('api.yaml'))
flickr = flickrapi.FlickrAPI(api['key'], api['secret'])
(token, frob) = flickr.get_token_part_one(perms='write')
if not to... |
"""
Copyright 2019 Goldman Sachs.
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... |
#!/usr/bin/env python
# coding: utf-8
import json
import torch
from torch.utils.data import Dataset
from random import choice
class GeometryDataset(Dataset):
"""Geometry dataset."""
def __init__(self, split, diagram_logic_file, text_logic_file, seq_file, tokenizer):
self.tokenizer = tokenizer
... |
"""
.. _extract_edges_example:
Extract Edges
~~~~~~~~~~~~~
Extract edges from a surface.
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
from pyvista import examples
###############################################################################
# From vtk documentation, the edges of a mesh are one o... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt;
train_X = np.linspace(-1, 1, 100);
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.legend()
plt.show()
X = tf.placeholder("float")
Y = tf.placeholder("float")
W = ... |
import abc
class DataCollector(object, metaclass=abc.ABCMeta):
def end_epoch(self, epoch):
pass
def get_diagnostics(self):
return {}
def get_snapshot(self):
return {}
@abc.abstractmethod
def get_epoch_paths(self):
pass
class PathCollector(DataCollector, metacla... |
'''
Created on Sep 20, 2013
@author: nshearer
'''
from datetime import datetime
from ConsoleSimpleQuestion import ConsoleSimpleQuestion
from ConsoleSimpleQuestion import UserAnswerValidationError
class ConsoleDateQuestion(ConsoleSimpleQuestion):
def __init__(self, question):
super(Con... |
#!/usr/bin/env python
import sys
import numpy
import math
from Bio.PDB import *
from Bio import pairwise2
# Allowed nucleotides in a loop
NUCLEOTIDE = set([ 'DA', 'DC', 'DG', 'DT', 'DI' ])
def nucleotide_translate(name):
# Subtitute 8-bromoguanosines for normal DG (see 2E4I)
if name == 'BGM':
return '... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
def main():
#print("誕生日のパラドックスの検証")
#print("文字列変換時に制度が失われるのでパーセント表示は厳密な値ではない")
x = []
y = []
a = _factorial(365)
for i in range(365):
j = i + 1
x.append(j)
b = 365 ** j
... |
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
start=end=0
cnt=[0]*128
count=res=0
while end<len(s):
if cnt[ord(s[end])]==0:
count+=1
cnt[ord(s[end])]+=... |
#Problem Link: https://www.hackerrank.com/challenges/defaultdict-tutorial/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
n,m = map(int,raw_input().split())
A = defaultdict(list)
index =1
for i in range(n):
word = raw_input()
A[word].append(inde... |
# coding: utf-8
""" Convert metadata into the new format """
from io import open
from click import echo, style
from tmt.utils import ConvertError, StructuredFieldError
import fmf.utils
import tmt.utils
import pprint
import yaml
import re
import os
log = fmf.utils.Logging('tmt').logger
# Import nitrate conditionall... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from copyandpay.models import Transaction
import responses, json
from .datas import SUCCESS_PAYMENT, RECURRING_SUCCESS
from .utils import create_scheduled_payment
from ..models import ScheduledPayment
DATA = '''{"id": ... |
import numpy as np
from pflacs import Premise, Calc
def rectangle_area(w, b=None):
"""Calculate the area of a rectange with side lengths «w» and «b».
https://en.wikipedia.org/wiki/Rectangle
"""
if b is None:
b = w
return w * b
def box_volume(h, w=None, b=None, base_area=None):
"""... |
from asyncio.events import AbstractEventLoop
from typing import List, Union
from .base import BaseResource
__all__ = [
'RBEResource',
]
class RBEInstrument(object):
__slots__ = [
'_id',
'_display_name',
'_data',
]
def __init__(self, data: dict) -> None:
self._id = da... |
import csv
from pathlib import Path
from win32com.client import Dispatch
from .images import Images
from ..config import get_analyze
from ..constants import msoOrientationHorizontal
from ..utils import (layouts, layout_to_dict, pt_to_px, is_text, is_image, is_title, check_collision_between_shapes,
... |
from rest_framework import serializers
from news.models import News
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = ['id', 'title', 'context']
|
n=int(input("Enter a no:"))
a=0
b=1
print(a)
sum=a+b
print(sum)
for i in range(n):
c=a+b
a=b
b=c
print(c)
|
# flake8: noqa: F401
from .copy_file import copy_file
from .git_version import git_version
from .local import local
from .remote import remote
from .sync import sync
|
# License: BSD 3-Clause
from collections import OrderedDict
import copy
import unittest
from distutils.version import LooseVersion
import sklearn
from sklearn import ensemble
import pandas as pd
import openml
from openml.testing import TestBase
import openml.extensions.sklearn
class TestFlowFunctions(TestBase):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 13:44:12 2019
@author: avelinojaver
"""
from .unet_base import UNetBase, ConvBlock, UpSimple, init_weights
import torch
import math
import collections
from torch import nn
from torchvision.models._utils import IntermediateLayerGetter
from tor... |
import disnake as discord
from disnake.ext import commands
from api.check import utils, block
from api.server import base, main
import sqlite3
connection = sqlite3.connect('data/db/main/Database.db')
cursor = connection.cursor()
class Dropdown(discord.ui.Select):
def __init__(self, guild):
self.guild = gu... |
# -*- coding: utf-8; -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import re
import sys
import copy
import argparse
import subprocess
from getpass import getpass
from functools import partial
import lxml.etree
import ruamel.yaml as yaml
from jenkins import Jenkins, Jenk... |
def steal(all_loots, comm):
count = int(comm[1])
items_to_steal = all_loots[-count:None]
print(", ".join(items_to_steal))
del all_loots[-count:None]
return all_loots
def drop(all_loots, comm):
index = int(comm[1])
if 0 <= index < len(all_loots):
all_loots.append(all_loots.pop(index... |
import numpy as np
class Householder:
"""
Classe que representa o algoritmo utilizado para fazer transformações de Householder
para reduzir uma matriz simétrica a uma tridiagonal simetrica semelhante.
Args:
A (numpy.ndarray): Array n por n que representa a matriz completa a ser reduzida.
print_ste... |
# Generated by Django 2.2.13 on 2020-12-14 08:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0105_auto_20201211_0758'),
]
operations = [
migrations.AddField(
model_name='country',
... |
# -*- coding: utf-8 -*-
from .processor import NormProcessor, SeqProcessor
from .dataset import NormDataset, SeqDataset
from .tool import split_dataset |
# coding: utf8
from marshmallow import (Schema, fields)
class CreateSuscriberSchema(Schema):
email = fields.String()
new_email = fields.String()
user_id = fields.String()
time_zone = fields.String()
lifetime_value = fields.Integer()
ip_address = fields.String()
custom_fields = fields.Dict... |
# -*- coding: utf-8 -*-
"""
functions for upgrading to the database version 2.
Created on Wed Dec 23 21:33:03 2020
@author: Alon Diament, Tuller Lab
"""
import json
import os
import pickle
import sqlite3
import paraschut as psu
def run(db_path=psu.QFile):
with connect(db_path, exists_OK=Fals... |
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append(u'../ftplugin')
import vim
from orgmode._vim import ORGMODE
from orgmode.py3compat.encode_compatibility import *
counter = 0
class EditStructureTestCase(unittest.TestCase):
def setUp(self):
global counter
counter += 1
vim.CMDHISTORY = []
v... |
#!/usr/bin/env python
from tabulate import tabulate
from sul.remote_integrity.models import Server, Checksum, Event
class Inspector:
def __init__(self, args):
self.args = args
def run(self):
if self.args.list == "servers":
return self._list_servers()
if self.args.list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.