id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1657295 | from django import template
from django.db.models import ObjectDoesNotExist
register = template.Library()
@register.simple_tag(takes_context=True)
def get_contact_email(context):
theme = get_theme(context)
email = theme.content.contact_email
if not email:
try:
defaults = context['req... | StarcoderdataPython |
1742764 | <gh_stars>0
#!/usr/bin/env python
from will.main import WillBot
if __name__ == '__main__':
bot = WillBot()
bot.bootstrap()
| StarcoderdataPython |
3341313 | import os
from flask import Flask, render_template
from flask_cors import CORS
template_dir = os.path.abspath('./src')
print(template_dir)
app = Flask(__name__, template_folder = template_dir, static_url_path = '', static_folder = './src/frontend/dist')
CORS(app)
data = 0
@app.route('/')
def index():
return rende... | StarcoderdataPython |
3265209 | <reponame>bopopescu/build
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine.types import freeze
DEPS = [
'depot_tools/bot_update',
'chromium',
'commit_position',
'file',
'depot_... | StarcoderdataPython |
1614707 | <reponame>ibrahimroshdy/django-places<gh_stars>10-100
from django.db import models
from places.fields import PlacesField
class Place(models.Model):
location = PlacesField(blank=True)
def __str__(self):
return self.location.place
class Route(models.Model):
name = models.CharField(max_length=50)... | StarcoderdataPython |
1639838 | <reponame>D-K-E/byeframe
# author: <NAME>
# license: see, LICENSE
"""
Deal with fprobe related function
"""
from moviepy.editor import VideoFileClip
import os
import pdb
from datetime import datetime as dt
class SilenceTrimmer:
def __init__(
self,
path: str,
thresh_min=0.02,
thres... | StarcoderdataPython |
4823348 | def bisection_method(f, a, b, epsilon=1e-5):
if a > b or f(a) * f(b) > 0:
raise ValueError('bisection method: invalid a and b values')
while abs(b - a) >= epsilon:
x = (a + b) / 2
if abs(f(x)) <= epsilon:
return x
if f(a) * f(b) >= 0:
a = x
else:
... | StarcoderdataPython |
30418 | <filename>setup.py
#!/usr/bin/env python
import os
import pkgutil
import sys
from setuptools import setup, find_packages
from subprocess import check_call, CalledProcessError
if not pkgutil.find_loader('relic'):
relic_local = os.path.exists('relic')
relic_submodule = (relic_local and
os... | StarcoderdataPython |
1688532 | #Libreria funciones
import pygame
ANCHO=600
ALTO=480
def dibujarPlano(o, pantalla):
pygame.draw.line(pantalla, [0, 255, 0], [o[0], 0], [o[0], 480] )
pygame.draw.line(pantalla, [0, 255, 0], [0, o[1]], [640, o[1]] )
def dibujarTriangulo(a, b, c, plano):
'''
pygame.draw.line(plano, [0, 255, 0]... | StarcoderdataPython |
3334105 | <filename>sfepy/homogenization/coefs_acoustic.py
from sfepy.base.base import *
from sfepy.fem import eval_term_op
from sfepy.homogenization.coefs_base import VolumeFractions, \
CorrMiniApp, MiniAppBase, CorrN, CoefN, CoefNN, \
create_scalar_pis
class ShapeDimM1( CorrMiniApp ):
def __call__( self, pr... | StarcoderdataPython |
1613977 | <reponame>Min-Hyuk98/boiler_web<gh_stars>0
# Generated by Django 2.2.2 on 2020-02-23 04:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0016_auto_20200223_1251'),
]
operations = [
migrations.AddField(
model_name='... | StarcoderdataPython |
1614114 | # -*- coding: utf-8 -*-
"""Command line interface for Axonius API Client."""
from ...context import CONTEXT_SETTINGS, click
from ...options import AUTH, add_options
from .grp_common import EXPORT, handle_export
OPTIONS = [
*AUTH,
EXPORT,
]
@click.command(name="get", context_settings=CONTEXT_SETTINGS)
@add_op... | StarcoderdataPython |
1708784 | <gh_stars>0
###############################################################################
# Copyright (c) 2017-2020 <NAME> (Cisco Systems), #
# <NAME> (Cisco Systems), <NAME> (Cisco Systems) and others #
# #
# ... | StarcoderdataPython |
3221289 | from django.db import models
class Document(models.Model):
name = models.CharField(max_length=200)
upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class DocPage(models.Model):
name = models.CharField... | StarcoderdataPython |
1654561 | import os
import mysql.connector as mydb
conn = mydb.connect(
host='mysql_container' if os.getenv(
'DB_HOST') == None else os.getenv('DB_HOST'),
port='3306' if os.getenv(
'DB_HOST') == None else '33066',
user='docker',
password='<PASSWORD>',
database='my_db'
)
conn.is_connected()
| StarcoderdataPython |
1685386 | <reponame>KeesV/azure-functions-durable-extension
import logging
import json
import azure.functions as func
import azure.durable_functions as df
def orchestrator_function(context: df.DurableOrchestrationContext):
num_activities = context.get_input()
tasks = []
for _ in range(num_activities):
tas... | StarcoderdataPython |
3335169 | <reponame>hackerdeen/Twitterbot
import requests
import json
from time import time, sleep
import tweepy
import credentials
status = "https://hub.57north.org.uk/api/status/current"
consumer_key = credentials.API_key
consumer_secret_key = credentials.API_secret_key
access_token = credentials.access_token
access_token_se... | StarcoderdataPython |
3204853 | <filename>polynomial_regression.py
############################
# NON LINEAR DATA MODEL: POLYNOMIAL REGRESSION
############################
# Reproduce the same scripts than Linear Regression (linear_regression.py)
"""##### 1 [ Split into training ] #####"""
"""##### 2 [ Extract train and test idx for later merge with ... | StarcoderdataPython |
1754581 | ## executa regras definidas em um arquivo
import helper
def exec(conexao):
cursor = conexao.cursor()
print("Executando Regras",end=' ')
print('')
arquivo = open('regras.txt','r')
regras = arquivo.readlines()
arquivo.close()
print('Montando as regras do arquivo')
while regras:
... | StarcoderdataPython |
53066 | <reponame>jawoszek/sc2-intelligent-agents
from keras.utils import to_categorical
from numpy import array
import sc2agents.learning.deep.keras.parsers as parsers
def train(model, input_data, output_data, epochs):
x_train = array(input_data)
y_train = to_categorical(array(output_data).T[0], num_classes=2)
... | StarcoderdataPython |
4818639 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
IDE : PyCharm
File Name : my_bisect
Description : bisect 模块包含两个主要函数,bisect 和 insort,两个函数都利用二分查找算法来在有序
序列中查找或插入元素。
Author : <EMAIL>
date : 2022/4/29 8:06
-----------------------------------------... | StarcoderdataPython |
1793640 | <gh_stars>1-10
"""find the weather per user name"""
import requests
ROOT_URL = "http://www.bom.gov.au/fwo/"
WEATHER_TEXT = (
"{name} -- Location {username}'s Place --Time {local_date_time} -- The "
"Wind is from the {wind_dir} -- Wind speed {wind_spd_kt} KPH -- Wind "
"gusts {gust_kmh} KPH -- Air ... | StarcoderdataPython |
3356090 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import soundcard as sc
peak, argpeak = np.min, np.argmin # replace with (np.max, np.argmax) for max values
# frequency sweep
freq = np.geomspace(30, 17000, num=100)
with open(__file__.replace('.py', '.csv'), 'w') as csv:
csv.write('freq, ... | StarcoderdataPython |
1777221 | from shift import shift
from private import private
if __name__ == '__main__':
s = shift(shift_name='Shift test', start_time='10:00', end_time='11:30')
s.print_shift()
p = private(shift_name='Private test', start_time='9:00', end_time='10:00')
p.print_shift()
| StarcoderdataPython |
3244973 | <reponame>IvoLeist/dash-cytoscape<filename>dash_cytoscape/Cytoscape.py
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Cytoscape(Component):
"""A Cytoscape component.
A Component Library for Dash aimed at facilitating network visualization in
Pyt... | StarcoderdataPython |
134217 | import random
import re
from locustio.common_utils import confluence_measure, fetch_by_re, timestamp_int, \
TEXT_HEADERS, NO_TOKEN_HEADERS, JSON_HEADERS, RESOURCE_HEADERS, generate_random_string, init_logger, \
raise_if_login_failed
from locustio.confluence.requests_params import confluence_datasets, Login, Vi... | StarcoderdataPython |
19051 | <reponame>anirudha-bs/Distributed_storage_ipfs
from files import write_key, load_key, encrypt, decrypt
import os
from ipfs import add,pin,get_file
def switch(option):
return switcher.get(option, default)()
# Encrypts file and adds to ipfs
def encrypt_ipfs_add():
file=input("Enter the file name to be added - "... | StarcoderdataPython |
182327 | import unittest
from algorithms.math.factorial import factorial
from algorithms.math.fibonacci import fibonacci_dp, fibonacci_recursive
class test_math(unittest.TestCase):
def test_factorial(self):
self.assertEqual(factorial(0), 0)
self.assertEqual(factorial(1), 1)
self.assertEqual(factori... | StarcoderdataPython |
1782092 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 <NAME>
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Error parameter numbers.")
print("Usage: pytho... | StarcoderdataPython |
3210314 | <filename>hw5/solution5.py
"""
This module contains solutions for fifth laboratory task of
Methods of Computation and Computational Workshop course.
"""
import math
from typing import Callable, Final, Sequence, Tuple
from hw1.solution1 import root_finding, secant
SEG_DEFAULT_BEG: Final = -1
SEG_DEFAULT_END: Final = ... | StarcoderdataPython |
4825569 | """Author: <NAME>, Copyright 2019"""
import tensorflow as tf
from ordered_attention.ordered_attention_layer import OrderedAttentionLayer
if __name__ == "__main__":
inputs = tf.random.normal([1, 7, 16, 16])
targets = tf.random.normal([1, 7, 16, 16])
layer = OrderedAttentionLayer(2, 2, 4, 16... | StarcoderdataPython |
3348795 | # -*- coding: utf-8 -*-
import math
# 素数
num = int(input("Enter the number "))
for i in range(2, num):
# 怎么优化?
if num % i == 0:
print("The number is not a prime")
break
else:
print("The number is a prime")
for i in range(2, int(math.sqrt(num)) + 1):
# 怎么优化?
# 只选择素数来检验
if num ... | StarcoderdataPython |
1601908 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/8/1
@Author : AnNing
功能:
1、计算G0、Gt、DNI
2、补全缺失的整点时次数据的Itol、Ib、Id
优化
1、修改为矩阵运算
2、优化assignE
3、DEBUG函数assignTime,原来的函数直接在hour加8可能超过24
"""
import os
import h5py
import numpy as np
from dateutil.relativedelta import relativedelta
from lib.lib_constant impo... | StarcoderdataPython |
30243 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 15:28:09 2018
@author: dataquanty
"""
import numpy as np
from math import sqrt, pi, acos,cos
from matplotlib import pyplot as plt
from scipy.misc import imsave
from bisect import bisect_left
h , w = 1000, 1000
img = np.ones((h,w))
center = (... | StarcoderdataPython |
1669717 | from rest_framework import mixins
from rest_framework.viewsets import ViewSetMixin
from rest_framework_mongoengine.generics import GenericAPIView
class GenericViewSet(ViewSetMixin, GenericAPIView):
""" Adaptation of DRF GenericViewSet """
pass
class ModelViewSet(mixins.CreateModelMixin,
... | StarcoderdataPython |
3228936 | <reponame>theGreenJedi/BciPy
import glob
import itertools
import logging
import random
from os import path, sep
from typing import Iterator
import numpy as np
import sounddevice as sd
import soundfile as sf
from PIL import Image
from psychopy import core
# Prevents pillow from filling the console with debug info
log... | StarcoderdataPython |
187783 | import random
import os
def jogar():
tema = define_tema()
arquivo = arquivo_do_tema(tema)
palavra_secreta = sorteia_palavra(arquivo)
loop_jogo_forca(palavra_secreta)
def loop_jogo_forca(palavra_secreta):
lista_historico = []
print(f"\nA palavra secreta tem {len(palavra_secreta)} letras\n")... | StarcoderdataPython |
28951 | <reponame>alvaro-budria/body2hands<filename>visualization/POF/utils/keypoint_conversion.py
import numpy as np
import numpy.linalg as nl
from utils.general import connMat
a4_to_main = {
'body': np.array([1, 0, 9, 10, 11, 3, 4, 5, 12, 13, 14, 6, 7, 8, 17, 15, 18, 16, 19, 20], dtype=np.int64), # convert to order of ... | StarcoderdataPython |
1714787 | <gh_stars>0
"""Read and parse wiki tar.bz2 dumps archives.
Notes
-----
This module is not properly integrated with the CLi and the package in general.
"""
import bz2
import os
import re
import logging
try:
import ujson as json
except ModuleNotFoundError:
import json
from uqa import dataset
logger = logging... | StarcoderdataPython |
1733558 | <reponame>wangkaibiao/SettlersFinancialData3
# -*- coding: utf-8 -*-
"""
aip public
"""
from .ocr import AipOcr
from .nlp import AipNlp
from .face import AipFace
from .imagecensor import AipImageCensor
from .imagecensor import AipImageCensor as AipContentCensor
from .kg import AipKg
from .speech import ... | StarcoderdataPython |
1705814 | <reponame>dubizzle/docker-weblate
#!/usr/bin/env python
import django
django.setup()
import sys,os
from django.contrib.auth.models import User
from django.core.management import call_command
try:
user = User.objects.get(username='admin')
except:
print 'Creating Admin...'
call_command('createadmin', password=os... | StarcoderdataPython |
3364658 | # Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 6.2.3
# WARNING! All changes made in this file will be lost!
from PySide6 import QtCore
qt_resource_data = b"\
\x00\x00\x09Q\
\x00\
\x00$\xbex\x9c\xe5Z\xebs\xdaH\x12\xff\x9e\xaa\xfc\
\x0f}\xbe|\xb0\xf7\x88\x... | StarcoderdataPython |
3358566 | <filename>pygix/tools.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A collection of useful tools for GIXS and fibre diffraction.
There are two main tools:
1. Four quadrant averaging:
Fibre diffraction patterns are related through four quadrant symmetry
(assuming ideal fibre texture). This means that t... | StarcoderdataPython |
3253717 | #!/bin/python
#coding=utf8
import roomai.games.common
logger = roomai.get_logger()
class AbstractStatePrivate(object):
'''
The Abstract class of the private state. The information in the private state is hidden from every player
'''
def __deepcopy__(self, memodict={}, newinstance = None):
if... | StarcoderdataPython |
3321936 | from typing import Tuple, List
from clearml import Task
import fire
def with_ret() -> Tuple:
print("With ret called")
return 1, 2
def with_args(arg1: int, arg2: List):
print("With args called", arg1, arg2)
def with_args_and_ret(arg1: int, arg2: List) -> Tuple:
print("With args and ret called", arg... | StarcoderdataPython |
1642190 | <gh_stars>10-100
import sys
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
sys.path.append('../')
from ifood.cfg import cfg
from ifood.datasets import iFoodDataset, iFoodInferenceDataset
data_transforms = {
'train': transforms.Compose([
transforms.Resize(227),
... | StarcoderdataPython |
1790877 | <gh_stars>1-10
"""Module containing kernel related classes"""
__author__ = 'wittawat'
from abc import ABCMeta, abstractmethod
import numpy as np
import scipy.signal as sig
from mskernel import util
class Kernel(object):
"""Abstract class for kernels"""
__metaclass__ = ABCMeta
@abstractmethod
def eva... | StarcoderdataPython |
55503 | <filename>igittigitt/__init__conf__.py
name = "igittigitt"
title = "A spec-compliant gitignore parser for Python"
version = "v2.0.4"
url = "https://github.com/bitranox/igittigitt"
author = "<NAME>"
author_email = "<EMAIL>"
shell_command = "igittigitt"
def print_info() -> None:
print(
"""\
Info for igitti... | StarcoderdataPython |
1679568 | import flask
from flask import Blueprint, Response, abort, current_app
from medallion import auth
from medallion.views import MEDIA_TYPE_TAXII_V20
mod = Blueprint('discovery', __name__)
@mod.route("/taxii/", methods=["GET"])
@auth.login_required
def get_server_discovery():
# Having access to the discovery metho... | StarcoderdataPython |
156617 | from django.db import models
# *****************************************************************************************
# Affairs
# *****************************************************************************************
class Affair(models.Model):
"""
model for affair
"""
# type choices
INQUIRY... | StarcoderdataPython |
3373646 | # Code stub taken from https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
base_dir ... | StarcoderdataPython |
120146 | from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def upload():
return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
#f.save(secure_filename(f.filename... | StarcoderdataPython |
1646236 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-25 17:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_topetherdeltatransaction_is_buyer'),
]
operations = [
migration... | StarcoderdataPython |
3228388 | <gh_stars>1-10
from future.builtins import str
from mrq.queue import Queue
from mrq.task import Task
from mrq.job import Job
from mrq.context import log, connections, run_task, get_current_config
import datetime
import time
class RequeueInterruptedJobs(Task):
""" Requeue jobs that were marked as status=interrupt... | StarcoderdataPython |
186054 | total = 0
current = 1
prev = 1
while current < 4000000:
temp = current
current = current + prev
prev = temp
if current % 2 == 0:
total += current
print (total) | StarcoderdataPython |
3283238 | # --------------
import yaml
# Read the data of the format .yaml type
with open(path,'r') as f:
data = yaml.load(f)
# Find data type of the file
print(type(data))
print("=================")
#print(match_details)
data_list=data.keys()
print(data_list)
# In which city, and at which venue the match was played and ... | StarcoderdataPython |
1665926 | <reponame>jtslade/satchmo-svn
from satchmo_store.contact.models import Organization, Contact, Interaction, PhoneNumber, AddressBook
from satchmo_utils.admin import AutocompleteAdmin
from django.contrib import admin
from django.utils.translation import get_language, ugettext_lazy as _
class Contact_Inline(admin.Tabular... | StarcoderdataPython |
1774453 | <filename>crypto/Shuffler/solve.py<gh_stars>1-10
from random import randint
from string import maketrans
def decrypt(msg):
x = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
y = '<KEY>'
z = maketrans(y, x)
return msg.translate(z)
ct = open('ciphertext.txt').read().strip()
for i in range(43):
ct... | StarcoderdataPython |
142147 | import sys
import random
import FormulaSolidityPort
import FormulaNativePython
from decimal import Decimal
from decimal import getcontext
getcontext().prec = 80 # 78 digits for a maximum of 2^256-1, and 2 more digits for after the decimal point
def singleHopTestFixed(balance1, weight1, balance2, weight2, amount):
... | StarcoderdataPython |
3387053 | import os
import numpy as np
from decimal import Decimal
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import ipdb
st = ipdb.set_trace
result_folder = 'results'
exp_root = 'experiment_runners/exp_files'
units = 'deg'
folders = os.listdir(exp_root)
if not os.path.exists(result_folder):
os.mak... | StarcoderdataPython |
1622898 | import json
import logging
from django.conf import settings
from django.http import HttpResponse, HttpRequest
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .tasks import process
logger = logging.getLogger(__name__)
class TaskQueuer(View):
@csrf_exempt
def post(self... | StarcoderdataPython |
1645923 | from os import path
import unittest
from prudentia.utils import io
class TestIO(unittest.TestCase):
def test_xstr(self):
self.assertEqual(io.xstr(None), '')
def test_yes(self):
self.assertTrue(io.input_yes_no('test topic', prompt_fn=lambda m: 'y'))
self.assertTrue(io.input_yes_no('te... | StarcoderdataPython |
1603000 | import os
from setuptools import setup
__here__ = os.path.abspath(os.path.dirname(__file__))
package_name = 'ham'
# define __version__
# execfile doesn't exist in python 3
# see: http://stackoverflow.com/questions/6357361/alternative-to-execfile-in-python-3-2
exec(open(os.path.join(__here__, package_name, '_version.... | StarcoderdataPython |
4802747 | <reponame>THU-KEG/NGS
import os
import re
import sys
import numpy as np
from constant import *
import torch
maskTag = 37
class Dataset:
def __init__(self, Tag):
print(Tag)
self.tag = Tag
self.Twords = np.load(dataPath + Tag + "_wordEmb.npy")
self.TinMask = np.load(dataPath + Tag + "... | StarcoderdataPython |
176578 | <gh_stars>1-10
from magicbus.compat import ntob
import os
thismodule = os.path.abspath(__file__)
import sys
from magicbus import bus
from magicbus.plugins import opsys
from magicbus.test import assertEqual, Process, WebAdapter, WebService
from magicbus.test import WebHandler
# from magicbus.plugins import loggers
# l... | StarcoderdataPython |
3241473 |
# @shared_task
# def get_team_file_weekly():
# date = timezone.now()
# print("team file weekly")
# print("weekly end date " + str(date))
# date_7 = date - datetime.timedelta(days=7)
# date_7 = date_7.date()
# print("weekly start date " + str(date_7))
# filename = 'Sushiksha-Team-Points-Week... | StarcoderdataPython |
165730 | <reponame>bcgov-c/wally
import json
from typing import List, Optional, Union
from pydantic import BaseModel
from geojson import Feature, FeatureCollection, Point
class WatershedDetails(BaseModel):
""" info about a watershed"""
potential_evapotranspiration_hamon: Optional[float]
potential_evapotranspiratio... | StarcoderdataPython |
4806234 | # Copyright 2021 Huawei Technologies Co., Ltd.
#
# 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 agre... | StarcoderdataPython |
3348331 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# as fields
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -----------------------------------------------------... | StarcoderdataPython |
4804416 | <filename>backend/project/thumbnail_processors.py
from PIL import Image, ImageDraw
def circle_processor(im, bang=False, **kwargs):
try:
bigsize = (im.size[0] * 3, im.size[1] * 3)
mask = Image.new("L", bigsize, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + bigsize, fill=255)
... | StarcoderdataPython |
3346535 | #!/usr/bin/env python3
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: op-test-framework/testcases/OpTestDlpar.py $
#
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2017
# [+] International Business Machines Corp.
#
#
# Licensed under the Apache License, Ve... | StarcoderdataPython |
3213159 | from rocheml.cv.face.faceposeextractor import FacePoseExtractor
import sys
import cv2
img = cv2.imread('headshot_square.png')
fp_extractor = FacePoseExtractor()
img_w_lines = fp_extractor.draw_pose_lines(img)
cv2.imwrite('new_output.jpg', img_w_lines)
| StarcoderdataPython |
1616192 | <reponame>hdknr/pecker<filename>lib/pecker/admin.py
from django.contrib import admin
from django.db.models import get_app,get_models
from models import *
for model in get_models( get_app("pecker")) :
if model.__name__ in ['Link','LinkResult',]:
continue
admin_class = type( "%sAdmin" % model.__... | StarcoderdataPython |
3247095 | <reponame>asanoviskhak/Outtalent<filename>Leetcode/840. Magic Squares In Grid/solution1.py<gh_stars>10-100
MAGIC = {1, 2, 3, 4, 5, 6, 7, 8, 9}
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
result = 0
for i in range(len(grid) - 2):
for j in range(len(gr... | StarcoderdataPython |
1689441 | <filename>models/place.py
#!/usr/bin/python3
"""Defines a class Place"""
from models.base_model import BaseModel
class Place(BaseModel):
"""Represents a class that inherits from BaseModel
Public class attributes:
city_id: string - empty string: it will be the City.id
user_id: ... | StarcoderdataPython |
3303018 | <reponame>devilry/devilry-django
from django.urls import reverse
from django.template import defaultfilters
from cradmin_legacy import crapp, crinstance
from cradmin_legacy import crmenu
from cradmin_legacy.crinstance import reverse_cradmin_url
class BreadcrumbMenuItem(crmenu.MenuItem):
template_name = 'devilry_c... | StarcoderdataPython |
178758 | <reponame>cribbslab/resimpy<filename>__init__.py
from omics.genomics.proj.sca.src.PathController import * | StarcoderdataPython |
1760400 | <reponame>quake0day/oj
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
r = len(dungeon)
c = len(dungeon[0])
dp = [[0] * c for _ in xrange(r)]
dp[-1][-1] = max(1, 1-dungeon[-1][-1])
... | StarcoderdataPython |
164714 | <gh_stars>0
SLACK_TOKEN = ''
APP_TOKEN = ''
WUNDERLIST_CLIENT_ID = ''
WUNDERLIST_TOKEN = ''
SLACK_WUNDERLIST_TOKENS = [ '' ]
| StarcoderdataPython |
3308227 | #!/usr/bin/env python3
from json import loads, dumps
import paho.mqtt.client as mqtt
class Connector:
def __init__(self, topic, config):
super(Connector, self).__init__()
self.topic = topic
self.client = mqtt.Client()
self.encoding = config['encoding']
self.host = confi... | StarcoderdataPython |
106966 | import os
import re
import numpy as np
from parsefchk import parse_fchk
LAST_UPDATE = '201706021601'
def gen_fchk(mfn, data, ofn='', title=None, suffix='_rlo', overwrite=False):
# text: info, energy, coeff, rest
# data: energy, coeff, dim
if not ofn:
t, ext = os.path.splitext(mfn)
ofn... | StarcoderdataPython |
1704147 | from collections import OrderedDict
from hitchstory import utils
from strictyaml import Map
from copy import copy
class Arguments(object):
"""A null-argument, single argument or group of arguments of a hitchstory step."""
def __init__(self, yaml_args, params):
"""Create arguments from dict (from yaml... | StarcoderdataPython |
163381 | <gh_stars>0
from bbpyp.lexicomb.parser.statement import Statement
class ReturnStatement(Statement):
def __init__(self, expression, *args, **kwargs):
super().__init__(*args, **kwargs)
self._expression = expression
def __repr__(self):
return f"{self.artifact_name}({self._expression})"
... | StarcoderdataPython |
113404 | <reponame>hajime9652/observations
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.slid import slid
def test_slid():
"""Test module slid.py by downloading
slid.csv and testing shape of
ex... | StarcoderdataPython |
3212963 | '''
This files defines ETL objects that all have a common "load" function.
Each object is meant for transferring one type of data to another type.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from django.conf import settings
from django.db import connections
from django... | StarcoderdataPython |
137764 | <filename>ons_utils/__init__.py
"""Init the package by importing the functions.
To import functions from pandas or testing modules, import directly:
>>> from ons_utils.pandas import shifted_within_year_apply
>>> from ons_utils.testing import to_date
"""
from .decorators import (
to_list,
to_spark_col,
)
from ... | StarcoderdataPython |
94011 | <filename>api/views.py
from django.db.models import Sum
from rest_framework.generics import ListAPIView
from .filters import MyFilter
from .models import Shop
from .pagination import ShopPagination
from .serializers import ShopSerializer
class ShopView(ListAPIView):
serializer_class = ShopSerializer
paginati... | StarcoderdataPython |
3217504 | import numpy
def nonlin(x, deriv=False):
if deriv:
return x * (1 - x)
return 1 / (1 + numpy.exp(-x))
X = numpy.array([
[0, 0, 1],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1]])
y = numpy.array([[0, 0, 1, 1]]).T
numpy.random.seed(1)
syn0 = 2 * numpy.random.random((3, 1)) - 1
l1 = None
for _ in ra... | StarcoderdataPython |
3207082 | <reponame>nixplay/bullet-train-api<gh_stars>0
from django.conf.urls import url, include
from rest_framework_nested import routers
from features.views import FeatureStateCreateViewSet
router = routers.DefaultRouter()
router.register(r'', FeatureStateCreateViewSet, basename="featurestates")
app_name = "features"
url... | StarcoderdataPython |
89571 |
import pandas as pd
def read(performances, out_table):
out = pd.DataFrame()
for performance in performances:
perf = pd.read_csv(performance, sep = "\t", index_col = 0)
cv_mode = "_".join(performance.split("/")[0].split("_")[-2:])
mode = "_".join(performance.split("/")[0].split("_")[1:... | StarcoderdataPython |
113140 | # ==================================================================================================
# A minimal example that renders a triangle mesh into a depth image using predefined perspective projection matrix
# Copyright 2021 <NAME>
#
# Please run script from repository root, i.e.:
# python3 ./tsdf_management/re... | StarcoderdataPython |
1647451 | <reponame>wallfacerlogic/Seq2seq_Chatbot
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import copy
# We disable pylint because we need python3 compatibility.
from six.moves import xrange # pylint: disable=redefined-builtin
from si... | StarcoderdataPython |
3355253 | <filename>telegram_bots/urls.py<gh_stars>1-10
from django.conf.urls import url
from . import views
app_name = 'telegram_bots'
urlpatterns = [
url(
regex=r'^$',
view=views.BotListView.as_view(),
name='telegram_bots_list',
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.Bo... | StarcoderdataPython |
1704170 | class resourceDirectoryManagerInterface:
def __init__(self, directoryFileName = 'filesDir.json', directoryRootPath = './files', versionControl= False):
super().__init__()
def scanDirectory(self):
raise NotImplementedError()
def getResourceInfo (self, fileName = False, fileUID = False):
... | StarcoderdataPython |
93739 | <filename>src/main.py
import sys
from fifi import investigate
if __name__=='__main__':
subject = sys.argv[1]
url = sys.argv[2]
# investigate('febre amarela', 'http://www.brasil.gov.br/home-1/ultimas-noticias')
investigate(subject, url)
| StarcoderdataPython |
164535 | import numpy as np
import numpy.testing as npt
from stumpy import core
import pytest
def naive_rolling_window_dot_product(Q, T):
window = len(Q)
result = np.zeros(len(T) - window + 1)
for i in range(len(result)):
result[i] = np.dot(T[i:i + window], Q)
return result
test_data = [
(np.array(... | StarcoderdataPython |
1614315 | <reponame>biochimia/python-json-reference
import datetime
import json
import unittest
import yaml as plainyaml
JSON_DATA = b'''{
"null": null,
"true": true,
"false": false,
"integer-number": 42,
"longish-number": 10633823966279326983230456482242756608,
"floating-point-number": 4.25,
"stri... | StarcoderdataPython |
1774959 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 dotzero <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ... | StarcoderdataPython |
3365694 | <reponame>owaisCS/TestHateSpeech<filename>run_baselines.py
"""
Code for training TF-IDF linear classifiers and obtaining their linear coefficients
Note: CountVectorizer performs better than TF-IDF. Perhaps the dataset is biased in that
long sequences are more likely to be offensive.
"""
from sklearn.linear_model ... | StarcoderdataPython |
1774351 | """ metric.py is a small script to turn psuedo-c metric descriptions
into executable c code as needed by zettair. Usage:
metric.py [--debug | --help] metricname.metric
If you want to debug your metric, i suggest you insert printf statements,
as there's nothing stopping you doing so.
Our input... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.