id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
9659752
import datetime from django.conf import settings from django.test.testcases import TestCase from django.urls import reverse from faker import Faker from rest_framework import status from rest_framework.test import APIClient from ado.apps.buses.models import Bus, Seat from ado.apps.routes.models import Route from ado....
StarcoderdataPython
1731208
<reponame>elimohl/pchc<filename>history_converter.py #!/usr/bin/env python import argparse import os import codecs import datetime from html.parser import HTMLParser from html.entities import name2codepoint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchem...
StarcoderdataPython
3585653
from django.utils.translation import gettext as _ from ..core.mail import mail_user from ..legal.models import Agreement from ..legal.utils import save_user_agreement_acceptance from .tokens import make_activation_token def send_welcome_email(request, user): settings = request.settings mail_subject = _("Wel...
StarcoderdataPython
1888884
# -*- coding: utf-8 -*- # Copyright (C) 2020 Red Hat, 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 applicabl...
StarcoderdataPython
4836933
<gh_stars>10-100 # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """ This example uses the light sensor on the Circuit Playground, located next to the picture of the eye on the board. Once you have the library loaded, try shining a flashlight on your Circuit Playground to ...
StarcoderdataPython
6419115
import pyperclip class User: """ This is to generate new contacts. """ user_list =[] def __init__(self,name1,name2,password,email): self.name1 = name1 self.name2 = name2 self.password = password self.email = email def save_user(self): User.user_lis...
StarcoderdataPython
216877
print("Test program was run")
StarcoderdataPython
1856069
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : <NAME> @Contact : <EMAIL> @Time : 2021/11/8 21:16 @File : decorators.py @Software: PyCharm @Desc : """ from warnings import warn from .timer import Timer from .color_print import * __all__ = ['deprecated', 'func_runtime_timer'] def deprecated(fu...
StarcoderdataPython
1714439
<reponame>Sherif-Abdou/RescueRobot import sentry_sdk sentry_sdk.init("https://1e9819f95a3d46fdb1ef8c96287c29e8@sentry.io/1310445") from serial import Serial # The class responsible for handling the robot's lights class Lights(): def __init__(self, light_serial: Serial=None, test_mode=False): self._l1 = Fals...
StarcoderdataPython
8038163
"""Otps app utilities.""" import math import random from snm.otps.models import Otp def generateOTP(): """Generate 6 random numeric OTP.""" numbers = "0123456789" otp = "" for i in range(6): otp += numbers[math.floor(random.random() * 10)] return otp def verifyOTP(otp): """Verify a...
StarcoderdataPython
3459779
from typing import Optional from sqlalchemy.orm import Session from app.api import models, schemas from app.api import consts def get_all_products(db: Session): return db.query(models.Product).all() def filter_products(query: Optional[str], product_status: Optional[consts.ProductStatus], pro...
StarcoderdataPython
1974744
""" import errors will import all common errors """ from .kafka_streams_error import KafkaStreamsError
StarcoderdataPython
9667933
# -*- coding: utf-8 -*- # This file is generated from NI-SWITCH API metadata version 19.6.0d7 enums = { 'CabledModuleScanAdvancedBus': { 'values': [ { 'documentation': { 'description': '' }, 'name': 'NISWITCH_VAL_NONE', ...
StarcoderdataPython
4867431
""" Misc functions cultivated across the chapter. Ported here for posterity, but'll keep on working them into later packages """ import socket from typing import Union, List class Helpers: """Static functions, to use as helpers""" @staticmethod def send_data(to_socket: socket.socket, data_stream: bytes, ...
StarcoderdataPython
1696881
x=0 def function(): #global x x=100 function() print(x)
StarcoderdataPython
3418530
<reponame>Colabo/datadogpy # Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2015-Present Datadog, Inc import os import string import sys # datadog from datadog.u...
StarcoderdataPython
1811247
from confu.util import config_parser_dict import os try: import configparser except ImportError: import ConfigParser as configparser def test_config_parser_dict(): path = os.path.join(os.path.dirname(__file__), "data", "configparse.cfg") config = configparser.ConfigParser() config.read(path) ...
StarcoderdataPython
3205144
from .base_node import BaseNode class AchUsNode(BaseNode): """Represents an ACH-US node.""" @classmethod def unverified_from_response(cls, user, response): """Create an AchUsNode instance for an ACH-US node that needs MFA. The API record is not actually created until the MFA has been cor...
StarcoderdataPython
6581905
import io import pytest import re import os import ctypes from cfiddle.CProtoParser import * from cfiddle.ProtoParser import BadParameter, UnknownType, BadParameterName, Prototype, Parameter @pytest.mark.parametrize("t,ct", [ ("long", ctypes.c_long), ("uint64_t", ctypes.c_ulonglong) ]) def test_get_ctype(CPars...
StarcoderdataPython
11319794
<reponame>sag-tgo/xpybuild<gh_stars>1-10 from pysys.constants import * from xpybuild.xpybuild_basetest import XpybuildBaseTest class PySysTest(XpybuildBaseTest): def execute(self): # run single threaded so we can look at order self.xpybuild(args=['-j1']) def validate(self): selectedtargets = 'build-output/BU...
StarcoderdataPython
46881
from heapq import heapify, heappush, heappop from collections import defaultdict import math def shortest_path(M, start, goal): frontier = {start} explored = set() came_from = dict() f_costs = get_initial_f_costs(M, start, goal) # heapq type g_costs = get_initial_g_costs(start) # defaultdict typ...
StarcoderdataPython
33107
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # dbcluster.py # GGHC cluster class # Copyright (c) 2021 Chinasoft International Co., Ltd. # # gghc is licensed under Mulan PSL v2. # You can use this software according to the terms # and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan P...
StarcoderdataPython
27888
import tkinter as tk from abc import ABCMeta, abstractmethod from ...frames.templates import FrameTemplate from ...elements import AddButton, EditButton, DeleteButton class ListFrameTemplate(FrameTemplate, metaclass=ABCMeta): def __init__(self, top, *args, **kw): super().__init__(top, *args, **kw) ...
StarcoderdataPython
23554
from configparser import ConfigParser from os import path def create_config() -> None: _config.add_section("Telegram") _config.set("Telegram", "api_id", "you api_id here") _config.set("Telegram", "api_hash", "you api_hash here") _config.set("Telegram", "username", "magicBot") _config.set("Telegram...
StarcoderdataPython
297415
<reponame>filiparag/school-bell import configparser from datetime import datetime from os import path, sep directory = path.dirname(path.realpath(__file__)) + sep config = None def get(section, key): global config if config is None: load() if config.get(section) is None: return None ...
StarcoderdataPython
11249431
"""DynamoDB implementation of the database facade.""" import typing from . import exceptions, models, types class Database: """Interface for DynamoDB database.""" @staticmethod def count_customer_models(*, sub: types.TSub) -> int: """ Count the number of models a customer has stored. ...
StarcoderdataPython
5076835
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # 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 ...
StarcoderdataPython
6479599
#!/usr/bin/env python import logging from toy_manifest_service import schema logging.basicConfig(level=logging.INFO) print(schema.create_manifest_layers_statement(12))
StarcoderdataPython
9774345
<reponame>BabyCakes13/Leader-Election<filename>leader_election_server.py #!/usr/bin/env python3 import logging import socket import time class LeaderElectionServer: """ Class which handles the server instance. """ TCP_IP = '' TCP_PORT = 5001 BUFFER_SIZE = 1024 TIMEOUT = 10 HEARTBEAT_...
StarcoderdataPython
9725749
<reponame>livioribeiro/django-smart-paging from django.core.paginator import Paginator import pytest from smart_pagination.pagination import make_paginator even_num_links = 6 odd_num_links = 5 testargs = 'num_links, num_page, first_link, last_link, current_index' testdata = [ (odd_num_links, 1, 1, 5, 0), # 1! 2 ...
StarcoderdataPython
9793078
import functools from typing import List import textx from textx import metamodel_from_file import textx.scoping.providers as scoping_providers from meco.definitions import GRAMMAR_PATH def build_model(model_path: str) -> textx: mm = metamodel_from_file(GRAMMAR_PATH, global_repository=True) mm.register_scop...
StarcoderdataPython
217346
# -*- coding: utf-8 -*- # from pyldapi_client import LDAPIClient from exporter.helpers import chunks, ld_find_subject, ld_find_as_object import pickle import xlsxwriter LDAPI_CLIENT_REMAPPER = { "http://linked.data.gov.au/dataset/asgs2016": "http://localhost:5000" } HEADERS = ( 'Identifier', 'Class' ) cl...
StarcoderdataPython
171627
<gh_stars>10-100 import re def get_answers_of_group(group): answers = {x for x in group if re.match('[a-z]', x)} return answers def get_unanimously_answered_questions(group): persons = group.split('\n') questions_answered = [{q for q in person} for person in persons] return set.intersection(*quest...
StarcoderdataPython
3359484
import pygame from Model.class_Animated import Animated from Model.class_Charac import Charac from Model.class_Mob import Mob from Model.class_Atk import Atk from utils import load_imgs # Hero est la classe générique des héros # Carastéristiques des héros: # Ils sont controlés au clavier # Ils peuvent double-saut...
StarcoderdataPython
9637953
import os import string CMD = "convert -background '#ffffff00' -fill white -font {font} -size 256x256 -pointsize 128 -gravity center 'label:{label}' {out_dir}/{filename}.png" def generate(out_dir, font, letter): os.system(CMD.format(font=font, label=letter.lower(), out_dir=out_dir, filename=f"{letter.lower()}_...
StarcoderdataPython
1780562
<reponame>yc541/Project-AWARE<filename>train.py import os import torch import numpy as np import torchvision import transforms as T import utils from PIL import Image from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor from engine i...
StarcoderdataPython
9689584
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2021 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free...
StarcoderdataPython
5165250
from django.conf.urls.defaults import * import test_utils.views as test_views urlpatterns = patterns('', url(r'^set_logging/(?P<filename>.*?)/', test_views.set_logging, name='test_utils_set_logging'), url(r'^set_loggin...
StarcoderdataPython
1849255
# Copyright 2013 Devsim 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 agreed to in writing, s...
StarcoderdataPython
11377385
import mock from rest_framework.test import APIRequestFactory from rest_framework.test import force_authenticate from django.contrib.contenttypes.models import ContentType from awx.api.views import ( TeamRolesList, ) from awx.main.models import ( User, Role, ) def test_team_roles_list_post_org_roles()...
StarcoderdataPython
1792662
# coding=utf-8 """ terminal.server.ws_server ~~~~~~~~~~~~~~~~~~~~~~~~~ 本模块提供WebSocket服务启动能力 """ import sys import asyncio import zmq import tornado.websocket import tornado.web import tornado.httpserver import tornado.options from talos.core import config from terminal.common.wshandler import SSHHandler from termin...
StarcoderdataPython
3413185
<filename>tests/models/test_segmentation.py<gh_stars>1-10 import unittest import torch import yaml from parameterized import parameterized from src.constructor.config_structure import TrainConfigParams from src.registry import TASKS example_backbones = [ 'hrnet_w18_small_v2', 'resnet18', 'gluon_resnet18_...
StarcoderdataPython
5104524
<filename>sources/parse_recipes.py #!/usr/bin/env python3 import json import re from json import JSONEncoder re_ingredient = re.compile(r'(?P<name>[\w ]+)(; (?P<subtype>[\w ]+))? (?P<recipe_page_nums>[\d, ]+)') re_consecutive_whitespace = re.compile(r'\s+') re_slugify_drop_chars = re.compile(r'[^a-zA-Z0-9 -]') def ...
StarcoderdataPython
1999938
<gh_stars>0 from django.http import HttpResponse def my_view(request): return HttpResponse('')
StarcoderdataPython
4989532
<filename>cogs/realm.py import random import asyncio import discord from bs4 import BeautifulSoup from discord.ext import commands from urllib.request import Request, urlopen from utils.configManager import RedditConfig, BotConfig from utils import consts, realmHelpers class Realm(commands.Cog): """Various Real...
StarcoderdataPython
12831128
<gh_stars>0 import os RUTA = os.getcwd() file_path = os.path.join(RUTA,'personas.txt') with open(file_path, mode='r',encoding='utf-8') as f: data_personas = f.readlines() pass # end with # print(data_personas) lista_persona = [] for p in data_personas: # Separo linea por separador '; data_p = p.spl...
StarcoderdataPython
6523981
<filename>src/core/views.py<gh_stars>0 from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, DeleteView, ListView, TemplateView from django.shortcuts import render from .models import Estoque from core.forms import InsereItemForm class HomeTemplateView(TemplateView): templ...
StarcoderdataPython
11371737
<gh_stars>1-10 from setuptools import setup, find_packages long_description = (open('README.rst').read() + open('CHANGES.rst').read() + open('TODO.rst').read()) setup( name='django-model-utils', version='1.4.0.post1', description='Django model mixins and utilities...
StarcoderdataPython
8185090
<filename>netman/adapters/switches/juniper/base.py # Copyright 2015 Internap. # # 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 req...
StarcoderdataPython
1929280
<gh_stars>1-10 # Copyright 2018 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. """Handles /webapps/download_slots requests. According to DUT (device under test) info embedded in request header, either it will assign a...
StarcoderdataPython
8138843
<gh_stars>1-10 import os import time import datetime import subprocess from collections import OrderedDict import enzyme from sendfile import sendfile from django.db.models import Q from django.urls import reverse from django.conf import settings from django.core import management from background_task import backgroun...
StarcoderdataPython
3439016
<reponame>Elizafox/taillight import unittest from taillight import signal class TestSignalObject(unittest.TestCase): def test_singleton(self): signal_a = signal.Signal("a") signal_b = signal.Signal("b") signal_a2 = signal.Signal("a") signal_b2 = signal.Signal("b") self.as...
StarcoderdataPython
1650564
def f(a, (b, c), d): pass
StarcoderdataPython
1632131
totalHits = 0 oldKey = None mostHits = 0 bestKey = None for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: continue thisKey, thisValue = data_mapped if oldKey and oldKey != thisKey: if totalHits > mostHits: mostHits = totalHits bestKey = oldKey print oldKey, "\t"...
StarcoderdataPython
8028346
# scraper_horse_racing.py # -*- coding: utf-8 -*- import os from selenium.webdriver import Firefox from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.options import Options # Variable with the URL of the website. my_url = "http://check.torproject.org" #...
StarcoderdataPython
12828392
""" Use the download_catss function to download all of the text files for the CATSS database to disk. """ import requests import time from pathlib import Path # Before writing the download function, we compile a series of # urls and filenames which will be used to download and output # the data. The culmination of...
StarcoderdataPython
8049675
<filename>mathics/builtin/intfns/combinatorial.py # -*- coding: utf-8 -*- """ Combinatorial Functions Combinatorics is an area of mathematics primarily concerned with counting, both as a means and an end in obtaining results, and certain properties of finite structures. It is closely related to many other areas of ma...
StarcoderdataPython
9713662
""" 算术运算符 比较(关系)运算符 赋值运算符 逻辑运算符 位运算符 成员运算符 身份运算符 运算符优先级 关于运算符的总结: 运算符是造飞机,使用的时候是拧螺丝; """ print(9/2) # 除 print(9//2) # 取整 # 逻辑运算符 a = 10 b = 20 if (a > 5 and b < 100) : print("True") else: print("False")
StarcoderdataPython
4893447
''' Created on 16 Sep 2019 @author: julianporter ''' from MIDI.util import SafeEnum class Converter(object): @staticmethod def Null(_): return None @staticmethod def OnOff127(data): x = data[0] return {0: 'OFF', 127: 'ON'}.get(x,'???') @staticmethod de...
StarcoderdataPython
12825025
<reponame>UCHIC/SurveyDataViewer from SurveyDataViewer.settings.base import * DEBUG = False TEMPLATE_DEBUG = False DEPLOYED = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] if "host" in data: ALLOWED_HOSTS.append(data["host"]) if "host_alt" in data: ALLOWED_HOSTS.append(data["host_alt"]) SITE_URL = 'survey...
StarcoderdataPython
9674677
# -*- coding: utf-8 -*- import helics as h def get_input(grantedtime): valid_input = False while not valid_input: print( "Enter request_time (int) (and value_to_send (float)) [e.g.: 4, 10.0]: ", end="", ) string = input() string = string.strip() ...
StarcoderdataPython
1882026
<filename>test_test11.py # Generated by Selenium IDE import pytest import time import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.suppor...
StarcoderdataPython
6626700
<filename>pureples/es_hyperneat/es_hyperneat.py<gh_stars>10-100 """ All logic concerning ES-HyperNEAT resides here. """ import copy import neat import numpy as np from pureples.hyperneat.hyperneat import query_cppn from pureples.shared.visualize import draw_es class ESNetwork: """ The evolvable substrate netw...
StarcoderdataPython
1660722
from pymongo import MongoClient from datetime import datetime from time import mktime, strptime import pandas import threading from pymongo.errors import DuplicateKeyError from pymongo.errors import DocumentTooLarge from pymongo.errors import CursorNotFound class DatabaseValid: def __init__(self): client...
StarcoderdataPython
3347092
<gh_stars>0 # -*- coding: utf-8 -*- import inspect import os from itertools import chain from flask_script import Command, Option class Cron(Command): """Used to run and display crons.""" @staticmethod def find_modules(directory, module_root=None): _module_root = os.path.basename(directory) ...
StarcoderdataPython
1603741
<filename>superset/utils/data.py # 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...
StarcoderdataPython
6518462
""" Generator for Siemens PLC Author: dgrill Date: 19 Dez 2018 """ from CodeGenerator.conf.config import * from datetime import datetime import logging from CodeGenerator.generators import BaseGenerator as bg from CodeGenerator.generators.Syntax import Syntax as syn #Class for generating the source code in Scl class ...
StarcoderdataPython
6531073
"""Placeholder.""" import os from typing import List from setuptools import find_packages, setup import versioneer _pkg: str = "smepu" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() # Declare minimal set for installation required_packages: List[str] = [] # Specific use c...
StarcoderdataPython
1793183
# # Copyright (c) 2018, <NAME> # import datetime import re from collections import OrderedDict from importlib import import_module import iso8601 _IMPLEMENTATIONS = {} class Implementation: module_name = None def __init__(self): self._module = None if self.module_name: try: ...
StarcoderdataPython
3415616
<reponame>max-stack/MWP-SS-Metrics # @Author: <NAME> from nltk.tokenize import word_tokenize from string import digits class PreprocessText: def __init__(self, segmented_text): self.segmented_text = segmented_text def preprocess(self): self.remove_numbers() self.convert_lower_case() ...
StarcoderdataPython
4836581
import csv import json import requests as requests from util.utils import set_cwd def preprocess(): url = "https://raw.githubusercontent.com/sunshower-io/provider-lists/master/aws/output/regions.json" r = requests.get(url, allow_redirects=True) rows = [] json_s = r.content keys = None dat...
StarcoderdataPython
1722352
import sys f=open(sys.argv[-1], 'rb') b=f.read() f.close() with open(sys.argv[-1] + ".cpp", 'w') as w: c=0 w.write("const unsigned char mjpg_frame[] = {\n") for i in b: w.write("0x%02x," % i) c+=1 if c==12: w.write("\n") c=0 w.write("\n};")
StarcoderdataPython
4938622
<reponame>TuomoKareoja/us-song-lyrics-sentiment # %% import os import matplotlib.pyplot as plt import nltk import numpy as np import pandas as pd import seaborn as sns from afinn import Afinn from IPython.core.interactiveshell import InteractiveShell from langdetect import DetectorFactory, detect from nltk.stem impor...
StarcoderdataPython
3374217
<reponame>eloigil/ossu-computer-science # if / else example num = int(input('type a number: ')) if num%2 == 0: print(str(num) + ' is even') else: print(str(num) + ' is odd')
StarcoderdataPython
18380
from Artist import Artist class Artwork: def __init__(self, title='None', year_created=0,\ artist=Artist()): self.title = title self.year_created = year_created self.artist = artist def print_info(self): self.artist.print_info() print('Title: %s, %d' % (self.title,...
StarcoderdataPython
1651309
<reponame>Atamisk/pyEqualizer<filename>lhsmdu/lhsmdu/benchmark/__init__.py<gh_stars>1-10 ''' This is a benchmark of the amount of time the algorithm takes to spit out LHS samples''' from time import time import lhsmdu def runtime(numDimensions, numSamples): ''' Checks runtime using standard variables ''' start...
StarcoderdataPython
9612690
<gh_stars>1-10 """AyudaEnPython: https://www.facebook.com/groups/ayudapython Definir una función denominada “recorta_nombres” que reciba por parámetro una lista de cadenas de caracteres. Deberá recortar cada cadena de la lista a la longitud de la última cadena de caracteres de dicha lista. NOTE: El enunciado no es cl...
StarcoderdataPython
298698
# Lint as: python3 # Copyright 2020, The TensorFlow Federated Authors. # # 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 ...
StarcoderdataPython
3440017
<filename>PySpace/mysql/mysql_connect.py #!/usr/bin/python3 # 文件名:mysql_connect.py import pymysql # 打开数据库连接 db = pymysql.connect('localhost','root','1234','fdtest') # 使用cursor()方法创建一个游标对象cursor cursor = db.cursor() # 使用execute() 方法执行SQL查询 cursor.execute("SELECT VERSION()") # 使用fetchone()方法获取单条数据 data = cursor.fetc...
StarcoderdataPython
3218793
## # Copyright 2018, <NAME> # Licensed under MIT. # Since: v1.0.0 ## # All modules in package __all__ = [ 'application', 'default' ]
StarcoderdataPython
1958060
<reponame>dolong2110/Algorithm-By-Problems-Python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # def increasingBST(self, root: TreeNode, next_in_order = None) -> TreeNode: # if not root: # return next_in_ord...
StarcoderdataPython
3554582
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy import signals import json import codecs import MySQLdb import sys reload(sys) sys.setdefaultencoding("utf-8") cla...
StarcoderdataPython
3571520
<filename>main.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel from starlette.responses import RedirectResponse from redis_database import Database class Item(BaseModel): url: list[str] app = FastAPI() URL = 'http://192.168.3.11:8889/' @app.get('/{item_id}') def redirect(item_id:...
StarcoderdataPython
12807103
import sys import argparse import matplotlib matplotlib.use('Agg') from decimal import * import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import numpy as np from math import sqrt from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) SPINE_COLOUR = 'gray' #...
StarcoderdataPython
5100164
<filename>baseline/__init__.py __all__ = ["baselinePokerPlayer", "callBaselinePokerPlayer", "consolePokerPlayer", "randomPokerPlayer"]
StarcoderdataPython
363117
# -*- coding: utf-8 -*- ############################################################################### # # SetValid # Sets a specified token as valid or invalid. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this...
StarcoderdataPython
1692590
from src.microphone import Microphone from src.speaker import Speaker while(True): mph = Microphone(language='pt-br') response = mph.listen() spk = Speaker(language='pt-br') spk.play(value=response)
StarcoderdataPython
6670433
import os import subprocess from typing import Optional, Tuple from platypush.plugins import action from platypush.plugins.camera import CameraPlugin, Camera class CameraIrMlx90640Plugin(CameraPlugin): """ Plugin to interact with a `ML90640 <https://shop.pimoroni.com/products/mlx90640-thermal-camera-breakout...
StarcoderdataPython
9779578
<gh_stars>0 # $Id$ # # Copyright (C) 2002-2006 <NAME> and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ utility funct...
StarcoderdataPython
9655036
from quasimodo.parameters_reader import ParametersReader from quasimodo.assertion_validation.sentence_comparator import SentenceComparator parameters_reader = ParametersReader() WHAT_QUESTION_FILE = parameters_reader.get_parameter("what-questions-file") or "" class WhatQuestionsComparatorSubmodule(SentenceComparator...
StarcoderdataPython
6535348
<reponame>misonuma/tsntm import os import re import random import argparse import _pickle as cPickle from collections import OrderedDict, defaultdict, Counter import numpy as np import pandas as pd from data_structure import Instance random.seed(1234) def get_df(path_data): data_dict = {} docs = np.load(path...
StarcoderdataPython
4892363
<gh_stars>0 '''Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.''' def escreva(msg): tamanho = len(msg) + 4 print('~' * tamanho) print(f' {msg}') print('~' * tamanho) escreva('Curso de Python no Youtube'...
StarcoderdataPython
4975163
<reponame>getsentry/zeus import sentry_sdk from datetime import timedelta from flask import current_app from zeus import auth from zeus.artifacts import manager as default_manager from zeus.config import celery, db from zeus.constants import Result from zeus.models import Artifact, Build, Job, Status from zeus.utils ...
StarcoderdataPython
99254
m: int; n: int; j: int; i: int m = int(input("Quantas linhas vai ter cada matriz? ")) n = int(input("Quantas colunas vai ter cada matriz? ")) A: [[int]] = [[0 for x in range(n)] for x in range(m)] B: [[int]] = [[0 for x in range(n)] for x in range(m)] C: [[int]] = [[0 for x in range(n)] for x in range(m)] print("Dig...
StarcoderdataPython
6503731
import argparse import csv import os from pydub import AudioSegment from parse_textgrid import remove_empty_lines, TextGrid from pydub.utils import which AudioSegment.converter = which("ffmpeg") # FIXME the segments overwrite each other - add a file specific prefix # FIXME create a new csv file then append all segmen...
StarcoderdataPython
1788137
from .split import * import argparse import sys if __name__=="__main__": ap = argparse.ArgumentParser() ap.add_argument("-r", "--ratio",nargs='*',type=float, help="The ratio to split. e.g. for train/val/test `.8 .1 .1` or for train/val `.8 .2`. Default is `.8 .1 .1`, just pass `-r` for default.") ap.ad...
StarcoderdataPython
11361286
<filename>src/driver/esc.py # coding:utf-8 # import RPi.GPIO as GPIO print 'hello,esc'
StarcoderdataPython
6567876
# -*- coding: utf-8 -*- from bottoku import Renderer class MutableListRenderer(Renderer): """Renderer which appends to list to render""" api = 'mutable_list' def __init__(self, mutable_list): super(MutableListRenderer, self).__init__() self.mutable_list = mutable_list def render(se...
StarcoderdataPython
1692359
<gh_stars>10-100 # -*- coding: utf8 -*- """ The main idea of this module, that you can combine any number of any filters without any knowledge about their implementation. You have only one requirement — user functions should return a filter (or something that can be cast to a filter). """ from __futur...
StarcoderdataPython
394244
from pyccel.decorators import types from pyccel.decorators import pure from pyccel.decorators import external_call #============================================================================== @pure @types('double[:]','double[:]','double[:]') def cross(a, b, r): r[0] = a[1]*b[2] - a[2]*b[1] r[1] = a[2]*b[0] ...
StarcoderdataPython