id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3355373
import dlib # 人脸识别的库dlib import numpy as np # 数据处理的库numpy import cv2 # 图像处理的库OpenCv # dlib预测器 detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # 读取图像 path = "F:/code/python/P_Dlib_face_cut/pic/" img = cv2.imread(path+"test_faces_6....
StarcoderdataPython
3222046
<filename>bigml/api_handlers/optimlhandler.py # -*- coding: utf-8 -*- # # Copyright 2018-2020 BigML # # 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/LICE...
StarcoderdataPython
1672156
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import random import unittest import numpy import torch import torch.nn.functional as F import nni from nni.compression.pytorch.pruning import ( LevelPruner, L1NormPruner, L2NormPruner, SlimPruner, FPGMPruner, Activation...
StarcoderdataPython
31754
<gh_stars>1-10 import json from pprint import pprint from urllib.request import urlopen import csv class Task: def __init__(self, taskId, duration, gcTime, executorId): self.taskId = int(taskId) self.duration = int(duration) self.gcTime = int(gcTime) self.executorId = int(executorI...
StarcoderdataPython
1613901
<filename>source/pkgsrc/games/unknown-horizons/patches/patch-run__uh.py<gh_stars>1-10 $NetBSD: patch-run__uh.py,v 1.1 2019/08/07 12:07:35 nia Exp $ Add PREFIX to list of search paths. --- run_uh.py.orig 2019-08-07 10:59:56.696840075 +0000 +++ run_uh.py @@ -159,7 +159,7 @@ def get_content_dir_parent_path(): # Unknow...
StarcoderdataPython
3364477
<gh_stars>1-10 class Foo(object): def __getitem__(self, item): return item Foo<warning descr="Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances">[</warning>0]
StarcoderdataPython
3295621
N, M = map(int, input().split()) sc = [list(map(int, input().split())) for _ in range(M)] S = [1] + [0] * (N-1) sc = sorted(sc, key=lambda x: x[0]) def get_unique_list(seq): seen = [] return [x for x in seq if x not in seen and not seen.append(x)] if N != 1 and [1, 0] in sc: print(-1) elif len(list(set(...
StarcoderdataPython
3218769
__version__ = 0.1 import argparse import urllib2 import webbrowser def execute_search(query): query = urllib2.quote("\\{}".format(query)) url = "https://duckduckgo.com/?q={}".format(query) webbrowser.open_new_tab(url) def execute_full_search(query): query = urllib2.quote("{}".format(query)) url...
StarcoderdataPython
3360118
<reponame>isabella232/srtracker # Copyright (C) 2012-2015, Code for America # This is open source software, released under a standard 3-clause # BSD-style license; see the file LICENSE for details. import datetime import requests CACHE_TIMEOUT = datetime.timedelta(seconds=60 * 10) services_list = None last_services_...
StarcoderdataPython
3204769
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re DEPS = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/properties', 'rec...
StarcoderdataPython
106220
from anytree import NodeMixin, iterators, RenderTree import math def Make_Virtual(): return SwcNode(nid=-1) def compute_platform_area(r1, r2, h): return (r1 + r2) * h * math.pi #to test def compute_two_node_area(tn1, tn2, remain_dist): """Returns the surface area formed by two nodes """ r1 = tn1....
StarcoderdataPython
32713
<reponame>BoyanPeychinov/object_oriented_programming class Book: def __init__(self, title, author, location): self.title = title self.author = author self.location = location self.page = 0 def turn_page(self, page): self.page = page
StarcoderdataPython
1716512
<filename>scattering.py from __future__ import division, print_function import numpy as np import bosehubbard # model base import graph # forcedirectedgraph layout import scipy.linalg as linalg import scipy.sparse as sparse # $$\ $$\ $$\ $$\ # $$$\ $$$ | ...
StarcoderdataPython
1720401
<gh_stars>100-1000 import numpy as np import scipy.sparse from scipy.optimize import fmin_l_bfgs_b from scipy.special import expit from sklearn import metrics class BinaryLogisticRegressionTrainer: """ Class to train l2-regularized binary logistic regression. Supports the following: [1] Training [2]...
StarcoderdataPython
111203
<reponame>yuqj1990/deepano_train #!/usr/bin/env python import numpy as np def loadCSVFile(file_name): file_content = np.loadtxt(file_name, dtype=np.str, delimiter=",") return file_content
StarcoderdataPython
3335500
<reponame>ralfgerlich/modypy # pylint: disable=missing-module-docstring import numpy as np from modypy.blocks.discont import saturation from modypy.model import Clock, System, signal_function from modypy.simulation import SimulationResult, Simulator from numpy import testing as npt def test_saturation(): system =...
StarcoderdataPython
3209025
<filename>assets/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import assets.asset_helpers import django.core.files.storage class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.Cr...
StarcoderdataPython
4837717
<reponame>PiRK/silx<filename>silx/gui/data/test/test_textformatter.py # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016-2017 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of t...
StarcoderdataPython
3358247
import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from pmpy.des import * ''' testing preemptive resources this is not working yet ''' def p1(a:entity,R): yield a.get(R,1,False) yiel...
StarcoderdataPython
1699726
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class UsersConfig(AppConfig): name = "apps.users" verbose_name = _("users") def ready(self): import apps.users.signals
StarcoderdataPython
3352803
import nbformat as nbf import glob import shutil import nb2html retrieve_name_from_cell = lambda cell_source: cell_source.replace('#','').strip() def retrieve_name_from_fname(fname): nb = nbf.read(open(fname),nbf.current_nbformat) for cell in nb['cells']: if cell['cell_type'] == 'markdown': ...
StarcoderdataPython
3389320
import requests from bs4 import BeautifulSoup import csv import os import glob import time from datetime import datetime from config import * ##################################################### # Function : get_latest_stats # Description : Gets the latest stats from the specified page and stores ...
StarcoderdataPython
3328028
<reponame>mithrindel/Misc-scripts<gh_stars>0 #!/usr/bin/python import os import time import datetime import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText ###SCRIPT VARIABLE### recordingPath_root = r'\\XXX' averageFileSizeCriteria = 5000 #bytes smtpServer =...
StarcoderdataPython
4810780
""" Collection of Data Scaling Transformers """ from typing import Dict, Iterable, Tuple, Union from ..changemap.changemap import ChangeMap from .running_stats import RunningStats class MinMaxScaler(RunningStats): """ Scalers are also very important to ML frameworks. Many model types, notably neural networks...
StarcoderdataPython
1685086
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json import sure # noqa import moto.server as server from moto import mock_secretsmanager """ Test the different server responses for secretsmanager """ DEFAULT_SECRET_NAME = "test-secret" @mock_secretsmanager def test_get_secret_value(): ...
StarcoderdataPython
3243950
from .. import ast from .base import BaseNodeTransformer class RaiseFromTransformer(BaseNodeTransformer): """Compiles: raise TypeError('Bad') from exc To raise TypeError('Bad') """ target = (2, 7) def visit_Raise(self, node: ast.Raise) -> ast.Raise: if node.cause: ...
StarcoderdataPython
3384445
# -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”...
StarcoderdataPython
3289051
<reponame>WhitePaper233/ShinoBot # -*- coding: utf-8 -*- async def get_weather_of_city(city: str) -> str: return f'{city}的天气是……'
StarcoderdataPython
196607
from queue import Queue import tldextract from time import sleep from requests_html import HTMLSession from concurrent.futures import ThreadPoolExecutor from collections import OrderedDict def spider(urls_q): while True: # check queue if urls_q.empty(): sleep(5) if urls_q.e...
StarcoderdataPython
184631
<filename>python_kivy_app/conex.py import socket class Conexao: def __init__(self, ip, porta): self.ip = ip self.porta =porta self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) dest=((self.ip,self.porta)) self.tcp.connect(dest) def enviar(self,msg): se...
StarcoderdataPython
1654306
from django.apps import AppConfig class ResumeAppConfig(AppConfig): name = 'resume_app'
StarcoderdataPython
1622089
<reponame>amir-esmaeili/IUSTCompiler # Generated from /home/amiresm/Projects/personal/compiler/tac.g4 by ANTLR 4.9.1 from antlr4 import * if __name__ is not None and "." in __name__: from .tacParser import tacParser else: from tacParser import tacParser # This class defines a complete listener for a parse tree...
StarcoderdataPython
68776
from droput_msg.droput_msg import create_app
StarcoderdataPython
109913
<filename>contrail/crawler/s3upload.py import gzip import json import logging import shutil import urllib.request import boto3 from contrail.configuration import config logger = logging.getLogger('contrail.crawler') class S3Client: _session = boto3.Session( aws_access_key_id=config['AWS']['access_key_i...
StarcoderdataPython
1776333
<gh_stars>0 import os WTF_CSRF_ENABLED = True SECRET_KEY = os.environ.get("PEPY_SECRET_KEY") DATABASE = { "host": os.environ.get("PEPY_DATABASE_HOST"), "user": os.environ.get("PEPY_DATABASE_USER"), "password": <PASSWORD>("PEPY_DATABASE_PASSWORD"), "database": os.environ.get("PEPY_DATABASE_NAME"), } D...
StarcoderdataPython
75248
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: push_message.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from...
StarcoderdataPython
4838153
# -*- coding: utf-8 -*- import mock import flask import pytest import webtest import sqlalchemy as sa from flask_sqlalchemy import SQLAlchemy from nplusone.core import exceptions from nplusone.ext.flask_sqlalchemy import NPlusOne from nplusone.ext.flask_sqlalchemy import setup_state from tests import utils @pytest...
StarcoderdataPython
3202045
<reponame>antho214/RayTracing from .specialtylenses import * class PN_33_921(AchromatDoubletLens): def __init__(self): # PN for Part number super(PN_33_921,self).__init__(fa=100.00,fb=78.32, R1=64.67,R2=-64.67, R3=-343.59, tc1=26.00, tc2=12.7, te=24.66, n1=1.670...
StarcoderdataPython
3311439
import torch torch.multiprocessing.set_sharing_strategy('file_system') import logging # noqa from torch_geometric.data import InMemoryDataset # noqa import time # noqa from time import time as now # noqa import multiprocessing # noqa import numpy as np # noqa from .hemibrain_dataset_random import HemibrainDatas...
StarcoderdataPython
3294002
<reponame>reshng10/Pro import unittest from soz_analizi.sekilci import isim_animals class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, False) def testMethod(self): if (isim_animals.animals.__contains__('Adadovşanı')): result=True expected=True...
StarcoderdataPython
4817166
"""Connections module.""" import pickle import zmq from .base import ConnectionManager class TCPConnectionManager(ConnectionManager): """ Manages pool-worker TCP communication. """ def __init__(self, cfg): """TODO.""" self._context = zmq.Context() self._sock = self._context...
StarcoderdataPython
1717159
# -*- coding: utf-8 -*- """ Created on 2019-11-26 16:26 @author: a002028 """ import os import sys package_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(package_path) name = "algaware" from algaware import core from algaware import plot from algaware import readers
StarcoderdataPython
107648
import json from datetime import datetime from discord.ext import commands from .util import send_embed_message from MongoDB.Connector import Connector import pathlib path = pathlib.Path(__file__).parent.absolute() class Corona(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(p...
StarcoderdataPython
102937
<reponame>intgr/django-cms try: from django.utils.encoding import force_unicode def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base,...
StarcoderdataPython
1673450
<gh_stars>100-1000 # Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #!/usr/bin/env python3 import glob import os from glob import glob SCRIPT_NAME = os.path.basename(__file__) PYRO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) library_files = set() os.chdir(f"{PYRO_...
StarcoderdataPython
3284493
<filename>match/migrations/0004_systemmessage.py # -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-18 07:52 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Mi...
StarcoderdataPython
51846
''' The cost of a stock on each day is given in an array. Find the max profit that you can make by buying and selling in those days. Only 1 stock can be held at a time. For example: Array = {100, 180, 260, 310, 40, 535, 695} The maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sel...
StarcoderdataPython
3385569
#main script to run for each analysis import csv with open(r"C:\Users\User\Desktop\python_challenge\Pybank\Budget_Data.csv") as csvfile: reader = csv.DictReader(csvfile) DatesConsidered = [] Profit_Loss = [] Change_data=[] previous_amount=0 total=0 #next(reader) for row in reader: # print(row['Date...
StarcoderdataPython
1613938
<gh_stars>0 ''' Created on Nov 4, 2017 @author: kiniap ''' import csv import cv2 import numpy as np import random import sklearn from sklearn.utils import shuffle from sklearn.model_selection import train_test_split import matplotlib import matplotlib.pyplot as plt lines = [] ''' Read the various file obtained from...
StarcoderdataPython
1629418
<gh_stars>0 import numpy as np from mpi4py import MPI from SIMP import TO_SIMP, make_Conn_matrix from PIL import Image def get_void(nely,nelx): v=np.zeros((nely,nelx)) R=min(nely,nelx)/15 loc=np.array([[1/3, 1/4], [2/3, 1/4],[ 1/3, 1/2], [2/3, 1/2], [1/3 , 3/4], [2/3, 3/4]]) loc=loc*np.array([[nely,ne...
StarcoderdataPython
4208
# Copyright 2013 Cloudbase Solutions Srl # # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # 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/LICENS...
StarcoderdataPython
3302160
""" Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ import unittest import s1ap...
StarcoderdataPython
1674506
<filename>tests/infura/test_celery.py from tests.common_tests.celery import ( push_block_range_multiple_thread, ) def test_infura_push_block_range_multiple_threads(infura_celery_worker, infura_settings): push_block_range_multiple_thread()
StarcoderdataPython
2174
<gh_stars>0 from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import pytest from flexget.entry import Entry # TODO Add more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config = """ templat...
StarcoderdataPython
3240237
<gh_stars>0 """Handle the console interface for the ClassifierNetwork package. This package, while intended to be used with the ModularMailer project, can be installed and used a standalone application, which this module handles the interface for. The intent of of this design is so that this package can be installed b...
StarcoderdataPython
3213642
"""Just a prototype for REST-ful.""" from .apis import Resource class Ping(Resource): """You pong when you are pinged...""" def get(self): return {'returned': 'pong'}
StarcoderdataPython
3258585
<reponame>decentfox/gapp-login<gh_stars>1-10 from authlib_gino.fastapi_session.gino_app import load_entry_point from authlib_gino.fastapi_session.models import Identity from gino import Gino db = load_entry_point("db", Gino) class WeChatIdentity(Identity): wechat_unionid = db.StringProperty() wechat_session_...
StarcoderdataPython
1717863
#!/usr/bin/env python """ Asset types S3 Group class Copyright 2020-2021 Leboncoin Licensed under the Apache License, Version 2.0 Written by <NAME> (<EMAIL>) """ # Standard library imports import logging from .asset_type import AssetType # Debug # from pdb import set_trace as st LOGGER = logging.getLogger('aws-tow...
StarcoderdataPython
1688827
<reponame>medewitt/pantab __version__ = "1.1.1" from ._reader import frame_from_hyper, frames_from_hyper from ._tester import test from ._writer import frame_to_hyper, frames_to_hyper __all__ = [ "__version__", "frame_from_hyper", "frames_from_hyper", "frame_to_hyper", "frames_to_hyper", "tes...
StarcoderdataPython
3241233
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. import os import posixpath from functools import singledispatch from pyiron_atomistics import Atoms from pyiron_atomist...
StarcoderdataPython
3225359
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if len(s) <= 1: return len(s) longest = 0 left = 0 seen = {} for right in range(len(s)): if s[right] in seen: ...
StarcoderdataPython
3323632
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui', # licensing of 'main.ui' applies. # # Created: Fri Jul 17 14:35:18 2020 # by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidg...
StarcoderdataPython
133865
<gh_stars>10-100 # -*- coding: utf-8 -*- # File generated according to Generator/ClassesRef/Output/OutLoss.csv # WARNING! All changes made in this file will be lost! """Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Output/OutLoss """ from os import linesep from sys impo...
StarcoderdataPython
3208125
from tornado.log import app_log class ValidationArgs(object): """ Arguments from the validation framework used by validators """ def __init__(self, idl, schema, table_name, row, p_table_name, p_row, is_new): # General arguments self.idl = idl self.schema = sche...
StarcoderdataPython
144042
import pytest from barista.models import Match def test_both_trigger_and_triggers(): with pytest.raises(ValueError): Match.parse_obj( { "replace": "asd", "trigger": "asd", "triggers": ["asd", "abc"], } ) def test_neither_tr...
StarcoderdataPython
40574
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange from ccxt.base.errors import ExchangeError from ccxt.base.errors import BadRequest from ccxt.base.e...
StarcoderdataPython
114647
'''interface with serlib.cparser module We'll use platform defined C-types int (np.intc) and long long int (np.ulonglong) for maximal portability because python C-api does not support fixed width C types: https://docs.python.org/3/c-api/long.html For numpy reference see https://numpy.org/devdocs/user/basics.types.html...
StarcoderdataPython
1686404
<reponame>Stunnerr/vkwave import typing import pydantic from enum import Enum class MessagesSendPeerIdsData(pydantic.BaseModel): peer_id: int = pydantic.Field( ..., description="", )
StarcoderdataPython
1663905
"""Unit test package for instrumentdatabaseapi."""
StarcoderdataPython
60906
def grade(x): if 101>x>=90: return 'Your Grade is A' elif 89>=x>=80: return 'Your Grade is B' elif 79>=x>=70: return 'Your Grade is C' elif 69>=x>=60: return 'Your Grade is D' return 'not a correct value' y = ['Score and Grade'] for i in range (0,10): a = input('Enter a score between 60 and 100. ->') x ...
StarcoderdataPython
90463
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import pytest from pandas_mate.tests import create_test_df from pandas_mate import util data_file_path = os.path.join(os.path.dirname(__file__), "data.csv") def setup_module(module): if not os.path.exists(data_file_path): df = create...
StarcoderdataPython
3281909
<reponame>zhengxiaowai/sshm<filename>sshr/cli.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import readline import click import json from six.moves import input as raw_input from collections import defaultdict from clients import get_client, init_client, get_supported_platform from utils import prompt_lin...
StarcoderdataPython
3225295
<filename>Project2/test_main.py import random from unittest import TestCase import datetime import matplotlib.pyplot as plt import numpy as np from main import gaussian_elimination, compute_tomograph class Test(TestCase): def test_gaussian_elimination(self): size = random.randint(0, 100) A = np.r...
StarcoderdataPython
50735
""" Builds wheel files for the dependencies of an app, specified in requirements.txt, into the wheels/ folder of the app repo, and updates the app's JSON config specifying any generated wheels as pip dependencies. NOTE: If running this script with the --repair_wheels flag, make sure the script is executed from a manyl...
StarcoderdataPython
1673104
#MousePressed def setup(): size(240, 120) strokeWeight(30) def draw(): background(204) stroke(102) line(40, 0, 70, height) if mousePressed: if mouseButton == LEFT:# Pinta a linha branca se o botão esquerdo for pressionado stroke(255) else: stroke(0)...
StarcoderdataPython
4808651
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : element_tree_xml_parser @Author : 周恒-z50003220 @Email : <EMAIL> @Create : 2019/8/12-10:21 @Python :Python 3.7.3 @IDE : PyCharm @Version : 0.0.1 @Change_log 2019/8/12-10:21 created """ import re from collections.abc import Iterable from xml.e...
StarcoderdataPython
194106
<filename>src/OpenSSL/__init__.py # Copyright (C) <NAME> # See LICENSE for details. """ pyOpenSSL - A simple wrapper around the OpenSSL library """ from OpenSSL import SSL, crypto from OpenSSL.version import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri...
StarcoderdataPython
25992
<gh_stars>0 # Copyright (C) 2015 Hewlett-Packard Development Company, L.P. # # 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 requi...
StarcoderdataPython
1798533
import torch import torch.utils.data as Data SCR_LEN = 5 # encoder输入的最大长度 TGT_LEN = 6 # decoder输入的最大长度 def create_data(): # S: decoder输入开始的标志 # E: decoder输出开始的标志 # P: padding用于填充句子 # [encoder_input, decoder_input, decoder_output] sentences = [['ich mochte ein bier P', 'S i want a ...
StarcoderdataPython
1630497
# Necessary imports. Provides library functions to ease writing tests. from lib import prebuild, testcase, SUBMITTY_TUTORIAL_DIR import subprocess import os import glob import shutil ############################################################################ # COPY THE ASSIGNMENT FROM THE SAMPLE ASSIGNMENTS DIRECTO...
StarcoderdataPython
12044
#!/usr/bin/env python3 # Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved. import argparse import os import pickle import shutil import numpy as np import PIL.Image import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector TB_DIR = os.path.join(os.getcwd(), "gan-tb") SPRITE_IMA...
StarcoderdataPython
112047
def print_line(): print("-" * 60) def print_full_header(build_step_name): print_line() print(" Build Step /// {}".format(build_step_name)) def print_footer(): print_line() def log(level, data): print("{0}: {1}".format(level, data))
StarcoderdataPython
3308317
# Importar librerías import numpy as np from matplotlib import pyplot as plt # Definir e incluir nuevas funciones al cuaderno def _buscar_intervalos(fun, ini, fin): """ Método para buscar intervalos en los que ocurra cambio de signo. ## Parámetros: fun (function): función para analizar. ...
StarcoderdataPython
3380361
<reponame>FerdinandKlingenberg/TestAvSentinel-2Python # -*- coding: utf-8 -*- import rasterio import cv2 #import numpy as np outfile = r'C:\Users\Ferdinand\Documents\imageEnhance_to24bit\Resultater\rasterio\GDAL_Composite8bitWithOpenCV.tif' #url to the bands b4 = r'C:\Users\Ferdinand\Documents\imageEnhance_...
StarcoderdataPython
3342263
import boto3 def describe_default_vpc(client): response = client.describe_vpcs( Filters=[ { 'Name': 'isDefault', 'Values': [ 'true', ] } ], ) return response.get('Vpcs', [{}])[0].get('VpcId', '')
StarcoderdataPython
105795
import json import os from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.http import HttpResponse, JsonResponse from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from .models import ( MediaFile, ImagePrediction, AudioPrediction, Vi...
StarcoderdataPython
1694582
# MIT License # # Copyright (c) 2020 Gcom # # 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...
StarcoderdataPython
45759
import copy import logging from datetime import datetime, timedelta from collections import namedtuple from blinker import Signal __all__ = [ 'Event', 'TrainingMachineObserver', 'TrainingMachine', ] logger = logging.getLogger(__name__) class Event(dict): """ Events that are expected by the process...
StarcoderdataPython
1654484
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version....
StarcoderdataPython
115802
import cv2 import numpy as np import chili_tag_detector as ctd import sys import time from behaviours.box_detection.utils import calculate_angle_and_distance #from utils import calculate_angle_and_distance #1227^2 + 136^2 = sqrt(1524025) = 1309.83 1234.51 #900^2 +136^2 = sqrt(828496) = 910.21 1004.99 #600^2 + 136^2 =...
StarcoderdataPython
4813862
import numpy as np import numpy.linalg as LA import matplotlib.pyplot as plt import torch import torch.nn as nn from tqdm import tqdm, trange from torch.utils.data import TensorDataset from plotly.subplots import make_subplots import plotly.graph_objects as go def visualize3D(vis_net, x, y, dir1, dir2, dir3, len1 = 1,...
StarcoderdataPython
121909
<gh_stars>10-100 from __future__ import annotations import asyncio import random from functools import cached_property from typing import Iterator, Literal, Optional, Union, overload import discord from discord.ext import commands from discord.utils import MISSING from ditto import BotBase, Cog, Context from ditto.ty...
StarcoderdataPython
3374930
# @Title: 二叉树的镜像 (二叉树的镜像 LCOF) # @Author: 18015528893 # @Date: 2021-01-20 21:00:02 # @Runtime: 56 ms # @Memory: 14.8 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def mirrorTree...
StarcoderdataPython
98913
import re import datetime import pytz import badgebakery import os import base64 import requests import gridfs from requests.auth import HTTPBasicAuth import json from bson.objectid import ObjectId from flask_login import UserMixin from pymongo import MongoClient from flask import jsonify, current_app from werkzeug.sec...
StarcoderdataPython
3275886
""" Plot results of the criterion Author : <NAME> Date : 11/10/2016 """ import os import pandas as pd import matplotlib.pyplot as plt import cPickle as pickle import numpy from itertools import cycle from sklearn.metrics import auc, average_precision_score,precision_recall_curve import seaborn as sns from matplotlib im...
StarcoderdataPython
3208969
import logging import joblib import scipy.sparse as sparce import numpy as np def save_matrix(df,matrix,out_path): id_matrix = sparce.csr_matrix(df.id.astype(np.int64)).T label_matrix = sparce.csr_matrix(df.label.astype(np.int64)).T result = sparce.hstack([id_matrix,label_matrix,matrix],format="csr") ...
StarcoderdataPython
1710354
# Aplicação em Python para detectar se uma pessoa tem diabetes ou não, usando Machine Learning! #Importando os pacotes Python import pandas as pd from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from PIL import Image imp...
StarcoderdataPython
192852
from .middleware import TestMasterMiddleware name = 'scrapy-testmaster'
StarcoderdataPython
1648936
import json from typing import Union from .validator import ( CollectionErrors, NoneValueException, Validator, ValidationError, StopValidation ) class Array(Validator): def __init__(self, message: Union[str, None] = None, parse: bool = True, ...
StarcoderdataPython
3272449
<filename>RushHourPy/library_of_states.py # Cards in original puzzle # Supplemental Cards #1 #2 #3 #4 ... ######### Various States ######### #########
StarcoderdataPython