id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6422210 | <gh_stars>0
from utils.lambda_decorators import async_handler, forward_exceptions_to_dlq
from .diffing_sync import DiffingDynamoDbSync
from ..dynamo_elastic_sync.dynamo_elastic_sync import sqs_client, dlq
_syncer = DiffingDynamoDbSync()
# N.B. DynamoDB streams call lambda synchronously, which means that setting the ... | StarcoderdataPython |
4961021 | import datetime
import typing
from .types import JsonicType
Tex = typing.TypeVar("Tex", bound=Exception)
def cause(ex: Tex, cause: Exception) -> Tex:
ex.__cause__ = cause
return ex
class DateConstructorProtocol(typing.Protocol):
def __call__(self, year: int, month: int, day: int):
... # pragm... | StarcoderdataPython |
61752 | <filename>taiwanpeaks/common/constants.py
from model_utils import Choices
class IndexableChoices(Choices):
def index_of(self, item):
for i in range(len(self._doubles)):
if item == self._doubles[i][0]:
return i
raise ValueError(f"{item} is not a valid choice.")
DIFFIC... | StarcoderdataPython |
214030 | from src.exception.PlayerPathObstructedException import *
from src.player.RandomBot import *
class BuilderBot(RandomBot):
def computeFencePlacingImpacts(self, board):
fencePlacingImpacts = {}
for fencePlacing in board.storedValidFencePlacings:
try:
impact = board.getFen... | StarcoderdataPython |
5011712 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import numpy as np
import cv2
import tensorflow.keras.backend as K
IMAGE_SHAPE = (448, 448, 3)
CLASS_NAME_TO_INDEX = {
'aeroplane': 0, 'bicycle': 1, 'bird': 2, 'boat': 3, 'bottle': 4, 'bus': 5,
'car': 6, 'cat': 7,... | StarcoderdataPython |
3234325 | ## 2/3
n = 0
while abs(u(n)**2 - 2) >= 2e-5:
n += 1
print(n)
# n == 4
# √2 ≈ 1.4142156862745097
## 2/4
n = 0
q = 4 # choose this
def u_q(n):
if n <= 0:
return 1
return (1/q)*(u(n-1)+q/u(n))
while abs(u_q(n)**q - q) >= q*1e-5:
n += 1
print(n)
## 3/1/a
def fact(n):
if n <= 1:
retur... | StarcoderdataPython |
1807465 | # Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import shutil
from collections import defaultdict
from mmdet.datasets import DATASETS
from .sot_test_dataset import SOTTestDataset
@DATASETS.register_module()
class GOT10kDataset(SOTTestDataset):
"""GOT10k dataset for the testing of... | StarcoderdataPython |
149700 | <reponame>kitsuyui/cachepot<filename>example/__init__.py
from typing import Any
from cachepot.backend.filesystem import FileSystemCacheBackend
from cachepot.serializer.json import JSONSerializer, JSONType
from cachepot.serializer.pickle import PickleSerializer
from cachepot.serializer.str import StringSerializer
from ... | StarcoderdataPython |
1860239 | __author__ = 'Jwely'
import os
from TeXFigureGenerator import TeXFigureGenerator
class TeXWriter:
def __init__(self, main_path, texfile_path):
self.main_path = os.path.abspath(main_path)
self.texfile_path = os.path.abspath(texfile_path)
self.content = [] # a list of content s... | StarcoderdataPython |
12854027 | <reponame>travisliu/data-spec-validator<filename>setup.py
import os
import setuptools
CUR_DIR = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(CUR_DIR, "data_spec_validator", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encoding="utf-8") as fh:
... | StarcoderdataPython |
3337950 | import numpy as np
from torchvision.transforms.functional import normalize
def denormalize(tensor, mean, std):
mean = np.array(mean)
std = np.array(std)
mean = -mean / std
std = 1 / std
if isinstance(tensor, np.ndarray):
return (tensor - mean.reshape(-1, 1, 1)) / std.reshape(-1, 1, 1)
... | StarcoderdataPython |
9728039 | <filename>materializationengine/workflows/dummy_workflow.py
import time
from celery import chain, chord
from celery.utils.log import get_task_logger
from materializationengine.celery_init import celery
from materializationengine.shared_tasks import fin
celery_logger = get_task_logger(__name__)
@celery.task(name="pr... | StarcoderdataPython |
11386134 | <reponame>Warlockk/Intensio-Obfuscator
# -*- coding: utf-8 -*-
# https://github.com/Hnfull/Intensio-Obfuscator
#---------------------------------------------------------- [Lib] -----------------------------------------------------------#
import fileinput
import random
import textwrap
import re
import sys
from progre... | StarcoderdataPython |
353479 | <reponame>dczifra/lightly
import unittest
import torch
from lightly.models.modules.heads import BarlowTwinsProjectionHead
from lightly.models.modules.heads import BYOLProjectionHead
from lightly.models.modules.heads import DINOProjectionHead
from lightly.models.modules.heads import MoCoProjectionHead
from lightly.mod... | StarcoderdataPython |
6506483 | <filename>FastSimulation/TrajectoryManager/python/ActivateDecays_cfi.py
import FWCore.ParameterSet.Config as cms
ActivateDecaysBlock = cms.PSet(
ActivateDecays = cms.PSet(
ActivateDecays = cms.bool(True),
# Maximum angle to associate a charged daughter to a charged mother
# Mostly done to a... | StarcoderdataPython |
3269370 | import json
import time
from unittest.mock import patch
from requests import Response
from raindropio import *
def test_refresh() -> None:
api = API(
{
"access_token": "old",
"refresh_token": "<PASSWORD>",
"expires_at": time.time() - 100000,
}
)
with p... | StarcoderdataPython |
9601806 | <reponame>xcffl/valacef<filename>genvalacef.py
import os
import sys
from valacefgen.cparser import Parser, Naming
from valacefgen.types import Repository, Function
from valacefgen.utils import TypeInfo
try:
CEF_INCLUDE_DIR = sys.argv[1]
except IndexError:
CEF_INCLUDE_DIR = "/app/include/cef/include"
try:
TOP = sys.... | StarcoderdataPython |
3546740 | import os
import tifffile as tif
import argparse
import glob
def parse_args():
"""Parse input arguments"""
parser = argparse.ArgumentParser(description='Load CIDRE-processed images into structured folder.')
parser.add_argument(
'--in_path', dest='in_path', required=True,
help='Processed im... | StarcoderdataPython |
1626189 | """Calculator Locator Class"""
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
from appium.webdriver.common.mobileby import MobileBy
class CalculatorPageLocator:
"""
Contains page locators for Calculator App
Each locator is a tuple: locat... | StarcoderdataPython |
5180949 | #!/usr/bin/env python
'''
Generates an AST_L1T-SO2 product
'''
from __future__ import print_function
import os
import json
import urllib3
import dateutil.parser
import requests
import numpy as np
from hysds.celery import app
import run_ratio
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
PROD_S... | StarcoderdataPython |
11389665 | """
:codeauthor: <NAME> (<EMAIL>)
salt.config.schemas
~~~~~~~~~~~~~~~~~~~
Salt configuration related schemas for future validation
"""
| StarcoderdataPython |
3432356 | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import mock
import os
import unittest
from properties import HasProperties as BaseModel
from ..daily_med import DailyMed
from ..models import SPL
mock_path = 'daily_med.daily_med'
class TestDailyMed(u... | StarcoderdataPython |
373428 | import numpy as np
from read_img import read_img
from time import time
import sys
def get_outputs(img_name = 'wordle.png'):
'''
Get outputs for the input image
:param: img_name
:type: str
'''
t1 = time()
COLORS = [np.array([[120, 124, 126]]), \
np.array([[201, 182, 95]])... | StarcoderdataPython |
5160591 | from time import time
import unicodedata
import datetime
def strip_accents(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def format_username(firstname, lastname):
return strip_accents("{}.{}.external".format(
''.join(e for e in fir... | StarcoderdataPython |
5065620 | <reponame>lastweek/source-freebsd<filename>src/tests/sys/netinet6/scapyi386.py<gh_stars>0
#!/usr/bin/env python
#-
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2019 Netflix, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following... | StarcoderdataPython |
3297369 | <filename>SnakeNest/scripts/Common_unitigs.py<gh_stars>10-100
#!/usr/bin/env python
# FIXME this one needs refactoring and factoring out the hardcoded paths
# FIXME normalize names and spaces
from __future__ import print_function
import re
import sys
import glob
import argparse
from os.path import basename, join, dirn... | StarcoderdataPython |
11352287 | from django.conf.urls import url
from . import views
app_name = 'leave'
urlpatterns = [
url(r'^', views.leave, name='leave'),
]
| StarcoderdataPython |
3243928 | <gh_stars>0
import datetime
import hashlib
import io
import json
import logging
import os
import socket
import getpass
from base64 import b64encode
try:
from urlparse import urlunparse
except ImportError:
from urllib.parse import urlunparse
from smb.SMBConnection import SMBConnection
from smb.base import Ope... | StarcoderdataPython |
3501191 | <gh_stars>10-100
#!/usr/bin/python3
import argparse
import signal
import sys
import AutoTuner
"""
Example script for interacting with the dhammer API
Usage: autotune.py --tune-stat-name OfferReceived --tune-stat-compare-name DiscoverSent
"""
##### Install a signal handler for CTRL+C #####
def signal_handler(sign... | StarcoderdataPython |
8196806 | """DGX Remote Shell is a program that allows remote access to the DGX shell for
debugging and information gathering.
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... | StarcoderdataPython |
5092585 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################
##ask user to specify a mode to execute
## 0: visit rooms on a given map (default)
## 1: step by step control
#############################################
import rospy
from state_machine.srv import State, StateResponse
de... | StarcoderdataPython |
1873368 | import json
import os
import requests
import mimetypes
import requests.cookies
from requests_toolbelt import MultipartEncoder
from bs4 import BeautifulSoup
from py3pin.BookmarkManager import BookmarkManager
from py3pin.Registry import Registry
from py3pin.RequestBuilder import RequestBuilder
from requests.structures im... | StarcoderdataPython |
1684344 | import numpy as np
class BinaryTree:
root = None
node_index = None
def __init__(self, index, value):
self.root = BinaryTreeNode(index, value)
self.node_index = {index: self.root}
def add_left_descendant(self, index, value, parent_index):
parent = self.node_index[parent_index... | StarcoderdataPython |
83717 | """A collection of simple bandit algorithms for comparison purposes."""
import math
from collections import defaultdict
from typing import Any, Dict, Tuple, Sequence, Optional, cast, Hashable
from coba.simulations import Context, Action
from coba.statistics import OnlineVariance
from coba.learners.core import Learne... | StarcoderdataPython |
3558323 | # -*- coding: utf-8 -*-
import click
from loguru import logger
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
@click.command()
def make():
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logge... | StarcoderdataPython |
5169415 | """
author: @endormi
Small script to check computer memory (total, available, usage, used and free)
"""
import psutil
file = 'file.txt'
mem = psutil.virtual_memory()
print(str(mem) + '\n')
print('Total memory: ' + str(mem.total))
print('Available memory: ' + str(mem.available))
print('Memory usage: ' + str(mem.... | StarcoderdataPython |
3254199 | <reponame>polkapolka/pybay
from django.db import models
from django.utils import timezone
class Countdown(models.Model):
title = models.TextField(help_text="Text above the countdown")
date = models.DateTimeField(help_text="The date the countdown counts to")
cta = models.TextField(help_text="Text on the bu... | StarcoderdataPython |
8065678 | <gh_stars>10-100
# src: https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/decoders/decoder.py
import torch
import torch.nn as nn
from neuroir.decoders.decoder import RNNDecoderBase
from neuroir.utils.misc import aeq
class RNNDecoder(RNNDecoderBase):
"""
Standard fully batched RNN decoder with ... | StarcoderdataPython |
11397578 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def circle(rad):
p_circle = rad * rad * 3.14
return p_circle
def cylinder():
radius = float(input("Радиус цилиндра: "))
height = float(input("Высота цилиндра: "))
mes = input("Для вывода площади боковой поверхности"
" введиите 1\nДл... | StarcoderdataPython |
3499377 | <filename>examples/basic_auth/app_oldap.py
from flask import Flask, g, request, session, redirect, url_for
from flask_simpleldap import LDAP
app = Flask(__name__)
app.secret_key = 'dev key'
app.debug = True
app.config['LDAP_OPENLDAP'] = True
app.config['LDAP_OBJECTS_DN'] = 'dn'
app.config['LDAP_REALM_NAME'] = 'OpenLD... | StarcoderdataPython |
11317089 | <filename>webstruct/webannotator.py
"""
:mod:`webstruct.webannotator` provides functions for working with HTML
pages annotated with WebAnnotator_ Firefox extension.
.. _WebAnnotator: https://github.com/xtannier/WebAnnotator
"""
from __future__ import absolute_import
import re
import warnings
import random
import itert... | StarcoderdataPython |
11381767 | """Morse potential dataset tests.
Scientific Machine Learning Benchmark:
A benchmark of regression models in chem- and materials informatics.
(c) <NAME> 2019, Citrine Informatics.
"""
def test_morse_potential_examples():
"""Tests instantiating Morse potential datasets."""
from smlb.datasets.synthetic.morse... | StarcoderdataPython |
6443942 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | StarcoderdataPython |
240033 | from mx.Proxy import WeakProxy
o = []
p = q = WeakProxy(o)
p = q = WeakProxy(o)
del o
print p
| StarcoderdataPython |
43990 | <gh_stars>0
"""Elliptic Curve Method using Montgomery Curves.
"""
import random
import time
from math import gcd
import numpy as np
from wheel_sieve.common import (
PRIME_GEN,
InverseNotFound,
CurveInitFail,
inv,
init_wheel,
)
def get_curve_suyama(sigma, n):
"""Given parameter sigma, generate ... | StarcoderdataPython |
5111694 | import requests
from Services.ApiAddressService import ApiAddressService
from Services.StorageCookieService import StorageCookieService
class FriendShipApiService(object):
def __init__(self):
self.apiaddress = ApiAddressService()
self.storagecookie = StorageCookieService()
def Mine(self):
... | StarcoderdataPython |
103573 | -- 코드를 입력하세요
SELECT c_p.cart_id as CART_ID ,if(sum(price)>minimum_requirement,0,1) as abused
from Cart_products as c_p join coupons as c
where c_p.cart_id = c.cart_id
group by c_p.cart_id;
| StarcoderdataPython |
9626554 | #!/usr/bin/env python
#
# Copyright 2007 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | StarcoderdataPython |
11215906 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
# -*- coding: utf-8 -*-
#
# Get-OTX-IOCs
# Retrieves IOCs from Open Threat Exchange
#
# Create an account and select your feeds
# https://otx.alienvault.com
#
# Changes:
# 16.12.2017 - Merged the changes by Scott with the code base
# 22.11.2017 - <NAME> <EMAIL>
# 13.02... | StarcoderdataPython |
1846634 | # -*- coding: utf-8 -*-
from sqlalchemy import Column, ForeignKey
from sqlalchemy import String
from sqlalchemy.orm import relationship
from app.model import Base
class HoloMemberTwitterUrl(Base):
__tablename__ = 'holo_member_twitter_url'
holo_member_tweet_id = Column(String(50), ForeignKey('holo_member_tw... | StarcoderdataPython |
246766 | import pymath
radius = float(input())
time = float(input())
cycles = float(input())
print("tangental speed = {}".format(pymath.physics.tangental_speed(radius, time, cycles)))
| StarcoderdataPython |
11341297 | import json
import subprocess
import os
import time
local = True
pool = []
run_server = "sudo docker exec -i participant ./bin/prac-server -node=co -preload -addr="
run_rl_server_cmd = "python3 downserver/main.py "
protocols = ["rac", "3pc", "2pc"]
logf = open("./tmp/progress.log", "w")
logf = open("./tmp/progress.lo... | StarcoderdataPython |
8075110 | <reponame>nsmai/2021-proejct-2
import tensorflow as tf
from tensorflow import keras
### Coefficient of Determination (결정계수)
### 결정계수 위키(영문) https://en.wikipedia.org/wiki/Coefficient_of_determination
### 결정계수 위키(국문) https://ko.wikipedia.org/wiki/%EA%B2%B0%EC%A0%95%EA%B3%84%EC%88%98
### 결정계수는 0~1 사이로 정의되나,
### 0미만의 값이... | StarcoderdataPython |
8043121 | # TODO Move to regex
REGEX_SUFFIX = r"\s*=[^\r\n]*"
PHP_ORIGIN = (
f"file_uploads{REGEX_SUFFIX}",
f"allow_url_fopen{REGEX_SUFFIX}",
f"memory_limit{REGEX_SUFFIX}",
f"upload_max_filesize{REGEX_SUFFIX}",
f"cgi.fix_pathinfo{REGEX_SUFFIX}",
f"max_execution_time{REGEX_SUFFIX}",
f"date.timezone{RE... | StarcoderdataPython |
199349 | <gh_stars>1-10
# coding=utf-8
# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... | StarcoderdataPython |
8082107 | # -*- coding: UTF-8 -*-
import networkx as nx
import numpy as np
import pandas as pd
import os
os.chdir(os.getcwd())
def build_graph(edge_file_path):
'''
Reads the input network using networkx.
'''
G = nx.read_edgelist(edge_file_path, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph()... | StarcoderdataPython |
354884 | <reponame>davegallant/tokenizer
#!/usr/bin/env python3
"""
The main entry point. Invoke as `aws-role-play' or `python -m aws-role-play'.
"""
from .cli import cli
def main():
cli(ctx=None)
if __name__ == "__main__":
main()
| StarcoderdataPython |
4965598 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='MDS',
ext_modules=[
CUDAExtension('MDS', [
'MDS_cuda.cu',
'MDS.cpp',
]),
],
cmdclass={
'build_ext': BuildExtension
}) | StarcoderdataPython |
8113817 | """Tests for the Airplane geometry class."""
# pylint: disable=redefined-outer-name
import machup.geometry as geom
import numpy as np
import pytest
@pytest.fixture
def single_wing_plane():
"""Return a plane for the single_wing.json example."""
filename = "test/geometry/testairplanes/single_wing.json"
pla... | StarcoderdataPython |
349505 | <reponame>cliffordlab/Sedline-Root-EEG-Toolbox
#
# REPO:
# https://github.com/cliffordlab/Sedline-Root-EEG-Toolbox
#
# ORIGINAL SOURCE AND AUTHORS:
# <NAME>
# Last Modified: January 14th, 2021
#
# COPYRIGHT (C) 2021
# LICENSE:
# This software may be modified and distributed u... | StarcoderdataPython |
11342972 | from .echogram import EchoGram
| StarcoderdataPython |
6491577 | import numpy as np
def convert_rsd_batch(batch, device=None):
"""Convert a batch of RSD data to the format the RSD model works with.
Parameters
----------
batch : list
List of dictionaries.
device : str, optional
The device to use (default: None).
Returns
-------
Dict... | StarcoderdataPython |
1724298 | import cv2
import numpy as np
from matplotlib import pyplot as plt
def read_data():
left = "tsukuba-imL.png"
right = "tsukuba-imR.png"
img_left = cv2.cvtColor(cv2.imread(left), cv2.COLOR_BGR2GRAY)
img_right = cv2.cvtColor(cv2.imread(right), cv2.COLOR_BGR2GRAY)
return left, right
if __name__ == "... | StarcoderdataPython |
9782168 | #!/usr/bin/python3
import operator
import sys, os
import json
import math
sys.path.append("..")
sys.path.append(os.getcwd())
import log
import hashlib
import traceback
import datetime
import sqlalchemy
import stmanage
import requests
import comm
import comm.error
import comm.result
import comm.values
from comm.result i... | StarcoderdataPython |
3260843 | <gh_stars>0
import pymysql
import config
def connection():
conn = pymysql.connect(host='localhost',
user=config.USER,
password=<PASSWORD>,
db='SuplDB',
charset='utf8mb4')
c = conn.cursor()
sq... | StarcoderdataPython |
3436907 | <gh_stars>0
# -*- coding: utf-8 -*-
from .object import Object
from .member import Member
from datetime import datetime
from .content import Content
class Message(Object):
"""Represents a Spectrum message object
Supported Operations:
+-----------+-----------------------------------------+
| ... | StarcoderdataPython |
3272652 | <gh_stars>1-10
import socket
import sys
import time
import traceback
import struct
CAN_MESSAGE_LENGTH = 25
MAX_UDP_SIZE = 1400 # This should match the programming on the node
PORT = 59581
node_adresses = {11:"192.168.1.2",
0:"192.168.1.5"}
# SOCK_DGRAM is the socket type to use for UDP sockets
serv... | StarcoderdataPython |
1895871 | from src.config import CENSUS_KEY
import json
import requests
import numpy as np
import pandas as pd
from numpyencoder import NumpyEncoder
# from numpy.lib.function_base import quantile
def get_census_response(table_url, get_ls, geo):
'''
Concatenates url string and returns response from census api query
... | StarcoderdataPython |
3208442 | # Copyright (c) 2018, ZIH, Technische Universitaet Dresden, Federal Republic of Germany
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the a... | StarcoderdataPython |
8021347 | <gh_stars>0
from collections import deque
from typing import Dict, NewType, Optional, Protocol, Tuple, Tuple, TypeVar, Union, List
# NOTE TO tree: TOPLEFT = (0, 0)
"""
y1
(0, 0) ------- (0, 5)
| |
x1 | | x2
-------
(0, 5) (5, 5)
... | StarcoderdataPython |
1924255 | """
Multi-job exceptions
"""
from multi_job.utils.colours import fail
from multi_job.utils.emojis import FIRE
class PrettyException(Exception):
def __init__(self, message):
pretty_msg = f"\n{FIRE}{fail('Oh my!')}{FIRE}\n{message}"
super().__init__(pretty_msg)
class ParserValidationError(PrettyE... | StarcoderdataPython |
4840873 | <filename>src/sentry/api/serializers/models/deploy.py
from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import Deploy, Environment
@register(Deploy)
class DeploySerializer(Serializer):
def get_attrs(self, item_list, user, *args, **kwargs):
e... | StarcoderdataPython |
11386646 | import robin_stocks as r
import os
import datetime
import time as t
'''
This is an example script that will print out options data every 10 seconds for 1 minute.
It also saves the data to a txt file. The txt file is saved in the same directory as this code.
'''
#!!! Fill out username and password
username = ''
passwo... | StarcoderdataPython |
9744908 | <reponame>brown170/fudge
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This is the 'Properties of Particles' or PoPs package. It defines a set of Python classes
for st... | StarcoderdataPython |
196526 | import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
from scipy import ndimage as ndi
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from sklearn.cluster import MeanShift
from PIL import Image
size = 100, 100
img_names = ["../Images/Segmentation/strawberry.png"... | StarcoderdataPython |
6419326 | <gh_stars>1-10
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
from django.core.exceptions import ValidationError
from .models import Admin
def validate_email_auth(value):
email = value
try:
Admin.objects.get(email=email)
except:
raise ValidationError("The email is incorr... | StarcoderdataPython |
4986738 | from setuptools import setup, find_packages
with open("README.md","r") as fh:
long_description = fh.read()
setup(
name='EMeRGE',
long_description=long_description,
long_description_content_type="text/markdown",
version='v1.5.1',
description='Emerging technologies Management and Risk evaluation... | StarcoderdataPython |
8011978 | <reponame>Ronlin1/switch-case-in-python
def Sunday():
return "Sunday"
def Monday():
return "Monday"
def Tuesday():
return "Tuesday"
def Wednesday():
return "Wednesday"
def Thursday():
return "Thursday"
def Friday():
return "Friday"
def Saturday():
return "Saturday"
... | StarcoderdataPython |
3523243 | #total = 0
#for num in range(101):
# total = total + num
#print(total)
print('My name is')
i = 0
while i < 5:
print('<NAME> Times (' + str(i) + ')')
i = i + 1
| StarcoderdataPython |
1689685 | import uvicorn
if __name__ == "__main__":
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
# WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.
def develop(app):
uvicorn.run('blogsley:app', host="0.0.0.0", port=800... | StarcoderdataPython |
8081143 | <gh_stars>0
"""
This script creates a test that fails when garage.tf.algos.TNPG performance is
too low.
"""
from garage.baselines import LinearFeatureBaseline
from garage.envs import normalize
from garage.envs.box2d import CartpoleEnv
import garage.misc.logger as logger
from garage.tf.algos import TNPG
from garage.tf.e... | StarcoderdataPython |
3438672 | <reponame>obyrned1/ledGrid
'''This is the test file'''
import sys
sys.path.append('.')
from ledGrid.main import *
def test_file_exists():
test_file = "http://claritytrec.ucd.ie/~alawlor/comp30670/input_assign3_d.txt"
# give a test file for testing. Will return error if it's not a real link
assert file_ex... | StarcoderdataPython |
11352832 | import os
import platform
import json
from random import choice
def clear():
"""Clear terminal."""
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def show_header(disp_width=79):
"""Show the program header."""
program_name = "QUARANTINE Movie S... | StarcoderdataPython |
9605291 | <filename>src/configs/configure.py
# First import the library
import pyrealsense2 as rs
import time
import json
from src.Globals import constants
import numpy as np
class CameraHandler:
__instance = None
@staticmethod
def get_instance():
""" Static access method. """
if CameraHandler.__i... | StarcoderdataPython |
12822839 | """
.. _basic_plotting:
Review of available plotting commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This example lists the different plotting commands available,
shown with the arguments available.
"""
from ansys.dpf import core as dpf
from ansys.dpf.core import examples
# from ansys.dpf.core.plotter import plot_cha... | StarcoderdataPython |
5049456 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2021) Hewlett Packard Enterprise Development LP
#
# 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/L... | StarcoderdataPython |
317833 | <reponame>AhKiu69/hotpoor_autoclick_xhs
from random import randrange
title = 'asdfghjkl;'
a = randrange(0 , (len(title)-1))
title = title.replace(title[a],'口红',1)
print(a)
print(title) | StarcoderdataPython |
5081884 | from datetime import datetime, timedelta
import pytest
from marshmallow import ValidationError
from app.constants import STATUS_MAP
from app.schemas import MessageSchema, UserSchema
def test_user_empty_data():
try:
UserSchema().load({})
except ValidationError as exc:
assert exc.messages == {... | StarcoderdataPython |
8134137 | import scrapy
import re
import time
import sys
class CondosSpider(scrapy.Spider):
name = "condos"
def start_requests(self):
# url = "https://www.livinginsider.com/searchword/Condo/Buysell/1/%E0%B8%A3%E0%B8%A7%E0%B8%A1%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%81%E0%B8%B2%E0%B8%A8-%E0%B8%82%E0%B8%B2%E0%B8%A2-%... | StarcoderdataPython |
4901502 | import json
from collections import defaultdict
import utils
"""
createTreeFromEdges constructs a directed graph structure from a set of directed edges and a set of vertices. The set
of edges and vertices used must contain a single root vertex.
"""
def createTreeFromEdges(edges, vertices, group, project, sub_node_lab... | StarcoderdataPython |
11318895 | <gh_stars>1-10
import os
import jinja2
from docx.shared import Mm
from docxtpl import DocxTemplate, InlineImage
from app.utils.docx.report_utils import li_multiple_plot, get_result, get_multiple_iback, sand_area_contraction
from config import Config
def set_sand_docxtpl(dict_data, location=''):
ites = dict_data... | StarcoderdataPython |
1959279 | <reponame>aditya-prasad-projects/Deep-Semantic-Code-Search
import ast
import sys
class ASTVisitor(ast.NodeVisitor):
def __init__(self):
self.api_seq = []
def visit(self, node):
if node is None:
return
return super().visit(node)
def visit_Assign(self, node):
fo... | StarcoderdataPython |
4955850 | import os.path as osp
import os
import scipy.io as scio
import cv2
from PIL import Image
from tqdm import tqdm
def parse_pascal_voc_aug(pth):
out_pth = osp.join(pth, 'VOC_AUG')
ds_pth = osp.join(pth, 'benchmark_RELEASE/dataset')
labels_pth = osp.join(ds_pth, 'cls')
lbmats = os.listdir(labels_pth)
... | StarcoderdataPython |
12852817 | # Copyright (c) 2017 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... | StarcoderdataPython |
3443470 | <reponame>ihaywood3/twsmb<filename>ntlm.py
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""Implement the NT Lan Manager (NTLMv2) challenge/response authentication
protocol
"""
from __future__ import absolute_import, division
from zope.interface import implementer, Interface
import struct... | StarcoderdataPython |
11383896 | # /* === 🌌 WELCOME TO ORBIT NEXT FRAMEWORK 🌌 ===
# *
# * By :
# *
# * ██████╗ ██████╗ ██████╗ ██╗████████╗ ████████╗██╗ ██╗██████╗ ███╗ ██╗███████╗██████╗
# * ██╔═══██╗██╔══██╗██╔══██╗██║╚══██╔══╝ ╚══██╔══╝██║ ██║██╔══██╗████╗ ██║██╔════╝██╔══██╗
# * ██║ ██║████... | StarcoderdataPython |
9614522 | <reponame>J0sueTM/Competitive-Programming<filename>Implementation/Mathematics/BasicMath/python/gcd.py
import math
def gcdpf(a, b):
if a == 0:
return b
if b == 0:
return a
if a == b:
return a
if a > b:
return gcdpf(a - b, b)
else:
return gcdpf(a, b - a)
def ... | StarcoderdataPython |
8012327 | import numpy as np
import torch
import torch.nn as nn
from model.backboneModel import EfficientNet,YOLOLayer,BasicBlock
class AutoNet(nn.Module):
def __init__(self, batch_size, step_size, anchors, detection_classes,freeze=False, device=None):
self.latent = 1000
self.fc_num = 400
self.batch... | StarcoderdataPython |
1975379 | <reponame>rdius/Corpus_builder_app<filename>app_collect.py
# Core pkgs
import streamlit as st
import altair as alt
## EDA Pkgs
import base64
import json
import jsonlines
import pandas as pd
import os
import numpy as np
import sys
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from wordcloud import W... | StarcoderdataPython |
6529574 | <filename>setup.py
from distutils.core import setup
with open('README.rst') as f:
readme = f.read()
setup(
name='pyvsc',
version='0.1',
description='VSC Losses Electrothermal Model',
long_description=readme,
author='<NAME>',
author_email='<EMAIL>',
packages=['pyvsc', 'pyvsc.tests'],
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.