filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_2040
import numpy as np import pandas as pd import xarray as xr import glob from statsrat.expr.schedule import schedule from statsrat.expr.oat import oat from copy import deepcopy class experiment: """ A class used to represent learning experiments. Attributes ---------- resp_type : str The typ...
the-stack_0_2042
# Copyright 2014-2016 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # 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 ...
the-stack_0_2045
"""SAC-Agent implementation""" from typing import Optional, Callable import jax import jax.numpy as jnp import numpy as np import optax from jaxdl.rl.networks.actor_nets import create_normal_dist_policy_fn, sample_actions from jaxdl.rl.networks.critic_nets import create_double_critic_network_fn from jaxdl.rl.networks...
the-stack_0_2046
from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) ...
the-stack_0_2050
#!/usr/bin/env python3.9 # -*- coding: utf-8 -*- # if you're interested in development, my test server is usually # up at https://c.cmyui.xyz. just use the same `-devserver cmyui.xyz` # connection method you would with any other modern server and you # should have no problems connecting. registration is done in-game #...
the-stack_0_2052
# send_notification_email.py """ This routine sends and email alerting the user of missing fields. """ import os import sys where_i_am = os.path.dirname(os.path.realpath(__file__)) sys.path.append(where_i_am) sys.path.append(where_i_am + "/dependencies") import boto3 # noqa: E402 from botocore.errorfactory import Cli...
the-stack_0_2053
import vim import re from os.path import abspath, basename, dirname, relpath from vim_pad.timestamps import timestamp from vim_pad.utils import get_save_dir class PadInfo(object): __slots__ = "id", "summary", "body", "isEmpty", "folder" def __init__(self, source): """ source can be: ...
the-stack_0_2054
import boto3 import json import os class ApiClient(): def __init__(self): apiId = os.environ['WEBSOCKET_API_ID'] region = os.environ['AWS_REGION'] stage = os.environ['STAGE'] url = f'https://{apiId}.execute-api.{region}.amazonaws.com/{stage}' self.client = boto...
the-stack_0_2056
from .._tier0 import execute from .._tier0 import create from .._tier0 import create_none from .._tier0 import plugin_function from .._tier0 import Image @plugin_function(output_creator=create_none) def crop(input : Image, output : Image = None, start_x : int = 0, start_y : int = 0, start_z : int = 0, width : int = 1,...
the-stack_0_2057
#!/usr/bin/env python #pylint: skip-file # This source code is licensed under the Apache license found in the # LICENSE file in the root directory of this project. class ApplicationListResult(object): def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name an...
the-stack_0_2059
import jsonpickle from model.group import Group import random, string import os.path import getopt import sys #n - колво генеруемых данных, опция f задает файл в который это все должно помещаться try: opts, args = getopt.getopt(sys.argv[1:], "n:f", ["numbers of groups", "file"]) except getopt.GetoptError as err: ...
the-stack_0_2060
last_names = [ "Smith", "Johnson", "Williams", "Brown", "Jones", "Miller", "Davis", "Garcia", "Rodriguez", "Wilson", "Martinez", "Anderson", "Taylor", "Thomas", "Hernandez", "Moore", "Martin", "Jackson", "Thompson", "White", "Lopez", "Lee", "Gonzalez", "Harris", "Clark"...
the-stack_0_2061
import os import unittest from smqtk_core.configuration import configuration_test_helper import numpy import pytest from smqtk_classifier import ClassifyDescriptor from smqtk_classifier.impls.classify_descriptor.classify_index_label_descriptor import ClassifyIndexLabelDescriptor from tests import TEST_DATA_DIR cla...
the-stack_0_2064
import json import discord import logging from pantheon import pantheon from util.decorator import only_owner logger = logging.getLogger("Verif") with open("private/rgapikey") as key: panth = pantheon.Pantheon("euw1", key.read(), True) #verified = {"discordId":"summonerId"} NOT_VERIFIED = "Vous n'êtes vérifié.\n...
the-stack_0_2065
import functools from types import FunctionType def log_request_and_response(func): """ Decorator that logs the responses (and the requests they are responses to) returned by any given 'func'. Useful if you want to log all the responses returned to / requests made by an API wrapper. """ @functool...
the-stack_0_2067
import tensorflow as tf from tensorflow.python import debug import constants as const import utils import os import models import exports from time import time, sleep from os import path import random from tensorflow.python.client import timeline import inputs import keras import keras.backend as K import keras.layers...
the-stack_0_2068
"""Helpers that help with state related things.""" import json import logging from collections import defaultdict import homeassistant.util.dt as dt_util from homeassistant.components.media_player import ( ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_SEEK_POSITION, ATTR_MEDIA_VOLUME_LEVEL, ATTR_M...
the-stack_0_2069
from classes.requester import Requester from classes.specializedMatchers import MD5Matcher, StringMatcher, RegexMatcher, HeaderMatcher from collections import Counter class CMSReq(Requester): def __init__(self, host, cache, results): super().__init__(host, cache, results) self.category = "CMS" self.match_class ...
the-stack_0_2070
import _plotly_utils.basevalidators class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name='showticklabels', parent_name='choropleth.colorbar', **kwargs ): super(ShowticklabelsValidator, self).__init__( ...
the-stack_0_2071
# -*- coding:utf-8 -*- # ------------------------ # written by Songjian Chen # 2019-02 # ------------------------ from scipy.ndimage.filters import gaussian_filter import scipy import math import numpy as np #this is borrowed from https://github.com/davideverona/deep-crowd-counting_crowdnet def gaussian_filter_densit...
the-stack_0_2074
import os import sys import random import math import numpy as np import skimage.io import matplotlib import cv2 import matplotlib.pyplot as plt # Root directory of the project ROOT_DIR = os.path.abspath("../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import util...
the-stack_0_2075
import psycopg2 import psycopg2.extras from website_monitor.stats import Stats from website_monitor.url_probe import UrlProbe class Repository: """ The URL probe repository. Implements the repository pattern to hide the database interaction details. """ def __init__(self, connection_string) -> ...
the-stack_0_2076
# Copyright 2019 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 applica...
the-stack_0_2079
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Font(_BaseLayoutHierarchyType): # class properties # -------------------- _parent_path_str = "layout.slider" _path_str = "layout.slider.font" _valid_props = {"color", "family", "size"} ...
the-stack_0_2082
""" User input utilities """ # Author: Ben Gravell def yes_or_no(question): reply = str(input(question+' (y/n): ')).lower().strip() if reply[0] == 'y': return True elif reply[0] == 'n': return False else: return yes_or_no("Invalid input... please enter ")
the-stack_0_2083
from __future__ import print_function import argparse import torch.multiprocessing as mp import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import torch.utils.data.distributed import horovod.torch as hvd # Training settings parser = argparse.A...
the-stack_0_2084
"""A notebook manager that uses the local file system for storage. Authors: * Brian Granger * Zach Sailer """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in...
the-stack_0_2085
import re from bs4 import BeautifulSoup from time import sleep import pickle import praw import OAuth2Util from allpages import getPages from lookup import findItem r = praw.Reddit('bot1') m = re.compile(r"\[\[[^\]]*\]\]") def respond(lim, rate, subs): with open('ids.pickle', 'rb') as handle: ids = pick...
the-stack_0_2087
from abc import abstractmethod import datetime import numpy as np import xarray as xr from pyproj import CRS from RAiDER.logger import * from RAiDER import utilFcns as util from RAiDER.models.model_levels import ( LEVELS_137_HEIGHTS, LEVELS_25_HEIGHTS, A_137_HRES, B_137_HRES, ) from RAiDER.models.wea...
the-stack_0_2088
# Copyright 2018 The TensorFlow Probability 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...
the-stack_0_2089
from rest_framework import serializers from .models import Entry from django.contrib.auth.models import User class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=255, min_length=2) first_name = serializers.CharField(max_length=255, min_length=2) last_name = serializers....
the-stack_0_2090
"""An ellipse widget.""" from typing import Optional from kivy.graphics.vertex_instructions import Ellipse as KivyEllipse from kivy.graphics.context_instructions import Color, Rotate, Scale from kivy.properties import NumericProperty from mpfmc.uix.widget import Widget MYPY = False if MYPY: # pragma: no cover f...
the-stack_0_2093
#!/usr/bin/python # # Copyright (c) 2016 Matt Davis, <mdavis@ansible.com> # Chris Houseknecht, <house@redhat.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANS...
the-stack_0_2094
# -*- coding: utf-8 -*- """Python's built-in :mod:`functools` module builds several useful utilities on top of Python's first-class function support. ``funcutils`` generally stays in the same vein, adding to and correcting Python's standard metaprogramming facilities. """ from __future__ import print_function import s...
the-stack_0_2095
"""imw_28363 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
the-stack_0_2097
def create_thread_by_reacted(posted_title, person): return { "type": "section", "text": { "type": "mrkdwn", "text": "こんばんは!\nあなたの投稿「" + posted_title + " 」に" + person + "さんからリアクションが届きました。", }, }
the-stack_0_2098
# SPDX-License-Identifier: Apache-2.0 from ..common._apply_operation import apply_cast from ..common._registration import register_converter from ..common._topology import Scope, Operator from ..common._container import ModelComponentContainer from .._supported_operators import sklearn_operator_name_map def convert...
the-stack_0_2099
from hypothesis import given from rithm import Int from tests.utils import (IntWithBuiltin, is_equivalent_to_builtin_int) from . import strategies @given(strategies.ints, strategies.ints) def test_alternatives(first: Int, second: Int) -> None: assert first - second == first + (-second) ...
the-stack_0_2100
# Copyright (c) Facebook, Inc. and its affiliates. # Inspired from maskrcnn_benchmark, fairseq import logging import os import pickle import socket import subprocess import warnings import torch from mmf.common.registry import registry from torch import distributed as dist try: import torch_xla.core.xla_model as...
the-stack_0_2101
""" Tests for ndarray-like method on the base Index class """ import pytest import pandas as pd from pandas import Index import pandas._testing as tm class TestReshape: def test_repeat(self): repeats = 2 index = pd.Index([1, 2, 3]) expected = pd.Index([1, 1, 2, 2, 3, 3]) ...
the-stack_0_2102
from datetime import datetime from os import listdir import pandas from application_logging.logger import App_Logger class dataTransformPredict: def __init__(self): self.goodDataPath = "Prediction_Raw_Files_Validated/Good_Raw" self.logger = App_Logger() def replaceMissi...
the-stack_0_2103
from __future__ import unicode_literals from .common import InfoExtractor class DefenseGouvFrIE(InfoExtractor): IE_NAME = "defense.gouv.fr" _VALID_URL = r"https?://.*?\.defense\.gouv\.fr/layout/set/ligthboxvideo/base-de-medias/webtv/(?P<id>[^/?#]*)" _TEST = { "url": "http://www.defense.gouv.fr/l...
the-stack_0_2106
""" Module for jenkinsapi Job """ import json import logging import xml.etree.ElementTree as ET import six.moves.urllib.parse as urlparse from collections import defaultdict from jenkinsapi.build import Build from jenkinsapi.custom_exceptions import ( NoBuildData, NotConfiguredSCM, NotFound, NotInQueue...
the-stack_0_2108
#!/usr/bin/env python # -*- coding: utf-8 -*- # # InteropDataset # Library encapsulating the XML and bin files from MiSeq and HiSeq output. # # InteropMetadata # Parser for XML files from MiSeq / HiSeq run data. # # See README for intro and basic examples. # # March 2013 # by nthmost (naomi.most@invitae.com) # with lot...
the-stack_0_2109
from multiprocessing import Queue import re import threading from typing import Optional, Tuple import zlib from ..candidate import CandidateResult from ..helpers import exception_to_string from ..permuter import ( EvalError, EvalResult, Feedback, FeedbackItem, Finished, Message, NeedMoreWo...
the-stack_0_2110
# TIC TAC TOE Minmax algorithm ''' 1. Backtracking algorithm 2. Max wiil try to maximize it utility 3. Min will try to minimize user or human utility to win 4. Time complexity : O(b^d) b : branching factor (choices, number of possible move) d : depth ''' # Format colour import random bright_cyan = "\033[0;96m" # i...
the-stack_0_2111
from django.apps import AppConfig from django.db.models.signals import post_migrate from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.signals import user_logged_in def add_cart_wish(sender, user, request, **kwargs): from products.models import Cart, WishList if request.session.ex...
the-stack_0_2112
# -*- coding: utf-8 -*- """datasettings.py The user needs to define the required data to be stored on the containers. This container stores all the attributes and settings for the required data. Created on Sat Mar 19 18:30:00 2022 @author: Dan Kotlyar and Bailey Painter Last updated on Tue Apr 01 11:30:00 2022 @auth...
the-stack_0_2113
# -*- coding: utf-8 -*- from sopel import web from sopel.module import commands import re def is_http_url(s): if re.match('(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,300})?',s): return True else: return False @commands('isup') def isup(bot, trigger): site = trigger.group(2) ...
the-stack_0_2115
# Copyright (c) 2020 Sorin Sbarnea <sorin.sbarnea@gmail.com> # # 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, mod...
the-stack_0_2118
#!/usr/bin/env python import logging import warnings import numpy as np from numpy.lib.ufunclike import isposinf from scipy.stats import chi EPS = 1e-8 class MultiVariateNormalDistribution(object): def __init__(self, shift, scale, cov, dim=None): # main components self.shift = shift self...
the-stack_0_2121
# -*- coding: utf-8 -*- # BSD 3-Clause License # # DeepGlint is pleased to support the open source community by making EasyQuant available. # Copyright (C) 2020 DeepGlint. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the followin...
the-stack_0_2123
# -*- coding: utf-8 -*- import six from six.moves import urllib from django import forms from django.contrib.admin.sites import site from django.contrib.admin.widgets import ForeignKeyRawIdWidget try: from django.templatetags import static except ImportError: # compatibility with django < 2.1 from django.co...
the-stack_0_2124
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.autograd import Variable from modules import MGRU torch.manual_seed(1111) # Hyper Parameters sequence_length = 28 input_size = 28 hidden_size = 128 num_layers = 2 num_classes = 10 batch_si...
the-stack_0_2125
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Class for merelcoind node under test""" import contextlib import decimal import errno from enum import...
the-stack_0_2129
# Desenvolva um programa que leia o nome, idade, e sexo de 4 pessoas. # No final do progrma, mostre: # # - A média de idade do grupo # - O nome do homem mais velho # - Quantas mulheres tem menos de 20 anos nome_velho = '' idade_maior = 0 soma = 0 cont_media = 0 cont_feminino = 0 for c in range(1, 5): nome = str(in...
the-stack_0_2131
def data_bars(df, column): n_bins = 100 bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)] ranges = [ ((df[column].max() - df[column].min()) * i) + df[column].min() for i in bounds ] styles = [] for i in range(1, len(bounds)): min_bound = ranges[i - 1] max_b...
the-stack_0_2132
from Color_Console import * import platform import re from logic import * def clear_console(): if is_linux: os.system('clear') else: os.system('cls') def get_move(): move = input().upper() while not re.match("(1|2|3)-(A|B|C)", move): ctext("Please observe format", "red") move = input().upper() return mo...
the-stack_0_2134
#!/usr/bin/python # $Id:$ import ctypes import pyglet lib = ctypes.windll.wintab32 LONG = ctypes.c_long BOOL = ctypes.c_int UINT = ctypes.c_uint WORD = ctypes.c_uint16 DWORD = ctypes.c_uint32 WCHAR = ctypes.c_wchar FIX32 = DWORD WTPKT = DWORD LCNAMELEN = 40 class AXIS(ctypes.Structure): _fields_ = ( ...
the-stack_0_2135
import urllib2 import logging import stormberry.plugin from urllib import urlencode class WundergroundUploader(stormberry.plugin.IRepositoryPlugin): def store_reading(self, data): """Internal. Continuously uploads new sensors values to Weather Underground.""" print('Uploading data to Weather Un...
the-stack_0_2136
# Copyright 2021 Injective Labs # # 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 writin...
the-stack_0_2137
# -*- coding: utf-8 -*- """ blog ~~~~~~~~~~~~~~ blog definition. :copyright: (c) 2016 by fengweimin. :date: 16/8/16 """ from datetime import datetime from bson.objectid import ObjectId from werkzeug.utils import cached_property from app.extensions import mdb from app.models import User from app....
the-stack_0_2138
"""This module contains functionality for all the sampling methods supported in UQpy.""" import sys import copy import numpy as np from scipy.spatial.distance import pdist import scipy.stats as sp import random from UQpy.Distributions import * import warnings def init_sm(data): ###################################...
the-stack_0_2140
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://ge...
the-stack_0_2141
from typing import Dict import pysftp from flask import Blueprint, current_app from paramiko import SSHException from models import Instrument from pkg.case_mover import CaseMover from pkg.google_storage import GoogleStorage from pkg.sftp import SFTP from util.service_logging import log mover = Blueprint("batch", __...
the-stack_0_2142
import numpy as np from typing import Tuple from IMLearn.metalearners.adaboost import AdaBoost from IMLearn.learners.classifiers import DecisionStump from utils import * import plotly.graph_objects as go from plotly.subplots import make_subplots def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.nd...
the-stack_0_2144
# Author: Tan Duc Mai # Email: tan.duc.work@gmail.com # Description: Three different functions to check whether a given number is a prime. # Return True if it is a prime, False otherwise. # Those three functions, from a to c, decreases in efficiency # (takes longe...
the-stack_0_2147
import pandas as pd from colassigner.core import allcols from encoref import CoReferenceLock, EntitySetPair, RelationPair from ..constants import sides from ..data_management import fe_raw_cols as fe_rc from ..data_management import fe_trepos as fe_t2 from ..data_management import pv_raw_cols as pv_rc from ..data_mana...
the-stack_0_2148
from __future__ import print_function from .conv_utils import convert_kernel from .. import backend as K import numpy as np def print_summary(model, line_length=None, positions=None, print_fn=print): """Prints a summary of a model. # Arguments model: Keras model instance. line_length: Total ...
the-stack_0_2149
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # from abc import ABC from typing import Any, Iterable, Mapping, MutableMapping, Optional import pendulum from airbyte_cdk.sources.streams import Stream from google.ads.googleads.v8.services.services.google_ads_service.pagers import SearchPager from .google_...
the-stack_0_2151
"""Markov Decision Processes (Chapter 17) http://aima.cs.berkeley.edu/python/mdp.html First we define an MDP, and the special case of a GridMDP, in which states are laid out in a 2-dimensional grid. We also represent a policy as a dictionary of {state:action} pairs, and a Utility function as a dictionary of {state:nu...
the-stack_0_2154
# Copyright 2021 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...
the-stack_0_2155
import pandas as pd import numpy as np import pickle import json from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.model_selection import ShuffleSplit from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSea...
the-stack_0_2156
# Copyright 2015 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 applica...
the-stack_0_2160
import discord import os from discord.ext import commands, tasks from discord.utils import get from discord.ext.commands import CheckFailure from discord.ext.commands import MissingPermissions import random from alive import alive import json intents = discord.Intents.all() intents.members = True def get_prefix(c...
the-stack_0_2163
"""users table Revision ID: 6c6be1ace116 Revises: Create Date: 2021-08-26 21:28:47.593295 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6c6be1ace116' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto genera...
the-stack_0_2165
from django.core.urlresolvers import reverse from tastypie import authorization from tastypie.authentication import MultiAuthentication from tastypie.exceptions import BadRequest from crits.campaigns.campaign import Campaign from crits.campaigns.handlers import add_campaign from crits.core.api import CRITsApiKeyAuthen...
the-stack_0_2166
# This file contains Att2in2, AdaAtt, AdaAttMO, TopDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Image Captioning ...
the-stack_0_2167
# -*- 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 or...
the-stack_0_2168
# -*- coding: utf-8 -*- import json import os import grpc from rpc.pb import result_pb2 from rpc.pb.result_pb2_grpc import ResultStub CHUNK_SIZE = 10 * 1024 def get_file_chunks(filename, folder_path): yield result_pb2.StreamUploadPictureRequest(filename=filename) with open(f'/usr/src/app/{folder_path}/' + ...
the-stack_0_2169
tab = '' def pow(x, n) : global tab tab += ' ' if n == 0 : return 1 print(tab+"%d*%d^(%d-%d)" % (x, x, n, 1)) return x * pow (x, n-1) print('2^4') print('답 -->', pow(2, 4))
the-stack_0_2170
''' setup.py for ConvLab-2 ''' import sys import os from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class LibTest(TestCommand): def run_tests(self): # import here, cause outside the eggs aren't loaded ret = os.system("pytest --cov=ConvLab-2 test...
the-stack_0_2172
from rest_framework import mixins, status, viewsets from rest_framework import response from rest_framework.response import Response from rest_framework.decorators import action from cride.users.models import Users from cride.circles.models import Circle from cride.circles.serializers import CircleModelSerializer fr...
the-stack_0_2174
from flask import Flask, render_template, url_for, session, request, redirect, flash from flask_pymongo import PyMongo import bcrypt app = Flask(__name__) app.config['MONGO_URI'] = "mongodb+srv://Marco:Password1@ludus-parthenope-u9h85.mongodb.net/Ludus-Parthenope?retryWrites=true&w=majority" mongo = PyMongo(app)...
the-stack_0_2176
# -*- coding: utf-8 -*- """ Manage users with the useradd command .. important:: If you feel that Salt should be using this module to manage users on a minion, and it is using a different module (or gives an error similar to *'user.info' is not available*), see :ref:`here <module-provider-override>`. "...
the-stack_0_2180
import bisect from functools import total_ordering from django.core.management import BaseCommand from classification.enums import SpecialEKeys from classification.models import Classification @total_ordering class ConversionSize: def __init__(self, vc: Classification): self.ref_length = vc.update_cach...
the-stack_0_2188
from time import time import flair import numpy as np import torch from flair.models import SequenceTagger from REL.mention_detection import MentionDetection from REL.training_datasets import TrainingEvaluationDatasets np.random.seed(seed=42) MAX_SIZE_DOCS = 10 base_url = "" wiki_version = "" datasets = TrainingEva...
the-stack_0_2189
# -*- coding: utf-8 -*- """ Exo sur output treetagger """ import argparse class Word: """ Classe Word : définit un mot simple de la langue """ def __init__(self, form, lemma, pos): self.form = form self.lemma = lemma self.pos = pos def __repr__(self): return f"{self.f...
the-stack_0_2190
from datetime import datetime from PIL import Image import numpy as np import matplotlib.pyplot as plt plt.switch_backend('agg') import io from torchvision import transforms as trans from data.data_pipe import de_preprocess import torch from model import l2_norm import pdb import cv2 from face_detection.accuracy_eval...
the-stack_0_2191
from numpy import rad2deg, deg2rad from qcodes import VisaInstrument, validators as vals def parse_on_off(stat): if stat.startswith('0'): stat = 'Off' elif stat.startswith('1'): stat = 'On' return stat def rad2deg_mod(rad): deg = rad2deg(float(rad)) return deg class Keysight_E825...
the-stack_0_2193
#! /usr/bin/env python3 # Script to parse spec output CSVs and produce C files. # Released by lisa neigut under CC0: # https://creativecommons.org/publicdomain/zero/1.0/ # # Reads from stdin, outputs C header or body file. # # Standard message types: # msgtype,<msgname>,<value>[,<option>] # msgdata,<msgname>,<field...
the-stack_0_2195
# 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 # d...
the-stack_0_2196
import sys import os sys.path.append(os.getcwd()) import torch import tokenizers import sklearn from tokenizers import SentencePieceBPETokenizer from tokenizers import SentencePieceUnigramTokenizer from tokenizers import BertWordPieceTokenizer from tokenizers import Tokenizer from tokenizers.models import...
the-stack_0_2198
from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.contrib.auth import authenticate, get_backends from django.contrib.auth.views import login as django_login_page, \ logout_then_login as django_logout_then_login from dja...
the-stack_0_2200
#oiracis import re out = open("out.txt", "w+") c = 0 with open("file.txt", "r+", errors="ignore") as f: #ignore all errors so it reads the file not matter what for line in f: c = c + 1 try: mail = (re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", line)) print("...
the-stack_0_2201
n, k =map(int, input().split()) # 17 4 res = 0 while True: tar = (n//k) * k #n이 k로 나누어 떨어지는 수가 될때까지 빼기 res += (n-tar) n=tar if n<k: #n이 k보다 작을 때 반복문 탈출 (더 이상 나눌수 없을때) break res +=1 n//=k res += (n-1) #마...
the-stack_0_2204
# -*- coding: utf-8 -*- """ py_vollib.black.implied_volatility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A library for option pricing, implied volatility, and greek calculation. py_vollib is based on lets_be_rational, a Python wrapper for LetsBeRational by Peter Jaeckel as described below. :copyright: © 2017 Gammon Capita...
the-stack_0_2205
from exceptionite.errors import Handler, StackOverflowIntegration, SolutionsIntegration from .JsonHandler import JsonHandler class ExceptionHandler: def __init__(self, application, driver_config=None): self.application = application self.drivers = {} self.driver_config = driver_config or ...
the-stack_0_2207
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from functools import partial import numpy as np from numpy.testing import assert_allclose import pytest from jax import random import jax.numpy as jnp from jax.scipy.linalg import cho_factor, cho_solve, inv, solve_triangular import...
the-stack_0_2208
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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 Licens...