id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
12858248
# _*_ coding: utf-8 _*_ class IgnoreRequest(Exception): pass
StarcoderdataPython
238563
from typing import * from time import perf_counter_ns ''' def Timer(n: int = 1): return [_Timer() for i in range(n)] class _Timer: def __init__(self): self.times: list[float] = [] def __enter__(self): self.start = perf_counter_ns() def __exit__(self, exc_type, exc_value, exc_traceback): self.end ...
StarcoderdataPython
3331807
<reponame>EchizenG/MAD-GAN_synthetic<filename>datasets/data_synthetic_bak_1D.py from common import scatter import matplotlib.pyplot as plt import random import numpy as np from attrdict import AttrDict import tensorflow.contrib.learn as tf_learn import pandas as pd from scipy import stats, integrate import seaborn as s...
StarcoderdataPython
27962
<gh_stars>0 import argparse from sklearn import decomposition from sklearn.manifold import TSNE from scripts.utils.utils import init_logger, save_npz from scripts.utils.documents import load_document_topics logger = init_logger() def main(): parser = argparse.ArgumentParser(description='maps a given high-dimensi...
StarcoderdataPython
112832
<filename>bin/04_transition_list.py<gh_stars>1-10 #!/bin/python # # TRANSITION LIST # =============== # # This executable produces the building transition list, mapping the # arrival and departure time of each user from each building. # # Arrival and departure times stands for the first session start and last # session...
StarcoderdataPython
9744982
<reponame>jcolekaplan/computer_vision<gh_stars>0 """ <NAME> keypoint_detection.py Check how consistent the results of Harris keypoint detection and SIFT keypoint detection with each other are. _/`.-'`. _ _/` . _.' ..:::::.(_) /` _.'_./ ...
StarcoderdataPython
1696776
<gh_stars>100-1000 from __future__ import annotations from psycopg2._psycopg import Column from local_data_api.models import Field from local_data_api.resources import PostgresSQL from tests.test_resource.test_resource import helper_default_test_field def test_create_connection_maker(mocker): mock_connect = moc...
StarcoderdataPython
3486188
# -*- coding: utf-8 -*- # File generated according to Generator/ClassesRef/Simulation/DriveWave.csv # WARNING! All changes made in this file will be lost! """Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/DriveWave """ from os import linesep from logging import getLo...
StarcoderdataPython
6529593
<gh_stars>0 from db import db from models.enums import RoleType class CreatorModel(db.Model): """Creator Model""" __tablename__ = "creators" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), nullable=False, unique=True) password = db.Column(db.String(255), nullable=Fa...
StarcoderdataPython
1663032
<reponame>markovmodel/pyemma_tutorials<gh_stars>10-100 import os import versioneer from setuptools import setup def copy_notebooks(): import shutil dest = os.path.join('pyemma_tutorials', 'notebooks') try: shutil.rmtree(dest, ignore_errors=True) shutil.copytree('notebooks', dest) ...
StarcoderdataPython
9653593
<reponame>luna-ml/leaderboard<filename>cartpole-v1/models/dqn-ritakurban/agent.py import pathlib import keras import numpy as np class Agent(): def __init__(self, **kwargs): self.model = self.load_model(f"""{kwargs.get("path")}/pretrained""") def load_model(self, path): """Load pretrained mode...
StarcoderdataPython
4904139
from src.pgassets import pgTextPanel class pgButton(pgTextPanel): def __init__(self, pos: tuple, size: tuple, text="", color=(255, 255, 255), borderwidth=2, transparent=False, fontsize=20): pgTextPanel.__init__(self, pos, size, text, color, borderwidth, transparent, fontsize=fontsize)
StarcoderdataPython
1661086
<filename>src/Sixth Chapter/Exercise12.py # Write a function is_factor(f, n) that passes the tests below. import sys def is_factor(f, n): return n % f == 0 def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: ...
StarcoderdataPython
4897108
<filename>src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spinn_front_end_common/utilities/reload/reload_buffered_vertex.py<gh_stars>1-10 # front end common imports from spinn_front_end_common.interface.buffer_management.buffer_models.\ sends_buffers_from_host_pre_buffered_impl import \ SendsBuffersFrom...
StarcoderdataPython
6454923
<reponame>ssinad/gcp """ Create a version of processed data used in our notebooks. Instead of selecting individual county and then make chart, we'll clean all counties at once, then subset. Save it to `data` to use for our RMarkdown repo: https://github.com/CityOfLosAngeles/covid19-rmarkdown """ import numpy as np im...
StarcoderdataPython
5116456
<filename>python-code/tiny-app/headpose-detection/videoCapture.py import numpy as np import cv2 import argparse import os.path as osp from hpd import HPD def main(args): filename = args["input_file"] if filename is None: isVideo = False cap = cv2.VideoCapture(0) cap.set(3, 640) ...
StarcoderdataPython
3451402
def get_numbers(src: list): for num in range(len(src) - 1): if src[num] < src[num + 1]: yield src[num + 1] pass src = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] print(*get_numbers(src))
StarcoderdataPython
5159159
import graphene class Query(graphene.ObjectType): hello = graphene.String(name=graphene.String(default_value="stranger")) def resolve_hello(self, info, name): return 'Hello ' + name schema = graphene.Schema(query=Query) result = schema.execute('{ hello ( name: "Test" )}') print(result.data['hello'...
StarcoderdataPython
1642268
<gh_stars>0 # coding: UTF-8 from __future__ import absolute_import import unittest from usig_normalizador_amba.NormalizadorDireccionesAMBA import NormalizadorDireccionesAMBA from usig_normalizador_amba.Direccion import Direccion from usig_normalizador_amba.Errors import ErrorCruceInexistente, ErrorCalleInexistente fro...
StarcoderdataPython
8122793
<filename>examples/nist_sre/helpers.py<gh_stars>1-10 from __future__ import absolute_import, division, print_function import os import pickle import shutil import warnings from collections import OrderedDict, defaultdict from enum import Enum from numbers import Number import numba as nb import numpy as np from scipy...
StarcoderdataPython
3452949
<filename>scripts/hooks/protect_branches.py import re import sys from subprocess import run from typing import NoReturn def ProtectBranches() -> NoReturn: hookid = "protect-branches" protected_branches = [r"main", r"branch-\d+\.\d+"] current_branch = run(["git", "branch", "--show-current"], capture_output...
StarcoderdataPython
1832305
__author__ = "<NAME>" # QProgressBar progressbar_style = ''' QProgressBar { border: 0px; border-top-left-radius: 4px; border-bottom-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; height: 8px; min-height: 8px; max-height: 8px; margin-top: 7px; m...
StarcoderdataPython
9723271
from __future__ import division, absolute_import from __future__ import print_function, unicode_literals import xgboost as xgb import numpy as np import pandas as pd from os import listdir from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.metrics import f1_score def aggregate_features(X): r...
StarcoderdataPython
6635600
from pyplayground.server.pyenki import EPuck from pyplayground.server.RobotBase import RobotBase class RobotEPuck( RobotBase, EPuck ): """ Clase para interactuar con los robots del tipo EPuck de pyenki """ tipo = "epuck" def __init__( self, name ): """ Constructor para robots del ...
StarcoderdataPython
1770982
<gh_stars>1-10 from hiclib.hicShared import byChrEig from mirnylib.genome import Genome import matplotlib.pyplot as plt from mirnylib.systemutils import setExceptionHook from mirnylib.plotting import nicePlot, maximumContrastList setExceptionHook() gen = Genome('../../../../hg19', readChrms=["#","X"]) mychroms = [0,2...
StarcoderdataPython
11391127
import numpy def add(a, b): """Calculates the sum of a and b. :param a: The first operand of the sum. :param b: The second operand of the sum. """ return a + b def subtract(a, b): """Calculates the subtraction of b from a. :param a: The first operand of the subtraction. :param b: The...
StarcoderdataPython
162820
from lml.registry import PluginInfoChain __test_plugins__ = PluginInfoChain(__name__).add_a_plugin("test_io2", "reader")
StarcoderdataPython
9600709
class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): l = "" head = self while head is not None: l += str(head.val) head = head.next return l class Solution: def addTwoNumbers(self, l1, l2): ...
StarcoderdataPython
8050913
<reponame>RealityBending/Pyllusion<filename>pyllusion/Delboeuf/delboeuf_parameters.py import numpy as np def _delboeuf_parameters( illusion_strength=0, difference=0, size_min=0.25, distance=1, distance_auto=False ): # Size inner circles parameters = _delboeuf_parameters_sizeinner( difference=diff...
StarcoderdataPython
4896440
import pytest from click.testing import CliRunner from pagefunc import * from cli import main @pytest.fixture def runner(): return CliRunner() def test_cli(runner): result = runner.invoke(main) assert result.exit_code == 0 assert not result.exception assert result.output.strip() == 'Hello, world....
StarcoderdataPython
9701554
<reponame>kjdavidson/NoisePy import pyasdf import numpy as np import time ''' this script compares the speed of reading ASDF files with different size the ultimate goal is to find the best way to read a chunck of data stored in the xxx ''' def read_data(sfile,nseg,data_type,path): with pyasdf.ASDFDataSet(sfile,m...
StarcoderdataPython
9790318
# Copyright (C) 2015-2020 ycmd contributors # # This file is part of ycmd. # # ycmd 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
4936907
from datetime import datetime import json import pg8000 import re from config import CONFIG_DICT from service import db_access INSERT_TITLE_QUERY_FORMAT = ( 'insert into title_register_data(' 'title_number, register_data, geometry_data, is_deleted, last_modified, official_copy_data, lr_uprns' ')' 'valu...
StarcoderdataPython
6653272
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt import sys import argparse import os import subprocess import builtins import webbrowser from . import VizTracer from . import FlameGraph from .report_builde...
StarcoderdataPython
8044747
from enum import Enum class CommandType(Enum): ROTATE = 1 MOVE = 2
StarcoderdataPython
1792813
from urllib.parse import urljoin from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from ...text import create_slug from ..magic import MisencodedCharField, MisencodedTextField ...
StarcoderdataPython
4951863
import os import psico.seqalign DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') FILENAME_FATCAT = os.path.join(DATA_DIR, '1ubqA-1hezE.fatcat') def test_needle_alignment(): A = psico.seqalign.needle_alignment("ACDEFGHIKLMN", "DEYGHVVVVIKLMN") assert str(A[0].seq) == "ACDEFGH----IKLMN" assert st...
StarcoderdataPython
3474691
#!/usr/bin/env python ''' Simple script to call conda build with the current revision and version. ''' import argparse import subprocess import json from re import match import os NAME = 'python-clingox' def get_build_number(channels, version): ''' Get the next build number. ''' try: pkgs = j...
StarcoderdataPython
8051545
import logging import sys from datetime import datetime from constants import TMP_DICT class LogAdapter(object): def getlogger(self, module_name): logger = logging.getLogger(module_name) # TODO: This need to be from config logger.setLevel(TMP_DICT['log_level']) handler = logging...
StarcoderdataPython
11248377
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from RecoMuon.MuonIsolation.muonPFIsolationValues_cff import * muPFIsoValueCharged03PFBRECO = muPFIsoValueCharged03.clone( deposits = {0: dict(src = 'muPFIsoDepositChargedPFBRECO')} ) muPFMeanDRIsoValueCharged03PFBRECO = muPFMea...
StarcoderdataPython
3422089
<reponame>XinghuiTao/ros2_turtlebot<filename>src/omniverse/omniverse/action_server.py import rclpy from rclpy.action import ActionClient from rclpy.node import Node from interfaces.action import Move class MyActionClient(Node): def __init__(self): super().__init__('my_action_client') self._action...
StarcoderdataPython
1603725
""" implement the qmix algorithm with tensorflow, also thanks to the pymarl repo. """ from functools import partial from time import time import numpy as np import tensorflow as tf from absl import logging from smac.env import MultiAgentEnv, StarCraft2Env from xt.algorithm.qmix.episode_buffer_np import EpisodeBatchNP...
StarcoderdataPython
3454218
import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.python.ops.linalg.sparse import sparse as tfsp from . import modes as modes from . import ops as ops def dot(a, b, transpose_a=False, transpose_b=False): """ Dot product between `a` and `b`, with automatic handling of batch dim...
StarcoderdataPython
6691822
from functools import reduce from operator import mul def persistence(n): return 0 if (n < 10) else (1 + persistence(reduce(mul, [int(d) for d in str(n)])))
StarcoderdataPython
3407424
# WiSe 17/18 from typing import List, Tuple import lecture_classes as lc # Leider braucht es für eine Erkennung der Namen mit pyflakes diesen # syntaktischen Käse, ansonsten tut der Code auch mit einem einfachen # from lecture_classes import * Lecture = lc.Lecture T = lc.T morgen = lc.morgen vormittag = lc.vormittag m...
StarcoderdataPython
1728777
<reponame>globusgenomics/galaxy class allele_walker: ''' Given a set of site concordant records, call consensus on variants with matching alleles. ''' def __init__(self, recordSet): self.recordSet = recordSet
StarcoderdataPython
1860173
<filename>core/controllers/filter_controller_var2.py from numpy import dot, maximum from numpy.linalg import solve from numpy import sign from scipy.linalg import sqrtm import cvxpy as cp import numpy as np import scipy from cvxpy.error import SolverError from .controller import Controller class FilterControllerVar2(C...
StarcoderdataPython
3345307
import requests import json class ForloopClient: def __init__(self, key=None, secret=None, url=None): self.key = key self.secret = secret #self.session = requests.Session() if url: self.url = url else: self.url = "https://www.forloop.ai" d...
StarcoderdataPython
5040893
<reponame>siddhantdixit/OOP-ClassWork p = None # print(id(p)) class Student: def __init__(self): self.name = "Siddhant" # print(id(self.name)) self.roll = 123 global p p = self.name def __del__(self): print("Deleted") del self.name del self....
StarcoderdataPython
6542341
try: from urllib.parse import urlencode except ImportError: from urllib import urlencode import uiza class UizaBase(object): data_validated = None connection = None def create(self, **data): """ Create data :param data: data body will be created """ data_b...
StarcoderdataPython
116909
<reponame>wood-ghost/PaddleOMZAnalyzer import os, sys, os.path import argparse import numpy as np import cv2 from openvino.inference_engine import IENetwork, IECore, ExecutableNetwork from IPython import display from PIL import Image, ImageDraw import urllib, shutil, json import yaml from yaml.loader import SafeLoader ...
StarcoderdataPython
8050099
''' 预处理文本 ''' import json def ht_txt2json(): ''' 将 txt格式的英文版HP转换为json文件 ''' res = {"title": "", "chapterCount": 0, "chapters": []} with open("tmp.txt", "r", encoding="utf-8") as rfp: lines = rfp.readlines() res["title"] = lines[0] chapindexes = [] for i in range(1,...
StarcoderdataPython
9656279
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology # # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, displ...
StarcoderdataPython
1708152
<reponame>mih/multimatch #!/usr/bin/python3 import numpy as np import math import sys import collections def cart2pol(x, y): """Transform cartesian into polar coordinates. :param x: float :param y : float :return: rho: float, length from (0,0) :return: theta: float, angle in radians """ ...
StarcoderdataPython
219447
<reponame>maxminoS/neurage<filename>packages/server/app/build_model.py import numpy as np import pandas as pd import tensorflow as tf import tensorflow.keras.layers as L # import plotly.express as px from sklearn.model_selection import train_test_split def preprocess_data(filename): data = pd.read_csv(filename) # Co...
StarcoderdataPython
11350955
<reponame>smart-cow/scow<gh_stars>0 from xml.dom.minidom import * from scowclient import ScowClient def listUsers(): url = 'users' sclient = ScowClient() document = parseString(sclient.get(url)) users = document.getElementsByTagName('user') for u in users: idTag = u.getElementsByTagName('id...
StarcoderdataPython
94697
''' * * Copyright (C) 2020 Universitat Politècnica de Catalunya. * * 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
11331840
import os import h5py import mat73 import numpy as np """ View HDF5 data structure ------------------------ """ def traverse_datasets(hdf_file): """ Peak into matlab file and print the Key, Shape, Data type. :param hdf_file: :return: """ def h5py_dataset_iterator(g, prefix=''): """ ...
StarcoderdataPython
11247368
<filename>Exercise_4_BTE_1.py<gh_stars>1-10 #Hexadecimal output ''' In this exercise, you’ll see how a bit of creativity, along with the built-in 'reversed' and 'enumerate' functions, can help you to get around issues. For this exercise, you need to write a function (hex_output) that takes a hex number and returns the ...
StarcoderdataPython
4974330
# -*- coding: utf-8 -*- # # # MIT License # # Copyright (c) 2018 <NAME> # # 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 ...
StarcoderdataPython
1632126
import numpy as np # With a Q-learning algorithm returns how good is each response. def player0(data, Q, player, valid, learning_rate, feedback): actual = Q[data[player][0]][data[player][1]][data[player][2] - 1][data[player][3]][ int(np.log2(data[player][4]))] # How much it weights the actual state. ...
StarcoderdataPython
3424451
#!/usr/bin/env python # This node subscribes to a topic published by rviz which gives a pose estimate for a robot # and corrects its frame_id so that it will properly work in a multi-robot system. # In a regular single robot system, rviz publishes pose estimates to /initialpose. In # the multibot system, rviz is conf...
StarcoderdataPython
1884941
<reponame>caser789/libcollection<filename>lib_collection/priority_queue/tt.py class Queue(object): def __init__(self, capacity=2): self.values = [None] * capacity self.n = 1 self.capacity = capacity def __len__(self): return self.n-1 def _resize(self, capacity): val...
StarcoderdataPython
1772497
<reponame>wk8/elle # Copyright (C) 2009-2016, Quentin "mefyl" Hocquet # # This software is provided "as is" without warranty of any kind, # either expressed or implied, including but not limited to the # implied warranties of fitness for a particular purpose. # # See the LICENSE file for more information. from .. impo...
StarcoderdataPython
5146724
<filename>hydrolm/__init__.py from hydrolm.lm import LM from hydrolm import util
StarcoderdataPython
9608020
# Hack so that tests are importable in different levels try: from . import DatasetHandlerTester except: from util import DatasetHandlerTester class SpotifyHandler(DatasetHandlerTester): @classmethod def setUpClass(cls): # Make DataHandlerTester class methods available super() ...
StarcoderdataPython
11209539
# pylint: disable=C0103 import tensorflow as tf def shape_list(input_tensor): """Return list of dims, statically where possible.""" tensor = tf.convert_to_tensor(input_tensor) # If unknown rank, return dynamic shape if tensor.get_shape().dims is None: return tf.shape(tensor) static = ten...
StarcoderdataPython
4931763
<reponame>relax-space/thread-first ''' 说明: 多线程并发执行任务,比单线程要节约时间 ''' import time from queue import Queue from threading import Thread def req1(param): time.sleep(1) return param def main1(): return [req1(1), req1(2)] def req2(param, res_value: Queue): time.sleep(1) res_value.put(param) def mai...
StarcoderdataPython
12852236
v = int(input('Digite um valor: ')) validador = 0 contador = 1 while contador < v: if v % contador == 0: validador += 1 contador +=1 if validador > 1: print(f'Esse número NÃO é primo, pois é divisível por {validador+1} números diferentes ') else: print('Esse número é primo')
StarcoderdataPython
1771095
import sys from pypy.translator.llvm.log import log from pypy.translator.llvm.typedefnode import create_typedef_node from pypy.translator.llvm.typedefnode import getindexhelper from pypy.translator.llvm.funcnode import FuncImplNode from pypy.translator.llvm.extfuncnode import ExternalFuncNode from pypy.translator.l...
StarcoderdataPython
11282276
<gh_stars>100-1000 from kivy.uix.popup import Popup from kivy.properties import ObjectProperty, StringProperty from kivy.lang import Builder import kivy.uix.filechooser Builder.load_file('persimmon/view/util/filedialog.kv') # TODO: firx for write csv class FileDialog(Popup): """File Dialogs is a popup that gets ...
StarcoderdataPython
4809896
from django.apps import AppConfig class ProductStockConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'product_management_models.product_stocks' verbose_name = 'Product Stocks'
StarcoderdataPython
290796
from random import randrange class CodeMaker: """Implementation of AI logic.""" def __init__(self): self.code = [None]*4 self.key_pegs = [0]*4 self.key_peg_amount = 0 def draw_code(self): code = [] for i in range(4): code.append(randrange(5)) s...
StarcoderdataPython
301171
from DbxSync.CodeTransformer.LineTransformer.StringLine import StringLine class LineTransformerResolver: def __init__(self, lineTransformers: list): self.__lineTransformers = lineTransformers def resolve(self, parsedLine): for lineTransformer in self.__lineTransformers: if lin...
StarcoderdataPython
397025
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head arr = [] ...
StarcoderdataPython
4943370
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester from DQMOffline.EGamma.photonAnalyzer_cfi import * dqmElectronOfflineClient = DQMEDHarvester("ElectronOfflineClient", Verbosity = cms.untracked.int32(0), FinalStep = cms.string("AtJobEnd"), InputFile = cm...
StarcoderdataPython
8033123
import numpy as np # BD-Rate and BD-PNSR computation # (c) <NAME> (<EMAIL>) def bj_delta(R1, PSNR1, R2, PSNR2, mode=0): lR1 = np.log(R1) lR2 = np.log(R2) # find integral if mode == 0: # least squares polynomial fit p1 = np.polyfit(lR1, PSNR1, 3) p2 = np.polyfit(lR2, PSNR2, 3) ...
StarcoderdataPython
4997936
def recaman(n): arr = [0] * n arr[0] = 0 print(arr[0], end=", ") for i in range(1, n): curr = arr[i-1] - i for j in range(0, i): if ((arr[j] == curr) or curr < 0): curr = arr[i-1] + i break arr[i] = curr print(arr[i], end=", ") # Driver code n = 10 recaman(n)
StarcoderdataPython
8098726
#!/usr/bin/python #encoding=utf8 info = {"name":"xiaoming", "age":23, "sex":"male"} print(info) #获取info的所有的key print(info.keys()) #获取所有的value print(info.values()) #以数组元素的形式输出 print(info.items()) #获取某一个key的值 name = info['name'] print('name: %s'%name) #获取一个不存在的key,并且设置默认值 print(info.get('home', 'www.baidu.com')) #...
StarcoderdataPython
264775
# encoding:UTF-8 import tkMessageBox from Tkinter import * __author__ = 'Hope6537' class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.nameInput = Entry(self) self.nameI...
StarcoderdataPython
11240264
import math import torch from .constants import STAGES from .constants import Any, Tensor, DataLoader from .constants import Tuple, Dict, List from .constants import Optional, Union class LoopState: """ Maintains train/valid/test loop state for a single run of a certain number of epochs, does not used to...
StarcoderdataPython
3283978
import asyncio from asyncio import CancelledError from typing import Any, Awaitable, Sequence, TypeVar, cast, Union from protoactor.actor.exceptions import OperationCancelled, EventLoopMismatch _R = TypeVar('_R') class CancelToken: def __init__(self, name: str, loop: asyncio.AbstractEventLoop = None) -> None: ...
StarcoderdataPython
4868646
<filename>assignments/counter_clinton.py # Copyright (C) 2021 <NAME> # MIT Open Source Initiative Approved License # counter_clinton.py # CIS-135 Python # Assignment #10 Counters in Loops # Rubric: 1 Point # Use a python while loop that continuously runs as long as a user inputs the # response 'y' for yes. Ins...
StarcoderdataPython
11952
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
StarcoderdataPython
17610
<gh_stars>0 divisor = int(input()) bound = int(input()) for num in range(bound, 0, -1): if num % divisor == 0: print(num) break
StarcoderdataPython
3200697
from collections import defaultdict import sys import copy # Read input data graph = defaultdict(set) dependencies = defaultdict(set) visited = defaultdict(bool) for line in sys.stdin: words = line.strip().split() edge1, edge2 = words[1], words[-3] graph[edge1].add(edge2) dependencies[edge2].add(edge1...
StarcoderdataPython
313641
import roxar import roxar.events def elist_qc_owners(elist): """Return a list of all events with non-standard event owners Args: elist: List of roxar events Returns: List of flawed events """ errlist = [] for eve in elist: evdet = roxar.events.Event.details...
StarcoderdataPython
3329075
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 4 08:12:49 2018 @author: juan """ import cv2 import numpy as np import torch from torch.utils.data import DataLoader from torchvision import transforms from torch.autograd import Variable from CDNet2014Dataset3d import CDNet2014Dataset3d, Rescale, ...
StarcoderdataPython
3223477
import glob import cv2 import os import numpy as np from keras.models import load_model labels = ["100won", "10won", "500won", "50won"] model = load_model('model/my_model.h5') img_path = glob.glob("data/origin_images/*.jpg") for path in img_path: # Read image org = cv2.imread(path) img = cv2.resize(org,...
StarcoderdataPython
6526579
# -*- coding: utf-8 -*- from django.urls import path from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token app_name = "auth" urlpatterns = [ path('login/', obtain_jwt_token, name="login"), path('verify/', verify_jwt_token, name="verify"), ]
StarcoderdataPython
3310451
<gh_stars>1-10 from bitcoin.core.script import * from bitcoin.core import Hash160 import bitcoin.base58 import struct import unittest from hashlib import sha256 def payment_script(time_lock, secret_hash, pub_0, pub_1): """ this function making payment script for mm2 atomic swap ported from mm2 rust code ...
StarcoderdataPython
4815112
<reponame>christopinka/django-civil # -*- coding: utf-8 -*- from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from civil.library.admin import BaseAdmin from .models import * #============================================================================== class SavedSearchItemIn...
StarcoderdataPython
4841173
<filename>python/cugraph/dask/pagerank/__init__.py from .pagerank import pagerank, get_chunksize
StarcoderdataPython
3460017
<gh_stars>0 """This module contains objects for auth endpoints""" import os import datetime import jwt from werkzeug.security import generate_password_hash, check_password_hash from functools import wraps from flask import Flask, jsonify, request, make_response, abort from flask_restful import Resource from flask_jwt...
StarcoderdataPython
294206
#!/usr/bin/python # # import gi gi.require_version('Notify', '0.7') from gi.repository import Notify # https://lazka.github.io/pgi-docs/Notify-0.7/functions.html Notify.init("Your App Name") # https://lazka.github.io/pgi-docs/Notify-0.7/classes/Notification.html Hello = Notify.Notification.new("Hello world...
StarcoderdataPython
235455
import requests from flask import render_template, url_for, request, redirect, jsonify, make_response from flask_restful import Resource from app import app, db, api from models import Slide class RestSlides(Resource): #Handles the GET requests def get(self): response = {} response['count'] = Slide.query.coun...
StarcoderdataPython
6652922
<gh_stars>0 import os from datetime import datetime from contextlib import redirect_stdout from modeling.losses import build_losses from modeling.miners import build_mining from data.samplers import build_sampler from modeling.models import build_model from modeling.solver.optimizer import build_optimizer from engine....
StarcoderdataPython
1661273
<reponame>adobe-research/beacon-aug # Copyright 2021 Adobe # All Rights Reserved. # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. from .operators import * # the class are not known until run time from .adv...
StarcoderdataPython
6638155
<reponame>robust-systems-group/illusion_system #!/usr/bin/python # # Copyright (C) 2020 by The Board of Trustees of Stanford University # This program is free software: you can redistribute it and/or modify it under # the terms of the Modified BSD-3 License as published by the Open Source # Initiative. # If you use thi...
StarcoderdataPython
79408
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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...
StarcoderdataPython