id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1696658 | import numpy as np
from gait import *
import cv2
import os
import pickle
kmeans = kmean_train(subject='001',choice='bg-01',override=True)
ret = supervision(kmeans,override=True)
if ret:
a = fetch_labels()
| StarcoderdataPython |
1798234 | #!/usr/bin/python3
import sys
import re
import numpy as np
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", dest="source_file", help="File with Scan commands")
parser.add_argument("-o", "--output", dest="output_file", help="File generated with Pu... | StarcoderdataPython |
94096 | import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn import decomposition
import scipy.signal
import os
import pandas as pd
from skimage.transform import resize
def get_mean(signal: np.ndarray, axis=0):
return signal.mean(axis=axis)
def get_std_dev(signal: np.nd... | StarcoderdataPython |
1693348 | """
This file
1. Reads in raw wikipedia sentences from /lfs/raiders7/0/lorr1/sentences
2. Reads in map of WPID-Title-QID from /lfs/raiders7/0/lorr1/title_to_all_ids.jsonl
3. Computes frequencies for alias-QID over Wikipedia. Keeps only alias-QID mentions which occur > args.min_frequency
4. Merges alias-QID map with ali... | StarcoderdataPython |
1717384 | <filename>indi_mr/i_to_m.py
"""Defines blocking function inditomqtt:
Receives XML data from indiserver on port 7624 and publishes via MQTT.
Receives data from MQTT, and outputs to port 7624 and indiserver.
"""
import sys, collections, threading, asyncio
from time import sleep
from datetime import... | StarcoderdataPython |
155701 | from examples.wmt_2020.common.util.download import download_from_google_drive
from examples.wmt_2020.ro_en.transformer_nmt_config import MODEL_TYPE, transformer_nmt_config, DRIVE_FILE_ID, \
MODEL_NAME, GOOGLE_DRIVE, TEMP_DIRECTORY, RESULT_FILE
from transquest.algo.transformers.run_model import QuestModel
import tor... | StarcoderdataPython |
3234494 | import numpy as np
import matplotlib
# matplotlib.use('module://matplotlib-backend-kitty')
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from zoo import Zoo
from sa import simulated_annealing
objectives = [Zoo().get('branin').make_explicit(),
Zoo().get('golds... | StarcoderdataPython |
1725659 | <reponame>nursix/STL
# -*- coding: utf-8 -*-
#
# Database upgrade script
#
# STL Template Version 2.1.3 => 2.1.4
#
# Execute in web2py folder after code upgrade like:
# python web2py.py -S eden -M -R applications/eden/modules/templates/STL/upgrade/2.1.3-2.1.4.py
#
#import datetime
import sys
#from s3 import S3DateTime
... | StarcoderdataPython |
4820031 | import aiml
import sys
from bottle import run
from bottle import route
from bottle import request
from bottle import redirect
from random import choice
from lib.views import index
from lib.views import Response
botbrain = aiml.Kernel()
botbrain.learn('brain/yulan.aiml')
@route('/')
def RenderIndex():
return ind... | StarcoderdataPython |
3337009 | # -*- coding: utf-8 -*-
import unittest
import ddt
import cefp
@ddt.ddt
class TestCEF(unittest.TestCase):
@ddt.file_data('test_cefp.json')
def test_parse(self, input, expected):
if isinstance(expected, dict):
self.assertEqual(cefp.parse(input), expected)
else:
self.ass... | StarcoderdataPython |
81881 | #coding=utf-8
########################################
# <NAME>
# Cloning update 2020
########################################
import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,getpass
os.system('rm -rf .txt')
for n in range(100000):
nmbr = random.randint(1111111, 9999999)
sys... | StarcoderdataPython |
3276796 | <filename>src/AOJ/ITP1_10_B.py
import math
def resolve():
a, b, C = map(float, input().split())
x = math.radians(C)
h = b * math.sin(x)
S = "{0:.8f}".format((a * h) / 2)
c = math.sqrt(a ** 2 + b ** 2 - 2 * a * b * math.cos(x))
L = "{0:.8f}".format(a + b + c)
print(S, L, h, sep="\n")
| StarcoderdataPython |
13769 | from __future__ import annotations
from math import log
from typing import List, Type, Union
from imm import MuteState, Sequence, lprob_add, lprob_zero
from nmm import (
AminoAlphabet,
AminoLprob,
BaseLprob,
CodonLprob,
CodonMarg,
DNAAlphabet,
FrameState,
RNAAlphabet,
codon_iter,
)... | StarcoderdataPython |
156429 | import pytest
from recipes.tests.share import create_recipes
from users.tests.share import create_user_api
pytestmark = [pytest.mark.django_db]
URL = '/api/users/subscriptions/'
RESPONSE_KEYS = (
'id',
'email',
'username',
'first_name',
'last_name',
'is_subscribed',
'recipes',
'recipe... | StarcoderdataPython |
186599 | from .queries import TerminalQuery, QueryParams
from .search import Searcher
from .services import SeqmotifService, SequenceService, StructureService, StructMotifService, TextService
class Command:
def __init__(self, url="https://search.rcsb.org/rcsbsearch/v1/query?", resp_type="entry",
start=0, ... | StarcoderdataPython |
3220658 | # Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if
# they consist of four octets, with values between 0..255 (included).
# Input to the function is guaranteed to be a single string.
# Examples
# // valid inputs:
# 1.2.3.4
# 172.16.17.32
# // invalid... | StarcoderdataPython |
3333338 | """Utility functions for the kraken integration."""
from __future__ import annotations
from pykrakenapi.pykrakenapi import KrakenAPI
def get_tradable_asset_pairs(kraken_api: KrakenAPI) -> dict[str, str]:
"""Get a list of tradable asset pairs."""
tradable_asset_pairs = {}
asset_pairs_df = kraken_api.get_t... | StarcoderdataPython |
170230 | <reponame>lennodev/ai-face-recognition-photo-grouping
import os
import shutil
import numpy as np
import tensorflow as tf
from PIL import Image as pilImage
from model.ModelLoader import ModelLoader
from service.FaceExtractService import FaceExtractService
from sklearn.preprocessing import LabelEncoder, Normalizer
cla... | StarcoderdataPython |
3210808 | """
Parallel HTTP transport
IMPORT from multiple independent processes running in parallel
"""
import pyexasol
import _config as config
import multiprocessing
import pyexasol.callback as cb
import pandas
import pprint
printer = pprint.PrettyPrinter(indent=4, width=140)
class ImportProc(multiprocessing.Process):
... | StarcoderdataPython |
170692 | <reponame>python-demo-codes/basics
# HEAD
# Augmented Assignment Operators
# DESCRIPTION
# Describes basic usage of all the augmented operators available
# RESOURCES
#
foo = 40
# Addition augmented operator
foo += 1
print(foo)
# Subtraction augmented operator
foo -= 1
print(foo)
# Multiplication augmented operator... | StarcoderdataPython |
143151 | # Add parent folder to path
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import unittest
import numpy as np
from src.Equations.KineticEnergy import KineticEnergy
from src.Common import particle_dtype
class test_kinetic_energy(unittest.TestCase):
def test(self):
num = 100
pA =... | StarcoderdataPython |
152103 | <gh_stars>0
#!/usr/bin/env python
# Egami: a very simple image gallery built using Flask, which
# serves image files found in the directory where it is executed.
# Copyright (C) 2011-2015 <NAME> <<EMAIL>>
# http://github.com/flebel/egami
#
# This program is free software: you can redistribute it and/or modify
# it und... | StarcoderdataPython |
150414 | <reponame>kjahan/evaluation
import os
from datetime import datetime
import pandas as pd
import tqdm
def load(filename, path, delim='\t'):
filename = os.path.join(path, filename)
dataframe = pd.read_csv(filename, sep=delim)
return dataframe
def parse_time(df):
date_parse = lambda x: pd.datetime.strp... | StarcoderdataPython |
142194 | <filename>python/xml_count_attrib.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 15:26:30 2019
@author: Ham
HackerRanch Challenge: XML 1 - Find the Score
You are given a valid XML document, and you have to print its score.
The score is calculated by the sum of the score of each element.
Fo... | StarcoderdataPython |
3200721 | from httpx import get,post
<KEY>CDFk=print
<KEY>DF='dunossauro'
KMcbLdesIhpqaHjnBNuvlOYmyASfQTPWVXtEJirGxgRUzwCkDo='meu_segrdo_123'
class KMcbLdesIhpqaHjnBNuvlOYmyASfQTPWVXtEJirGxgRUzwCDko:
def __init__(<KEY>):
KMcbLdesIhpqaHjnBNuvlOYmyASfQTPWVXtEJirGxgRUzwCkFD.atributo=7
def <KEY>D(<KEY>):
return KMcbLdesIhpqaHj... | StarcoderdataPython |
82870 | import json
import os
import os.path
import cv2
import numpy as np
import torch
import torch.utils.data as data_utl
from tqdm import tqdm
from dataset.vidor import VidOR
from frames import extract_all_frames
def video_to_tensor(pic):
"""Convert a ``numpy.ndarray`` to tensor.
Converts a numpy.ndarray (T x H ... | StarcoderdataPython |
137403 | <filename>sample_app/tasks/features/environment.py<gh_stars>1-10
import uuid
from django.core.management import call_command
from toolkit.helpers.bdd import setup_test_environment
from toolkit.helpers.utils import snakify
# The scenario param is used behind the scenes
def before_scenario(context, scenario):
setu... | StarcoderdataPython |
3235832 | # Generated by Django 3.1.13 on 2021-11-09 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0106_descrierepage_sistem_structural_observatii'),
]
operations = [
migrations.RemoveField(
model_name='bisericapage',
... | StarcoderdataPython |
1635614 | <filename>api/serializers/image.py
from rest_framework import serializers
from api.fields import Base64StringField
from election.models import Image
class ImageSerializer(serializers.ModelSerializer):
base64Image = Base64StringField(source='file', allow_null=True)
class Meta:
model = Image
f... | StarcoderdataPython |
1790343 | <gh_stars>100-1000
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
171784 | """
Linux Kernel 4.8+ libgpiod
"""
import threading
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
from ...types import ConfigType, PinType
from . import GenericGPIO, InterruptEdge, InterruptSupport, PinDirection, PinPUD
if TYPE_CHECKING:
# pylint: disable... | StarcoderdataPython |
1771910 | <reponame>dcmvdbekerom/exojax<filename>src/exojax/plot/__init__.py
__all__ = []
__version__ = "1.0.0"
__uri__ = ""
__author__ = "<NAME> and collaborators"
__email__ = "<EMAIL>"
__license__ = ""
__description__ = "plotting modules in exojax"
from exojax.plot.atmplot import (
plottau,
plotcf,
)
| StarcoderdataPython |
3315765 | import torch
from .mlp_kernel import MLPKernel
from .rbf_net import RBFNetKernel
| StarcoderdataPython |
1687447 | <gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, <NAME> and contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above cop... | StarcoderdataPython |
1699807 | from django.urls import path
from .views import (
CustomLoginView,
DashboardView,
SingleApplicationView,
)
urlpatterns = [
path('login/', CustomLoginView.as_view(), name='login'),
path('', DashboardView.as_view(), name='dashboard'),
path('<int:pk>/', SingleApplicationView.as_view())
]
| StarcoderdataPython |
81256 | # -*- coding: utf-8 -*-
#
# Contributhon 2020 documentation build configuration file
# -- General configuration ------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
#extensio... | StarcoderdataPython |
1743034 | <gh_stars>1-10
from keep_current_storage.shared import use_case as uc
from keep_current_storage.shared import response_object as res
class DocumentListUseCase(uc.UseCase):
def __init__(self, repo):
self.repo = repo
def process_request(self, request_object):
domain_document = self.repo.list(f... | StarcoderdataPython |
90255 | from embedding_encoder.core import EmbeddingEncoder
__all__ = ["EmbeddingEncoder"]
| StarcoderdataPython |
194111 | from .compose import Compose
from .formating import Reformat
# from .loading import LoadAnnotations, LoadImageFromFile, LoadProposals
from .loading import *
from .test_aug import DoubleFlip
from .preprocess import Preprocess, Voxelization, AssignLabel, AssignTarget
__all__ = [
"Compose",
"to_tensor",
"ToT... | StarcoderdataPython |
29567 | """
.. module:: django_core_models.locations.urls
:synopsis: django_core_models locations application urls module
django_core_models *locations* application urls module.
"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^addresses/$',
... | StarcoderdataPython |
3291282 | <gh_stars>0
import tkinter as tk # For tkinter Widgets
import os # For access to os properties such as path
from tkinter import ttk # Themed tkinter for beautiful interfaces
from tkinter import filedialog # Tkinter file dialo... | StarcoderdataPython |
1665279 | <gh_stars>1-10
#!/usr/bin/env python3
from termcolor import cprint
import argparse
import os
from xcanalyzer.xcodeproject.parsers import XcProjectParser
from xcanalyzer.xcodeproject.generators import OccurrencesReporter
from xcanalyzer.xcodeproject.exceptions import XcodeProjectReadException
from xcanalyzer.language... | StarcoderdataPython |
1675334 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
1791183 | <filename>10codons.py
#!/usr/bin/env python3
# Define Variables
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA'
s = len(dna)
# Loop
for i in range(0,s,3):
print(dna[i:i+3])
print('End of Reading Frame')
| StarcoderdataPython |
3380522 | <reponame>CompassMentis/mosaic_tiles
class Settings:
screen_width = 1800
screen_height = 950
tile_width = 40
tile_height = tile_width
factories_centre = 360, 350
factories_circle_radius = 250
factory_circle_radius = 80
spacing = 10
grid_colour = 128, 128, 128
active_grid_colo... | StarcoderdataPython |
3244143 | <gh_stars>0
import cv2
def fool_proof_webcam():
# Create a named window
# This window will be called by its name, hence the variable
window_name = "Live Video Feed"
cv2.namedWindow(window_name)
# Get first available camera : index=0 (int)
cap = cv2.VideoCapture(0)
# Check if video captur... | StarcoderdataPython |
3347731 | <reponame>caoxiaoyue/PyAutoFit
import pytest
from autofit.database.migration import Step, Migrator
@pytest.fixture(
name="step_1"
)
def make_step_1():
return Step(
"INSERT INTO test (id) VALUES (1)"
)
@pytest.fixture(
name="step_2"
)
def make_step_2():
return Step(
"INSERT INTO ... | StarcoderdataPython |
4802679 | <gh_stars>1-10
from collections import defaultdict
import time
from django.core.management.base import BaseCommand
import csv
import shapefile
class CSVImportCommand(BaseCommand):
help = 'Import data from a CSV file'
def __init__(self, skip_header=False, encoding=None):
self.skip_header = skip_heade... | StarcoderdataPython |
1627451 | <filename>examples/streamtube_demo1.py<gh_stars>0
#!/usr/bin/env python
# Example taken from:
# http://www.mathworks.com/access/helpdesk/help/techdoc/ref/streamtube.html
from scitools.easyviz import *
from scipy import io
wind = io.loadmat('wind_matlab_v6.mat')
x = wind['x']
y = wind['y']
z = wind['z']
u = wind['u']... | StarcoderdataPython |
122604 | from django.db import models
from datetime import datetime
class TestModel(models.Model):
date = models.DateField(default=datetime.today())
| StarcoderdataPython |
4834316 | from todo.constants import COMMANDS
from todo.parser.base import BaseParser
class InitializeConfigParser(BaseParser):
"""
usage: td init-config
td ic
initialize config
optional arguments:
-h, --help show this help message and exit
"""
command = COMMANDS.INITIALIZE_C... | StarcoderdataPython |
1696795 | import logging
import json
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller import dpset
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.exception import RyuException
from ryu.ofproto import ofproto_v1_3
from ryu.lib imp... | StarcoderdataPython |
1749245 | #!/usr/bin/env python
from __future__ import print_function
import sys
import json
import logging
from argparse import ArgumentParser
from util import get_url, post_and_wait, tagmapping
def imageName2id(imageName):
#
url='image/importation?name={0}'.format(imageName)
response = get_url(url)
return res... | StarcoderdataPython |
118156 | import requests
import json
from tokens.settings import BLOCKCYPHER_API_KEY
def register_new_token(email, new_token, first=None, last=None):
assert new_token and email
post_params = {
"first": "MichaelFlaxman",
"last": "TestingOkToToss",
"email": "<EMAIL>",
"token": new_token... | StarcoderdataPython |
186522 | #!/usr/bin/env python
'''
0104 89C3 MOV BX,AX
0106 D1E8 SHR AX,1
010C 91 XCHG AX,CX
010D BA0102 MOV DX,0201
0110 D1C2 ROL DX,1
0112 D1EB SHR BX,1
0114 D1D1 RCL CX,1
0116 38DE CMP DH,... | StarcoderdataPython |
127608 | from ground.base import (Location,
Relation)
from hypothesis import given
from orient.planar import (point_in_multisegment,
point_in_polygon,
point_in_segment,
segment_in_multisegment,
se... | StarcoderdataPython |
1714839 | # Copyright 2019 Splunk, Inc.
#
# Use of this source code is governed by a BSD-2-clause-style
# license that can be found in the LICENSE-BSD2 file or at
# https://opensource.org/licenses/BSD-2-Clause
import random
from jinja2 import Environment
from .sendmessage import *
from .splunkutils import *
from .timeutils imp... | StarcoderdataPython |
4840222 | <reponame>CartoDB/bigmetadata<gh_stars>10-100
def copy_from_csv(session, table_name, columns, csv_stream):
'''
Creates a table, loading the data from a .csv file.
:param session: A SQL Alchemy session
:param table_name: Output table name
:param columns: Dictionary of columns, keys are named, values... | StarcoderdataPython |
3260886 | <reponame>haesleinhuepf/napari-webcam<gh_stars>0
"""
This module is an example of a barebones QWidget plugin for napari
It implements the ``napari_experimental_provide_dock_widget`` hook specification.
see: https://napari.org/docs/dev/plugins/hook_specifications.html
Replace code below according to your needs.
"""
im... | StarcoderdataPython |
34381 | <filename>Lab11/BacktrackingRecursive.py
l = ["+", "-"]
def backRec(x):
for j in l:
x.append(j)
if consistent(x):
if solution(x):
solutionFound(x)
backRec(x)
x.pop()
def consistent(s):
return len(s) < n
def solution(s):
... | StarcoderdataPython |
141552 | <reponame>Calebu6214/Neighborhood
from django.test import TestCase
from django.contrib.auth.models import User
from .models import *
import datetime as dt
# Create your tests here.
class neighbourhoodTestClass(TestCase):
def setUp(self):
self.kibra = neighbourhood(neighbourhood='kibra')
def test_insta... | StarcoderdataPython |
37603 | <reponame>visinf/style-seqcvae<gh_stars>0
import os
import pickle
import numpy as np
from datasets.config_attrib_selection import attrib_selection
def save_obj(obj, path):
with open(path, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(path):
with open(path, 'rb') as f... | StarcoderdataPython |
3230487 | # Autores:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
import random, math
alturaCilindro = 1/2
ptosCircunfCilindro = 0
ptosCircunfCentro = 0
ptosCircunfInferior = 0
ptosCircunfSuperior = 0
ptosRuedaEsferica = 0
radioCircunfCilindro = 1/2
radioCircunfSuperior = 2
radioCircunfCentro = 4
radioCirunfInferior = 1
radioRuedaE... | StarcoderdataPython |
1675001 | # coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. 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 r... | StarcoderdataPython |
3354036 | import numpy as np
import ast
import sys
import json
from auxiliary_functions import SampleListToArray
import matplotlib
from matplotlib import rc
rc('text', usetex=True)
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
matplotlib.rc('xtick', labelsize=30)
matplotlib.rc('ytick', labelsize=30)
imp... | StarcoderdataPython |
21303 | <filename>joplin/pages/official_documents_page/factories.py
import factory
from pages.official_documents_page.models import OfficialDocumentPage, OfficialDocumentCollectionOfficialDocumentPage
from pages.base_page.factories import JanisBasePageFactory
from pages.official_documents_collection.factories import OfficialDo... | StarcoderdataPython |
140501 | <reponame>federicober/funk-lines
"""File for the results class."""
import statistics
from typing import List, Optional, Sequence
from .ast_processors import StmtInfo
class Results:
"""Class for holding the results of an analysis.
The Analyser classes return a Result object.
"""
def __init__(self, t... | StarcoderdataPython |
1736665 | import asyncio
from discord.ext import commands
from discord_slash import SlashContext, cog_ext
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
asyncio.create_task(self.bot.slash.sync_all_commands())
def cog_unload(self):
self.bot.slash.remove_cog_comman... | StarcoderdataPython |
189289 | # Via http://pydanny.com/jinja2-quick-load-function.html
from jinja2 import FileSystemLoader, Environment, StrictUndefined
def render_from_template(directory, template_name, **kwargs):
loader = FileSystemLoader(directory)
env = Environment(loader=loader, undefined=StrictUndefined)
template = env.get_templa... | StarcoderdataPython |
1751642 | import os
import yaml
class Project(object):
def __init__(self, data, source=None, dir=None, annotation=None):
self.data = data
self.source = source
self.dir = dir
self.annotation = annotation
self.command_line_flags = []
self.command_line_profiles = []
def att... | StarcoderdataPython |
3329799 | <filename>networks.py
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from PNL import *
from progress.bar import Bar
from ast import literal_eval
df = pd.read_csv('data/essays.csv')
df_save = pd.DataFrame(columns=['final_score','c1', 'c2', 'c3', 'c4', 'c5',
'nodes', 'edge... | StarcoderdataPython |
1767921 | <reponame>douzepouze/python-mcumgr
from mcumgr import *
| StarcoderdataPython |
3392490 | <filename>msaf/pymf/nmfals.py
#!/usr/bin/python
#
# Copyright (C) <NAME>, 2010.
# Licensed under the GNU General Public License (GPL).
# http://www.gnu.org/licenses/gpl.txt
"""
PyMF Non-negative Matrix Factorization.
NMFALS: Class for Non-negative Matrix Factorization using alternating least
squares ... | StarcoderdataPython |
3247994 | <filename>tests/test_travis_project_exists.py<gh_stars>1-10
from setup_python_package.utils import travis_project_exists
def test_travis_project_exists():
assert travis_project_exists() | StarcoderdataPython |
1690449 | <reponame>Arastorn/Pokemon_RL
import time
import re
import random
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from app.src.showdownai.exceptions import *
class Selenium():
BASE_URL="http://play.pokemonshowdown.com"... | StarcoderdataPython |
24729 | <filename>oembed/migrations/0001_initial.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.conf import settings
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'StoredOEmbed'
... | StarcoderdataPython |
3372020 | from pathlib import Path
import randomname
def test_get_name():
name = randomname.get_name('music_theory', 'cats').split('-', 1)
assert len(name) > 1
assert name[0] in randomname.util.get_groups_list('a/music_theory')
assert name[1] in randomname.util.get_groups_list('n/cats')
assert 'asdf' in ra... | StarcoderdataPython |
3272326 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import unittest
import unittest.mock as mock
from fastapi.testclient import TestClient
from projects.api.main import app
from projects.database import session_scope
import tests.util as util
app.dependency_overrides[session_scope] = util.override_session_scope
TEST_CLIENT = Te... | StarcoderdataPython |
3285000 | <gh_stars>100-1000
import json
import subprocess
import pytest
from all_repos.push import github_pull_request
from testing.auto_namedtuple import auto_namedtuple
from testing.git import init_repo
@pytest.fixture
def fake_github_repo(tmpdir):
# hax: make the repo end with :repo/slug so it "looks" like a github r... | StarcoderdataPython |
1619360 | import numpy as np
from info import freq_to_notes
class Note:
def __init__(self, pitch, signal, loudness, timestamp, duration=None, typ=None):
self.pitch = round(pitch, 3)
self.signal = round(signal, 3)
self.loudness = round(loudness, 3)
self.timestamp = timesta... | StarcoderdataPython |
1637105 | from HTMLParser import HTMLParser
class CourseHTMLParser(HTMLParser):
def __init__(self):
self.status_classes = ["open-status-open", "open-status-closed", "open-status-warning", "open-status-archived"]
self.section_names = []
self.section_statuses = []
self.valid = True
HTM... | StarcoderdataPython |
1642639 | <reponame>alinenog/Mundo_Python-1-2-3<gh_stars>0
#Exercício Python 37:
# Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário
# escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.
num = int(input("Digite um número inteiro: "))
print('''Esc... | StarcoderdataPython |
104847 | # Add 5 to number
add5 = lambda n : n + 5
print(add5(2))
print(add5(7))
print()
# Square number
sqr = lambda n : n * n
print(sqr(2))
print(sqr(7))
print()
# Next integer
nextInt = lambda n : int(n) + 1
print(nextInt(2.7))
print(nextInt(7.2))
print()
# Previous integer of half
prevInt = lambda n : int(n // 2)
print(p... | StarcoderdataPython |
1614414 | <filename>code/backend/twitter/wrappers/postgresql_wrapper.py
## @package twitter.wrappers
# coding: UTF-8
import psycopg2
import logging
import credentials as credentials
from api.enums import Policy as enum_policy
import django.dispatch
log = logging.getLogger("PostgreSQL")
log.setLevel(logging.DEBUG)
handler = lo... | StarcoderdataPython |
3299284 | import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
| StarcoderdataPython |
1602233 | from contracts.models import Contract, Offence, Penalty, Termination
import datetime
def get_contract(contract_id):
contract = Contract.objects.get(pk=contract_id)
return contract
def get_penalty(penalty_id):
penalty = Penalty.objects.get(pk=penalty_id)
return penalty
def get_termination(terminati... | StarcoderdataPython |
161098 | # coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee <EMAIL> #
# #
# version 1.0 ... | StarcoderdataPython |
3309146 | from typing import List
from app.core.DatetimeUtils import DatetimeUtils
from app.core.ServiceEntity import ServiceEntity
from app.core.ServiceMethodEntity import ServiceMethodEntity
class ServiceMethodFactory:
@staticmethod
def parse(services: dict, target, prefix):
result = list()
... | StarcoderdataPython |
1728599 | """Definition of the bot's Utility module."""
import asyncio
import random
import re
import sys
import time
import aiohttp
import async_timeout
import discord
import os
import socket
import contextlib
import textwrap
import util.commands as commands
import util.json as json
from contextlib import suppress
from collecti... | StarcoderdataPython |
3310068 | from ._JSONError import JSONError
class JSONPropertyError(JSONError):
"""
Base class for all errors involving JSON properties.
"""
pass
| StarcoderdataPython |
169975 | <filename>src/setup.py
from setuptools import setup, find_packages
setup(
name='pyschedule',
version='0.2.34',
description='A python package to formulate and solve resource-constrained scheduling problems',
url='https://github.com/tpaviot/pyschedule',
author='<NAME>',
author_email='<EMAIL>',
... | StarcoderdataPython |
1626006 | <gh_stars>0
import inspect
from typing import Any, Dict, Union
import aft_common.aft_utils as utils
import boto3
from boto3.session import Session
logger = utils.get_logger()
def persist_metadata(
payload: Dict[str, Any], account_info: Dict[str, str], session: Session
) -> Dict[str, Any]:
logger.info("Func... | StarcoderdataPython |
193461 | import numpy as np
import torch
import pickle
import experiment_runner as er
from torch import nn
import sklearn.datasets
from sklearn.model_selection import train_test_split
from torch.utils.data import TensorDataset
print("test")
n_classes = 10
X, y = sklearn.datasets.make_classification(n_samples=1000,
... | StarcoderdataPython |
57497 | <gh_stars>0
from flask import Blueprint, render_template, url_for
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return render_template("login.html")
@auth.route('/logout')
def logout():
return render_template("logout.html")
@auth.route('/sign_up')
def sign_up():
return render_tem... | StarcoderdataPython |
3338642 | #!/usr/bin/python3
c = list('614752839')
def dec(i):
i = int(i) - 1
if i == 0: i = 9
return str(i)
def move(c):
t = c[1:4]
c[1:4] = []
val = dec(c[0])
while val in t:
val = dec(val)
i = c.index(val)
print(t, c, i)
c[i+1:i+1] = t
return c[1:] + [c[0]]
for _ in ran... | StarcoderdataPython |
1717157 | <reponame>gathierry/FashionAI-KeyPointsDetectionOfApparel<gh_stars>100-1000
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
import cv2
class KPDA():
def __init__(self, config, data_dir, train_val):
self.config = config
if train_val == 'test':
... | StarcoderdataPython |
3244712 | <gh_stars>1-10
from typing import Any, List
from src.spotlight.rules import Rule
from .validator_test import ValidatorTest
class ExactlyFiveCharsRule(Rule):
"""Exactly 5 characters"""
name = "five_chars"
def passes(self, field: str, value: Any, parameters: List[str], validator) -> bool:
self.me... | StarcoderdataPython |
122706 | <gh_stars>0
""" This class will handle a set of configurations and launch several
instances of a Run homogeneous in purpose and structure.
"""
import os
import sys
import yaml
import pyclbr
import logging
from itertools import groupby
from pyrate.utils import strings as ST
from pyrate.utils import functions as FN
... | StarcoderdataPython |
11132 | <filename>django_elastic_appsearch/slicer.py<gh_stars>10-100
"""A Queryset slicer for Django."""
def slice_queryset(queryset, chunk_size):
"""Slice a queryset into chunks."""
start_pk = 0
queryset = queryset.order_by('pk')
while True:
# No entry left
if not queryset.filter(pk__gt=star... | StarcoderdataPython |
1614565 | <gh_stars>10-100
#!/bin/sh
''''exec python3 -u -- "$0" ${1+"$@"} # '''
# #! /usr/bin/env python3
# Copyright 2016 Euclidean Technologies Management LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may o... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.