id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
26681 | from django import template
register = template.Library()
@register.filter
def has_group(user, name):
return user.groups.filter(name=name).exists()
| StarcoderdataPython |
3267177 | # Generated by Django 2.0.2 on 2018-02-19 14:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0005_auto_20160504_1520'),
]
operations = [
migrations.AlterField(
model_name='notification',
name=... | StarcoderdataPython |
34073 | <reponame>asuol/worky
"""
MIT License
Copyright (c) 2020 <NAME> <<EMAIL>.lousa.<EMAIL>ques at gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without lim... | StarcoderdataPython |
30126 | <filename>app/__init__.py<gh_stars>1-10
import os
import sys
from instance.config import DATABASE_URI
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRA... | StarcoderdataPython |
3277041 | '''For computing flag vector of product in various bases
>>> product_formula(2,3)
array([[[ 1, 12, 30, 34, 120, 21, 120, 180],
[ 1, 15, 39, 44, 159, 26, 159, 240],
[ 1, 18, 45, 48, 180, 27, 180, 270]],
<BLANKLINE>
[[ 1, 16, 40, 44, 160, 26, 160, 240],
[ 1, 20, 52,... | StarcoderdataPython |
83704 | <reponame>ecly/adventofcode2020
import sys
from collections import defaultdict
def parse():
lines = sys.stdin.read().strip().split("\n")
rules_fwd = defaultdict(list)
rules_bwd = defaultdict(list)
for line in lines:
if not line.strip():
continue
bag, rest = line.split(" ba... | StarcoderdataPython |
3341008 | <filename>profiles/serializers_test.py<gh_stars>10-100
# pylint: disable=unused-argument,too-many-arguments,redefined-outer-name
"""
Tests for serializers for profiles REST APIS
"""
import pytest
import factory
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.exceptions import Validatio... | StarcoderdataPython |
1694857 | <gh_stars>0
from flask import Flask
import os
app = Flask(__name__, static_url_path='')
app.config.from_object('config')
# __file__ refers to the file settings.py
APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top
APP_STATIC = os.path.join(APP_ROOT, 'static')
from app.routes import... | StarcoderdataPython |
1710415 | #!/usr/bin/env python
# Author: <NAME>
# Description: a.k.a. foo.py as posted at https://www.biostars.org/p/95929/
# Solves the problem of orphan reads in a pair that may remain after retaining
# only those that align uniquely (i.e., after filtering using grep -v "XS:i:")
# This script is invoked by samtools_PE_RNA... | StarcoderdataPython |
3337280 | from django.apps import AppConfig
class GallerysConfig(AppConfig):
name = 'gallerys'
| StarcoderdataPython |
1716064 | import pandas as pd
import numpy as np
import aif360.datasets
# generators for biased data by models
def feature_bias(rho_a, rho_z, N, d, mu):
'''
Bias that occurs when different protected attributes have different means (mu)
Parameters
-----------
rho_a : float
p(a = 1)
rho_z : float
... | StarcoderdataPython |
11481 | <gh_stars>1-10
import unittest
from ....providers.aws.interactive import requires_replacement
def generate_resource_change(replacement=True):
resource_change = {
"Action": "Modify",
"Details": [],
"LogicalResourceId": "Fake",
"PhysicalResourceId": "arn:aws:fake",
"Replaceme... | StarcoderdataPython |
3281330 | <gh_stars>0
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... | StarcoderdataPython |
3336654 | <filename>ansibleplaybookgrapher/__init__.py
__version__ = "0.9.1"
__prog__ = "ansible-playbook-grapher"
| StarcoderdataPython |
1724971 | x:[int] = None
x = []
x[0] = 4
| StarcoderdataPython |
3397664 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Core module for pypcurve
"""
from .pypcurve import PCurve
__all__ = ["PCurve"]
__version__ = PCurve.__version__
| StarcoderdataPython |
3265910 | # -*- coding: utf-8 -*-
"""! Test OPM Archive library.
@author zer0
@date 2015-12-16
"""
import unittest
import os
import __main__ as main
import libopm.archive as Archive
ARCHIVE_NAME = 'test_archive'
CURRENT_SCRIPT = os.path.basename(main.__file__)
class TestArchive(unittest.TestCase):
@classmethod
def... | StarcoderdataPython |
1718803 | from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import views_v1_1
from . import views_v1_2
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('data', views.rest_get, name='rest_get'),
path('v1.1/data', views... | StarcoderdataPython |
1630237 | import os
import asyncio
if os.name == 'nt':
from hotplug.windows_notifier import WindowsNotifier as Notifier
else:
from hotplug.linux_notifier import LinuxNotifier as Notifier
__instance = None
def get_notifier():
global __instance
if __instance is not None:
return __instance
... | StarcoderdataPython |
3225648 | __version__ = "3.0.2"
from .formatter import ConllFormatter
from .utils import init_parser
| StarcoderdataPython |
4839326 | import os
import pytest
from . import run
from .conditions import has_http
def test_unit(cmake, unittest):
cwd = cmake(
["sentry_test_unit"], {"SENTRY_BACKEND": "none", "SENTRY_TRANSPORT": "none"}
)
env = dict(os.environ)
run(cwd, "sentry_test_unit", ["--no-summary", unittest], check=True, env... | StarcoderdataPython |
1765007 | from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe.utils import floor, flt, today, cint, cstr
@frappe.whitelist()
def calculate_deductible_hours(self,method):
deductible_hours = 0
if self.status == "Present":
if flt(self.working_hours) < 7.5 and flt(self... | StarcoderdataPython |
166572 | # Shoot!
# by KidsCanCode 2014
# A generic space shooter - prototype (no art)
# For educational purposes only
import pygame
import sys
import random
# define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BGCOLOR = BLACK
class Meteor(pygame.sprite.Sprit... | StarcoderdataPython |
178263 | #!/usr/bin/env python3
import rospy
from std_msgs.msg import Int32
zodiac_num = 0
print("卯")
def cb(message):
global zodiac_num
zodiac_num = message.data
zodiac_num = zodiac_num - 1995
while zodiac_num > 12:
if zodiac_num > 12:
zodiac_num = zodiac_num - 12
elif zodiac_num... | StarcoderdataPython |
1692499 | from abc import ABCMeta, abstractmethod
class AbstractDataHandler(object):
"""Abstract Data Handler Class
The data handler is an abstract base class providing an interface for all
subsequent (inherited) data handlers (both live and historic).
The goal of a (derived) data handler object is to output ... | StarcoderdataPython |
3242158 | #!/usr/bin/env python
import functools
import subprocess
import re
import shutil
import os
import git
import pathlib
from copy import deepcopy
from cached_property import cached_property
from packaging.version import Version, InvalidVersion
from packaging.specifiers import SpecifierSet
from astropy.table import Table... | StarcoderdataPython |
3380991 | # Copyright 2022 IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | StarcoderdataPython |
3292961 | #!/usr/bin/env python2
"""Stego Helper Identification Tool - Hide"""
from scipy.misc import imread as read_img
import numpy as np
import util
import os
import json
###############################################################################
######################################################################## bi... | StarcoderdataPython |
1631330 | import pandas as pd
from flask import Flask, jsonify, request, Response
import pickle
import base64
import jsonpickle
import numpy as np
import cv2
import json
from PIL import Image
# app
app = Flask(__name__)
prototxt = 'model/bvlc_googlenet.prototxt'
model = 'model/bvlc_googlenet.caffemodel'
labels = 'model/synset... | StarcoderdataPython |
1638372 | """Module containing class `PluginTypePluginType`."""
from vesper.plugin.plugin_type_plugin_interface_1_0 import \
PluginTypePluginInterface_1_0
import vesper.plugin.plugin_utils as plugin_utils
class PluginTypePluginType(PluginTypePluginInterface_1_0):
"""
The plugin type of plugin types.
... | StarcoderdataPython |
3219970 | <gh_stars>0
def romanToDecimal(roman_number):
roman_list = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for index,current_number in enumerate(roman_number):
if (index+1) == len(roman_number) or roman_list[current_number] >= roman_list[roman_number[index+1]]:
resu... | StarcoderdataPython |
1652812 | from deepleaps.dataloader.transforms import *
"""
All transform methods are registered here. If the default transform method path is here, import the transform method.
"""
TRANSFORM = {}
TRANSFORM['ToTensor'] = ToTensor
TRANSFORM['ToNumpy'] = ToNumpy | StarcoderdataPython |
3388597 | <gh_stars>0
import sys
import time
import requests
from tqdm import tqdm
import pickle
import os.path
delay = 0.50
def delay_call(clock_since_call):
delay_since_call = time.time() - clock_since_call
if delay_since_call < delay:
time.sleep(delay - delay_since_call)
def save(item, file_name):
with ... | StarcoderdataPython |
47012 | <reponame>Speedy1991/graphene-django-jwt
from django.contrib.auth.models import AnonymousUser
from graphene_django_jwt.blacklist import Blacklist
from graphene_django_jwt.shortcuts import get_user_by_token
from graphene_django_jwt.utils import get_credentials, get_payload
def _load_user(request):
token = get_cre... | StarcoderdataPython |
3327014 | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import PreApprovedSalesViewSet, RegisteredSaleViewSet
app_name = "core"
router = DefaultRouter()
router.register("preapproved", PreApprovedSalesViewSet)
router.register("sale", RegisteredSaleViewSet)
urlpatterns = [
... | StarcoderdataPython |
105068 | <gh_stars>1-10
"""
Tests to ensure that flows get stratified correctly.
That is, when a stratification is applied, there are the right number of flows,
connected to the right compartments, with the right adjustments applied.
"""
import pytest
from summer import AgeStratification
from summer import Compartment... | StarcoderdataPython |
4833296 | <gh_stars>0
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''The model architecture used was first created by the user polomarco for a Kaggle competition:
https://www.kaggle.com/polomarco/ecg-classification-cnn-lstm-attention-mechanism
However, this example has been altered to fit the FLUTE ... | StarcoderdataPython |
19815 | from apscheduler.schedulers.background import BackgroundScheduler
from des.ccd import start_pipeline
def download_queue():
start_pipeline()
scheduler = BackgroundScheduler()
scheduler.add_job(
download_queue,
'interval',
# minutes=1
seconds=20,
max_instances=1,
id='des_download_ccd'
)
... | StarcoderdataPython |
4837499 | """
BinarySearchTree
Interface:
==========
insert(value)
remove(value)
search(value): Return True if found and False otherwise.
traverse(order): `order` can be one of `pre_order`, `post_order`, in_order`, `out_order`, or `breadth_first_order`.
isEmpty()
height
clear()
size
... | StarcoderdataPython |
3272148 | __________________________________________________________________________________________________
class Solution:
def calculateTime(self, keyboard: str, word: str) -> int:
pos = 0
ans = 0
for ch in word:
cur = keyboard.find(ch)
ans += abs(cur - pos)
pos =... | StarcoderdataPython |
198601 | from simbatch.core import core
from simbatch.core import settings
import pytest
import os
@pytest.fixture(scope="module")
def sib():
# TODO pytest-datadir pytest-datafiles vs ( path.dirname( path.realpath(sys.argv[0]) )
settings_file = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +... | StarcoderdataPython |
1653718 | <gh_stars>1-10
import os
import numpy as np
from math import log10, sqrt
from numpy.fft import fft2, ifft2
from skimage import io
from scipy.signal import gaussian
# Get the peek signal to noise ratio for images
def PSNR(original, compressed):
mse = np.mean((original - compressed) ** 2)
if(mse == 0):
... | StarcoderdataPython |
133012 | from numpy import interp
from os import listdir
from PIL import Image, ImageStat
# Directory for block textures extracted from version jar
textures = 'assets/minecraft/textures/block'
# Special case: animated blocks like crimson_stem are
# taller than 64px: crop when compositing later?
# List of blocks to allow load... | StarcoderdataPython |
3240597 | import logging
import random
import time
import numpy
import torch
from .obs_ga import ObsGA
from .policy_ga import PolicyGA
from ..environment import Environment
LOG = logging.getLogger(__name__)
class TimeStat:
def __init__(self):
self._start_time = None
def start(self):
self._start_tim... | StarcoderdataPython |
107473 | <gh_stars>0
def main(event, context):
print(f'This is from Lambda 2nd function.') | StarcoderdataPython |
3362231 | <filename>canteen/app.py
from flask import (
Flask,
render_template,
)
app = Flask(
__name__,
static_folder='../static/dist',
template_folder='../static',
)
@app.route('/')
def index():
return render_template('index.html')
| StarcoderdataPython |
3206585 | <reponame>gregflynn/configs<filename>modules/pacman/__init__.py
from sanity.initializer import BaseInitializer
from sanity.settings import ExecWrapper
class Initializer(BaseInitializer):
@property
def requirements(self):
return ['pacman']
def install(self):
self.bin('pac', self.base_path(... | StarcoderdataPython |
199070 | # -*- coding: utf-8 -*-
"""Generic requests handlers."""
import datetime
from operator import itemgetter
from google.appengine.ext import ndb
from jinja2 import FileSystemLoader
from webapp2 import cached_property
from webapp2 import RequestHandler
from webapp2 import uri_for
from webapp2_extras import auth
from webap... | StarcoderdataPython |
3390285 | import sys
from collections import defaultdict
MAX_SIZE = 400
INF = 999999
SAFE_DIST = 10000
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def get_manhattans(points, dest_point):
return sum(map(lambda point: manhattan(point, dest_point), points))
def get_safe_points(points):
f... | StarcoderdataPython |
1784764 | <reponame>rainmanwy/robotframework-DatabaseLib
# -*- coding: utf-8 -*-
"""
Create by <EMAIL> at 7/3/19
"""
import os
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker, scoped_session
import sqlparse
from robot.utils import ConnectionCache
from robot.api i... | StarcoderdataPython |
1731531 | import datetime
import json
import logging
import shutil
import subprocess
logger = logging.getLogger(__name__)
class ContCommandResult:
"""A representation engine command results."""
def __init__(self, exit_status=None, stdout=None, stderr=None, command=None):
self.exit_status = exit_status
... | StarcoderdataPython |
3386454 | import logging
import configparser
from marshmallow import ValidationError
from mongoengine import DoesNotExist, ValidationError as ValidationErr, NotUniqueError
from pymongo.errors import DuplicateKeyError
from utils.responses import bad_request, not_found
def create_error_handlers(app):
@app.errorhandler(Vali... | StarcoderdataPython |
8920 | <reponame>noshluk2/Wifi-Signal-Robot-localization<filename>scripts/Interfacing/encoder_class.py
import RPi.GPIO as GPIO
import threading
class Encoder(object):
def __init__(self, r_en_a,r_en_b,l_en_a,l_en_b):
GPIO.setmode(GPIO.BCM)
GPIO.setup(r_en_a, GPIO.IN)
GPIO.setup(r_en_b, GPIO.IN)
... | StarcoderdataPython |
1614669 | import sys
import os.path
import pprint
sys.path.append(os.path.abspath(__file__ + "\..\.."))
import windows
from windows.generated_def.winstructs import *
import windows.native_exec.simple_x86 as x86
class SingleSteppingDebugger(windows.debug.LocalDebugger):
SINGLE_STEP_COUNT = 4
def on_exception(self, exc):... | StarcoderdataPython |
3234757 | <reponame>facebookresearch/worldsheet
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import skimage.io
import numpy as np
import torch
f... | StarcoderdataPython |
4828272 | # -*- coding: utf-8 -*-
"""
==============================================================================
@author: <NAME>
@date: Thu May 13 09:50:26 2021
@reference: Ojala, A Comparative Study of Texture Measures with Classification on Feature Distributions
Ojala, Gray Scale and Roation Invariaant Te... | StarcoderdataPython |
1714969 | <gh_stars>1-10
"""
Import as:
import helpers.hgit as hgit
"""
import collections
import functools
import logging
import os
import pprint
import re
from typing import Any, Dict, List, Match, Optional, Tuple
import helpers.hdbg as hdbg
import helpers.hio as hio
import helpers.hprint as hprint
import helpers.hsystem as... | StarcoderdataPython |
3225366 | from django.core.mail import send_mail
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from users.forms import CreationForm
class SignUp(CreateView):
form_class = CreationForm
success_url = reverse_lazy('login')
template_name = 'reg.html'
def form_valid(self, fo... | StarcoderdataPython |
1782008 | # Copyright (c) 2018 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""The signac framework aids in the management of large and
heterogeneous data spaces.
It provides a simple and robust data model to create a
well-defined indexable storage ... | StarcoderdataPython |
3337518 | from .base import *
DEBUG = False
ALLOWED_HOSTS = [
# À changer avec le nom de domaine de votre site web
"www.monsiteweb.fr"
]
| StarcoderdataPython |
126569 | import re
from ..exo_classes.exo_classes import BuiltInFunction, Number
from ..exo_classes.exo_context import Context
from ..exo_utils.exo_interpreter import Interpreter, SymbolTable
from ..exo_utils.exo_lexer import Lexer
from ..exo_utils.exo_parser import Parser
global_symbol_table = SymbolTable()
global_symbol_tab... | StarcoderdataPython |
80152 | <filename>backend_test/forms.py
"""Forms to upload the menu."""
#Django
from django import forms
#Models
from .utils.models import Ingredients, Menu, User, Orders
class MenuForm(forms.Form):
"""Form based on model Menu"""
dish_name = forms.CharField(
max_length=150,
required=True
)
de... | StarcoderdataPython |
184020 | from key_events import *
import os
os.nice(40)
pos = position()
for x in range(1000):
#time.sleep(.25)
mouseclick(*pos)
| StarcoderdataPython |
3244027 | def home(self, room_name):
return {'room_name': room_name}
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth import get_user_model
from core.models import Thread, Message
class ReturnThreads(APIVie... | StarcoderdataPython |
122410 | import os
# from sklearn.metrics import log_loss, roc_auc_score
import time
from librerank.utils import *
from librerank.reranker import *
from librerank.rl_reranker import *
def eval(model, data, l2_reg, batch_size, isrank, metric_scope, _print=False):
preds = []
# labels = []
losses = []
data_size... | StarcoderdataPython |
3315014 | from pytest import LogCaptureFixture
from .util import get_main_output
def test_content_types(caplog: LogCaptureFixture) -> None:
for _ in ("js_output.cwl", "js_output_workflow.cwl"):
commands = [
"https://raw.githubusercontent.com/common-workflow-language/common-workflow-language/main/v1.0/v... | StarcoderdataPython |
128150 | <reponame>NunoEdgarGFlowHub/katecheo
"""
python QuestionDetector_Test.py
"""
import unittest
import json
import os
os.environ[
'KATECHEO_NER'] = 'health=https://storage.googleapis.com/pachyderm-neuralbot/ner_models/health.zip,faith=https://storage.googleapis.com/pachyderm-neuralbot/ner_models/faith.zip'
import ... | StarcoderdataPython |
170009 | <gh_stars>0
import yaml
import json
from configparser import ConfigParser
def to_flatdict(file_path):
raw_file_path = file_path.replace("\t","\\t").replace("\n","\\n").replace("\b","\\b").replace("\f","\\f").replace("\r","\\r")
if file_path.endswith(".yaml") or file_path.endswith(".yml"):
return yaml_... | StarcoderdataPython |
4836665 | __version__ = '1.1.0+smth'
import numpy as np
import pyrep
pr_v = np.array(pyrep.__version__.split('.'), dtype=int)
if pr_v.size < 4 or np.any(pr_v < np.array([4, 1, 0, 2])):
raise ImportError(
'PyRep version must be greater than 4.1.0.2. Please update PyRep.')
from rlbench.environment import Environmen... | StarcoderdataPython |
3340148 | <filename>FSJ_django20_project/FSJ/forms/forms_student.py
"""All ModelForms based on the Student model"""
from ..models import Student
from .forms_modelform import ModelForm
from django.forms import TextInput
class StudentForm(ModelForm):
"""Unrestricted student form available to coordinators creating a new stude... | StarcoderdataPython |
166325 | <filename>src/game/law_scope.py<gh_stars>1-10
from enum import Enum, auto
class LawScope(Enum):
state = auto()
city = auto()
| StarcoderdataPython |
199682 | import re
from collections import deque
from contextlib import closing
from cStringIO import StringIO
from flanker.mime.message.headers.parsing import parse_stream
from flanker.mime.message.headers import MimeHeaders
def detect(message):
headers = collect(message)
return Result(
score=len(headers) / f... | StarcoderdataPython |
3212542 | <filename>airbyte-integrations/connectors/source-mailgun/source_mailgun/__init__.py
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from .source import SourceMailgun
__all__ = ["SourceMailgun"]
| StarcoderdataPython |
3395541 | from aiogram import types, Dispatcher
from aiogram.dispatcher.storage import FSMContext
from app.states import CheckState
from app.db_worker import db_worker
from asyncio import sleep
# дает пользовтелю инструкции
async def begining(message: types.Message, state: FSMContext):
await state.finish()
db_worker... | StarcoderdataPython |
29772 | from logging import getLogger
from typing import Dict, List, Optional
from tmtrader.entity.order import FilledBasicOrder
from tmtrader.entity.position import ClosedPosition, Position, Positions, \
PositionsRef
from tmtrader.exchange_for_backtest.usecase.order_to_share import from_order
logger = getLogger(__name__... | StarcoderdataPython |
1703347 | <gh_stars>1000+
"""Test getting __version__ for VTK package
"""
import vtkmodules
from vtkmodules.vtkCommonCore import vtkVersion
from vtkmodules.test import Testing
class TestVersion(Testing.vtkTest):
def testVersionAttribute(self):
"""Test the __version__ attribute
"""
x,y,z = vtkmodules... | StarcoderdataPython |
3320633 | <reponame>ragibson/ModularityPruning
from .shared_testing_functions import generate_connected_multilayer_ER, generate_random_partitions
from modularitypruning.champ_utilities import partition_coefficients_3D
from modularitypruning.louvain_utilities import multilayer_louvain_part_with_membership, \
check_multilayer_... | StarcoderdataPython |
3356475 | <gh_stars>0
from typing import Optional, Dict
from id_definition.error_codes import VizErrorCode
class VizException(Exception):
status_code = 400
code = VizErrorCode.GENERAL_ERROR
message = "Exception Occured"
def __init__(
self, message: Optional[str] = None, status_code: Optional[int] = No... | StarcoderdataPython |
1693027 | from CvPythonExtensions import *
import CvUtil
gc = CyGlobalContext()
class CvPediaProject:
def __init__(self, main):
self.iProject = -1
self.top = main
self.X_INFO_PANE = self.top.X_PEDIA_PAGE
self.Y_INFO_PANE = self.top.Y_PEDIA_PAGE
self.W_INFO_PANE = 380 #290
self.H_INFO_PANE = 120
self.W_ICON =... | StarcoderdataPython |
20079 | <reponame>bateman-research/search-sifter
import pytest
import searchsifter.relationships.minhash as mh
import searchsifter.relationships.jaccard as jc
@pytest.mark.parametrize("a, b, result", [
({1, 2}, {2}, 0.5),
({1, 2}, {2, 3}, 1/3),
({1}, {2}, 0),
({1}, {1}, 1)
])
def test_jaccard(a, b, result):
... | StarcoderdataPython |
3291864 | from scipy.stats import scoreatpercentile
import re
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
try:
from . import plotting
except ImportError:
print( 'WARNING: unable to import "plotting" in stats. some functions may be disabled' )
from . import reshape
class BlockMath( reshape.... | StarcoderdataPython |
3313403 | """Create BayesCMD configuration file for PLOS simulated data."""
import pandas as pd
import json
from pathlib import Path
import os.path as op
p = Path(op.abspath(__file__))
from bayescmd.abc import priors_creator
current_file = Path(op.abspath(__file__))
param_df = pd.read_csv(op.join(current_file.parents[2],
... | StarcoderdataPython |
1740763 | from monolithe.generators.lib import TemplateFileWriter
from monolithe.specifications import SpecificationAttribute
from monolithe.lib import Printer
import os
import shutil
import json
class APIVersionWriter(TemplateFileWriter):
""" This class is reponsible to write files for a particular api version. """
d... | StarcoderdataPython |
1834 | import os
from datetime import timedelta
basedir = os.path.abspath(os.path.dirname(__file__))
API_DATA_URL = "https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/"
API_LASTPRICES_URL = "https://invest-public-api.tinkoff.ru/rest/\
tinkoff.public.invest.api.contract.v1.Mar... | StarcoderdataPython |
4839779 | from django.apps import AppConfig
class NewswebsiteConfig(AppConfig):
name = 'newsWebsite'
| StarcoderdataPython |
3342993 | <reponame>IamMayankThakur/test-bigdata<filename>adminmgr/media/code/python/map1/BD_188_1000_1767_mapper.py<gh_stars>1-10
#!/usr/bin/python3
import sys
import csv
infile = sys.stdin
#next(infile)
#fuel column index 8
for line in infile:
line = line.strip()
my_list = line.split(',')
isBall = my_list[0]
if(isBall == ... | StarcoderdataPython |
1744306 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, unicode_literals, division,
print_function)
from ..representation import CartesianRepresentation
from ..baseframe import BaseCoordinateFrame, TimeFrameAttribute, fram... | StarcoderdataPython |
3259770 | <filename>util/stock.py
'''This module includes utility functions related to stock operation.
'''
'''
Copyright (c) 2017, WinQuant Information and Technology Co. Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditi... | StarcoderdataPython |
1755350 | import os.path as osp
from mmcv.runner import HOOKS, Hook, master_only
from mmcv.runner.checkpoint import save_checkpoint, get_state_dict, weights_to_cpu
from torch.optim.swa_utils import AveragedModel
from mmdet.core import EvalHook, DistEvalHook
import torch
import mmcv
@HOOKS.register_module()
class SWAHook(Hook)... | StarcoderdataPython |
35414 | <reponame>osaizar/sand
import random
import numpy as np
MATRIX = [(7, 6, 2, 1, 0, 3, 5, 4),
(6, 5, 0, 1, 3, 2, 4, 7),
(1, 0, 3, 7, 5, 4, 6, 2),
(7, 5, 2, 6, 1, 3, 0, 4),
(0, 4, 2, 3, 7, 1, 6, 5),
(7, 1, 0, 2, 3, 5, 6, 4),
(3, 4, 2, 6, 0, 7, 5, 1),
(6, 1, 5, 2, 7, 4, 0, 3),
(3, 1, 4, 5, 0, 7, 2, 6),
(3, 2, 6, 5, 0, 4, ... | StarcoderdataPython |
1653857 | from asyncio import iscoroutinefunction
from functools import wraps
from types import MethodType
from typing import Callable
from fastapi import Request
from ..utils import run_sync
from .backends.base import BaseCacheBackend
from .helpers import get_cache_backend, get_request_object
from .key import get_cache_key
... | StarcoderdataPython |
3272190 | """
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import json
from os import path
import jsonschema.exceptions
from jsonschema import validate
def getDeploymentConfig(file: str) -> dict:
"""
Load and validate the deployment configuration json file
... | StarcoderdataPython |
1611478 | <filename>genetic algorithm/conference building/hidden genes genetic algorithm/finlandia_talo_ga_stochastic.py<gh_stars>1-10
import numpy as np
from shapely.geometry import Polygon, MultiPolygon, LineString, MultiLineString, Point, LinearRing
from shapely.ops import polygonize, cascaded_union
from scipy.spatial.qhull i... | StarcoderdataPython |
3293378 | <filename>nipy/core/image/image_spaces.py
""" Utilities for working with Images and common neuroimaging spaces
>>> from nipy.core.api import Image, vox2mni, img_rollaxis, xyz_affine, as_xyz_affable
Make a standard 4D xyzt image in MNI space.
First the data and affine:
>>> data = np.arange(24).reshape((1,2,3,4))
>>>... | StarcoderdataPython |
33355 | from __future__ import absolute_import
import unittest
import sys
from testutils import ADMIN_CLIENT
from testutils import harbor_server
from library.project import Project
from library.user import User
from library.repository import Repository
from library.repository import push_image_to_project
from li... | StarcoderdataPython |
3295389 | <reponame>TheDevAtlas/IRIS
# <NAME> 2021 #
# Create Or Load Bot For Use #
# Imports For Data Display And Manipulation
import datetime as dt # The Date And Time
import numpy as np # Basic Functions
import pandas as pd # Data Manipulation And Translations
import matplotlib.pyplot as plt # Visualization
# Imports From T... | StarcoderdataPython |
1654492 | <filename>cdk-layer-factory/functions/start_layer_creation.py
import boto3
import datetime
import os
import sys
import hashlib
ec2_client = boto3.client('ec2')
iam_client = boto3.client('iam')
ddb_client = boto3.client('dynamodb')
#ami_id = 'ami-0a8b4cd432b1c3063'
ami_id = 'ami-0ef2003049dd4c459'
instance_type = 't3.s... | StarcoderdataPython |
3282051 | # coding:utf-8
from tasks.workers import app
from page_get import user as user_get
from db.seed_ids import get_seed_ids, get_seed_by_id, insert_seeds, set_seed_other_crawled
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
seed = get_seed_by_id(uid)
if seed.other_crawled == 0:
rs = user_get... | StarcoderdataPython |
1612359 | <filename>PyPI/package_analysis.py
#!/usr/bin/env python3
"""Analysis of Python packages."""
import json
import logging
import os
import re
import shutil
import sys
import tarfile
from os import walk
import pymysql.cursors
if sys.version_info[0] == 2:
from urllib import urlretrieve
else:
from urllib.request... | StarcoderdataPython |
4836520 | #! usr/bin/python
# coding: utf8
from tools import MsSQL
connection = MsSQL()
def get_color_dict():
"""
key is color_code and value is color_name
:return:
"""
color_dict = dict()
sql = "select color_code,color from joom_color where color_code is not Null"
with connection as con:
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.