id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
135271 | <reponame>topspinj/medcodes
from .elixhauser_charlson import comorbidity_mappers
from .icd9_descriptions import icd9cm
from .icd10_descriptions import icd10
__all__ = ['icd9cm', 'comorbidity_mappers', 'icd10'] | StarcoderdataPython |
1679077 | <gh_stars>1-10
from typing import List
from trustregistry import crud
from trustregistry import schemas
from .test_main import override_get_db
actor_model = schemas.Actor(
id="mickey-mouse",
name="Mickey Mouse",
roles=["verifier", "issuer"],
didcomm_invitation="xyz",
did="did:sov:abc",
)
actor_m... | StarcoderdataPython |
3349716 | # Created by lan at 2021/11/9
from math import sqrt
import pandas
date_patterns = ['%d/%m/%Y', '%d-%m-%Y', '%Y-%m-%d', '%Y/%m/%d', '%y/%m/%d', '%d/%m/%y']
import datetime
def is_numeric(value):
"""
check whether the given value is a numeric value. Numbers with decimal point or thousand separator can be prop... | StarcoderdataPython |
144644 | """
Module implementing a rate-limited multi-threaded download client for downloading from Sentinel Hub service
"""
import logging
import time
from threading import Lock, currentThread
import requests
from .handlers import fail_user_errors, retry_temporal_errors
from .client import DownloadClient
from ..sentinelhub_s... | StarcoderdataPython |
1792393 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-26 07:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_auto_20160517_2208'),
]
operations = [
migrations.RemoveField(
... | StarcoderdataPython |
72693 | <reponame>totbicer/Stratified-Sampling<filename>Stratified_sampling.py
#!/usr/bin/env python 3
# -*- coding: UTF-8 -*-
karsilama= """
_____________________________________________________________________________________
S T R A T I F I E D S A M P L I N G P R O G R A M
Ver... | StarcoderdataPython |
1687672 | # Copyright 2011-2012 Yelp
# Copyright 2015-2016 Yelp
#
# 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 a... | StarcoderdataPython |
141611 | <gh_stars>0
"""Chapter 12 - Be a pythonista"""
# vars
def dump(func):
"""Print input arguments and output value(s)"""
def wrapped(*args, **kwargs):
print("Function name: %s" % func.__name__)
print("Input arguments: %s" % ' '.join(map(str, args)))
print("Input keyword arguments: %s" % k... | StarcoderdataPython |
3375403 | <filename>LearnPanda5.py
# In this we cover concatenation.
import pandas as pd
df1 = pd.DataFrame({'HPI':[78, 35, 48, 71], 'Int_Rate':[2, 3, 4, 5],
'US_GST':[34, 29, 38, 47]},
index = [2001, 2002, 2003, 2004])
df2 = pd.DataFrame({'HPI':[78, 35, 48, 71], 'Int_Rate':[2, 3, ... | StarcoderdataPython |
3373609 | # Generated by Django 2.1.2 on 2018-11-18 23:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scoreboard', '0002_configuration'),
]
operations = [
migrations.AlterField(
model_name='configuration',
name='value'... | StarcoderdataPython |
4812614 | <reponame>utv-teaching/foundations-computer-science
# Foundations of Computer Science
# BSc Computer Engineering, University of <NAME>
# Exercise: Implement an image redscale effect.
def redScalePicture(picture):
# @param picture:Picture;
pixels = getPixels(picture)
for pixel in pixels:
setGreen(pixel, 0)
... | StarcoderdataPython |
2748 | <gh_stars>0
#!/usr/bin/env python
"""Classes to store and manage hunt results.
"""
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib.rdfvalues import structs as rdf_structs
from grr_response_proto import jobs_pb2
from grr.server import access_control
from grr.server import aff4
from grr.server imp... | StarcoderdataPython |
141845 | <filename>mayan/apps/checkouts/tests/test_links.py
from mayan.apps.documents.permissions import permission_document_file_new
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from mayan.apps.sources.links import link_document_file_upload
from mayan.apps.sources.tests.mixins.base_mixins import Sour... | StarcoderdataPython |
13197 | #!/usr/bin/env python
# coding: utf-8
# This script generates a zone plate pattern (based on partial filling) given the material, energy, grid size and number of zones as input
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from numba import njit
from joblib import Parallel, delayed
from tqdm import tq... | StarcoderdataPython |
32095 | <reponame>abhigyan709/dsalgo
class Employee:
def __init__(self, name, emp_id, email_id):
self.__name=name
self.__emp_id=emp_id
self.__email_id=email_id
def get_name(self):
return self.__name
def get_emp_id(self):
return self.__emp_id
def get_email_id(self):
... | StarcoderdataPython |
1619318 | <gh_stars>1-10
from dataclasses import dataclass
from typing import List
import datetime
@dataclass
class TimeStamp:
start: datetime.time
end: datetime.time
def calculateTimeDiffInSecs(self):
placeholder_date = datetime.datetime(datetime.MINYEAR, 1, 1)
new_start_datetime = datetime.datetim... | StarcoderdataPython |
3319479 | <reponame>TemaHunter/beem
# -*- coding: utf-8 -*-
import logging
import struct
import time
from datetime import timedelta
from binascii import unhexlify
from beemgraphenebase.py23 import bytes_types, integer_types, string_types, text_type
from .account import Account
from .utils import formatTimeFromNow, formatTimeStri... | StarcoderdataPython |
3236561 | <reponame>makinacorpus/ionyweb
# -*- coding: utf-8 -*-
import floppyforms as forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from ionyweb.forms import ModuloModelForm
fro... | StarcoderdataPython |
1766247 | """
Taken from ESPNet
"""
import torch
class PostNet(torch.nn.Module):
"""
From Tacotron2
Postnet module for Spectrogram prediction network.
This is a module of Postnet in Spectrogram prediction network,
which described in `Natural TTS Synthesis by
Conditioning WaveNet on Mel Spectrogram Pr... | StarcoderdataPython |
19043 | <reponame>Wasabii88/Games<gh_stars>1-10
'''initialize'''
from .ski import SkiGame
from .maze import MazeGame
from .gobang import GobangGame
from .tetris import TetrisGame
from .pacman import PacmanGame
from .gemgem import GemGemGame
from .tankwar import TankWarGame
from .sokoban import SokobanGame
from .pingpong import... | StarcoderdataPython |
4807357 | import os
import json
import logging
import time
import src.adsb_exchange as ads
import src.utilities as utils
import src.twilio_api as twil
from datetime import datetime as dt
from datetime import date, timedelta
# GLOBAL
START_TIME = dt.now()
SEEN_AIRCRAFT = set()
def check_if_duplicate(identifier: str) -> None:
... | StarcoderdataPython |
172183 | <reponame>haynieresearch/unusual_options_activity
#**********************************************************
#* CATEGORY SOFTWARE
#* GROUP MARKET DATA
#* AUTHOR <NAME> <<EMAIL>>
#* DATE 2020-10-20
#* PURPOSE UNUSUAL OPTIONS ACTIVITY
#* FILE ERRORS.PY
#**********************************************************
#* MOD... | StarcoderdataPython |
3257656 | """
Block until all dependent services come online.
"""
import requests
import time
import sys
from relation_engine_server.utils.config import get_config
_CONF = get_config()
def wait_for_service(service_list):
'''wait for a service or list of services to start up'''
timeout = int(time.time()) + 60
serv... | StarcoderdataPython |
1710591 | <reponame>lohzhishen/Cropping-Tool
import cv2 as cv
import os
import numpy as np
from Mask.Mask import Mask
class Image:
"""This class models an image."""
def __init__(self, path: str) -> None:
"""Constructor of the Image class."""
self.raw_image = cv.imread(path)
se... | StarcoderdataPython |
87971 | <reponame>ShenDezhou/CAIL
# -*- coding: utf-8 -*-
# @Time : 2019/12/4 10:53
# @Author : THU
"""
此模块包含了检测算法的图片预处理组件,如随机裁剪,随机缩放,随机旋转,label制作等
"""
from .iaa_augment import IaaAugment
from .augment import *
from .random_crop_data import EastRandomCropData,PSERandomCrop
from .make_border_map import MakeBorderMap
from .... | StarcoderdataPython |
1674958 | <filename>datagrid_gtk3/ui/__init__.py
"""Data grid MVC package.
Usage::
from gi.repository import Gtk
from datagrid_gtk3.ui.grid import DataGridContainer, DataGridController
from datagrid_gtk3.db.sqlite import SQLiteDataSource
win = Gtk.Window()
datagrid_container = DataGridContainer(win)
dat... | StarcoderdataPython |
1734029 | <filename>decronym/lookup/wikipedia.py
# -*- coding: utf-8 -*-
from .base import Lookup
from .type import LookupType
from ..result import Result
from ..util import *
from ..config import Config
import requests
import getpass
from bs4 import BeautifulSoup
from collections import defaultdict
from typing import (
Any... | StarcoderdataPython |
1798088 | import os
import h5py
import shutil
import numpy as np
from copy import deepcopy
from contextlib import contextmanager
from gonzales.simulator.space import Space
import gonzales.simulator.simulation as sim
# ---------------------------------------------------------
# Utility functions
# -----------------------------... | StarcoderdataPython |
4834970 | <reponame>farrepa/cla_frontend
import json
import logging
from requests import ConnectionError
from slumber.exceptions import HttpClientError
from django.contrib.auth import load_backend
from api.client import get_auth_connection
from .models import ClaUser
from .utils import get_zone_profile
logger = logging.getLo... | StarcoderdataPython |
4809493 | <reponame>vitkarpenko/math-expression-parser
import pytest
@pytest.fixture
def parser():
from math_expression_parser import Parser
return Parser()
@pytest.mark.parametrize('test_input, expected', [
('3 + 8', '3 8 +'),
('( 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 )', '3 4 2 * 1 5 - 2 3 ^ ^ / +'),
])
def test_eva... | StarcoderdataPython |
1772587 | <reponame>factioninc/snmp-unity-agent
class EnclosureCurrentPower(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_enclosure_current_power(idx_name)
class EnclosureCurrentPowerColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_... | StarcoderdataPython |
3302209 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from redis.asyncio.client import Pipeline, Redis
def from_url(url, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
... | StarcoderdataPython |
3209672 | import asyncio
import pathlib
import ssl
import websockets
import logging
import price
import parser_message
logging.basicConfig(filename='realtime.txt',level=logging.INFO)
stock_ids_hnx = open("StockIDs/HNX.txt", "r")
stock_ids_hsx = open("StockIDs/HSX.txt", "r")
stock_ids_upc = open("StockIDs/UPC.txt", "r")
list_id_... | StarcoderdataPython |
3324078 | print("Bienvenidos/as al Curso Bootcamp Python 3")
print("Impartido por <NAME> (<EMAIL>)") | StarcoderdataPython |
3316483 | # coding=utf-8
import os
import subliminal
import helpers
from items import get_item
from lib import get_intent, Plex
from config import config
def get_metadata_dict(item, part, add):
data = {
"item": item,
"section": item.section.title,
"path": part.file,
"folder": os.path.dirn... | StarcoderdataPython |
16072 | <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /vn/testNode.py was not found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>... | StarcoderdataPython |
35296 | from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential()
model.add(Embedding(vocabulary_size, embedding_dim, input_shape=(90582, 517)))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
mode... | StarcoderdataPython |
3225305 | #!/usr/bin/env python
import argparse
from typing import Dict
import requests
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("version_type", choices=["stable", "latest", "current"])
return parser.parse_args()
def get_current_version() -> str:
VERSION: Dict[str, str] = {}
... | StarcoderdataPython |
1774401 | # 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, Mapping, Optional, Sequence, Union, overload
from .. import... | StarcoderdataPython |
1660642 | from PIL import Image
import numpy as np
import io
import array
import subprocess
import os
import sys
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
def inpaint(img_arr, mask_arr):
... | StarcoderdataPython |
3228042 | <reponame>Randi-Seeberg/Towers-of-Hanoi
from stack import Stack
print("\nLet's play Towers of Hanoi!!")
#Create the Stacks
stacks = []
left_stack = Stack("Left")
middle_stack = Stack("Middle")
right_stack = Stack("Right")
stacks += [left_stack, middle_stack, right_stack]
#Set up the Game
num_disks = int(... | StarcoderdataPython |
179209 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tornado.ioloop
from tornado.options import define, options
define('port', default=8000, help='run on this port', type=int)
define('debug', default=True, help='enable debug mode')
options.parse_command_line()
import app
def runserver():
app.r... | StarcoderdataPython |
3308318 | <reponame>swapnanildutta/Social-Media-Sentiment-Analysis-API
#Import the model
from Model import model
#Import the Packages
import tweepy
import json
from flask import Flask
#Initialize API credentials
api_key='YOUR API KEY'
api_secret='YOUR API SECRET'
access_token='YOUR ACCESS TOKEN'
access_secret='YOUR ACCESS SEC... | StarcoderdataPython |
1717145 | <gh_stars>10-100
#!/usr/bin/python
# This script unshreds a shredded image (visit http://bit.ly/sCMAD5 for details)
# author: <NAME> <<EMAIL>>
from PIL import Image, ImageChops, ImageStat
from argparse import ArgumentParser
import sys, heapq
MAGIC_THRESHOLD = 11 # carefully handpicked to work with your reference inp... | StarcoderdataPython |
92829 | import mock
from mock import ANY
import requests
from werckercli.metrics import track_application_startup, default_command_name
from werckercli.tests import TestCase
track_command_usage_path = "werckercli.metrics.track_command_usage"
class MetricsTests(TestCase):
def test_track_application_startup_fails_silent... | StarcoderdataPython |
4831056 | <gh_stars>0
from typing import Dict, NoReturn
from h1st.model.predictive_model import PredictiveModel
from .student import Student, StudentModeler
from .ensemble import Ensemble
"""
Oracle architecture:
@startuml
allowmixing
Component Oracle #EEE {
Class Teacher
Class Student
Class Ensemble
}
Actor "AI Engineer... | StarcoderdataPython |
3363468 | <filename>authorize/registry.py
# -*- coding: utf-8
import os
import sys
import jwt
import time
import random
import ipaddress
from netaddr import IPNetwork, IPAddress
from commons.settings import DOMAIN, NODE_NETWORK, REGISTRY_IP_WHITELIST, LAIN_ADMIN_NAME
from ipaddress import IPv4Address
from log import logger
PR... | StarcoderdataPython |
170577 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
from torchknickknacks import metrics
x1 = torch.rand(100,)
x2 = torch.rand(100,)
r = metrics.pearson_coeff(x1, x2)
x = torch.rand(100, 30)
r_pairs = metrics.pearson_coeff_pairs(x)
| StarcoderdataPython |
1791542 | """committee of linear classifiers"""
import collections
import numpy
import sklearn
class LinearCommittee(object):
""" committee of linear classifiers (SGDclassifier)"""
def __init__(self, numOfVoters, policy, loss_function):
"""
numOfVoters: number of linear classifiers in the committee
... | StarcoderdataPython |
170205 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/3/18 12:57 下午
# @Author : xinming
# @File : 46_permute.py
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
k = len(nums)
path = []
def back_track(st... | StarcoderdataPython |
4834141 | # -*- coding: utf-8 -*-
# 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 writin... | StarcoderdataPython |
3200675 | import randomium
def main():
print(randomium.animal())
| StarcoderdataPython |
3259944 | <filename>utils.py
import sys
import math
from time import time
from ffmpeg import probe
def line():
print('-----------------------------------------------------------------------------------------------------------')
def is_list(argument_object):
return isinstance(argument_object, list)
def force_decima... | StarcoderdataPython |
3386667 | <filename>scripts/npc/infoArcher.py
# Created by MechAviv
# [<NAME>] | [10200]
# Maple Road : Split Road of Destiny
sm.setSpeakerID(10200)
sm.sendNext("Bowmen are blessed with dexterity and power, taking charge of long-distance attacks, providing support for those at the front line of the battle. Very adept at using... | StarcoderdataPython |
59158 | from .__version__ import __version__, __version_info__
from .cli import cli_entry
__all__ = ["cli_entry", "__version__", "__version_info__"]
| StarcoderdataPython |
3355071 | from drawable import Drawable
from polygon import Polygon
from opengraph import OpenGraph
from scalable import Scalable
from background import Background
from arrow import Arrow
from text import Text
class DrawingBackend(object):
DEFAULT_SCALE = 1
DEFAULT_PIXELS_PER_UNIT = 20
DEFAULT_SHADOW_TRANSLATION = ... | StarcoderdataPython |
3319185 | from .torch_profiler import TorchProfiler | StarcoderdataPython |
102032 | <gh_stars>10-100
import argparse
import torch
from brnolm.language_models import language_model
def main(args):
if args.force_cpu:
lm = torch.load(args.lm, map_location='cpu')
else:
lm = torch.load(args.lm)
language_model.torchscript_export(lm, args.frozen_lm)
if __name__ == '__main__':
... | StarcoderdataPython |
117301 | # Generated by Django 2.2.4 on 2019-10-22 17:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('email_verification', '0002_auto_20190415_1718'),
]
operations = [
migrations.CreateModel(
name='SessionState',
field... | StarcoderdataPython |
142219 | <filename>ROSSi_workspace/rossi_plugin/src/rossi_plugin/Ros2UI/UI/Editors/RosNodeEditor/GraphEntities/RosCodeVariableGraphEntity.py
from typing import Dict
from PyQt5 import QtCore
from PyQt5.QtCore import QRectF
from .....utils import fullname
from ....BaseGraphEntities.AbstractGraphEntity import DataObject
from ..... | StarcoderdataPython |
85731 | """
This module calculates the standard deviation of various gauge parameters during the "pre-effect window", which is an
arbitrary, variable length period of time before the impact of a given hurricane is "felt" at a gauge, and uses that to determine
the length of the effect of the hurricane on the river for each para... | StarcoderdataPython |
187929 | from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.timezone import utc
import datetime
make_choice =(('toyota','Toyota'),
('nissan','Nissan'),
('ford','Ford'),
('chevrolet','Chevrolet... | StarcoderdataPython |
1789517 | <filename>maintenance/database.py<gh_stars>0
#!/usr/bin/env python3
"""Infoset ORM classes.
Manages connection pooling among other things.
"""
# Main python libraries
import sys
import os
# PIP3 imports
try:
import yaml
from sqlalchemy import create_engine
import pymysql
except ImportError:
import p... | StarcoderdataPython |
25654 | from . import get_main_movies_base_data
from . import get_main_movies_full_data
from . import get_celebrities_full_data
from . import down_video_images
from . import down_celebrity_images
| StarcoderdataPython |
1636377 | class IrodsError(Exception):
pass
class IrodsWarning(IrodsError):
pass
class IrodsSchemaError(Exception):
pass
| StarcoderdataPython |
4813376 | import time
import numpy as np
from tqdm import trange
def expected_value(f, ni):
return np.einsum("iaj,j->ia", ni, f)
def calculate_gain(transition_probabilities, average_rewards, steps):
P_star = np.linalg.matrix_power(transition_probabilities, steps)
return P_star @ average_rewards
def calculate_b... | StarcoderdataPython |
79460 | <filename>fdrtd/plugins/simon/accumulators/accumulator_statistics_bivariate.py
import math as _math
from fdrtd.plugins.simon.accumulators.accumulator import Accumulator
from fdrtd.plugins.simon.accumulators.accumulator_statistics_univariate import AccumulatorStatisticsUnivariate
class AccumulatorStatisticsBivariate(... | StarcoderdataPython |
1613009 | <filename>mmdet3d/models/detectors/single_stage_sparse.py<gh_stars>0
import MinkowskiEngine as ME
from mmdet.models import DETECTORS
from mmdet3d.models import build_backbone, build_head
from mmdet3d.core import bbox3d2result
from .base import Base3DDetector
@DETECTORS.register_module()
class SingleStageSparse3DDete... | StarcoderdataPython |
3293761 | import json
import httpretty
import pytest
import pypuppetdb
def stub_request(url, data=None, method=httpretty.GET, status=200, **kwargs):
if data is None:
body = '[]'
else:
with open(data, 'r') as d:
body = json.load(d.read())
return httpretty.register_uri(method, url, body=... | StarcoderdataPython |
1767976 | <filename>pki_framework/apps.py
from django.apps import AppConfig
class PkiFrameworkConfig(AppConfig):
name = 'pki_framework'
| StarcoderdataPython |
60406 | from pfwrapper import PyPatternFinder
from collections import namedtuple
Pattern = namedtuple('Pattern', ['base', 'sens', 'pBase', 'pAll',
'pDX', 'pD_X', 'pX',
'pDY', 'pD_Y', 'pY',
'pDXY', 'pD_XY', 'pXY'])
DivergentPa... | StarcoderdataPython |
196460 | import pytest
import config
from app import create_app, db
from app.adapters.auth0.auth0_adapter import Auth0Adapter
@pytest.fixture(scope='module')
def app():
app = create_app(config.Test)
with app.app_context():
yield app
@pytest.fixture(scope='module')
def app_db(app):
db.drop_all()
with ... | StarcoderdataPython |
3398232 | #load a stl/obj file as argv[1]
import sys
import sensenet
from random import randint
env = sensenet.make("BlankEnv-v0",{'render':True,'obj_path':sys.argv[1]})
done = False
while (1):
if done:
env.reset()
action = randint(0, 1)
#action = randint(0, env.action_space.n)
observation,reward,done,inf... | StarcoderdataPython |
3337715 | import math
import numpy as np
"""Agrandit un tableau 2D en rajoutant des zeros à droite et en bas"""
def grow(array, growX = 0, growY = 0) :
if (array.ndim != 2) :
raise ValueError("Le tableau doit être de dimension 2")
sx, sy = array.shape
hgrow = np.zeros(sx * growY).reshape(sx, growY)
... | StarcoderdataPython |
3310620 | <reponame>valentinvarbanov/software_engineering_2021
from enum import Enum
import math
class RelativePosition(Enum):
NO_COMMON_POINTS = 1
TOUCHING = 2
INTERSECTING = 3
SAME = 4
def distance(a, b):
try:
assert isinstance(a, Point)
assert isinstance(b, Point)
except:
prin... | StarcoderdataPython |
1651201 | import os
def set_django_settings_module():
if os.getenv('LOGUI_DEV'):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'worker.settings.development')
else:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'worker.settings.docker') | StarcoderdataPython |
3271406 | <reponame>guoxiaowhu/lenstronomy<filename>lenstronomy/Data/coord_transforms.py
import numpy.linalg as linalg
import numpy as np
import lenstronomy.Util.util as util
class Coordinates(object):
"""
class to handle linear coordinate transformations of a square pixel image
"""
def __init__(self, transform... | StarcoderdataPython |
87176 | <gh_stars>1-10
# Aalto University, School of Science
# T-61.5140 Machine Learning: Advanced probabilistic Methods
# Author: <EMAIL>, 2016
# Author: <EMAIL>, 2016
# Author: <EMAIL>, 2016
from numpy import outer, eye, ones, zeros, diag, log, sqrt, exp, pi, size, shape, sum, transpose, logaddexp
from numpy.linalg import ... | StarcoderdataPython |
1647060 | def decipher(message,pasword):
for changer in pasword:
message=message.replace(changer[0],changer[1])
return message
| StarcoderdataPython |
3261521 | <gh_stars>0
import os
import time
import logging
from linux_plex_updater.service import UpdateService
# Configure logging
logging.basicConfig(
format="%(asctime)s\t%(levelname)s\t%(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
)
def main():
# Get and check parameters
params = {
... | StarcoderdataPython |
1694912 | #!/usr/bin/env python
# coding: utf-8
# In[23]:
import jieba
import jieba.posseg as pseg
print ("加載用戶詞典 ......")
jieba.load_userdict('data/pos.txt')
jieba.load_userdict('data/neg.txt')
# In[24]:
# 分詞,返回List
def segmentation(sentence):
seg_list = jieba.cut(sentence)
seg_result = []
for w in seg_list:... | StarcoderdataPython |
3234852 | from pyspark.sql.functions import *
from pyspark.sql.session import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, LongType
spark = SparkSession.builder.master('local').getOrCreate()
df = spark.read.format("json").load("D:/Santhu_practice/practice/Spark-The-Definitive-Guide/data/flight... | StarcoderdataPython |
1780046 | <reponame>hpecl-sspku/hpecl-2017<filename>kaggle/src/functions.py
import numpy as np
import pandas as pd
from skimage import morphology
from skimage.morphology import binary_closing, binary_opening, disk, binary_dilation
def run_length_encoding(x):
dots = np.where(x.T.flatten() == 1)[0]
run_lengths = []
pr... | StarcoderdataPython |
38840 | from django.utils import timezone
from django.shortcuts import get_object_or_404
from backend.cuida24.serializers import *
logger = logging.getLogger("mylogger")
def habitsFrontToBackJSON(request_data, user):
request_data['caregiver'] = get_object_or_404(Caregiver, info=user.pk).pk
return request_data
def ... | StarcoderdataPython |
3263180 | <reponame>JonasSchatz/DepixHMM
from typing import Tuple, List
from unittest import TestCase, skip
from PIL import ImageFont, Image
from resources.fonts import DemoFontPaths
from text_depixelizer.training_pipeline.original_image import ImageCreationOptions, generate_image_from_text, \
OriginalImage, draw_character... | StarcoderdataPython |
3221678 | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
3298562 | # TODO: create a list of numbers
numbers = [_, _, _, _]
# add the numbers together
s = sum(numbers)
# count how many values are in numbers
N = len(numbers)
# TODO: compute the arithmetic mean
mean = _ / _
# TODO: display the arithmetic mean
print(f"Mean: {____}")
# The program should output:
# Mean: 4.0
| StarcoderdataPython |
112937 | from . import utils # noqa: F401
from .pgd import pgd # noqa: F401
| StarcoderdataPython |
5158 | from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
class BlacklistValidator:
blacklist = []
def __call__(self, value):
# Validation logic
if value in self.blacklist:
raise... | StarcoderdataPython |
101157 | <reponame>nightblade9/steam-review-checker<filename>main.py
import datetime
from fetchers.steam_fetcher import SteamFetcher
from fetchers.discussion_fetcher import DiscussionFetcher
from fetchers.game_fetcher import GameFetcher
from fetchers.review_fetcher import ReviewFetcher
import http.server
import json
impo... | StarcoderdataPython |
7842 | <reponame>Aaron-Ming/websocket_terminal<filename>server-python3/server.py<gh_stars>10-100
import os
import urllib.parse
import eventlet
import eventlet.green.socket
# eventlet.monkey_patch()
import eventlet.websocket
import eventlet.wsgi
import wspty.pipe
from flask import Flask, request, redirect
from wspty.EchoTermi... | StarcoderdataPython |
3311926 | # -*- coding: utf-8 -*-
"""
tmdbsimple
~~~~~~~~~~
*tmdbsimple* is a wrapper, written in Python, for The Movie Database (TMDb)
API v3. By calling the functions available in *tmdbsimple* you can simplify
your code and easily access a vast amount of movie, tv, and cast data. To find
out more about The Movi... | StarcoderdataPython |
1756199 | <filename>macrostrat/show_color.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Sun May 29 13:17:48 2016
@author: jhusson
"""
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
#LIST OF COLORS
cnames={}
for name, hex in matplotlib.colors.cnames.iteritems():
... | StarcoderdataPython |
3346931 | import random
import os
import time
import numpy as np
import coords
import strategies
from strategies import MCTSPlayer
import utils
from features import extract_features, NEW_FEATURES
import preprocessing
strat_args=strategies.main('')
def play(network, args, device=None):
''' Plays out a self-play match, retur... | StarcoderdataPython |
191524 | #!/usr/bin/env python2
from __future__ import print_function
import base64
import sys
payload = """
fetch('http://challenge.acictf.com:51204/article/1').then(function(resp) {
return resp.text();
}).then(function(text) {
flag = text.match(/ACI{.*}/g);
window.location = 'http://requestbin.net/r/u36iixu3?f=' + fl... | StarcoderdataPython |
3214133 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0010_auto_20151016_1654'),
]
operations = [
migrations.AddField(
model_name='article',
nam... | StarcoderdataPython |
163775 | import logging
import os
import re
import urllib.parse
from typing import Set, List, Iterable, Dict, Optional
import requests
from bauh.api.http import HttpClient
from bauh.gems.arch import AUR_INDEX_FILE, git
from bauh.gems.arch.exceptions import PackageNotFoundException
URL_INFO = 'https://aur.archlinux.org/rpc/?v... | StarcoderdataPython |
57670 | def run():
return "I am open to the public"
| StarcoderdataPython |
82251 | <filename>base/client/tile.py
'''
@ <NAME> (<EMAIL>)
Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot
Tile: Objects for representing Generals IO Tiles
'''
from queue import Queue
import time
import logging
from .constants import *
class Tile(object):
def __init__(self, gamemap, x... | StarcoderdataPython |
1747701 | N = int(input())
print((N % 12) + 1) | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.