id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
93246 | from collections import defaultdict
def load_words(filename = "words.txt"):
with open(filename) as f:
for word in f:
yield word.rstrip() # return a generator
def all_anagram(s):
'''
s: string
'''
d = defaultdict(list)
for i in s:
signature = ''.join(sorted(i)) # siganature is a after-sort string of ch... | StarcoderdataPython |
1731411 | import marshmallow as ma
from .. import models
from ..serializers.base import BaseSchema
from .dataset_version import DatasetVersionSchema
from .storage_provider import StorageProviderSchema
class DatasetSchema(BaseSchema):
MODEL = models.Dataset
id = ma.fields.Str()
name = ma.fields.Str()
descripti... | StarcoderdataPython |
54237 | # TODO
class A:
def __init__(self, value):
self.value = value
def __matmul__(self, other):
print('__matmul__')
return A(self.value * other.value)
def __imatmul__(self, other):
print('__imatmul__')
self.value *= other.value
return self
a = A(1)
b = A(2)
p... | StarcoderdataPython |
3256610 | from random import random
from django.http import HttpRequest
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View
from pycdi import Inject, Producer
from pycdi.core import CDIContainer
from pycdi.utils import Singleton
@Singleton()
class MySi... | StarcoderdataPython |
3326724 | <reponame>bowen-zhang/mongo_utils
import datetime
import unittest
import dict_format
import test_pb2
class DictFormatTests(unittest.TestCase):
def setUp(self):
self._proto = test_pb2.Test(
int_value=123,
float_value=123.456,
string_value='Hello World!',
int_list=[1,... | StarcoderdataPython |
102515 | <gh_stars>0
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
from __future__ import division
"""
File for MyMotif class which is the more general version of the BioPython motif obect
and other motif r... | StarcoderdataPython |
3324597 | """
DREA.py - Executes the Fortran code DREA
"""
import os
from numpy import array
from numpy import float as numpy_float
from openmdao.main.datatypes.api import Int, Float, Array, Enum, VarTree
from openmdao.lib.components.api import ExternalCode
from openmdao.util.namelist_util import Namelist
... | StarcoderdataPython |
3368325 | from flask import jsonify, make_response, request
from app import db
from app.Models.product import Products
def index():
"""
Get all data
Returns:
make_response -- jsonify
"""
res = {}
try:
datas = Products.query.all()
data = generate(datas)
... | StarcoderdataPython |
77178 | import unittest
from nose.tools import (assert_in, assert_raises, assert_equals)
import logging
import numpy
from sknn.mlp import Regressor as MLPR
from sknn.mlp import Layer as L, Convolution as C
class TestDataAugmentation(unittest.TestCase):
def setUp(self):
self.called = 0
self.value = 1.0
... | StarcoderdataPython |
3327776 | <filename>migrations/versions/0dad6c8372e4_index_email.py<gh_stars>10-100
"""index email
Revision ID: 0dad<PASSWORD>
Revises: <KEY>
Create Date: 2018-08-20 10:11:58.474348
"""
from alembic import op
import sqlalchemy as sa
import geoalchemy2
# revision identifiers, used by Alembic.
revision = '0dad<PASSWORD>'
down_... | StarcoderdataPython |
3315420 | <filename>radiantkit/scripts/tiffcu.py
"""
@author: <NAME>
@contact: <EMAIL>
"""
import argparse
from joblib import cpu_count, delayed, Parallel # type: ignore
import logging
import os
from radiantkit import argtools as ap
from radiantkit import image, path
import re
import sys
def init_parser(subparsers: argparse.... | StarcoderdataPython |
1680028 | def sum_array(arr):
if not arr:
return 0
return arr[0] + sum_array(arr[1:])
| StarcoderdataPython |
3350095 | <filename>src/pytiger/utils/test_decorators.py
# -*- coding: utf-8 -*-
from .decorators import cached_property, singleton
import unittest
class TestCachedProperty(unittest.TestCase):
# Adapted from Django
# Copyright (c) Django Software Foundation and individual contributors.
# All rights reserved.
#... | StarcoderdataPython |
1652648 | import pygame
from utils import *
from random import randint
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class ColorFillSquare():
_top = 0
_left = 0
_height = 0
_width = 0
_currentColor = COLORS.GREEN
_nextColor = COLORS.GREEN
square_up = None
square_right = None
square_down = None
squa... | StarcoderdataPython |
41660 | <reponame>Zhu-Jianwei/LaTeX-helper
import json
json_data =r'''
{
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
},
"hello": {
"prefix": "hello",
"body": [
... | StarcoderdataPython |
177876 | from project import main
from project.tables import profile
from datetime import datetime
from typing import List
async def get_profile(profile_id: str):
db = main.get_db()
query = ("""
SELECT
id,
name,
profile_img,
description,
phone_number
... | StarcoderdataPython |
4835950 | <filename>pywren_ibm_cloud/compute/backends/cloudrun/config.py
import os
import sys
from pywren_ibm_cloud.version import __version__
from pywren_ibm_cloud.utils import version_str
RUNTIME_NAME_DEFAULT = 'pywren-cloudrun'
RUNTIME_TIMEOUT_DEFAULT = 600 # 10 minutes
RUNTIME_MEMORY_DEFAULT = 256 # 256Mi
CONCURRENT_WORK... | StarcoderdataPython |
1796262 | <reponame>eisnerh/DjangoInventory
# Generated by Django 2.0.4 on 2018-04-10 00:58
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... | StarcoderdataPython |
1653691 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'cal2.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCor... | StarcoderdataPython |
3339600 | <filename>Tradable/items/forms.py
from django import forms
from .models import Item
class ItemCreateForm(forms.ModelForm):
class Meta:
model = Item
fields = [
'name',
'description',
'price',
'condition',
'displayPhoto'
]
class I... | StarcoderdataPython |
3337010 | from bankroll.model import (
AccountBalance,
Cash,
Currency,
Stock,
Bond,
Option,
OptionType,
Position,
CashPayment,
Trade,
TradeFlags,
)
import bankroll.brokers.schwab as schwab
from datetime import date
from decimal import Decimal
from itertools import groupby
from pathlib ... | StarcoderdataPython |
139570 | import FWCore.ParameterSet.Config as cms
# Geometry and Magnetic field must be initialized separately
# Geant4-based CMS Detector simulation (OscarProducer)
# - returns label "g4SimHits"
#
from SimG4Core.Application.g4SimHits_cfi import *
| StarcoderdataPython |
3263044 | '''OpenGL extension EXT.blend_subtract
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_EXT_blend_subtract'
_DEPRECATED = False
GL_FUNC_SUBTRACT... | StarcoderdataPython |
134935 | import sqlalchemy as sa
metadata = sa.MetaData()
commission_metas = sa.Table(
'commission_metas',
metadata,
sa.Column(
'broker',
sa.String,
nullable=False),
sa.Column(
'model',
sa.String,
nullable=False
),
sa.Column(
'exchange',
s... | StarcoderdataPython |
38455 | <reponame>vovamedentsiy/mpdnn
import matplotlib
matplotlib.use('PS')
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import random
def autolabel(rects, ax, coeff = 1):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height... | StarcoderdataPython |
119570 | """
Copyright 2013 Rackspace
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 agreed to in writing, software
dist... | StarcoderdataPython |
1719241 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... | StarcoderdataPython |
1603585 | from plugin.models.m_sync.result import SyncResult, SyncResultError, SyncResultException
from plugin.models.m_sync.status import SyncStatus
| StarcoderdataPython |
1669261 | <filename>commands.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author : yanyongyu
@Date : 2020-04-14 21:00:04
@LastEditors: yanyongyu
@LastEditTime: 2020-04-14 21:34:58
@Description : None
@GitHub : https://github.com/yanyongyu
"""
__author__ = "yanyongyu"
from datetime import d... | StarcoderdataPython |
1754944 | #
# This file is part of Orchid and related technologies.
#
# Copyright (c) 2017-2021 Reveal Energy Services. All Rights Reserved.
#
# LEGAL NOTICE:
# Orchid contains trade secrets and otherwise confidential information
# owned by Reveal Energy Services. Access to and use of this information is
# strictly limited and... | StarcoderdataPython |
1649489 | <filename>poetry/vcs/__init__.py
from poetry.utils._compat import Path
from .git import Git
def get_vcs(directory): # type: (Path) -> Git
directory = directory.resolve()
for p in [directory] + list(directory.parents):
if (p / ".git").is_dir():
return Git(p)
| StarcoderdataPython |
3348284 | import logging
import aiohttp
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("serverchan")
async def push_message(sendkey, message):
url = f"https://sctapi.ftqq.com/{sendkey}.send"
data = {"title": f"【粉丝牌助手推送】", "desp": ... | StarcoderdataPython |
3350797 | #!/usr/bin/python3
########################################
#
# This is a proof of concept. This code is neither good nor commented.
#
########################################
import sys
import signal
import os
import ast
import docker as d
import configparser
import glob
dry_run=False
debug_run=False
info_run=False... | StarcoderdataPython |
3307765 | from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'permissions', views.PermissionViewSet)
urlpatterns = [
path('auth/', include(r... | StarcoderdataPython |
1666682 | <filename>gmn/src/d1_gmn/manage.py
#!/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-2017 DataONE
#
# Licensed under... | StarcoderdataPython |
3357352 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Blueprint, request, current_app, session, redirect, url_for, render_template
from fish_core.utils.common_utils import check_validity_for_dict
from fish_dashboard.fault import register_alarm_email
user = Blueprint('user', __name__)
@user.route('/login',... | StarcoderdataPython |
4829587 | <reponame>ACLUmass/RMV-FaceSurveilance-Emails<filename>pdf_processing/rqMatch.py
import sys
import json
import re
import tabulate
import datetime
import time
from nameparser import HumanName
#usage in python3 environment
# python rqMatch.py nodupMails.json allLogs.json > nodupDbg.txt
#filenames must be relative to pdf... | StarcoderdataPython |
1775203 | <filename>app/prom/metrics/general/tablespace.py
from prometheus_client import Gauge
from app.prom.database import util as db_util
from app.prom.metrics.abstract_metric import AbstractMetric
TABLESPACE = '''tablespace'''
TYPE = '''type'''
CURR_BYTES = '''curr_bytes'''
USED_BYTES = '''used_bytes'''
MAX_BYTES = '''max_... | StarcoderdataPython |
3360566 | <gh_stars>100-1000
import tests.exog.test_random_exogenous as testrandexog
testrandexog.test_random_exogenous( 75,80); | StarcoderdataPython |
3321703 | from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from mixins.assets import TimeStampMixin
from suppliers.models import Supplier
class Bill(TimeStampMixin):
"""
Bill model
"""
purchase_order_number = models.CharField(max_length=100)
slug = models.S... | StarcoderdataPython |
3232392 | import streamlit as st
from fastai.learner import Learner, load_learner
from fastai.vision.all import PILImage
from ml_for_programmers.cats_vs_dogs.pretrained import is_cat # noqa
from ml_for_programmers.cats_vs_dogs.pretrained import (
AnimalType,
classify,
model_file_path,
)
learner: Learner = load_lea... | StarcoderdataPython |
59913 | <filename>PerfectCRM/views.py
# -*- coding: utf-8 -*-
"""
@Datetime: 2018/10/21
@Author: <NAME>
"""
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
def acc_login(request):
error_msg = ''
if request.method == 'POST':
username = request.POST.get... | StarcoderdataPython |
1777047 | <reponame>bo4e/BO4E-python<filename>tests/test_enums.py
import inspect
import re
from pathlib import Path
from typing import List, Optional, TypeVar
import pytest # type:ignore[import]
from bo4e.enum import anrede
from bo4e.enum.strenum import StrEnum
class TestEnums:
"""
A test class that checks the enum ... | StarcoderdataPython |
103733 |
class IBeacon():
def __init__(self, driver_instace) -> None:
self.ble_driver_instace = driver_instace
def setUUID(self, uuid : str) -> None:
"uuid is 16 bytes should be represented as a string of hex-decimal format: XX XX XX XX ..."
self.uuid = uuid
def setMajor(self, major : str... | StarcoderdataPython |
1739046 | from datetime import date
from pathlib import Path
import pandas as pd
import pytest
import rumydata.rules.cell
import rumydata.table
from rumydata import field
from rumydata.table import ParquetFile
from tests.utils import mock_no_module
@pytest.fixture()
def basic_good(tmpdir):
p = Path(tmpdir, 'good.parquet'... | StarcoderdataPython |
3243421 | <gh_stars>10-100
"""
PyTorch implementation of the SMAL/SMPL model
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import pickle as pkl
from smal.batch_lbs i... | StarcoderdataPython |
101104 | <gh_stars>1-10
#!/usr/bin/python3
import argparse
import os
import shutil
from atcodertools.common.judgetype import ErrorType, NormalJudge, DecimalJudge, MultiSolutionJudge, InteractiveJudge, JudgeType, NoJudgeTypeException, DEFAULT_EPS
from atcodertools.tools.models.metadata import Metadata
from atcodertools.common.l... | StarcoderdataPython |
4831228 | <gh_stars>10-100
import unittest
from unittest.mock import *
from datetime import datetime
from cexio.ws_client import CEXWebSocketAuth
test_config = {
'auth': {
'user': 'TestCex1027',
'key': '<KEY>',
'secret': '<KEY>',
},
'uri': {
'ws': 'wss://ws.cex.io/ws/',
'rest': 'https://cex.io/api/',
}
}
test_s... | StarcoderdataPython |
51403 | import io
import time
import wx
from .screenshot_thread import ScreenshotThread, EVT_SCREENSHOT
class DeviceFrame(wx.Frame):
def __init__(self, device,
png=True,
resize_quality=wx.IMAGE_QUALITY_NORMAL,
size_divisor=640,
*args, **kwargs):
super().__init__(N... | StarcoderdataPython |
169139 | # test_ss.py
import unittest
from SelectionSort import sortSS
class SelectionSortTest(unittest.TestCase):
def test_empty_array(self):
self.assertEqual(sortSS([]), [])
def test_one_value_array(self):
self.assertEqual(sortSS([2]), [2])
def test_sort1(self):
self.assertEqual(sortSS(... | StarcoderdataPython |
1627777 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ... | StarcoderdataPython |
4829285 |
DesignSpec = {
'DPNV' : True,
'p' : 1,
'ps' : 2,
'Q' : 12,
'J' : 5e6, # Arms/m^2
'wire_A' : 2*1e-6, # cross sectional area of conductors m^2
'Kcu' : 0.5, # Stator slot fill/packing factor... | StarcoderdataPython |
135623 | <filename>Problemset/jump-game/jump-game.py<gh_stars>1-10
# @Title: 跳跃游戏 (Jump Game)
# @Author: 18015528893
# @Date: 2021-02-22 00:17:58
# @Runtime: 48 ms
# @Memory: 16 MB
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_i = 0
last = len(nums) - 1
for i in range(len(nums)):
... | StarcoderdataPython |
1727320 | <filename>opendatasets/utils/kaggle_api.py
import os
from opendatasets.utils.kaggle_direct import get_kaggle_dataset_id, is_kaggle_url
import click
def _get_kaggle_key():
user_input = click.prompt("Your Kaggle Key", hide_input=True)
if user_input.startswith('{'):
try:
import json
... | StarcoderdataPython |
77651 | from crummycm.validation.types.values.element.numeric import Numeric
A_EX_TEMP = {"my_num": Numeric(default_value=int(0), required=False, is_type=int)}
# type
A_required_EX_TEMP = {"my_num": Numeric(required=True, is_type=float)}
# # type
A_int_EX_TEMP = {"my_num": Numeric(is_type=int)}
A_float_EX_TEMP = {"my_num": Nu... | StarcoderdataPython |
1627249 | <reponame>CryptologyExchange/terra.py
from .delegation import (Delegation, Redelegation, RedelegationEntry,
UnbondingDelegation, UnbondingDelegationEntry)
from .validator import Commission, CommissionRates, Description, Validator
__all__ = [
"Delegation",
"UnbondingDelegation",
"Un... | StarcoderdataPython |
131116 | """The working horse: Gets counts out of rootfiles into the .csv tables."""
from .root_to_table import FileToCounts, TablesFromFiles
__all__ = ["FileToCounts", "TablesFromFiles"]
| StarcoderdataPython |
1723730 | <reponame>chrislaskey/kingdom
from flask.ext.security import RoleMixin
from . import db
roles_users = db.Table(
'roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)
class Role(db.Model, RoleMixin):
id = db.Column(... | StarcoderdataPython |
3285537 | <reponame>mikedingjan/commercetools-python-sdk
import typing
from typing import List, Optional
from commercetools import schemas, types
from commercetools.services import abstract
from commercetools.typing import OptionalListStr
__all__ = ["ChannelService"]
class ChannelDeleteSchema(abstract.AbstractDeleteSchema):
... | StarcoderdataPython |
3331708 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import TodoSerializer
from .models import Todo
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
| StarcoderdataPython |
140525 | # Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
import os
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config(default=os.environ.get('DATABASE_URL'))
| StarcoderdataPython |
1781009 | FOLDER_IDS = [""]
ITEM_STATE_COLORS = {
"remote-only": "#919191",
"synced": "#fafafa",
"local-only": "#69cc2b",
"modified-locally": "#cc912b",
"deleted-locally": "#cc402b",
}
| StarcoderdataPython |
4828685 | from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from bootstrap4.utils import render_tag
from .text import text_value
def render_alert(content, alert_type=None, dismissible=True):
"""Render a Bootstrap alert."""
button = ""
if not alert_type:
alert... | StarcoderdataPython |
39336 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
1714122 | import unittest
import os
from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform
set_wrapper_choice(os.environ.get('NANOMSG_PY_TEST_WRAPPER',
get_default_for_platform()))
from nanomsg import (
SUB,
PUB,
SUB_SUBSCRIBE,
Socket
)
SOCKET_ADDRESS = os.e... | StarcoderdataPython |
1653795 | from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Python code to illustrate Sending mail from alstom email id
import smtplib, datetime
def sendSummaryEmail(message, ExpiryDays, fromEmailId, pwdOfEmail, toEmailId, LicenseAdminName, ccEmailId):
try:
print("\nSending ... | StarcoderdataPython |
99247 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def crear_recursos_desde_aulas(apps, schema_editor):
Aula = apps.get_model('app_reservas', 'Aula')
Recurso = apps.get_model('app_reservas', 'Recurso')
# Recorre todas las aulas existentes.
for aul... | StarcoderdataPython |
46503 | from lsassy.dumpmethod import IDumpMethod
class DumpMethod(IDumpMethod):
def __init__(self, session, timeout):
super().__init__(session, timeout)
self.waiting_time = 5
def prepare(self, options):
self.waiting_time = options.get("rdrleakdiag_wait", self.waiting_time)
return Tru... | StarcoderdataPython |
57112 | #!/usr/bin/python
# -*- coding: utf-8 -*-
inputs = [
"LLLRLLULLDDLDUDRDDURLDDRDLRDDRUULRULLLDLUURUUUDLUUDLRUDLDUDURRLDRRRUULUURLUDRURULRLRLRRUULRUUUDRRDDRLLLDDLLUDDDLLRLLULULRRURRRLDRLDLLRURDULLDULRUURLRUDRURLRRDLLDDURLDDLUDLRLUURDRDRDDUURDDLDDDRUDULDLRDRDDURDLUDDDRUDLUDLULULRUURLRUUUDDRLDULLLUDLULDUUDLDLRRLLLRLDUDRUU... | StarcoderdataPython |
3395364 | <filename>clone_repo.py
import git, os, shutil
DIR_NAME = "models"
REMOTE_URL = "https://github.com/tensorflow/models"
if os.path.isdir(DIR_NAME):
shutil.rmtree(DIR_NAME)
os.mkdir(DIR_NAME)
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin',REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0]... | StarcoderdataPython |
3281058 | <gh_stars>0
"""
This file is part of SleekBot. http://github.com/hgrecco/SleekBot
See the README file for more information.
"""
__author__ = '<NAME> <<EMAIL>>'
__license__ = 'MIT License/X11 license'
import logging
from abc import ABCMeta, abstractproperty
from .pluginbase import PluginDict, Plugin
class ... | StarcoderdataPython |
3343451 | <reponame>itcarroll/dvc
INDEX_FIELD = "step"
REVISION_FIELD = "rev"
FILENAME_FIELD = "filename"
REVISIONS_KEY = "revisions"
TYPE_KEY = "type"
SRC_FIELD = "src"
| StarcoderdataPython |
158527 | <reponame>nholeman/raster-vision
from rastervision.label_stores.object_detection_geojson_file import (
ObjectDetectionGeoJSONFile)
from rastervision.label_stores.classification_geojson_file import (
ClassificationGeoJSONFile)
from rastervision.label_stores.segmentation_raster_file import (
SegmentationInput... | StarcoderdataPython |
3390220 | <filename>bluemary/ui/libbluemary.py
import npyscreen
from collections import namedtuple
from bluemary.bluetooth.libbluetooth import BluetoothController
class BluetoothDevice:
def __init__(self,name,ssid):
self.name = name
self.ssid = ssid
class BluetoothSummaryForm(npyscreen.Form):
def cre... | StarcoderdataPython |
46638 | <filename>project/experiments/exp_035_fight_smp_benchmark/src/gym_envs/smp_envs.py
class SMPRobot():
pass | StarcoderdataPython |
3295973 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-02-22 16:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nfdcore', '0024_auto_20180222_1556'),
]
operations = [
migrations.AddField(... | StarcoderdataPython |
34974 | <reponame>MihailMarkovski/Python-Advanced-2020
def create_matrix(rows_count):
matrix = []
for _ in range(rows_count):
matrix.append([int(x) for x in input().split(', ')])
return matrix
def get_square_sum(row, col, matrix):
square_sum = 0
for r in range(row, row + 2):
for c in range... | StarcoderdataPython |
1657100 | <reponame>minjoong507/Image-Captioning<filename>src/make_vocab.py
from pycocotools.coco import COCO
import nltk
from collections import Counter
import pickle
import os
class Vocab:
def __init__(self):
self.word2idx = {}
self.idx2word = {}
self.idx = 0
def add_word(self, word):
... | StarcoderdataPython |
155474 | <filename>evennia/scripts/__init__.py
"""
This sub-package holds the Scripts system. Scripts are database
entities that can store data both in connection to Objects and Accounts
or globally. They may also have a timer-component to execute various
timed effects.
"""
| StarcoderdataPython |
3247558 | <reponame>oblaznjc/IntroductionToPython
"""
Your chance to explore Loops and Turtles!
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
their colleagues and <NAME>.
"""
########################################################################
# TODO: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name... | StarcoderdataPython |
68474 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | StarcoderdataPython |
89925 | """
# Relative Path Markdown Extension
During the MkDocs build we rewrite URLs that link to local
Markdown or media files. Using the following pages configuration
we can look at how the output is changed.
pages:
- ['index.md']
- ['tutorial/install.md']
- ['tutorial/intro.md']
## Markdown URLs
When l... | StarcoderdataPython |
3372367 | <filename>Project 1/1.3.py
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
from scipy.optimize import curve_fit
dt = 0.001
omega_0 = 2
tmax = 20
def plot_labels(x, y):
plt.xlabel(x)
plt.ylabel(y)
plt.show()
def acc(x, dx, gamma):
return -omega_0**2 * x - gamma * dx
def e... | StarcoderdataPython |
121822 | <gh_stars>10-100
# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests
import time
num_test = 5
def calling(_data):
start_time = time.time()
requests.post('https://t7p0v4a94l.execute-api.eu-west-1.amazonaws.com/Prod/post',
_data)
pr... | StarcoderdataPython |
3323576 | """Tests for common code."""
from cubi_tk import common
def test_is_uuid():
assert not common.is_uuid(1)
assert not common.is_uuid(None)
assert not common.is_uuid("x")
assert common.is_uuid("123e4567-e89b-12d3-a456-426655440000")
| StarcoderdataPython |
124258 | """ boosts and favs """
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.shortcuts import redirect
from django.utils.decorators import method_d... | StarcoderdataPython |
1650126 | <reponame>velankar/LEGO<filename>data/nyuv2/nyuv2_loader.py
from __future__ import division
import json
import os
import numpy as np
import scipy.misc
from glob import glob
class nyuv2_loader(object):
def __init__(self,
dataset_dir,
split='train',
crop_bottom=Fal... | StarcoderdataPython |
1700373 | # -*- coding: utf-8 -*-
import copy
import logging
from django.db import models
from django.utils.functional import cached_property
from .signals import post_ondelta_signal
logger = logging.getLogger('ondelta')
class OnDeltaMixin(models.Model):
class Meta:
abstract = True
def __init__(self, *arg... | StarcoderdataPython |
109488 | # first we need to import the logging module
from ._logging import get_logger, setup_logging # noqa: F401
# then we make sure the codec is available
from ._codec import register_codec
register_codec()
# now the regular imports may follow
from .masterserver import MasterServer # noqa: F401 E402
__all__ = (MasterSe... | StarcoderdataPython |
1706207 | from . import base
from ..services.torch.torch_service import TorchService
from ..services.torch.hook_service import HookService
class TorchClient(base.BaseClient):
def __init__(self,
min_om_nodes=1,
known_workers=list(),
include_github_known_workers=True,
... | StarcoderdataPython |
37500 | from maru import pymorphy
from maru.lemmatizer.abstract import ILemmatizer
from maru.tag import Tag
from maru.types import Word
class PymorphyLemmatizer(ILemmatizer):
def lemmatize(self, word: Word, tag: Tag) -> Word:
best_parse = max(
pymorphy.analyze(word),
key=lambda parse: (
... | StarcoderdataPython |
169612 | """
In reduce_embeddings.py we don't filter out duplicated sentences.
However, for analysis with the TK data we need to make sure all the
job ids are used.
e.g. if the same sentence is used in two job adverts only one of them is brought
forward, and thus the analysis will miss out including the second job advert in th... | StarcoderdataPython |
3397411 | import os
import torch
import numpy as np
import pickle
from torchvision import datasets, transforms
import PIL
from PIL import Image
import matplotlib.pyplot as plt
# from multiprocessing import cpu_count
class Pad(object):
def __init__(self):
return
def __call__(self, input):
... | StarcoderdataPython |
3383970 | from typing import Union, Type, List
from avishan.descriptor import Project
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management import BaseCommand
# WARNING: no import from avishan here
class AvishanConfigure:
@staticmethod
def command_line_c... | StarcoderdataPython |
12559 | <gh_stars>0
from django.contrib import admin
from .models import Student
# Register your models here.
class StudentAdmin(admin.ModelAdmin):
list_display = ('first_name','middle_name',
'last_name','identification_number')
search_fields = ('first_name','middle_name',
'las... | StarcoderdataPython |
77772 | from __future__ import annotations
from typing import TYPE_CHECKING
import random
from enum import Enum
from configuration import config
from src.genotype.mutagen.option import Option
from src.genotype.neat.gene import Gene
if TYPE_CHECKING:
pass
class NodeType(Enum):
INPUT = 0
HIDDEN = 1
OUTPUT =... | StarcoderdataPython |
17533 | <reponame>kokizzu/v8cgi
import sys
import re
PATH_GLUT = 'glut.h'
FILE_GLUT = 'glutbind.cpp'
TEMPLATES = ['glutInit', 'glutTimerFunc']
def main():
"""
Still some things have to be hand-made, like
changing argv pargc values in the glutInit method definition
Also change the TimerFunc method with some ... | StarcoderdataPython |
114270 | <gh_stars>0
# pred is the list of predicted labels, sensitive is the list of labels for sensitive attribute
# unprotected_vals is the label for unprotected group. e.g. 1 means unprivilege, 0 means privilege
# positive_pred is the favorable result in prediction task. e.g. get approved for a loan
def DIbinary(pred,sensit... | StarcoderdataPython |
3261669 | import pytest
# jax imports
import jax
import jax.numpy as jnp
# crs imports
import cr.nimble as cnb
from cr.sparse.dsp import *
atol = 1e-6
rtol = 1e-6
def test_dct1():
for n in [4,8,16]:
for i in range(n):
print(n, i)
y = cnb.vec_unit(n, i)
a = dct(y)
x ... | StarcoderdataPython |
1701136 | <filename>tests/unit_tests/test_without_train_test.py<gh_stars>1-10
import shutil
import unittest
import os
from super_gradients import SgModel, \
ClassificationTestDatasetInterface, \
SegmentationTestDatasetInterface, DetectionTestDatasetInterface
from super_gradients.training.metrics import Accuracy, Top5
fro... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.