id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
115686 | from utils.models import LinkedListNode
def merge_two_sorted_lists(l1: LinkedListNode, l2: LinkedListNode) -> LinkedListNode:
temp_head = tail = LinkedListNode(data=0)
while l1 and l2:
if l1.data < l2.data:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
... | StarcoderdataPython |
3324020 | <filename>scrapers/scraper_primorske.py
import requests
from bs4 import BeautifulSoup as bs
import hashlib
from database.dbExecutor import dbExecutor
import datetime
import sys
from tqdm import tqdm
import re
"""
formatDate ni uporaben, datum je na strani ze v pravi obliki
napake, so verjetno zaradi praznih... | StarcoderdataPython |
127827 | <reponame>bcgov/CIT<gh_stars>1-10
from django.contrib.gis.db import models
from django.contrib.gis.db.models import MultiPolygonField
from django.contrib.gis.geos import Point
from pipeline.constants import WGS84_SRID
class HealthAuthorityBoundary(models.Model):
NAME_FIELD = "HLTH_AUTHORITY_NAME"
hlth_autho... | StarcoderdataPython |
91761 | <reponame>kponder/astrorapid
import numpy as np
def find_nearest(array, value):
"""
Find the index nearest to a given value.
Adapted from: https://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
"""
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
re... | StarcoderdataPython |
3350183 | <filename>src/help_command.py
"""help command functionality"""
import os
import discord
from discord import Embed
Test_bot_application_ID = int(os.getenv('TEST_BOT_APP_ID'))
###########################
# Function: helper
# Description: Directs the help functions when called
# and is executes !help command
# Inputs:
... | StarcoderdataPython |
3296020 | <gh_stars>10-100
import numpy as np
import itertools
import os
A_DIM = 6
BITRATE_LEVELS = 6
class VideoLoader:
def __init__(self, filename):
self.filename = filename
self.video_size = {} # in bytes
self.vmaf_size = {}
self.VIDEO_BIT_RATE = [375, 750, 1050, 1750, 3000... | StarcoderdataPython |
128951 | # import the pandas, os, and sys libraries and load the nls and covid data
import pandas as pd
import os
import sys
import pprint
nls97 = pd.read_pickle("data/nls97f.pkl")
covidtotals = pd.read_pickle("data/covidtotals720.pkl")
# import the outliers module
sys.path.append(os.getcwd() + "/helperfunctions")
import outli... | StarcoderdataPython |
1636222 | <reponame>36000/cnn_colorflow<gh_stars>0
import numpy as np
import sys
import os
from keras.models import load_model
sys.path.append("../utilities")
import constants
from data import get_train_test
from metrics import plot_n_roc_sic
datasets_c = ['h_qq_rot_charged', 'h_gg_rot_charged', 'cp_qq_rot_charged', 'qx_qg_rot... | StarcoderdataPython |
3351934 | # source:https://github.com/zhuogege1943/dgc/blob/439fde259c/layers.py
# arxiv:https://arxiv.org/abs/2007.04242
import torch
import torch.nn as nn
import torch.nn.functional as F
class DynamicMultiHeadConv(nn.Module):
global_progress = 0.0
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
... | StarcoderdataPython |
107325 | <filename>u8timeseries/tests/test_timeseries.py<gh_stars>1-10
import unittest
import pandas as pd
from timeseries import TimeSeries
class TimeSeriesTestCase(unittest.TestCase):
__test__ = True
pd_series1 = pd.Series(range(10), index=pd.date_range('20130101', '20130110'))
series1: TimeSeries = TimeSeries... | StarcoderdataPython |
3326419 | <filename>tests/test_handshake.py<gh_stars>10-100
import unittest
import sys
import os
proj_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
socket_folder = os.path.join(proj_folder, 'websocket')
sys.path.insert(0, socket_folder)
import websock as WS
class TestHandShake(unittest.TestCase):
... | StarcoderdataPython |
1721269 | <reponame>JuliaHuck/nighres
from nighres.microscopy.mgdm_cells import mgdm_cells
from nighres.microscopy.stack_intensity_regularisation import stack_intensity_regularisation
| StarcoderdataPython |
3253106 | <reponame>quick-sort/scrapy-spiders
# -*- coding: utf-8 -*-
from scrapy import Spider
from scrapy.utils.spider import iterate_spider_output
from scrapy.exceptions import NotConfigured, NotSupported
import xlrd
import logging
logger = logging.getLogger(__name__)
def xlsiter(response, headers = None, sheet_index = 0):
... | StarcoderdataPython |
1640170 | <filename>django/tango_with_django_project/__init__.py
__author__ = 'matheuskonzeniser'
| StarcoderdataPython |
3215067 | # coding=utf-8
# pynput
# Copyright (C) 2015-2017 <NAME>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# Th... | StarcoderdataPython |
1761165 | <reponame>gollum18/enterprise-db-systems-labs
from . import app
import os
def main():
# setup the flask environment variables
os.putenv("FLASK_APP", "company-app")
os.putenv("FLASK_ENV", "development")
# start the flask app
app.create_app().run()
if __name__ == '__main__':
main()
| StarcoderdataPython |
1636540 | from typing import Dict
import math
import numpy as np
import os
import json
import time
# ROS
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState, LaserScan, Imu
from geometry_msgs.msg import Pose, Twist, Quaternion, Transform, Point, Vector3
from nav_msgs.msg import Odometry
import tf2_ro... | StarcoderdataPython |
4824516 | <filename>lib/surface/logging/cmek_settings/describe.py
# -*- coding: utf-8 -*- #
# Copyright 2019 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... | StarcoderdataPython |
1701017 | <reponame>fossabot/hotpot
import config
import fasttext
import numpy as np
import pandas as pd
from annoy import AnnoyIndex
from gensim.models import KeyedVectors
from scipy.spatial import cKDTree
from tqdm import tqdm
# ============================================================
# Script purpose:
# Use nearest-neigh... | StarcoderdataPython |
3217479 | # -*-coding:utf-8-*-
import cv2
import numpy as np
import os
"""
이 스크립트는 기본적으로 수집한 원본 데이터를 기반으로 데이터 증가 작업을 수행하여
딥러닝 모델이 학습 할 수 있는 데이터셋을 늘리기 위한 스크립트이다.
openCV 라이브러리를 직접 사용하여 이미지 수정 및 저장을 하였으나, 나중에 찾아보니
Keras 에서는 ImageGenerator를 사용해서 유사한 작업을 할 수 있다고 한다... ㅎ
"""
TS_PATH = "C:\\Users\\dry8r3ad\\PycharmProjects\\catBreedC... | StarcoderdataPython |
61888 | <gh_stars>0
# -------------------------------------------------------------------------
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
# ----... | StarcoderdataPython |
3248459 | '''
* publisher
*
* Copyright (c) 2020-2021, Magik-Eye Inc.
* author: <NAME>, <EMAIL>
'''
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import PointCloud2, PointField
from std_msgs.msg import String
import threading
import time
import pymkeapi
import numpy as np
from pymkeros2.device_info import Device... | StarcoderdataPython |
1737008 | import sys
import time
from neopixel import *
# Read percentage value passed to script when called.
input = sys.stdin.readline().rstrip('\n')
percents = input.split(',')
dlPercent = float(percents[0])+0.5
ulPercent = float(percents[1])+0.5
dlMax = int(dlPercent * 0.55)
ulMax = 120 - int(ulPercent * 0.55)
print dlMax,... | StarcoderdataPython |
3270304 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: kingofwolf
# @Date: 2018-11-20 18:34:53
# @Last Modified by: kingofwolf
# @Last Modified time: 2019-03-21 10:45:17
# @Email: <EMAIL>
'Info: a Python file '
__author__ = 'Wang'
TASK_FILE_MODE=1
# when this equals 0:
#task file like:
# # 0
# 1 1774760
# 8 341... | StarcoderdataPython |
3283710 | <filename>bsbolt/Utils/ParserHelpMessages.py<gh_stars>1-10
alignment_help = '''
bsbolt Align -F1 {fastq1} -DB {bsbolt db} -O {output}
-h, --help show this help message and exit
Input / Output Options:
-F1 File path to fastq 1
-F2 File path to fastq 2 [null]
-O File output Prefix
-OT Int n... | StarcoderdataPython |
3211425 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-07 10:07
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0004_message_last_reply_date'),
]
operations = [
migrations.AlterUniqueTogeth... | StarcoderdataPython |
1798712 | """
Flask-MAB
-------------
An implementation of the multi-armed bandit optimization pattern as a Flask extension
If you can pass it, we can test it
"""
from setuptools import setup
setup(
name='Flask-MAB',
version='2.0.1',
url='http://github.com/deacondesperado/flask_mab',
license='BSD',
author='... | StarcoderdataPython |
1727618 |
# Copyright (c) 2012, <NAME> [see LICENSE.txt]
# Python 2 to 3 workarounds
import sys
if sys.version_info[0] == 2:
_strobj = str
_xrange = xrange
elif sys.version_info[0] == 3:
_strobj = str
_xrange = range
import os
import pylab
import numpy as np
from collections import Counter
from pyvttbl.... | StarcoderdataPython |
4836167 | <reponame>trucktar/inquisitive
from datetime import datetime, timedelta
import jwt
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
class UserManager(BaseUserManager):
def create_user(self, username, email, password, **extra_fi... | StarcoderdataPython |
3275752 | from django.conf.urls import url
urlpatterns = [
url(r'^list/$', 'screenshots_listing', prefix='crits.screenshots.views'),
url(r'^list/(?P<option>\S+)/$', 'screenshots_listing', prefix='crits.screenshots.views'),
url(r'^add/$', 'add_new_screenshot', prefix='crits.screenshots.views'),
url(r'^find/$', 'f... | StarcoderdataPython |
1619082 | import os
import sys
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
from tools.path import ILSVRC2012_path
from simpleAICV.classification import backbones
from simpleAICV.classification import losses
import torchvision... | StarcoderdataPython |
1667539 | <reponame>andrewnc/geometric-neural-processes
from skimage.transform import resize
import matplotlib.pyplot as plt
import numpy as np
import os
from tqdm import tqdm
#for f in tqdm(os.listdir("./train2014")):
# image = plt.imread("./train2014/{}".format(f))
# resized = resize(image, (32,32), anti_aliasing=True)
... | StarcoderdataPython |
3396143 | <reponame>GravYong/scalarized_ns<gh_stars>0
""" A quadratic scalar-tensor theory
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "GPL"
import numpy as np
class STG_quadratic(object):
""" The quadratic scalar-tensor theory defined in
Damour & Esposito-Farese 1996
"""
def __init__(s... | StarcoderdataPython |
1682444 | import proverb
def main():
print(proverb.saying())
| StarcoderdataPython |
3292188 | from pyfirmata import Arduino, util
import time
import argparse
import yaml
import logging.config
config = None
with open('config.yml') as f:
config = yaml.load(f)
config['logging'].setdefault('version', 1)
logging.config.dictConfig(config['logging'])
logger = logging.getLogger(__name__)
logger.debug('Using con... | StarcoderdataPython |
3268272 | import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.cm as mplcm
import matplotlib.colors as colors
from utils.embedding import *
from utils.geometry import *
from utils.constants import *
from shapely.geometry import Point, LineString, Polygon, LinearRing
chip_1, chip_2, connections... | StarcoderdataPython |
153368 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import mptt.fields
import django.db.models.deletion
import yepes.fields
class Migration(migrations.Migration):
dependencies = [
('posts', '0001_initial_schema'),
]
initial = True
operat... | StarcoderdataPython |
1708049 | import numpy as np
from nose.plugins.attrib import attr
from cStringIO import StringIO
from nose.tools import raises
from microscopes.lda import utils
def test_docs_from_document_term_matrix():
dtm = [[2, 1], [3, 2]]
docs = [[0, 0, 1], [0, 0, 0, 1, 1]]
assert utils.docs_from_document_term_matrix(dtm) == ... | StarcoderdataPython |
1623066 | import redis
from board import Board
class RedisBoard(Board):
"""This will create a message board that is backed by Redis."""
def __init__(self, *args, **kwargs):
"""Creates the Redis connection."""
self.redis = redis.Redis(*args, **kwargs)
def set_owner(self, owner):
self.owner ... | StarcoderdataPython |
1790834 | u = 0.5*sin(2*pi*x)+1
| StarcoderdataPython |
1662938 | <filename>libraries/stats/widgets/RedRvar_test.py<gh_stars>1-10
"""F Test widget
.. helpdoc::
Performs the F-test on connected data.
"""
"""<widgetXML>
<name>F Test</name>
<icon>default.png</icon>
<summary>Performs an F test.</summary>
<tags>
<tag priority="10">
Stats... | StarcoderdataPython |
1651316 | <filename>core/emri/data_proc.py
import SimpleITK as sitk # For loading the dataset
import numpy as np # For data manipulation
import glob # For populating the list of files
from scipy.ndimage import zoom # For resizing
import re # For parsing the filenames (to know their modality)
import cv2 # For processing imag... | StarcoderdataPython |
129821 | <filename>src/pyglue/DocStrings/ExceptionMissingFile.py
class ExceptionMissingFile:
"""
An exception class for errors detected at runtime, thrown when OCIO cannot
find a file that is expected to exist. This is provided as a custom type to
distinguish cases where one wants to continue looking for missin... | StarcoderdataPython |
167177 | import copy
import os
import torch
import torchvision
import warnings
import math
import utils.misc
import numpy as np
import os.path as osp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import models.modified_resnet_cifar as modified_resnet_cifar
import models.modified_resnetmtl_cif... | StarcoderdataPython |
1793359 | #!python3
#encoding:utf-8
import dataset
import time
import random
class Language:
def __init__(self, db_path_repo):
self.db_repo = dataset.connect('sqlite:///' + db_path_repo)
"""
Insert programming language information for each GitHub repository into the database.
@params [dict] langs is [Lis... | StarcoderdataPython |
1752421 | <reponame>WiitterSimithYU/-scollview-imissMusic
import uuid
import os
# 管理平台上传图片
def user_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid.uuid4().hex[:10], ext)
str = os.path.join("music", filename)
return str
# 保存APP上传的图片
def upload_image(f, song):
... | StarcoderdataPython |
3369381 | <reponame>stefan-feltmann/lands
"""
This file contains all possible Biome as separate classes.
"""
import re
def _un_camelize(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
class _BiomeMetaclass(type):
def __new__(mcs, name, parents, dct... | StarcoderdataPython |
67496 | #Type of sequence multiplier must be constant
from polyphony import testbench
def list_multiplier(x):
l = [1, 2, 3] * x
return l[0]
@testbench
def test():
list_multiplier(5)
test() | StarcoderdataPython |
75799 | <reponame>osaaso3/brainiak
# The following code is designed to perform a searchlight at every voxel in the brain looking at the difference in pattern similarity between musical genres (i.e. classical and jazz). In the study where the data was obtained, subjects were required to listen to a set of 16 songs twice (two ru... | StarcoderdataPython |
65169 | <gh_stars>1000+
#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for the cmd_helper module."""
import unittest
import subprocess
import sys
import time
from devil import dev... | StarcoderdataPython |
3348667 | <filename>c7n/resources/dynamodb.py
# Copyright 2016-2019 Capital One Services, 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 r... | StarcoderdataPython |
72802 | <filename>justvpn/util.py
import re
import os
from urllib.parse import urlparse
| StarcoderdataPython |
3234099 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
def customise(process):
# process.dtDataIntegrityUnpacker.inputLabel = cms.untracked.InputTag('rawDataCollector')
# process.DQMOfflineCosmics.remove(process.hcalOfflineDQMSource)
# process.load("FWCore.Modules.printContent_cfi")
# proc... | StarcoderdataPython |
3331745 | __author__ = "<NAME>"
__version__ = '0.3.0'
from log_calls import log_calls
import doctest
##############################################################################
# doctests
##############################################################################
#=======================================================... | StarcoderdataPython |
1781981 | <filename>examples/eager_examples/scripts/example_switch_engine.py
#!/usr/bin/env python3
# ROS packages required
import rospy
from eager_core.eager_env import BaseEagerEnv
from eager_core.objects import Object
from eager_core.wrappers.flatten import Flatten
from eager_bridge_webots.webots_engine import WebotsEngine ... | StarcoderdataPython |
3225342 | #-------------------------------------------------------------------------------
# Name: Pet_Game.py
# Purpose: To create a class to play with a virtual pet!
#
# Author: odanielb, <NAME>
#
# Acknowledgements:
# The following images were borrowed and then edited:
# Shop: https://cdn2.iconfinder.com/data/i... | StarcoderdataPython |
1740239 | <reponame>rgerkin/pyrfume
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %l... | StarcoderdataPython |
67057 | from pyinaturalist.constants import PROJECT_ORDER_BY_PROPERTIES, JsonResponse, MultiInt
from pyinaturalist.converters import convert_all_coordinates, convert_all_timestamps
from pyinaturalist.docs import document_request_params
from pyinaturalist.docs import templates as docs
from pyinaturalist.pagination import add_pa... | StarcoderdataPython |
1736910 | # import argparse
import boto3
import ffmpeg
import json
import logging
import os
import posixpath
import sys
import tarfile
import tempfile
from concurrent.futures import ThreadPoolExecutor
def extract_frames(in_filename, out_directory, fps=1, height=720):
print("\n\n\n{}\n\n\n".format(os.listdir("./")))
(
... | StarcoderdataPython |
24338 | <gh_stars>0
import os
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import config
def view_data():
nrows, ncols = 3, 3
pic_index = 0
fig = plt.gcf()
fig.set_size_inches(nrows * 4, ncols * 4)
pic_index = 2
next_rock = [os.path.join(config.TRAIN_DIR, 'rock', fname) for fname... | StarcoderdataPython |
3223270 | <filename>src/find_shortest_path.py
'''
Separating code for SRP
'''
import sys
import os
sys.path.append(os.path.dirname(__file__)+"/../")
from src import constants
from src.get_vehicles import getvehicles
from src.find_orbit_time import Orbit
class Shortest:
'''
This class finds the shortest path for the ride... | StarcoderdataPython |
1638213 | <filename>platform/hwconf_data/efr32fg14v/modules/PIN/PIN_Snippets.py
"""
Generated from a template
"""
import efr32fg14v.PythonSnippet.RuntimeModel as RuntimeModel
from efr32fg14v.modules.PIN.PIN_Defs import PORT_PINS
def activate_runtime():
pass
| StarcoderdataPython |
3344827 | from request_log import RequestLogMiddleware
| StarcoderdataPython |
3225660 | <reponame>edrossy/tableau_tools
from tableau_connection import TableauConnection
from tableau_datasource import TableauDatasource
from tableau_parameters import TableauParameters, TableauParameter
from tableau_document import TableauColumns, TableauDocument
from tableau_file import TableauFile
from tableau_workbook imp... | StarcoderdataPython |
1605906 | """adapterpattern
Example to show a Pythonic way of implementing an adapter pattern.
The example shows how to use Python's language feature, first-class
functions, to implement adapter pattern.
This example is created to illustrate a design pattern discussed in the book
Learning Python Application Development (Packt... | StarcoderdataPython |
1643514 | <filename>misc/datatools.py
#!/usr/bin/env python3
import json
from typing import Callable, List
import pandas as pd
from loguru import logger
from .taxonomy import process_keywords_str, process_single_kws
def parse_kws(kw_str, level=2):
res = kw_str.split(",")
res = map(lambda kw: [_.strip().lower() for _... | StarcoderdataPython |
1677447 | <filename>CompareTheTriplets.py
"""
https://www.hackerrank.com/challenges/compare-the-triplets
"""
#!/bin/python3
import sys
a0,a1,a2 = input().strip().split(' ')
a0,a1,a2 = [int(a0),int(a1),int(a2)]
b0,b1,b2 = input().strip().split(' ')
b0,b1,b2 = [int(b0),int(b1),int(b2)]
# Write Your Code Here
"""
alice = 0
bob ... | StarcoderdataPython |
1722486 | <filename>tests/test_git.py
try:
from unittest.mock import patch, MagicMock as Mock
except ImportError:
from mock import patch, MagicMock as Mock
from dulwich.repo import MemoryRepo
from dulwich.objects import Tree, Blob
from gitdb.repo import Data
from gitdb.git import GitRepo
def test_current_commit_is_non... | StarcoderdataPython |
1655831 | <reponame>vadi2/codeql<gh_stars>1000+
# -*- coding: utf-8 -*-
# Autogenerated by Sphinx on Mon May 16 13:41:38 2016
topics = {'assert': '\n' }
| StarcoderdataPython |
130987 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import windtools.util as util
class Weibull(object):
def __init__(self, data, ws_field='ws', wd_field='wd', wd_bin_size=30, ws_bin_size=1, prepare_data=True):
self.data = pd.DataFrame(data)
self.dat... | StarcoderdataPython |
4805463 | <reponame>pkestene/COSMA
#!/usr/bin/env python3
import argparse
import os
import sys
import tempfile
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument(
'prefix',
type=str,
help='Installation prefix for dependencies'
)
args = parser.parse_args()
if not os.path.is... | StarcoderdataPython |
4800935 | # Databricks notebook source
# MAGIC %md
# MAGIC #Import Libraries
# COMMAND ----------
# 0) Import Libraries
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.streaming import StreamingContext
# COMMAND ----------
... | StarcoderdataPython |
38148 | from unittest.mock import patch, MagicMock, call
import json
from datetime import datetime
from copy import deepcopy
import pytest
from PIL import Image
from sm.engine import DB, ESExporter, QueuePublisher
from sm.engine.dataset_manager import SMapiDatasetManager, SMDaemonDatasetManager
from sm.engine.dataset_manager ... | StarcoderdataPython |
3308819 | <reponame>clauddio-silva/ope-1<filename>ope-backend/src/infra/repository/product_order_repository.py
from sqlalchemy.exc import IntegrityError, NoResultFound, MultipleResultsFound
from src.infra.config import DBConnectionHandler
from src.infra.db_entities import Products_Orders as Product_Order
class Product_OrderRep... | StarcoderdataPython |
1740218 | <filename>rbacProject/apps/system/models.py
from django.db import models
from db.baseModel import *
# Create your models here.
class SystemSetup(models.Model):
loginTitle = models.CharField(max_length=20, null=True, blank=True, verbose_name='登录标题')
mainTitle = models.CharField(max_length=20, null=True, blank=... | StarcoderdataPython |
175713 | <reponame>gcollard/lightbus<filename>lightbus/client/commands.py
import logging
from typing import NamedTuple, Optional, List, Tuple
from lightbus.api import Api
from lightbus.message import EventMessage, RpcMessage, ResultMessage
from lightbus.utilities.internal_queue import InternalQueue
logger = logging.getLogger... | StarcoderdataPython |
1734734 | from FichaDB import FichaDB
class Ficha(object):
def __init__(self, lista=None):
if lista is None:
self.lista = [] * 129
self.info = {}
def insertFicha(self):
banco = FichaDB()
try:
c = banco.conexao.cursor()
c.execute(" insert into fich... | StarcoderdataPython |
1603404 | <reponame>samkennerly/suneku<gh_stars>1-10
from setuptools import setup
setup(
author='<NAME>',
author_email='<EMAIL>',
description='Python package which builds its own Docker images.',
name='suneku',
packages=['suneku'],
url='https://github.com/samkennerly/suneku',
version='1.0.0')
| StarcoderdataPython |
92413 | <filename>setup.py
import os
from pathlib import Path
from setuptools import setup, find_packages
# The directory containing this file
here = Path(__file__).parent
# The text of the README file
README = (Path(__file__).parent / "README.md").read_text()
data_files = []
for pipeline in ['fastapi', 'flux_pack', 'libra... | StarcoderdataPython |
50478 | <reponame>aMurryFly/Old_Courses<filename>OOP_Python/4_Jueves/calculos/__init__.py
#Son directorios donde se almacenan módulos
'''
1) Crear una carpeta con un archivo __init__.py <- constructor
'''
| StarcoderdataPython |
3329459 | class Config(object):
# Config.ini 文件目录
INI_PATH = "/etc/radiaTest/messenger.ini"
# 模式
DEBUG = False
TESTING = False
# 日志
LOG_LEVEL = "INFO"
# PXE服务器
# PXE地址(必须配置免密登录,如果和server为同一台机器,则不需要)
# dhcp配置文件
DHCP_CONF = "/etc/dhcp/dhcpd.conf"
# tftp-server 文件存储路径
# TFTP_P... | StarcoderdataPython |
1657540 | # toda variavel pode ser alterada, sempre deve criada em minuscula
# por convensao, variaveis em maiusculas sao como se fosse constantes, nao devem ser alteradas
PI = 3.14
GRAVITY = 9.8
def get_extension(file):
return file[file.index(".") +1:] # pega o nome do arquivo, dentro qual o indice do ponto, e pega do ind... | StarcoderdataPython |
182377 | import cv2
cap = cv2.VideoCapture('image_rec/test_video.mp4')
if (cap.isOpened()== False):
print("Error opening video stream or file")
while cap.isOpened():
ret, image = cap.read()
cv2.imshow('video', image)
# Press Q on keyboard to exit
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cv2... | StarcoderdataPython |
1777976 | _base_ = [
# 'configs/_base_/models/upernet_swin.py',
'configs/_base_/datasets/cityscapes.py',
'configs/_base_/default_runtime.py',
'configs/_base_/schedules/schedule_160k.py'
]
# By default, models are trained on 8 GPUs with 2 images per GPU
data = dict(samples_per_gpu=4)
# model settings
norm_cfg = di... | StarcoderdataPython |
3373369 | from . import input_output
from . import network
from . import plotting
from . import model
from . import simulation
from . import dhn_from_osm
from . import optimization
| StarcoderdataPython |
3310187 | <gh_stars>0
import copy
import datetime
import threading
import time
import uuid
from dateutil.relativedelta import relativedelta
class Scheduler:
thread_dict = dict()
def set_cron(self, timelist, func, *args, **kwargs):
cron_id = uuid.uuid4()
next_dt = datetime.datetime.now() + relativedel... | StarcoderdataPython |
107715 | <reponame>sthagen/pconf
import os
import re
from ast import literal_eval
from warnings import warn
class Env(object):
def __init__(
self,
separator=None,
match=None,
whitelist=None,
parse_values=False,
to_lower=False,
convert_underscores=False,
docke... | StarcoderdataPython |
3300888 | <reponame>Milstein/sorted_containers
# -*- coding: utf-8 -*-
from __future__ import print_function
from sys import hexversion
import random
from .context import sortedcontainers
from sortedcontainers import SortedSet
from nose.tools import raises
from functools import wraps
import operator
if hexversion < 0x03000000... | StarcoderdataPython |
1679793 | def hamming_weight(n: int) -> int:
"""Calculate the number of '1' bit in the given it.
:param int n:
:return: number of '1' bit in the int
"""
weight = 0
while n != 0:
weight += 1
n &= n - 1
return weight
| StarcoderdataPython |
1709892 | from sklearn.externals import joblib
import csv
cls = joblib.load('model.h5')
fo = open("userAgents5.csv", "r")
lines=fo.readlines()
vec = joblib.load('vec_count.joblib')
with open('results_logRegfinal.csv', mode='w') as results_file:
results_writer = csv.writer(results_file, delimiter=',', quotechar='"', quoting=c... | StarcoderdataPython |
114036 | __author__ = 'chris'
"""
Package for holding all of our protobuf classes
"""
| StarcoderdataPython |
3372583 | <reponame>danheath/pykol-lib
from typing import Optional
from dataclasses import dataclass
import libkol
@dataclass
class ItemQuantity:
item: "libkol.Item"
quantity: int
@dataclass
class Listing:
item: Optional["libkol.Item"] = None
price: int = 0
stock: int = 0
limit: int = 0
limit_rea... | StarcoderdataPython |
1702713 | from pkg_resources import iter_entry_points
from typeguard import check_argument_types
from typing import Sequence
nodefault = object()
def traverse(obj, target:str, default=nodefault, executable:bool=False, separator:str='.', protect:bool=True):
"""Traverse down an object, using getattr or getitem.
If ``executa... | StarcoderdataPython |
1726890 | <gh_stars>10-100
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from light_classification.tl_class... | StarcoderdataPython |
3218462 | <gh_stars>10-100
from data_pipeline.pipeline import Pipeline, run_pipeline
from data_pipeline.datasets.gnomad_sv_v2 import prepare_gnomad_structural_variants
pipeline = Pipeline()
###############################################
# Variants
###############################################
pipeline.add_task(
"prep... | StarcoderdataPython |
1793182 | # -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# License URL : https://store.webkul.com/license.html/
# All Rights Reserved.
#
#
#
# This pr... | StarcoderdataPython |
3283403 | <gh_stars>0
import json
import os
import requests
from quart import abort
from src.utils.array_utils import get_nested_value
from time import sleep
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/54.0... | StarcoderdataPython |
1735931 | <filename>dcompy/waitlist.py
"""
Copyright 2021-2021 The jdh99 Authors. All rights reserved.
等待队列
Authors: jdh99 <<EMAIL>>
"""
import dcompy.log as log
from dcompy.block_tx import *
from dcompy.system_error import *
from typing import Callable
import threading
class _Item:
def __init__(self):
self.prot... | StarcoderdataPython |
3203313 | from mathematics import PBox
import numpy as np
class PermutationCipher:
def __init__(self, key: list):
self.pbox = PBox.from_list(key)
self.inverse = self.pbox.invert()
self.columns = len(key)
self.key = np.array(key)
def encrypt(self, plaintext: str) -> str:
P = self... | StarcoderdataPython |
3314815 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# Copyright 2019-2020 Mastercard
# 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 above copyright notice, th... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.