id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
270365 | # Copyright 2015 ARM Limited
#
# 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 |
3245829 | import json
# create a list of the extracted properties and combine their facets to them -> using the property_dictionary.json
# .. from the wikidata_research
# .. per timeframe
#
def create_dict_based_on_properties_dict_timeframe_and_Wikidata_property_dict_per_timeframe(location, mode, redundant_mode):
if mode no... | StarcoderdataPython |
1845403 | """Support for the Hive binary sensors."""
from datetime import timedelta
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OPENING,
DEVICE_CLASS_SMOKE,
DEVICE_CLASS_SOUND,
BinarySensorEntity,
)
from . import ATTR_AVAILABLE, ATTR_... | StarcoderdataPython |
1794800 | from loguru import logger
from bubop import logger, loguru_set_verbosity
def test_loguru_set_verbosity(caplog):
logger.debug("kalimera")
loguru_set_verbosity(0)
logger.debug("kalinuxta")
captured = caplog.text
assert "kalimera" in captured
assert "kalinuxta" not in captured
| StarcoderdataPython |
4965273 | from os.path import isfile
from pickle import dump, load
import pygame
from pygame.font import Font
from pygame.time import Clock
from pyperclip import paste
from audio_player import AudioPlayer
from game import Game
from library import Library
from track import Track
from util import ALL_LAYERS, seconds_to_readable_... | StarcoderdataPython |
1976590 | <gh_stars>1-10
import pandas as pd
from pulp import *
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def best_reco(required_resources, instance_df):
prob = LpProblem("InstanceRecommender", LpMinimize)
instances = instance_df['name'].value... | StarcoderdataPython |
3465386 | import vk_api, time, random
from server_logout import Client_output, Logs
class Vk_accounts:
def read_file_token(file_name):
try:
file = open(file_name, 'r')
except:
file.close()
return None
list = []
for line in file.readlines():
... | StarcoderdataPython |
3254020 | <filename>src/pyenv_inspect/path.py
from __future__ import annotations
import os
from pathlib import Path
from .exceptions import PathError
def get_pyenv_root() -> Path:
try:
pyenv_root = Path(os.environ['PYENV_ROOT']).resolve()
except KeyError:
pyenv_root = Path.home() / '.pyenv'
if not... | StarcoderdataPython |
6590636 | <filename>invenio_userprofiles/admin.py<gh_stars>1-10
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin views for invenio-user... | StarcoderdataPython |
3319135 | # Generated by Django 3.1.1 on 2020-11-20 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('report', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='report',
name='reportfile',
... | StarcoderdataPython |
1691647 | <filename>tests/analysis/test_label.py
import os
import numpy as np
import pandas as pd
import pytest
import trackintel as ti
from trackintel.analysis.labelling import _check_categories
class TestCreate_activity_flag:
"""Tests for create_activity_flag() method."""
def test_create_activity_flag(self):
... | StarcoderdataPython |
3591521 | <filename>dataloaders/dataloader_triplet.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 16:05:38 2019
- Dataloader for triplet of graph-data.
- trainset only includes ids that has valid positive-pairs (iou > threshold.) e.g. 0.6
- randomly sample anchors [same as previous]
-... | StarcoderdataPython |
6486671 | from .attn_talling_head import *
from .cls_block import *
| StarcoderdataPython |
11373183 | import numpy as np
def evaluate_model(dataset, interpreter):
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
predictions = []
labels = []
done = 0
for test_images, test_labels in dataset:
# Run predictions on every image in the "test" data... | StarcoderdataPython |
11399611 | # Copyright 2009-2010 <NAME>
# Copyright 2009-2010 Intelerad Medical Systems Incorporated
# Copyright 2010-2011 Fog Creek Software
# Copyright 2010-2011 Unity Technologies
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''setup f... | StarcoderdataPython |
9774857 | import os
from tkinter import *
from tkinter import filedialog
from tkmacosx import Button, CircleButton
import tkinter.font as font
import datetime as dt
import SongDB as s_db
import PlaylistDB as p_db
import Tapes as tp
import Playlists as pl
import ProjTools as pt
import numpy as np
class CreatePlayList(Frame):
... | StarcoderdataPython |
53578 | from django.shortcuts import render
from django.views.generic import CreateView
from django.urls import reverse_lazy
from dal import autocomplete
# from .models import Country, Person
# from .forms import PersonForm
from .models import Country
from .forms import CountryForm
# Create your views here.
# class PersonCrea... | StarcoderdataPython |
1721856 | <filename>github_loading.py
import logging
from requests.models import Response
from EntityLoader import LoadBehaviour
def get_url_params(params: dict) -> str:
_params = '&'.join(['{}={}'.format(k, v) for k, v in params.items()])
return '?{}'.format(_params) if len(_params) > 0 else ''
class GithubLoadBeha... | StarcoderdataPython |
3203734 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
import gym
import numpy
from gym.spaces.box import Box
__all__ = ["NoisyWrapper"]
class NoisyWrapper(gym.ObservationWrapper):
"""Make observation dynamic by adding noise"""
def __init__(self, env=None, percent_pad=5, bottom_margin=20):
... | StarcoderdataPython |
1822258 | <gh_stars>1-10
import random
import string
lowercase = "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
uppercase = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
def firstName():
names=('Alexia'... | StarcoderdataPython |
1801424 | <reponame>a-shah8/LeetCode
class Solution:
def maxDepth(self, s: str) -> int:
max_depth = 0
count = 0
for c in s:
if c=='(':
count += 1
max_depth = max(max_depth, count)
elif c==')':
c... | StarcoderdataPython |
95456 | # From Dalgaard page 83 [R755c9bae090e-1]_, suppose the daily energy intake for 11
# women in kilojoules (kJ) is:
intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
7515, 8230, 8770])
# Does their energy intake deviate systematically from the recommended
# value of 7725 kJ? Our n... | StarcoderdataPython |
3595381 | <reponame>jorasdf24/workflow-manager<filename>Workflow-manager.py<gh_stars>1-10
import os
import sys
import time
import sqlite3
import urllib.request as req
import urllib.parse as p
def is_valid_url(url):
"""Return True if the URL is valid, and false if not"""
try:
request = req.Request(url)
try:
... | StarcoderdataPython |
1771175 | <filename>tests/util/py/decorators_test.py
# Copyright 2014-2020 <NAME> <<EMAIL>>.
#
# 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 |
4996216 | <reponame>kitawarairon/curso-pyton-engenharia
import time
from intermediario.Clientes import Cliente
from intermediario.Contas import Conta, ContaEspecial
from intermediario.Bancos import Banco
pedro = Cliente('pedro', '77445588', '33344466678')
maria = Cliente('maria', '99885533', '11111111111')
polly = Cliente('poll... | StarcoderdataPython |
1622040 | <gh_stars>1-10
import pytest
from wyrd.constrained_types import (
UnmetConstraintError,
ConstrainedFloat,
add_constraint,
)
@add_constraint(lambda x: x == 3.0, "Pi is exactly 3")
class PiNumber(ConstrainedFloat):
pass
@add_constraint(lambda x: x >= 1.5, "must be greater than or equal to 1.5")
@add_... | StarcoderdataPython |
9621239 | """
Module for CAS communication using the bottle framework
"""
from client import CASClient, CASMiddleware
| StarcoderdataPython |
3396862 | # pylint: disable=protected-access
from collections import OrderedDict
from inspect import getmembers
from rest_framework.decorators import action
from rest_framework import viewsets as vsets
from ..exceptions import VSTUtilsException
def __get_nested_path(name, arg=None, arg_regexp='[0-9]', empty_arg=True):
path... | StarcoderdataPython |
366141 | <filename>diary/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dia... | StarcoderdataPython |
299570 | """
Direct ports of Julia's `nextprod` [1], with helper function `nextpow` [2],
which are in Julia 1.2.0.
[1] https://github.com/JuliaLang/julia/blob/c6da87ff4bc7a855e217856757ad3413cf6d1f79/base/combinatorics.jl#L248-L262
[2] https://github.com/JuliaLang/julia/blob/c6da87ff4bc7a855e217856757ad3413cf6d1f79/base/intfun... | StarcoderdataPython |
11237313 | <reponame>celioroberto06/cursopythonexercicios
print('-' * 15)
print('LOJA O BARATÃO')
print('-' * 15)
total_compra = mais_caro = mais_barato = nome_barato = 0
perg = cont = 0
while True:
nome = str(input('Nome do produto: '))
preco = float(input('Preço: R$'))
total_compra += preco
cont += 1
if prec... | StarcoderdataPython |
5035015 | # -*- coding: utf-8 -*-
#
# Copyright 2010 <NAME>
#
# 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 |
8002143 | from django.shortcuts import render
from .models import Purchase
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.shortcuts import get_ob... | StarcoderdataPython |
205554 | #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from os import path
import re
from bes.compat.map import map
from bes.system.execute import execute
from bes.key_value.key_value_list import key_value_list
from bes.text.text_line_parser import text_line_parser
from bes.common.a... | StarcoderdataPython |
9629528 | def calculate(n, summ):
if n <= 1:
return n
summ += calculate(n//2, summ)
summ += n%2
return summ
print(calculate(7, 0)) | StarcoderdataPython |
9602373 | import api
class MpAwsEks:
policies = [
api.AcceptLink(filters=[
api.f.endpoint("app", "kube-system.kube.kube-proxy"),
api.f.type("NAE"),
api.f.endpoint("process", "kube-proxy", who="client"),
api.f.endpoint("dns_pattern", ":.*\.eks\.amazonaws... | StarcoderdataPython |
1771854 | ################################################################################################################################################################
# @project Open Space Toolkit ▸ Core
# @file bindings/python/test/types/test_integer.py
# @author <NAME> <<EMAIL>>
# @license ... | StarcoderdataPython |
8104041 | # -*- coding: utf-8 -*-
"""
Created 5 March 2019
epsc_peak_x.y.z.py
"""
# from __main__ import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import elephant
from neo.io import IgorIO
import os
from collections import OrderedDict
import math
def get_metadata(file, data_notes):
'''Takes... | StarcoderdataPython |
16483 | <reponame>sverbanic/ps2-npjBM
from .result import Result
import numpy as np
import pandas as pd
class DiffAbunRes(Result):
def __init__(self, otu_table, transform_pipe=None, percent=False, **kwargs):
super().__init__()
self.pre_vs_skin = diff_rel_abun(otu_table, compare='pre_vs_skin', transform_... | StarcoderdataPython |
1704449 | <gh_stars>0
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from .layers import Encoder, Decoder
from .utils_deep import Optimisation_VAE
import numpy as np
from ..utils.kl_utils import compute_kl, compute_kl_sparse, compute_ll
import pytorch_lightning as pl
fr... | StarcoderdataPython |
1902371 | from django.shortcuts import get_object_or_404
from django.contrib.auth import get_user_model
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_restframework_2fa.serializers import RequestLoginSerializer
from twilio.base.exceptions impo... | StarcoderdataPython |
5087461 | <gh_stars>1-10
from __future__ import print_function
import logging
import os
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from collections.abc import Iterable
from pprint import pformat
import birdvoxclassify
from birdvoxclassify.core import DEFAULT_MODEL_NAME
from birdvoxclassify.birdv... | StarcoderdataPython |
11235240 | from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import ArchivePost
def archive_post_year_list(request):
year_list = ArchivePost.objects.all()
data = {"results": list(year_list.values("year"))}
return JsonResponse(data)
def archive_post_year_detail(r... | StarcoderdataPython |
3242274 | <reponame>radovankavicky/pymaclab
import pymaclab as pm
import pymaclab.modfiles.models as models
rbc = pm.newMOD(models.stable.rbc1_num,mesg=False,ncpus='auto')
# Try to update all of the wrapped objects and test if this has worked
# Do for paramdic, set_item
def test_paramdic_item():
eta_key = 'eta'
eta_ol... | StarcoderdataPython |
46817 | <gh_stars>1-10
class Recommendation:
def __init__(self, title):
self.title = title
self.wikidata_id = None
self.rank = None
self.pageviews = None
self.url = None
self.sitelink_count = None
def __dict__(self):
return dict(title=self.title,
... | StarcoderdataPython |
3444930 | <reponame>MorvanZhou/my_research<filename>self_driving_research_DQN/learning_methods.py
# View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
import pandas as pd
impor... | StarcoderdataPython |
8130453 | from __future__ import absolute_import, division, print_function, unicode_literals
import torch
from tests import utils
class SimpleUnsqueezeModel(torch.nn.Module):
def __init__(self, dimension, inplace=False):
super(SimpleUnsqueezeModel, self).__init__()
self.dimension = dimension
self.i... | StarcoderdataPython |
11362544 | <gh_stars>0
import os
import re
import pandas as pd
from extractor import extract
from voluptuous import (Schema, Required, All, Optional, Length, Any,
MultipleInvalid, Match, Coerce)
# Lookups
iso_country = pd.read_csv('./Lookups/ISO_COUNTRY.csv', dtype='str',
encodin... | StarcoderdataPython |
52506 | <reponame>MichaelWiciak/SortingAlgorithms
def insertionSort(aList):
first = 0
last = len(aList)-1
for CurrentPointer in range(first+1, last+1):
CurrentValue = aList[CurrentPointer]
Pointer = CurrentPointer - 1
while aList[Pointer] > CurrentValue and Pointer >= 0:
a... | StarcoderdataPython |
1619678 | <reponame>jcnelson/syndicate<gh_stars>10-100
#!/usr/bin/python
import socket
import time
import sys
import urllib2
import base64
auth = "<PASSWORD>:<PASSWORD>"
hostname = sys.argv[1]
port = int(sys.argv[2] )
filename = sys.argv[3]
data = sys.argv[4]
offset = 0
if len(sys.argv) > 5:
offset = int(sys.argv[5])
s =... | StarcoderdataPython |
1652482 | <reponame>sheepy0125/hisock
# import pytest
# from server import start_server
# from client import connect
# from utils import get_local_ip
| StarcoderdataPython |
9783126 | <reponame>Arusey/Porfolio-website<gh_stars>0
# Generated by Django 3.1.6 on 2021-02-21 07:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0003_auto_20210221_0617'),
]
operations = [
migrations.AddField(
model... | StarcoderdataPython |
7337 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Module Name
Description...
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, <NAME>"
__credits__ = ["<NAME>","etc."]
__date__ = "2021/04/12"
__license__ = "GPL"
__version__ = "1.0.0"
__pythonversion__ = "3.9.1"
__maintainer__ = "<NAME>"
... | StarcoderdataPython |
11390394 | <reponame>Andrei486/class_export<gh_stars>0
import logging
LOG_FILE = "course_export.log"
logging.basicConfig(filename=LOG_FILE, level=logging.INFO) | StarcoderdataPython |
5019400 | <reponame>dladowitz/bitcoincorps
import sqlite3
import time
import pytest
import handing_threads
from ibd.four.crawler import *
from ibd.three.complete import Address
@pytest.fixture(scope="function")
def db(tmpdir):
# FIXME do this in-memory
import os
f = os.path.join(tmpdir.strpath, "test.db")
c... | StarcoderdataPython |
6548074 | <reponame>fxavier/echosys
from rest_framework import serializers
from openmrs_viamo.models import Visit
class VisitSerializer(serializers.ModelSerializer):
class Meta:
model = Visit
fields = (
'id',
'type_visit',
'province',
'district',
... | StarcoderdataPython |
3497380 | #
# Automated Dynamic Application Penetration Testing (ADAPT)
#
# Copyright (C) 2018 Applied Visions - http://securedecisions.com
#
# Written by <NAME> - http://www.siegetechnologies.com/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... | StarcoderdataPython |
8027243 | #!/usr/bin/env python
def pgeplt(rc):
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
rc.loadenergies()
bd=pg.mkPen(width=2,color=(200, 200, 255), style=QtCore.Qt.DotLine)
plotWidget = pg.plot(title="Change in energies for "+rc.dirname,labels={'left':'dE','bottom':'twci'})
... | StarcoderdataPython |
6648908 | <filename>b_cfn_elasticsearch_index_test/testing_infrastructure.py<gh_stars>0
from aws_cdk.core import Stack
from aws_cdk.aws_elasticsearch import Domain, ElasticsearchVersion, CapacityConfig, ZoneAwarenessConfig, EbsOptions
from aws_cdk.aws_ec2 import EbsDeviceVolumeType
from b_cfn_elasticsearch_index.resource import... | StarcoderdataPython |
67283 | # -*- coding: utf-8 -*-
# This file is distributed under the same License of Python
# Copyright (c) 2014 <NAME> <<EMAIL>>
"""
build_manpage.py
Add a `build_manpage` command to your setup.py.
To use this Command class import the class to your setup.py,
and add a command to call this class::
from build_manpage ... | StarcoderdataPython |
3593201 | <gh_stars>0
"""
Write Python code that asks a user how many pizza slices they want. The pizzeria charges Rs
123.00 a slice. if user order even number of slices, price per slice is Rs 120.00. Print the total
price depending on how many slices user orders.
"""
n = int(input("Enter no' of slices: "))
if n%2==0:
p... | StarcoderdataPython |
3335217 | from django.contrib import admin
# Register your models here.
# Setup the URLs and include login URLs for the browsable API. | StarcoderdataPython |
1663455 | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone... | StarcoderdataPython |
9671040 | <gh_stars>0
import os
from flask import Flask, flash, request, redirect, url_for, jsonify
from werkzeug.utils import secure_filename
import json
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/... | StarcoderdataPython |
9650450 | """
App entry point
Authors:
- <NAME> (<EMAIL>)
"""
import glob
import os
import time
import traceback
from multiprocessing import Process
from multiprocessing.managers import SyncManager
from typing import Any, Dict, List, Optional
import click
from click.core import Context
from click.exceptions import Abort
fr... | StarcoderdataPython |
1753836 | import requests
from . import FeedSource, _request_headers
class Bittrex(FeedSource):
def _fetch(self):
feed = {}
url = "https://bittrex.com/api/v1.1/public/getmarketsummaries"
response = requests.get(url=url, headers=_request_headers, timeout=self.timeout)
result = response.json()... | StarcoderdataPython |
12842869 | from abc import ABCMeta, abstractmethod
class AbstractTransformation:
__metaclass__ = ABCMeta
@abstractmethod
def transform_image(self, image): pass
@abstractmethod
def transform_position(self, x, y, width, height): pass
@abstractmethod
def generate_random(self): pass
| StarcoderdataPython |
3488975 | <filename>api/endpoints/projects/topicProject.py
from flask import Blueprint, jsonify, request
from models.models import (
db,
TopicModel,
ProjectModel,
RelProjectTopic,
)
topicProject_api = Blueprint("topicProject_api", __name__)
@topicProject_api.route("/addProjectTopic", methods=("POST",))
def ad... | StarcoderdataPython |
8156959 | <gh_stars>0
from django.apps import AppConfig
class DjangoKmatchConfig(AppConfig):
name = 'django_kmatch'
verbose_name = 'Django Kmatch'
| StarcoderdataPython |
1836164 | import json
import argparse
import numpy as np
import tensorflow as tf
import transformers as tm
from load_data import *
def build_clf_model(vocab_size, params):
# Build Transformer for Language Modeling task
model = tf.keras.Sequential()
model.add(tf.keras.layers.Embedding(vocab_size, params["embed"], ... | StarcoderdataPython |
5046346 | <reponame>lht19900714/Leetcode_Python<filename>Algorithms/0119_Pascal's_Triangle_II/Python/Pascal's_Triangle_II_Solution_1.py
# Space: O(n)
# Time: O(n^2)
# same approach as solution 1, compress space from n^2 to n
class Solution:
def getRow(self, rowIndex):
data = [1 for _ in range(rowIndex + 1)]
... | StarcoderdataPython |
5005804 | <gh_stars>0
#!/usr/local/bin/python
#encoding:utf8
import sys, os, datetime, time, pty, pprint, shutil, re
sys.path.insert(0, "..")
from fabric.api import(
run, env, prompt, put, cd
)
from fabric.contrib.files import (
exists as fab_exists,
append as fab_append,
)
from fabric.context_managers import (
... | StarcoderdataPython |
8045148 | <filename>streamlabs/streamlabsrun.py
import requests
from config import STREAMLABS_SECRET, STREAMLABS_ID, STREAMLABS_REDIRECT
from decimal import Decimal
import pprint
import os
import json
import time
def streamlabs_handler(q_twitchbeagle, q_gpio):
#Grab streamlabs tokens
headers = []
while True:
... | StarcoderdataPython |
6471510 | import numpy as np
from ptools.R4C.policy_gradients.actor_critic_shared.ac_shared_model import ACSharedModel
from ptools.R4C.trainer import FATrainer
class ACSharedTrainer(FATrainer):
def __init__(
self,
acs_model: ACSharedModel,
verb= 1,
**kwargs):
... | StarcoderdataPython |
1651508 | from enum import Enum, unique
@unique
class Game(str, Enum):
ALL = "All"
HALO_CE = "HaloCombatEvolved"
HALO_2 = "Halo2"
HALO_2_ANNIVERSARY = "Halo2Anniversary"
HALO_3 = "Halo3"
HALO_4 = "Halo4"
HALO_REACH = "HaloReach"
| StarcoderdataPython |
1765839 | <gh_stars>0
from app import app
import urllib.request,json
from .models import source,article
Source = source.Source
Article = article.Article
# Getting api key
api_key = app.config['NEWS_API_KEY']
base_url = app.config["SOURCE_API_BASE_URL"]
articles_url = app.config["ARTICLE_API_BASE_URL"]
def get_sources(category)... | StarcoderdataPython |
11270812 | <filename>matplotlib_exercise/interactive/rm_point.py
from matplotlib import pyplot as plt
import numpy as np
LEFT_CLICK = 1
RIGHT_CLICK = 3
class PointRemover:
"""point remover"""
def __init__(self, pts):
pts = np.asarray(pts)
fig, ax = plt.subplots()
self.fig = fig
self.ax ... | StarcoderdataPython |
12806610 | # Copyright FuseSoC contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
r"""Support for parsing String expression syntax in core files
FuseSoC core files allow strings matching the following pseudo-BNF:
exprs ::= expr
| expr exprs
ex... | StarcoderdataPython |
1941341 | class Solution:
def pad_words(self, accumulated, L):
if len(accumulated) == 1:
return accumulated[0].ljust(max(len(accumulated[0]), L), ' ')
raw_size = sum([len(i) for i in accumulated])
remain_padding_size = L - raw_size
result = []
padded_words = 0
whi... | StarcoderdataPython |
8082900 | #
# This module holds functions which are used to create our DNS requests.
#
import logging
import math
import random
import struct
logger = logging.getLogger()
#
# A lookup table for our query types.
#
query_types = {
"a": 1,
"ns": 2,
"md": 3,
"mf": 4,
"cname": 5,
"soa": 6,
"mb": 7,
"mg": 8,
"mr": 9,
"n... | StarcoderdataPython |
9692948 | from typing import List
import databases
import pytest
import sqlalchemy
from fastapi import FastAPI
from starlette.testclient import TestClient
import ormar
from tests.settings import DATABASE_URL
app = FastAPI()
metadata = sqlalchemy.MetaData()
database = databases.Database(DATABASE_URL, force_rollback=True)
app.s... | StarcoderdataPython |
9646345 | <filename>utils/noise.py
import numpy as np
import torch
class RandomActionNoise:
def __init__(self, action_dim, mu=0, theta=0.1, sigma=1):
self.action_dim = action_dim
self.mu = mu
self.theta = theta
self.sigma = sigma
self.x = np.ones(self.action_dim) * self.mu
def r... | StarcoderdataPython |
1919821 | <reponame>upamanyus/primerunning<filename>src/primefunctions.py
class PrimeFunctions:
def __init__(self, textName):
primeFile = open(textName)
primeStrings = primeFile.read().split()
primeFile.close()
self.maxValue = int(primeStrings[0])
self.primes = [int(num) for num in pri... | StarcoderdataPython |
8149615 | from __future__ import division
import numpy as np
import math
from decimal import Decimal
def MLEstimation(graph, data):
gragh_flip=np.array(map(list,zip(*graph)))
cptList=[]
for i in range(len(gragh_flip)):
variable=i
parents=[]
for k in range(len(gragh_flip[i])):
if ... | StarcoderdataPython |
92565 | <gh_stars>1-10
#! /usr/bin/env python
# Use setuptools, falling back on provide
try:
from setuptools import setup, find_packages
except ImportError:
import distribute_setup
distribute_setup.use_setuptools()
from setuptools import setup, find_packages
import sys
from seqmagick import __version__ as ve... | StarcoderdataPython |
3337850 | from django import forms
from users.models import User
class UserForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
lastname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
email = forms.CharField(widget=forms.EmailInput(attrs={'c... | StarcoderdataPython |
1709393 | <gh_stars>0
from django import forms
from .models import *
from pyuploadcare.dj.forms import ImageField
from django.contrib.auth.models import User
class EditProfileForm(forms.ModelForm):
"""
Form to edit user profile
"""
class Meta:
model=User_profile
fields = ('bio','profile_pic','em... | StarcoderdataPython |
3202760 | from serene_load.helpers.containers.container_base import TempFileContainer, BaseContainer, BaseProcessor
import logging
import datetime
import io
import re
import subprocess
log = logging.getLogger()
class SevenZipFileContainer(TempFileContainer):
def decompress(self, source, target):
subprocess.check_c... | StarcoderdataPython |
4934819 | <reponame>khaledboka/point_to_line<gh_stars>0
from django.apps import AppConfig
from . import APP_NAME
class PointToLineConfig(AppConfig):
name = APP_NAME
verbose_name = "Point To Line"
| StarcoderdataPython |
1947115 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
from time import sleep
import datetime
import serial
import os
import smtplib
from email.mime.text import MIMEText
GPIO.setmode(GPIO.BCM)
#Here you can choose whether you want to receive an email when the Raspberry Pi restarts - 1 to ac... | StarcoderdataPython |
328326 | import pandas as pd
from chispa import assert_df_equality
from cishouseholds.derive import assign_filename_column
from cishouseholds.pipeline.ETL_scripts import extract_input_data
def test_assign_filename_column(pandas_df_to_temporary_csv, spark_session):
pandas_df = pd.DataFrame(
data={
"id"... | StarcoderdataPython |
1979564 | <gh_stars>0
termn = input("Number of Terms: ")
termn = int(termn)
terms = []
final =0
for i in range (0, termn):
cu = input("Term " +str(i + 1)+ ": ")
cu = int(cu)
terms.append(cu)
for item in terms:
final += item
print(final) | StarcoderdataPython |
9797954 | <gh_stars>100-1000
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_noop
from django.views.generic import View
from djng.views.mixins import (
JSONRe... | StarcoderdataPython |
4870223 | import base64
import logging
from Crypto.Util.Padding import pad
from padding_oracle import AESPaddingOracle, Base64OracleClient
logger = logging.getLogger('padding-oracle')
logger.setLevel('INFO')
if __name__ == "__main__":
bas64_ciphertext = "<KEY>~~"
bas64_ciphertext = bas64_ciphertext.replace('~', '=').... | StarcoderdataPython |
1682464 | #!/usr/bin/env python
#purpose: extract reciprocal best BLAST matches for a pair of datasets
#usage: ./reciprocal_blast_hits.py a_vs_b b_vs_a col_query col_match col_score sort_order out_file
#example, requires both blast hits attained highest bit score (12th column in blast's '-outfmt 6'):
# ./reciprocal_blast_hit... | StarcoderdataPython |
3438773 | <gh_stars>0
"""*****************************************************************************
* Copyright (C) 2018-2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* r... | StarcoderdataPython |
3406898 | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import sys
import re
import six
from subprocess import check_output
def to_string(ver):
if not ver:
return ""
return ".".join([six.text_type(c) for c in ver])
def exit_if_not_within(ver, min_ver, max_ver=None):
if ver ... | StarcoderdataPython |
1898549 | <filename>profile/blog.py
import flask
import werkzeug.exceptions
import profile.admin
import profile.db
bp = flask.Blueprint('blog', __name__, url_prefix='/blog')
@bp.route('/')
def index():
"""Display posts"""
db = profile.db.get_db()
query = (
'SELECT p.id, title, body, created, author_id, us... | StarcoderdataPython |
3255732 | <reponame>toonsegers/sec_groups
"""Secure norm protocols by <NAME>, adapted by <NAME>.
See: https://www.researchgate.net/profile/Thijs_Veugen
"""
import itertools
from mpyc.runtime import mpc
def norm(self, x):
"""Recursive norm (adapted from mpc._norm())."""
def _norm(x):
n = len(x)
... | StarcoderdataPython |
6505394 | # -*- coding: utf-8 -*-
from django.db import models
from config.common import Common
from django.utils.translation import ugettext_lazy as _
from agent.models import Agent
from django_fsm import FSMKeyField, transition
import datetime
from django.db.models.signals import post_save
from django.utils.formats import date... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.