id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3343876 | import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from typing import Any, Dict, List, Type
from torch.distributions import kl_divergence
from tianshou.policy import A2CPolicy
from tianshou.data import Batch, ReplayBuffer
class NPGPolicy(A2CPolicy):
"""Implementation of Natural... | StarcoderdataPython |
3321424 | print("Successfully imported 'other_script.py'")
| StarcoderdataPython |
3200078 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""This module provides functions and constants used in other modules in this package."""
import asyncio
import json
from typing import Union
import httpx
import requests
from privatebinapi.exceptions import BadServerResponseError, PrivateBinAPIError
__all__ = ('get_loop', ... | StarcoderdataPython |
3203852 | # Generated by Django 2.2.5 on 2020-02-18 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0021_auto_20200127_2207'),
]
operations = [
migrations.AlterField(
model_name='user',
name='last_name_kana'... | StarcoderdataPython |
102815 | <reponame>pootle/pimotors
#!/usr/bin/python3
"""
This module provides feedback control for motors
So far a PID controller......
"""
class PIDfeedback():
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_... | StarcoderdataPython |
1693586 | <gh_stars>1-10
# -*- coding: utf-8 -*-
###############################################################################
#
# Person
# Returns members of Congress and U.S. Presidents since the founding of the nation.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, ... | StarcoderdataPython |
4841605 | <filename>setup.py<gh_stars>1-10
import os
from setuptools import setup, find_packages
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
# intentionally *not* adding an encoding option to open, See:
#... | StarcoderdataPython |
139708 | <reponame>xe1gyq/metal
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved.
#
from oslo_config import cfg
from oslo_utils._i18n import _
INVENTORY_LLDP_OPTS = [
cfg.ListOpt('drivers',
default=... | StarcoderdataPython |
3335861 | import logging
import socket
from datetime import datetime
from os import path, remove
from subprocess import DEVNULL, CalledProcessError, check_call
from time import sleep
from typing import Union
from urllib.parse import urlparse
import redis
from azure.storage.blob import BlobServiceClient
from pythonjsonlogger imp... | StarcoderdataPython |
162899 | <filename>conanfile.py
from conans import ConanFile, CMake, tools
class LibCommuniConan(ConanFile):
name = "communi"
version = "3.6.0"
license = "MIT"
author = "Edgar <EMAIL>"
url = "https://github.com/AnotherFoxGuy/libcommuni-cmake"
description = "A cross-platform IRC framework written with Q... | StarcoderdataPython |
3383696 | # Generated by Django 2.0.5 on 2019-04-23 15:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hostlock', '0002_host_owner'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
2528 | # encoding: utf-8
#
# Copyright (C) 2018 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 lat... | StarcoderdataPython |
3218996 | import logging
logging.basicConfig(format='%(message)s', level=logging.INFO)
logger = logging.getLogger(__package__)
| StarcoderdataPython |
3346985 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 20:03:20 2020
@author: hexx
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from shutil import copyfile
from myFunctions import createFolder
today = pd.to_datetime('today')
today =today.strftime("%Y-%m-%d")
today = '2020-09... | StarcoderdataPython |
3396779 | <gh_stars>10-100
import numpy as np
import os
import pdb
from PIL import Image, ImageDraw
import cv2
import glob as gb
# import av
from skvideo.io import ffprobe
import pandas as pd
import sys
"""
Add keys for videos without any detections, add also frame keys for those videos
"""
split = 'train'
src_det_file_pa... | StarcoderdataPython |
4841645 | <gh_stars>10-100
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache Licens... | StarcoderdataPython |
3368921 | import numpy
from tkinter import *
from tkinter import ttk
from Constants import Constant_Images
from PIL import Image, ImageTk
save = Toplevel()
save.title("Save Page")
save.geometry("300x300")
# radio button değerleri için
var = IntVar()
var.set(2)
def combo():
"""
Combobox u ekranda gösterir. Ayrıca tıkl... | StarcoderdataPython |
1736535 | <filename>flavio/physics/bdecays/bvll/observables_bs.py
"""Functions for exclusive $B_s\to V\ell^+\ell^-$ decays, taking into account
the finite life-time difference between the $B_s$ mass eigenstates,
see arXiv:1502.05509."""
import flavio
from . import observables
from flavio.classes import Observable, Prediction
im... | StarcoderdataPython |
1629985 | <reponame>prihoda/bgc-pipeline-1<filename>bgc_detection/evaluation/confusion_matrix.py
#!/usr/bin/env python
# <NAME>
# Plot confusion matrix from a given Domain CSV prediction file
# and prediction threshold defined by the TPR or FPR values to be achieved
import argparse
import pandas as pd
import numpy as np
from sk... | StarcoderdataPython |
37114 | import pytest
from django.urls import reverse
class TestImageUpload:
@pytest.mark.django_db
def test_upload_image_not_authenticated(self, client, small_jpeg_io):
upload_url = reverse("cast:api:upload_image")
small_jpeg_io.seek(0)
r = client.post(upload_url, {"original": small_jpeg_io... | StarcoderdataPython |
3231028 | ########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. 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... | StarcoderdataPython |
37090 | # Basic String Operations (Title)
# Reading
# Iterating over a String with the 'for' Loop (section)
# General Format:
# for variable in string:
# statement
# statement
# etc.
name = 'Juliet'
for ch in name:
print(ch)
# This program counts the number of times the letter T
# ... | StarcoderdataPython |
1706547 | <filename>BotErrors/RepeatedUserError.py
class RepeatedUserError(Exception):
pass
| StarcoderdataPython |
1763230 | import logging
import telegrampy
from telegrampy.ext import commands
logging.basicConfig(level=logging.INFO, format="(%(asctime)s) %(levelname)s %(message)s", datefmt="%m/%d/%y - %H:%M:%S %Z")
logger = logging.getLogger("telegrampy")
# Make sure to never share your token
bot = commands.Bot("token here")
# Create a... | StarcoderdataPython |
1665884 | #! /usr/bin/env python3.6
"""
server.py
Stripe Sample.
Python 3.6 or newer required.
"""
import json
import os
import random
import string
import stripe
from dotenv import load_dotenv, find_dotenv
from flask import Flask, jsonify, render_template, redirect, request, session, send_from_directory, Response
import urll... | StarcoderdataPython |
1748719 | <gh_stars>0
import tensorflow as tf
import sys
START_ID=0
PAD_ID = 1
END_ID=2
class PointerWrapper(tf.contrib.seq2seq.AttentionWrapper):
"""Customized AttentionWrapper for PointerNet."""
def __init__(self,cell,attention_size,memory,initial_cell_state=None,name=None):
# In the paper, Bahdanau Attention Mechan... | StarcoderdataPython |
129278 | # python3
# coding=<UTF-8>
import os
import re
from lxml.etree import parse, HTMLParser
from urllib.request import quote
from ..params_container import Container
from ..target import Target
from ..exceptions import EmptyPageException
__author__ = 'akv17'
__doc__ = \
"""
National Corpus of Russian
=====... | StarcoderdataPython |
1680731 | import boto3
from botocore.exceptions import ClientError
client = boto3.client('rds')
def get_parameter_group_family(engine_name,engine_version):
try:
response = client.describe_db_engine_versions(
Engine=engine_name,
EngineVersion=engine_version
)
... | StarcoderdataPython |
1633619 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import multiprocessing
class BaseExtractor(object):
def __init__(self, names, max_workers=None):
self._names = names
self._max_workers = max_workers or (multiprocessing.cpu_count() * 4)
def run(self, j... | StarcoderdataPython |
1739238 | <gh_stars>0
#!/usr/bin/python
import os
import shutil
# Obtain and import the installLib library - should work on Windows and Linux / MacOS.
if os.path.exists("install-lib"):
os.system("git -C install-lib pull https://github.com/dhicks6345789/install-lib.git")
else:
os.system("git clone https://github.com/dhicks6345... | StarcoderdataPython |
100755 | """
<NAME>, 2018
All rights reserved
"""
import torch
from torchvision import datasets, transforms
def load_training_data(args, kwargs):
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.ToTensor()),
batc... | StarcoderdataPython |
1706158 | <gh_stars>0
import decimal
from django.conf import settings
from django.db import models
from shop.models import Product
from django.core.validators import MinValueValidator, MaxValueValidator
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='or... | StarcoderdataPython |
1762584 | <reponame>cristi2019255/LocalSearchAlgorithms
import numpy as np
import math
def generate_graph(size = 10, fully_connected = False, random = False):
""" Generate a graph for graph bipartitioning problem
Args:
size (int, optional): The number of vertices for the generated graph. Defaults to 10.
... | StarcoderdataPython |
4499 | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype validators.**
This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable)
classes enabling callers ... | StarcoderdataPython |
1729035 | <reponame>ilopezgp/human_impacts
#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import anthro.viz
import anthro.io
from pywaffle import Waffle
colors = anthro.viz.plotting_style()
data = pd.read_csv('../../../data/agriculture/FAO_fish_production_quantities/processed/FAO_FishStatJ_total_mas... | StarcoderdataPython |
4824689 | <filename>mailchimp3/entities/campaignfolders.py
# coding=utf-8
"""
The Campaign Folders API endpoints
Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/campaign-folders/
Schema: https://api.mailchimp.com/schema/3.0/CampaignFolders/Instance.json
"""
from __future__ import unicode_literals... | StarcoderdataPython |
3262956 | '''
Description:
Version: 1.0
Autor: Zhangzixu
Date: 2022-01-02 18:46:09
LastEditors: Zhangzixu
LastEditTime: 2022-01-10 13:25:22
'''
# optimizer
optimizer = dict(type='SGD', lr=1e-4, momentum=0.90, weight_decay=5e-4)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='poly', power=0.9, min_lr=1e-6, by_ep... | StarcoderdataPython |
83182 | <filename>practice/string/string/string/string.py
print(' a string that you "dont" have to escape \n This \n is a multi-line \n heredoc string -------> example')
| StarcoderdataPython |
1703680 | # File: api_caller.py
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
import json
class ApiCaller:
CONST_REQUEST_METHOD_GET = 'get'
CONST_REQUEST_METHOD_POST = 'post'
CONST_EXPECTED_DATA_TYPE_JSON = 'json'
CONST_EXPECTED_DATA_TYPE_FILE = 'file'
CONST_API_AUTH_... | StarcoderdataPython |
1700698 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
import datetime
import json
import os
from enum import Enum
# TODO: implement
def index_coordinates(pages):
"""Creates an index of coordinates by text offsets.
Gets called by `self.from_json()`.
"""
coords = []
for page in pages:
for tok... | StarcoderdataPython |
1618028 | <gh_stars>1-10
import numpy as np
#########################
### SIMULATION PARAMS ###
#########################
timestep = 1.
runtime = 20000.
num_threads = 9
######################
### NETWORK PARAMS ###
######################
#bg_noise_d1 = 95.
bg_noise_d1 = 80.
bg_noise_d2 = 57.
bg_weight_d1 = 2.5
bg_weight... | StarcoderdataPython |
3393473 |
class DbColumn(object) :
def __init__(self, name, javaType, jdbcType, comment, nullable, maxLen) :
self.name = name
self.javaType = javaType
self.jdbcType = jdbcType
self.comment = comment
self.nullable = nullable
self.maxLen = maxLen
def __str__(self) :
... | StarcoderdataPython |
1788932 | <filename>data_collection/gazette/spiders/sc_balneario_picarras.py
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScBalnearioPicarrasSpider(FecamGazetteSpider):
name = "sc_balneario_picarras"
FECAM_QUERY = "cod_entidade:33"
TERRITORY_ID = "4212809"
| StarcoderdataPython |
55410 | import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
class Generator(nn.Module):
def __init__(self, configs, shape):
super(Generator, self).__init__()
self.label_emb = nn.Embedding(configs.n_classes, configs.n_classes)
self.shape = shape
def block(... | StarcoderdataPython |
102437 | # Copyright 2016-2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
#
# or in the "license" f... | StarcoderdataPython |
1651200 | <reponame>Rohitmaan2012/Twitter_Sentiment_Analysis<gh_stars>0
"""
Numpy version of DCNN, used for prediction, instead of training
"""
import numpy as np
from numpy_impl import (conv2d, LogisticRegression)
_MODEL_PATH = "models/filter_widths=10,7,,batch_size=10,,ks=20,5,,fold=1,1,,conv_layer_n=2,,ebd_dm=48,,nke... | StarcoderdataPython |
3211532 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
def hash160(data):
d32 = hashlib.sha256(data).digest()
h = hashlib.new('ripemd160')
h.update(d32)
d20 = h.digest()
return d20
def sha256(data):
d32 = hashlib.sha256(data).digest()
return d32
def double_sha256(data):
d32... | StarcoderdataPython |
43835 | from xml.etree import ElementTree as Etree
from xml.dom import minidom
from elavonvtpv.enum import RequestType
from elavonvtpv.Response import Response
import datetime
import hashlib
import requests
class Request:
def __init__(self, secret, request_type, merchant_id, order_id, currency=None, amount=None, card=Non... | StarcoderdataPython |
1600155 | # -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... | StarcoderdataPython |
151672 | <reponame>JohnnyPeng18/coach
#
# Copyright (c) 2020 Intel Corporation
#
# 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 b... | StarcoderdataPython |
5470 | <filename>main.py
'''
Created on Jun 17, 2021
@author: Sean
'''
import PDF2CSV_GUI
def main():
j = PDF2CSV_GUI.Convert_GUI()
if __name__ == "__main__":
main() | StarcoderdataPython |
1727528 | <gh_stars>0
import unittest
from unittest.mock import patch
from eiffelactory import artifactory
from eiffelactory import config
artifact_filename = 'artifact.txt'
build_path_substring = 'job/TEST/job/BUILD_NAME/255'
query_string =\
'items.find({"artifact.name":"artifact.txt",' \
'"artifact.module.build.url":... | StarcoderdataPython |
3312893 | <filename>scenarios/wifi/connect_test.py<gh_stars>0
import pytest
from conftest import get_remote_hosts_dict, skip_if_not_enough_remote_nodes
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2017, Technische Universität Berlin"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
# skip all tests from this pytest module... | StarcoderdataPython |
3205721 | <gh_stars>0
from . import db
from contextlib import contextmanager
'''
Column | Type | Collation | Nullable | Default
----------------------+-------------------------+-----------+----------+---------
name | character varying(255) | | |
instance_id... | StarcoderdataPython |
1656663 | <gh_stars>10-100
from tinkoff_voicekit_client.Operations.long_running import ClientOperations
from tinkoff_voicekit_client.Operations import aio_long_running as aio
| StarcoderdataPython |
1702705 | import unittest
class SDSPythonSampleTests(unittest.TestCase):
@classmethod
def test_main(cls):
import program
if __name__ == '__main__':
unittest.main() | StarcoderdataPython |
1696253 | from ._DatasetViewSet import DatasetViewSet
| StarcoderdataPython |
4837397 | <filename>NEW_PRAC/LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Array/plusOne.py
#############Method 1#########################
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
a = [str(i) for i in digits]
str_a = int("".join(a))
str_a = str(str_a + 1)
... | StarcoderdataPython |
3291822 | <filename>10_poisson.py
# Import libraries
###############################
import numpy # numerics
from matplotlib import pyplot # plotting
from matplotlib import cm # colormap
from mpl_toolkits.mplot3d import Axes3D # 3d plot
######################################################################
# FUNCTION DEFINITION... | StarcoderdataPython |
68202 | <reponame>surveybott/psiTurk<filename>tests/conftest.py
from __future__ import print_function
# https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects
from builtins import object
import pytest
import os
import sys
import pickle
import json
import datetime
import dateutil.parser
i... | StarcoderdataPython |
4805212 | <filename>Função def .py
def divisao(n1, n2):
if n2 == 0:
return
return n1 / n2
divide = divisao(8,2)
if divide:
print(divide)
else:
print('Conta Invalida')
def divisao(n1, n2):
if n2 == 0:
return
return n1 / n2
divide = divisao(60,4)
if divide:
print(divide)
else:
... | StarcoderdataPython |
4801636 | from setuptools import setup, find_packages
setup(
name="flexlmtools",
version="0.1.0",
install_requires=[],
extras_require={
"develop": ["pytest"]
},
author="<NAME>",
author_email="<EMAIL>",
description="Package for Flexlm License Manager",
packages=find_packages(),
cla... | StarcoderdataPython |
50146 | def main():
# input
N, K = map(int, input().split())
# compute
def twoN(a: int):
if a%200 == 0:
a = int(a/200)
else:
a = int(str(a) + "200")
return a
for i in range(K):
N = twoN(N)
# output
print(N)
if __name__ == '__main_... | StarcoderdataPython |
16737 | <gh_stars>0
# -*- coding: utf-8 -*-
import argparse
import cv2 as cv
import mediapipe as mp
import sys
import time
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--video_device", type=int, default=0)
parser.add_argument("--video_file", type=str, default="")
args =... | StarcoderdataPython |
4813604 | <reponame>SuddenDevs/SuddenDev<gh_stars>1-10
import flask
import flask_login
import flask_socketio as fsio
import sqlalchemy
from . import socketio, redis
from .models import db, User
from .game_instance import GameInstance
from .tasks import play_round
from .rooms import (
get_room_of_player,
get_color_of_play... | StarcoderdataPython |
3314311 | import numpy as np
import random
def mixup(X_train, Y_train, class_n,
ratio=0.5,
alpha=1.0,
beta=1.0):
new_data_n = int(X_train.shape[0] * ratio)
new_X = []
new_Y = []
count = 0
idxset = set(range(X_train.shape[0]))
while count < new_data_n:
... | StarcoderdataPython |
195748 | import random
from graph import Graph
def create_signal_tree(integers):
vertices = [integers[0]]
edges = []
for i in range(1, len(integers)):
v1 = integers[i - 1]
v2 = integers[i]
if v2 not in vertices:
vertices.append(v2)
edges.append((v1, v2, min(v1, v2)))
graph = Graph(vertices, edges, directed =... | StarcoderdataPython |
3309671 | <reponame>d39b/DQSnake<filename>qlearner.py
import tensorflow as tf
import numpy as np
from qnetwork import QNetwork
#trains a deep q-network
#uses double q-learning, i.e. separate train and target networks (with output Q_train and Q_target respectively)
#let (s,a,s2,r,t) be a transition, then the train network is tra... | StarcoderdataPython |
3353648 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .change_trust_asset import ChangeTrustAsset
from .int64 import Int64
__all__ = ["ChangeTrustOp"]
@type_checked
class ChangeTrustO... | StarcoderdataPython |
3387729 | import lightgbm as lgb
import numpy as np
import sklearn
import pandas as pd
from sklearn.datasets import load_svmlight_file
from sklearn.metrics import mean_squared_error
import riskrewardutil as rru
basePath = '/research/remote/petabyte/users/robert/Utilities/ltr-baseline/mslr10k/'
expPath = "/research/remote/petaby... | StarcoderdataPython |
1764585 | <reponame>mengjian0502/StructuredCG_RRAM<gh_stars>0
"""
Channel Gating Layers
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .qmodules import WQ, AQ
def _gen_mask(mtype, dim):
"""
Pre-defined computation masks
"""
mask = torch.ones((dim[2], dim[3])).cuda()
reverse = ... | StarcoderdataPython |
107588 | <filename>LeetCodeSolutions/LeetCode_0371.py<gh_stars>10-100
class Solution:
def getSum(self, a: int, b: int) -> int:
a &= 0xFFFFFFFF
b &= 0xFFFFFFFF
while b:
carry = a & b
a = a ^ b
b = ((carry) << 1) & 0xFFFFFFFF
return a if a < 0x80000000 else ~... | StarcoderdataPython |
1744616 | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
# declaration
class cudaCoolingStep:
"""
Encapsulation of the state of the calculation at some par... | StarcoderdataPython |
144545 | from typing import List
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
st = []
l, r = len(nums), 0
for i, n in enumerate(nums):
while st and n < nums[st[-1]]:
l = min(l, st.pop())
st.append(i)
st = []
for i, n... | StarcoderdataPython |
1758437 | <filename>tests/test_utils.py
import json
import os
from connect.config import Config
from typing import Dict, Any
class TestUtils:
@staticmethod
def get_request(file, model_class):
with open(os.path.join(os.path.dirname(__file__), file)) as request_file:
request = model_class.deserialize(... | StarcoderdataPython |
3308891 | #!/usr/bin/python3
__DOC__ = """ talk to EMM server *at all* from ordinary Python
See also https://github.com/google/android-management-api-samples/blob/master/notebooks/quickstart.ipynb
"""
# Copyright 2018 Google LLC.
# © <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use ... | StarcoderdataPython |
3212412 | #! python
import time, datetime
# отсчет времени
startTime = time.time()
time.sleep(1)
print(time.time())
time.sleep(1)
endTime = time.time()
print('Время %s ' % (endTime - startTime))
# сейчас
dateNow = datetime.datetime.now()
print(dateNow.year)
print(dateNow.hour)
print(dateNow.second)
# дату в... | StarcoderdataPython |
3342754 | <gh_stars>0
import traceback
import bson
import struct
import json
import websockets
import random
from os.path import isfile
from autobahn.twisted.websocket import WebSocketServerProtocol
db = {}
fp = None
if isfile("maplist.bson"):
fp = open("maplist.bson", 'a+b')
fp.seek(0)
try:
db = bso... | StarcoderdataPython |
1664161 | <gh_stars>1-10
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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')
... | StarcoderdataPython |
58637 | '''Desenvolva um programa que leia o comprimento de três retas e diga ao
usuário se elas podem ou não formar um triângulo.'''
#minha resolução
#https://escolaeducacao.com.br/condicao-da-existencia-de-um-triangulo/
a = float(input('Digite o primeiro comprimento: '))
b = float(input('Digite o segundo comprimento: '))
c ... | StarcoderdataPython |
1635421 | # The MIT License
#
# Copyright (c) 2008 <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 use, copy, modify, merg... | StarcoderdataPython |
90574 | <filename>watcher/tests/datasource/test_gnocchi_helper.py<gh_stars>0
# -*- encoding: utf-8 -*-
# Copyright (c) 2017 Servionica
#
# 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://ww... | StarcoderdataPython |
63933 | <reponame>opendatadiscovery/odd-collector-aws
from odd_collector_aws.adapters.sagemaker.domain.artifact import (
create_artifact,
Image,
Model,
Dataset,
)
def test_create_artifact():
image_artifact = {
"name": "SageMaker.ImageUri",
"uri": "1111.dkr.ecr.us-east-1.amazonaws.com/predi... | StarcoderdataPython |
3265799 | <gh_stars>0
import datetime
import json
import logging
import textwrap
from django.conf import settings
from django.contrib.auth import login as django_login, logout as django_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import... | StarcoderdataPython |
3252498 | n, m = map(int, input().split())
w = []
for i in range(1, n + 1):
x1, y1, x2, y2 = map(int, input().split())
w.append((x1, y1, x2, y2, i))
for _ in range(m):
x, y = map(int, input().split())
found = False
for i, s in reversed(list(enumerate(w))):
if x >= s[0] and x <= s[2] and y >= s[1] a... | StarcoderdataPython |
3371900 | class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
if strs.count < 1 {
return ""
}
if strs.count < 2 {
return strs.first!
}
var result = ""
var minLen = Int.max
for item in strs {
minLen = min(minLen, it... | StarcoderdataPython |
1691432 | <filename>src/XmlDataReader.py
from Types import DataType
from DataReader import DataReader
import xml.etree.ElementTree as ET
class XmlDataReader(DataReader):
def __init__(self) -> None:
self.students: DataType = {}
def read(self, path: str) -> DataType:
with open(path, encoding="utf-8") as... | StarcoderdataPython |
1759433 | <filename>packages/pyre/primitives/Path.py
# -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2022 all rights reserved
#
# externals
import collections
import functools
import io
import os
import pwd
import stat
# helpers
def _unaryDispatch(f):
"""
Wrapper for functions that require the string repre... | StarcoderdataPython |
3207107 | <gh_stars>1-10
from smsiran.sms_ir import SmsIR
from smsiran.ghasedak import Ghasedak
| StarcoderdataPython |
3207613 | <filename>test/test_fetch.py<gh_stars>0
from pytest import mark
from test.util import postcodes_io_ok
@mark.skipif(postcodes_io_ok() is False, reason="Postcodes IO Down!")
@mark.asyncio
class TestApi:
async def test_true(self):
assert False
| StarcoderdataPython |
66504 | """Decorate functions with contracts."""
# pylint: disable=invalid-name
# pylint: disable=protected-access
# pylint: disable=wrong-import-position
# We need to explicitly assign the aliases instead of using
# ``from ... import ... as ...`` statements since mypy complains
# that the module icontract lacks these import... | StarcoderdataPython |
4829176 |
from django.conf import settings
TEMPLATE_BASE = settings.AUTH_TEMPLATE_BASE or "helios_auth/templates/base.html"
# enabled auth systems
from . import auth_systems
ENABLED_AUTH_SYSTEMS = settings.AUTH_ENABLED_SYSTEMS or list(auth_systems.AUTH_SYSTEMS.keys())
DEFAULT_AUTH_SYSTEM = settings.AUTH_DEFAULT_SYSTEM or None... | StarcoderdataPython |
3254956 | <gh_stars>1-10
import pandas.io.json
import sys
def convert_file(json_file, operation):
try:
normalized = pandas.io.json.json_normalize(json_file)
normalized.to_csv(operation)
except AttributeError as err:
print("Cannot create a .csv file due to nature of the json file ({}) - File's na... | StarcoderdataPython |
13880 | """Use TIMESTAMP column for latest submission
Revision ID: eff<PASSWORD>0<PASSWORD>
Revises: <PASSWORD>
Create Date: 2017-01-08 22:20:43.814375
"""
# revision identifiers, used by Alembic.
revision = 'eff<PASSWORD>'
down_revision = '<PASSWORD>'
from alembic import op # lgtm[py/unused-import]
import sqlalchemy as ... | StarcoderdataPython |
1782679 | <gh_stars>0
"""
Simple wrapper that adds some extra encoding capabilities needed for
this project.
"""
import collections
import datetime
import decimal
from json import JSONDecodeError # noqa
import json as json_impl
class JsonExtendedEncoder(json_impl.JSONEncoder):
"""
Needed for the json module to underst... | StarcoderdataPython |
3294230 | <gh_stars>0
__author__ = 'michael'
from pyyelp.pyyelp import Yelp
def search_test():
yelp = Yelp()
print(yelp.search(term='Starbucks', location='San Francisco'))
def business_test():
yelp = Yelp()
print(yelp.get_business_by_id('yelp-san-francisco'))
def phone_test():
yelp = Yelp()
print(y... | StarcoderdataPython |
3389044 | <reponame>tradenity/python-sdk<gh_stars>1-10
# coding: utf-8
"""
Tradenity API
Tradenity eCommerce Rest API
Contact: <EMAIL>
"""
from __future__ import absolute_import
import re
import pprint
# python 2 and python 3 compatibility library
import six
from tradenity.api_client import ApiClient
class... | StarcoderdataPython |
161332 | <reponame>abingham/ackward<filename>site_scons/bygg/build_products.py
class BuildProducts(object):
'''A class to help keep track of build products in the build.
Really this is just a wrapper around a dict stored at the key
'BUILD_TOOL' in an environment. This class doesn't worry about
what stored in th... | StarcoderdataPython |
3341673 | <filename>cinder/volume/drivers/netapp/iscsi.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 NetApp, Inc.
# Copyright (c) 2012 OpenStack 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 Li... | StarcoderdataPython |
3294338 | <reponame>SamuelHorvath/Variance_Reduced_Optimizers_Pytorch
import argparse
from datetime import datetime
import os
def parse_args(args):
parser = initialise_arg_parser(args, 'Variance Reduction.')
parser.add_argument(
"--total-runs",
type=int,
default=3,
help="Number of times... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.