id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3306005 | <filename>app/news_cdut/routes.py
from flask import render_template, current_app, request, url_for, redirect, flash
from flask_login import login_required
from sqlalchemy import and_
from app.news_cdut import bp
from app.news_cdut.form import SearchForm
from app.news_cdut.models import NewsCdut
@login_required
@bp.r... | StarcoderdataPython |
3248864 | """
The Parser module contains the abstract class Parser
And two concrete instances, WordFileParser and
AutomataParser
"""
import abc
import re
from typing import Dict, List, Tuple, Union, Set
from more_itertools import grouper
class Parser(abc.ABC):
"""
Base Parser class
"""
@abc.abstractmethod
... | StarcoderdataPython |
3382560 | #
# Preprocess MLPerf conf templates.
#
# Developers:
# - <NAME>, dividiti, 2020
#
import json
import os
import re
from pprint import pprint
def ck_preprocess(i):
ck=i['ck_kernel']
rt=i['run_time']
deps=i['deps']
env=i['env']
new_env={} # new environment to be added to the run script
bat='\n... | StarcoderdataPython |
104657 | <gh_stars>1-10
from adventcode.utils import read_file
import re
import numpy as np
file_path = './input/day13.txt'
def parse_file(file_content=read_file(file_path)):
rows = re.split(r'\n\n', file_content)
steps = rows[1].split('\n')
steps = [parse_isntruction(step) for step in steps]
dots = rows[0].... | StarcoderdataPython |
4830487 | <gh_stars>100-1000
# Authors: <NAME> <<EMAIL>>
# + All contributors to <https://github.com/smarie/python-pytest-cases>
#
# License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE>
import pytest
from pytest_cases import assert_exception
def test_assert_exception():
# goo... | StarcoderdataPython |
1628146 | """Unit test package for dynamic_bernoulli_embeddings."""
| StarcoderdataPython |
1677278 | <gh_stars>1-10
# We use App.py For Api Integrations
from flask import Flask,render_template,url_for,request
from flask_material import Material
import joblib
import pandas as pd
import numpy as np
app = Flask(__name__)
Material(app)
#We have to Say Flask Where you have route
@app.route('/')
def index():
retu... | StarcoderdataPython |
21781 | <filename>tensorflow_tts/processor/baker_online_tts.py
#!/usr/bin/env python
# coding: utf-8
# 调用方式
# python online_tts.py -client_secret=你的client_secret -client_id=你的client_secret -file_save_path=test.wav --text=今天天气不错哦 --audiotype=6
from typing import TextIO
import requests
import json
import argparse
import os
impo... | StarcoderdataPython |
1670182 | import json
from datetime import datetime
from flask import Response
class Dicer2Response(Response):
""" DICER2请求响应基类 """
msg = "OK"
charset = 'utf-8'
default_status = 200
default_mimetype = "application/json"
def __init__(self, data, start_time, **kwargs):
"""
请求响应初始化
... | StarcoderdataPython |
83712 | <reponame>ifraixedes/saltstack-salt<filename>tests/unit/utils/test_ssdp.py
"""
:codeauthor: :email:`<NAME> <<EMAIL>>`
"""
import datetime
import salt.utils.ssdp as ssdp
import salt.utils.stringutils
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase, skipIf
try:
import py... | StarcoderdataPython |
1674015 | <reponame>jessegonzalez-life360/itsybitsy
# Copyright # Copyright 2020 Life360, Inc
# SPDX-License-Identifier: Apache-2.0
"""
Assumptions:
- A Jump/Bastion server is used
- The Jump/Bastion server is configured in an ssh config file per host, default ~/.ssh/config
"""
import asyncio
import asyncssh
import os
i... | StarcoderdataPython |
1662988 | <reponame>winius/chat-bot
import random
import datetime
import shelve
def main(vk, peer_id, text):
sm = '📆'
week = datetime.datetime.today().strftime('%A')
whatnow = int(datetime.datetime.today().strftime('%H'))
################################################################## опеределяем ... | StarcoderdataPython |
4838120 | import cv2
import _pickle as p
def write(path, Object):
"Writes object to given path."
with open(path, "wb") as output:
p.dump(Object, output, -1)
path = input("path to image: ")
outpath = input("output path: ")
img = cv2.imread(path)
ys,xs,_ = img.shape
map = []
for x in range(xs):... | StarcoderdataPython |
103056 | # Copyright (c) 2022, NVIDIA CORPORATION.
import pytest
from pandas import NA
from dask import dataframe as dd
from dask_cudf.tests.utils import _make_random_frame
@pytest.mark.parametrize(
"func",
[
lambda x: x + 1,
lambda x: x - 0.5,
lambda x: 2 if x is NA else 2 + (x + 1) / 4.1,
... | StarcoderdataPython |
5939 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | StarcoderdataPython |
1670215 | from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Create my urls here.
urlpatterns = [
path('', views.index, name='index'),
path('signin/', views.signin, name="signin"),
path('create/', views.create, name="create"),
path('contact/', views.contact, name="contact"),
... | StarcoderdataPython |
3367768 | <filename>test/vanilla/Expected/AcceptanceTests/RequiredOptional/requiredoptional/models/__init__.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project ro... | StarcoderdataPython |
3306853 | <gh_stars>0
#
# This file is part of sitscwl
# Copyright (C) 2022 INPE.
#
# sitscwl is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
class SITSMachineLearningModel(dict):
name = None
def __str__(self):
arguments = ",... | StarcoderdataPython |
79758 | def test_get_empty_collection(client):
empty_response = client.get('/data')
assert empty_response.status_code == 200
assert 'json' in empty_response.content_type
assert empty_response.is_json
assert empty_response.json['href'].startswith('http')
assert empty_response.json['href'].endswith('/data... | StarcoderdataPython |
3273932 | <gh_stars>0
import numpy
arr = numpy.ndarray(shape =(3,3,3),dtype =int)
print("Array size",arr.size)
print('Array shape',arr.shape)
print("Array dimension",arr.ndim)
print('Array dtype',arr.dtype)
print('')
val = 1
x = arr.shape[0]
y = arr.shape[1]
z = arr.shape[2]
for i in range(x):
for j in range(y):
... | StarcoderdataPython |
4811544 | """
This script allows to automate basic gameplay of the Idle Breakout game.
https://armorgames.com/idle-breakout-game/18584
"""
import time
import numpy as np
import cv2
import pyautogui as gui
from utils import show, dump
from frames_provider import FramesProvider, FrameSources
def detect_bricks(
i... | StarcoderdataPython |
3366363 | <filename>murano/tests/unit/dsl/test_property_access.py
# Copyright (c) 2014 Mirantis, Inc.
#
# 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... | StarcoderdataPython |
36328 | <filename>apps/test/models.py
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
class Workspace(models.Model):
code = models.CharField(_('코드'), max_length=40, unique=True, editable=False)
name = models.CharField(_('이름'), max_length=50, unique=... | StarcoderdataPython |
3232134 | <reponame>Hawa-Evakali/LOCKERs
import unittest # Importing the unittest module
from credentials import Credentials
class TestCredentials(unittest.TestCase):
'''
Test class that defines test cases for Credentials class behaviours
Args:
unittest.TestCase: TestCase class that helps in creating t... | StarcoderdataPython |
25339 | from django.db import models
# Create your models here.
class Car_basic(models.Model):
car_number = models.CharField(max_length=10, null=True, blank=True)
car_color = models.CharField(max_length=10, null=True, blank=True)
register_date = models.DateTimeField(null=True, blank=True)
user_name = models.C... | StarcoderdataPython |
176098 | import threading
import grpc
import client.grpc_out.chat_pb2 as chat_proto
import client.grpc_out.chat_pb2_grpc as chat_grpc
class ChatClient:
"""
Класс - клиент чата.
В gRPC довольно легко работать с сервером, но мы сделаем прослойку, чтобы было совсем просто.
"""
def __init__(self, port=5000, ... | StarcoderdataPython |
3262505 | # coding:utf-8
# 知识点:使用MD5加密
import hashlib
if __name__ == '__main__':
md5 = hashlib.md5()
md5.update('Hello World.世界,你好!'.encode('utf-8'))
print('MD5:', md5.hexdigest())
print(md5.digest_size, md5.block_size)
print('------------------') | StarcoderdataPython |
100539 | <reponame>kiwicom/kiwi-platform-py<filename>kw/platform/aiohttp/utils.py
"""
Helpers and Utils
=================
"""
import asyncio
import time
from functools import wraps
from aiohttp import web
from .. import settings
from ..utils import UserAgentValidator, httpdate
def set_sunset(response, when=None, info_url=N... | StarcoderdataPython |
3253221 | <reponame>James-Montgomery/romus<filename>romus/discrete_likelihood.py
"""
Discrete Likelihood Models
=====
This module includes conjugate model classes for discrete likelihood functions.
"""
import numpy as np
# import scipy.stats as st
import logging
from romus._utils import check_fitted, check_input_gt_zero, check... | StarcoderdataPython |
4819142 | import discord
from discord.ext import commands
import requests
import yaml
import json
from settings.db_commands import mysql_command
import time
async def parser(ctx, mult, mod, sinal, resultado):
splited = []
len_r = len(resultado)
for i in range(mult):
start = int(i*len_r/mult)
end = ... | StarcoderdataPython |
1640286 | from .utils import Tree | StarcoderdataPython |
3210018 | from distutils.core import setup
setup(name="DiffKemp",
version="0.1",
description="A tool for semantic difference analysis of kernel functions.",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/viktormalik/diffkemp",
packages=["diffkemp"],
install_requires=["... | StarcoderdataPython |
1604076 |
import peewee
import datetime
import sqlite3
from playhouse.sqlite_ext import SqliteExtDatabase, FTSModel
#from playhouse.apsw_ext import APSWDatabase
def initialize(db):
class BaseModel(peewee.Model):
class Meta:
database = db
class Credentials(BaseModel):
##blocfileds will ... | StarcoderdataPython |
1708195 | # Copyright 2017 Novartis Institutes for BioMedical Research Inc. 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 |
3212559 | from random import randint
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.contacts = {}
self.interests = {}
def add_contact(self, contact):
self.contacts[contact.first_name] = contact
return... | StarcoderdataPython |
1713249 | <gh_stars>0
import os
import glob
from PIL import Image
import tensorflow as tf
import numpy as np
new_model = tf.keras.models.load_model("./models/pingo_0.925_0.263.h5")
IMG_SIZE = (300, 300)
def classfication_image(path, target):
try:
img = tf.keras.preprocessing.image.load_img(
path, tar... | StarcoderdataPython |
4837339 | <reponame>enricorusso/incubator-ariatosca
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Versi... | StarcoderdataPython |
75702 | class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
ans = []
self.wordSet = set(words)
for word in words:
self.wordSet.remove(word)
if self.search(word):
... | StarcoderdataPython |
13616 | <gh_stars>1-10
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from enum import Enum
from indico.core.errors import IndicoError
from indico.core.logger i... | StarcoderdataPython |
3370961 | from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
from app.models import User, Blog
app = create_app("production")
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command("db", MigrateCommand)
manager.add_command("server", Server)
... | StarcoderdataPython |
177358 | <reponame>Panopta/python-panopta-api-client
from panopta_api import Client
import unittest
class ClientTest(unittest.TestCase):
def setUp(self):
self.client = Client('fake-api-key',
host='http://api2.panopta-testing.com',
version='test',
... | StarcoderdataPython |
3245610 | import random
import string
f = open("data-iot.txt","w+")
header_statement = "# DDL\n\nCREATE DATABASE IOT-generator\n\n# DML\n\n# CONTEXT-DATABASE: IOT-generator\n\n"
f.write(header_statement)
time = 1483250400
states = ["California", "Texas", "New_York"]
temperature_ca = [random.randint(80,401), random.randint(80,401... | StarcoderdataPython |
1785099 |
from cp_request.unit import Unit, UnitEncoder, UnitDecoder
from cp_request.version import Version, VersionEncoder, VersionDecoder
from cp_request.value import Value, ValueEncoder, ValueDecoder
from cp_request.attribute import Attribute, AttributeEncoder, AttributeDecoder
from cp_request.named_entity import (
Name... | StarcoderdataPython |
1713269 | from model.group import Group
import random
import pytest
def test_delete_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test"))
old_group = db.get_group_list()
with pytest.allure.step('Выбираем группу'):
group = random.choice(old_group)
w... | StarcoderdataPython |
121776 | import random
import re
from contextlib import suppress
from socket import socket
from typing import Any, Tuple
from socks import ProxyError
from ripper.constants import HTTP_STATUS_CODE_CHECK_PERIOD_SEC
from ripper.context import Context, Errors
HTTP_STATUS_PATTERN = re.compile(r" (\d{3}) ")
class HttpFlood:
... | StarcoderdataPython |
3387504 | <reponame>JimenaAndrea/architext
import mongoengine
from . import item as item_module
from . import room as room_module
class Exit(mongoengine.Document):
name = mongoengine.StringField(required=True)
destination = mongoengine.ReferenceField('Room', required=True)
description = mongoengine.StringField()
... | StarcoderdataPython |
1642047 | import logging
import os
import random
import boto3
import yaml
from ocs_ci.ocs.exceptions import TimeoutExpiredError
from ocs_ci.framework import config, merge_dict
from ocs_ci.utility import aws, vsphere, templating
from ocs_ci.utility.retry import retry
from ocs_ci.ocs import constants, ocp, exceptions
from ocs_ci... | StarcoderdataPython |
45819 | #!/usr/bin/env python
'''
run social sim trials
'''
import actionlib
import rospy
from rospy_message_converter import message_converter
import tf
from geometry_msgs.msg import PoseArray, Pose
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionGoal
from social_sim_ros.msg import TrialStart, Tria... | StarcoderdataPython |
1668558 | <gh_stars>0
# BOJ 10026
# redgreen
import sys
from copy import deepcopy
sys.setrecursionlimit(10000)
dx = (-1, 1, 0, 0)
dy = (0, 0, 1, -1)
dcolor = ('R', 'G', 'B')
n = int(input())
grid = []
grid_rg = []
for i in range(n):
grid.append(list(input()))
grid_rg = deepcopy(grid)
res_norm = 0
res_rg = 0
def... | StarcoderdataPython |
29150 | # receive_msg.py
#
# SPDX-FileCopyrightText: Copyright 2021 <NAME>
#
# SPDX-License-Identifier: MIT
#
# Receive message from IOTA tangle
#
import iota_client
import os
import pprint
# Config
msg_meta = False
env_node_address = 'HORNET_NODE_ADDRESS'
# Print Message data
def show_message(message, meta=False):
if... | StarcoderdataPython |
3243243 | from abc import ABC, abstractmethod
import numpy as np
from sklearn.utils.stats import _weighted_percentile
class LossFunction(ABC):
@abstractmethod
def __call__(self, y, y_hat):
raise NotImplemented
@abstractmethod
def negative_gradient(self, y, y_hat):
raise NotImplemented
@ab... | StarcoderdataPython |
99622 |
# Copyright (c) 2020, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
import time
import jso... | StarcoderdataPython |
3239764 | import click
import requests
import re
from validator_collection import validators, checkers
import os.path
__author__ = "<NAME>"
@click.group()
def main():
"""
Python CLI XVideos Downloader. Academic Purposes Only. How to Use: x.py url http... or x.py file file.txt
"""
pass
@main.command()
@click.... | StarcoderdataPython |
166507 | <gh_stars>10-100
from boa3.builtin import public
from boa3.builtin.interop.storage import delete
@public
def Main(key: str):
delete(key)
| StarcoderdataPython |
1665772 | #!/usr/bin/python3
class Sender:
def __init__(self, id: int, links: dict, mention_name: str, name: str, version: str):
self.id = id
self.links = links
self.mention_name = mention_name
self.name = name
self.version = version
class Room:
def __init__(self, id: int, is_a... | StarcoderdataPython |
4842946 | # Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test if the memory size is correctly written in the firmware.
Description
-----------
Linux kernel trusts the available memory region specified from f... | StarcoderdataPython |
1761564 | # Copyright (C) 2006-2013 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = """\n""".join(['<NAME> <<EMAIL>>',
'<NAME> (<EMAIL>)',
'<NAME> (<EMAIL>)'])
__all__ = ['c... | StarcoderdataPython |
3312975 | #<EMAIL>
def common_words(first, second):
dd = set()
for s in first.split(","): dd.add(s)
return ",".join(sorted([w for w in second.split(",") if w in dd]))
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert common_words("hello,world... | StarcoderdataPython |
3304579 | <filename>notebooks/energy_flux/conversion.py
# A module to calculate conversion and useful values for energy flux.
# Based on Kelly et al 2010.
import numpy as np
import pressure
from salishsea_tools import grid_tools, psu_tools
def bathymetry_gradient(bathy, e1u, e2v):
"""Calculate the bathymetry gradient, H... | StarcoderdataPython |
1622954 | <filename>assets/resources/simple-tutorial/ML04/tf_solve_chihuahua_muffin.py
#@title MIT License
#
# Copyright (c) 2018 IBM
#
# 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 restricti... | StarcoderdataPython |
126033 | <reponame>JosephChataignon/pyclustering<filename>pyclustering/nnet/examples/pcnn_segmentation.py
"""!
@brief Examples of usage and demonstration of abilities of Pulse Coupled Neural Network in image segmentation.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
from PIL import Image
... | StarcoderdataPython |
4826420 | <reponame>Giuseppe-Rizzo/DLLibrary<filename>TestFileLoader.py
# -*- coding: utf-8
#from scipy.io import arff
from neuralnetworks.LayerFactory import LayerFactory
from datasource.FileLoader import FileLoader
from preprocessing.Preprocessor import Preprocessor
#from neuralnetworks.deprecated.MLNWithoutKeras import MLNWit... | StarcoderdataPython |
132191 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
3362450 | <reponame>ineslacerda/PE2LGP-Translator<filename>PE2LGP/Modulo_tradutor/freq_json.py<gh_stars>1-10
import json
import operator
import re
def abrir_freq(file):
"""
Abre o ficheiro json com o dicionário das frequências das regras.
:param file: ficheiro json
:return: dicionário com as frequências das regras no corpus... | StarcoderdataPython |
3344833 | <reponame>georgejhunt/python-mbtiles
#!/usr/bin/env python2
# -*- coding: UTF-8 -*-
# Download satellite imagess from Sentinel Cloudless
# notes to set up this exploration
# -- the symbolic link satellite.mbtiles is set to source
# -- output placed in ./work/sat_<name>.mbtiles
# -- just a -z option throw app into vi... | StarcoderdataPython |
1681615 | <filename>test/test_special_iocommands.py
# coding: utf-8
import os
import stat
import tempfile
import pytest
import okcli.packages.special
from okcli.packages.special.main import CommandNotFound
from utils import db_connection, dbtest
def test_set_get_pager():
okcli.packages.special.set_pager_enabled(True)
... | StarcoderdataPython |
3348404 | """Disk load tester
Usage:
disk_load_tester.py [<destination>] [--reps=<reps>] [--nprocs=<nprocs>]
Options:
<destination> The target directory [Default: /mnt/user_storage]
--reps=<reps> Number of read/write loops, per process [Default: 200]
--nprocs=<nprocs> Number of parallel processes ... | StarcoderdataPython |
48240 | <reponame>HKGx/smolmath
from dataclasses import dataclass, field
from textwrap import dedent
from typing import Literal
from smol.parser.expressions import *
from smol.parser.statements import *
from smol.lexer import Token, Lexer, TokenType
from smol.utils import StageContext
@dataclass
class Program:
statement... | StarcoderdataPython |
117969 | <reponame>ChaoticMarauder/Project_Rosalind<filename>Algorithms/004_FIB.py
def rabbit_pairs(n,k):
if(n==1):
return 1
if(n==2):
return 1
else:
return k*rabbit_pairs(n-2,k)+rabbit_pairs(n-1,k)
def main():
with open('datasets/rosalind_fib.txt') as input_data:
n,k=map(... | StarcoderdataPython |
3313235 | import torch
import numpy as np
import pylab as plt
from collections import deque
from ai_traineree.agents.dqn import DQNAgent
from ai_traineree.runners.env_runner import EnvRunner
from ai_traineree.loggers import TensorboardLogger
from ai_traineree.networks.heads import NetChainer
from ai_traineree.networks.bodies im... | StarcoderdataPython |
3379261 | <reponame>facade-technologies-inc/facile
"""
..
/------------------------------------------------------------------------------\
| -- FACADE TECHNOLOGIES INC. CONFIDENTIAL -- |
|------------------------------------------------------------------------------|
| ... | StarcoderdataPython |
3372255 | <reponame>artigianitecnologici/docker<filename>nginx/web/public/program/dummy_robot.py
def begin():
print("begin")
def end():
print("end")
def forward(n=1):
print("forward %d" %(n))
def backward(n=1):
print("backward %d" %(n))
def left(n=1):
print("left %d" %(n))
def right(n=1):
print("righ... | StarcoderdataPython |
1791222 | class Alert:
"""Maps a Rule to an Action, and triggers the action if the rule
matches on any stock update"""
def __init__(self, description, rule, action):
self.description = description
self.rule = rule
self.action = action
def connect(self, exchange):
self.exchange = ... | StarcoderdataPython |
144797 | from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import math
a = 0
cores = ( (1,0,0),(1,1,0),(0,1,0),(0,1,1),(0,0,1),(1,0,1),(0.5,1,1),(1,0,0.5) )
def piramide():
raio = 2
raio2 = 2
N = 5
H = 4.0
pontosBase = []
pontosBase1 = []
angulo =(2*math.pi)/N
glPush... | StarcoderdataPython |
3331804 | <filename>__main__.py
#!/usr/bin/env python
# import sys
import footmark
#from footmark.ecs.connection import ECSConnection
def main():
print "Hello World!"
if __name__== "__main__":
main()
print "This is main Program"
#app=ECSConnection()
#app.run()
| StarcoderdataPython |
3223389 | <gh_stars>1-10
true = TRUE = True
false = FALSE = False
null = NULL = None
| StarcoderdataPython |
3258032 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anythi... | StarcoderdataPython |
90345 | <filename>polyorg/views.py
from django.utils.translation import ugettext as _
from django.http import HttpResponseForbidden, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.template.context import RequestContext
from django.contrib.aut... | StarcoderdataPython |
3312970 | import vxi11
class SDM3055:
def __init__(self, ip = '192.168.1.155'):
self.instr = vxi11.Instrument(ip)
try:
print(self.instr.ask("*IDN?"))
except:
print("connecting to instrument failed.. exiting")
def get_voltage(self, acdc = 'DC'):
return self.instr.... | StarcoderdataPython |
50941 | import torch
import torch.nn as nn
import torch.nn.functional as F
from datas.benchmark import Benchmark
from datas.div2k import DIV2K
from models.ecbsr import ECBSR
from torch.utils.data import DataLoader
import math
import argparse, yaml
import utils
import os
from tqdm import tqdm
import logging
import sys
import ti... | StarcoderdataPython |
9637 | from importlib import _bootstrap
from . import util
import collections
import imp
import sys
import unittest
class PathHookTests(unittest.TestCase):
"""Test the path hook for extension modules."""
# XXX Should it only succeed for pre-existing directories?
# XXX Should it only work for directories contai... | StarcoderdataPython |
1670922 | """
题目:输入某年某月某日,判断这一天是这一年的第几天(需考虑闰年情况)。
输入:2016 1 1 输出 1
输入:2016 3 2 输出 62
"""
#%%
year = int(input("year:"))
month = int(input("month:"))
day = int(input("day:"))
days = 0
months = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days = sum(months[:month]) + day
#%%
if ((year % 400 == 0) or ((year % 4 == 0) and... | StarcoderdataPython |
1700355 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# <NAME>. 12:49 31/08/2020
from flask import Flask, request, render_template, jsonify
from flask_bootstrap import Bootstrap
from flask import send_from_directory
import os
from Tools import api_news
#criando o app
app = Flask(__name__,static_url_path='/static',template_fol... | StarcoderdataPython |
1792764 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 ckitagawa <<EMAIL>>
#
# Distributed under terms of the MIT license.
import logging
import threading
import serial
import serial.tools.list_ports
import fiber_reading
from collections import deque
def select_device():
"""User-pr... | StarcoderdataPython |
3342321 | from enum import Enum
from typing import Mapping, Iterable, Any, Optional, Dict
import algoneer.dataschema
import algoneer.dataset
class AttributeSchema:
class Type(Enum):
Numerical = 1
Timestamp = 2
Integer = 3
Float = 4
Ordinal = 5
Categorical = 6
Boole... | StarcoderdataPython |
3278661 | <reponame>tarakania/discord-bot
from handler import Context, Arguments, CommandResult
from rpg.race import Race
from rpg.class_ import Class
from rpg.player import Player, NickOrIDUsed
from rpg.rpg_object import UnknownObject
async def run(ctx: Context, args: Arguments) -> CommandResult:
nick = args[0]
if no... | StarcoderdataPython |
96320 |
# -*- coding:utf-8 -*-
import re
def parse(s):
l = re.sub(r'\s+', ', ', (' '+s.lower()+' ').replace('(', '[').replace(')', ']'))[2:-2]
return eval(re.sub(r'(?P<symbol>[\w#%\\/^*+_\|~<>?!:-]+)', lambda m : '"%s"' % m.group('symbol'), l))
def cons(a, d):
if atom(d):
return (a, d)
return (lambda... | StarcoderdataPython |
1692012 | <reponame>lordjack/oficina_introducao_programacao_python
import exercicios.ex01
| StarcoderdataPython |
27412 | <filename>wagtailshowsimilar/views.py
from django.apps import apps
from django.views.decorators.http import require_GET
from django.http import JsonResponse
from django.urls import reverse
from wagtail.search.backends import get_search_backend
from wagtail.core.models import Page
backend = get_search_backend()
@requ... | StarcoderdataPython |
4841999 | # 2020.01.12
# Problem Statement:
# https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
# very similar to question 105
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left... | StarcoderdataPython |
1710606 | <gh_stars>0
#
# Based on sample code provided with Keras documentation
#
import random, math
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
try:
from numba import jit
print("numba imported")
except Exception as e:
# no numba
print("numba not... | StarcoderdataPython |
3289597 | from .constants import Guess
from .urls import parse_url_for_date, filter_url_for_undateable
def guess_date(url):
"""Guess the date of publication of a url.
Attributes
----------
url : str
url used to retrieve the webpage
Returns
-------
date_guesser_rc.constants.Guess object.
... | StarcoderdataPython |
3264421 | #
# @lc app=leetcode id=63 lang=python3
#
# [63] Unique Paths II
#
# https://leetcode.com/problems/unique-paths-ii/description/
#
# algorithms
# Medium (35.16%)
# Likes: 2590
# Dislikes: 289
# Total Accepted: 359.9K
# Total Submissions: 1M
# Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]'
#
# A robot is located at... | StarcoderdataPython |
153024 | <filename>notexbook/settings.py
# encoding: utf-8
# ------------------------------------------------------------------------
# <NAME> <@leriomaggio> 2020
# IPython magic function to enable TeXBook Jupyter notebook Theme
# Author: <NAME> <github.com/leriomaggio>
# Code: https://github.com/leriomaggio/notexbook-jupyter-... | StarcoderdataPython |
1639473 | from matplotlib.ticker import PercentFormatter
from scipy.stats import skew, kurtosis
from typing import Tuple
import matplotlib.pyplot as plt
import pandas as pd
__all__ = [
'univariate_plot',
'univariate_plot_v2',
'boxplot_summary',
'pareto_plot',
]
def univariate_plot_v2(independent_variable: pd.... | StarcoderdataPython |
4811911 | <reponame>seunghwanly/CODING-TEST
def solution(s):
answer = 0
for i in range(len(s)):
if i != 0:
front = s[0]
s = s[1:] + front
tempStack = []
tempString = list(s)
while tempString:
top = tempString.pop()
tempStack.append(top)
... | StarcoderdataPython |
174779 | <reponame>king4arabs/wsnsims2
import itertools
import numpy as np
from wsnsims.core.data import segment_volume
class ToCSEnergyModelError(Exception):
pass
class ToCSEnergyModel(object):
def __init__(self, simulation_data, environment):
"""
:param simulation_data:
:type simulation_... | StarcoderdataPython |
3376390 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Script to convert the SVHN data provided in .mat files (available from
http://ufldl.stanford.edu/housenumbers/) to a CIFAR-style binary format.
"""
import os
import scipy.io
def preprocess(file_path="", save_path=""):
"""Preprocesses the train and test dataset of the stree... | StarcoderdataPython |
1683413 | <reponame>stv0g/meine-stadt-transparent
import os
import sys
from pathlib import Path
import environ
from django.core.exceptions import ImproperlyConfigured
env = environ.Env()
env_file = Path(".env")
# This works good enough for the console, pycharm and travis ci
TESTING = sys.argv[1:2] == ["test"] or "pytest" in s... | StarcoderdataPython |
76966 | <reponame>giswqs/eemont<gh_stars>1-10
import ee
import unittest
from eemont import feature
ee.Initialize()
class Test(unittest.TestCase):
"""Tests for `eemont` package."""
def test_BBoxFromQuery(self):
"""Test the BBoxFromQuery constructor"""
test = ee.Feature.BBoxFromQuery('Colombia',use... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.