id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5183179 | <reponame>chidanandpujar/python_pyez_scripts
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
dev = Device(host='xx.xx.xx.xx', user='xyz', password='<PASSWORD>', gather_facts=False)
dev.open()
dev.timeout=300
with Config(dev, mode='ephemeral', ephemeral_instance='test1') as cu:
try:
... | StarcoderdataPython |
3321854 | <reponame>ChrisTimperley/roswire
# -*- coding: utf-8 -*-
__all__ = ("ROS2LaunchManager",)
import os
import shlex
import typing
from typing import Collection, List, Mapping, Optional, Sequence, Tuple, Union
import attr
from loguru import logger
from .reader import ROS2LaunchFileReader
from ... import exceptions as ex... | StarcoderdataPython |
6590878 |
db = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '',
'db': 'testdb'
}
| StarcoderdataPython |
1912902 | #!/usr/bin/env python
import glob
import os
import subprocess
import sys
from distutils.command.build_ext import build_ext
from setuptools import setup, find_packages, Extension
# top level bindings directory
BINDINGS_DIR = os.path.dirname(os.path.abspath(__file__))
# top level repo directory
TOPDIR = os.path.dirnam... | StarcoderdataPython |
1934033 | <filename>dipferromagtheory/reso.py
"""
"""
### IMPORTS
import numpy as np
import json
from dipferromagtheory import resdir
def sigma_lambda(q, q_mean, dlam):
"""
Standard deviation of the wavelength distribution in q space
Parameters
----------
q : float
momentum/q transfer va... | StarcoderdataPython |
11333551 | import math
import numpy as np
from digital_image_processing.algorithms.edge_detection_algorithms.threshold.threshold_based_edge_detection import (
fbc_threshold,
)
from digital_image_processing.tools.logger_base import log as log_message
def forward_difference(img_to_forward: np.ndarray) -> np.ndarray:
"""R... | StarcoderdataPython |
8152320 | #!/usr/bin/env python3
import os, json
import requests
from datetime import datetime
from flask import Flask, jsonify, request, url_for, make_response, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db_path = os.path.join(os.path.dirname(__file__), 'app.db')
db_uri = 'sqlite... | StarcoderdataPython |
1674749 | # -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... | StarcoderdataPython |
4859535 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class FileObject(object):
"""Abstract class for a generic file."""
__metaclass__ = ABCMeta
@abstractmethod
def close(self):
# type: () -> None
"""
Close the file.
... | StarcoderdataPython |
12847151 | <gh_stars>1-10
import time
import json
import sys
from pathlib import Path
from pprint import pprint
import wikidata_utils
from graphviz import Digraph
NL = "\n"
def find_subclasses_between(subclass, superclass):
# Query Stardog for subclasses
subclassesJSON = wikidata_utils.query_subclasses_stardog(supercl... | StarcoderdataPython |
5194768 | <filename>applaud/endpoints/app_preview_sets.py
from __future__ import annotations
from .base import Endpoint, IDEndpoint, SortOrder, endpoint
from ..fields import *
from typing import Union
from ..schemas.models import *
from ..schemas.responses import *
from ..schemas.requests import *
from ..schemas.enums import *
... | StarcoderdataPython |
11298377 | import cv2
import numpy as np
from sklearn.cluster import KMeans
from skimage.feature import greycomatrix, greycoprops
from skimage import data
histsogram_centers_file_name = 'HistogramCenters.npy'
n_indexed_colors=256
n_color_histogram_categories=64
dct2_size = 100
GLCM_resize_size = 200
GLCM_step = 20
# speed-up op... | StarcoderdataPython |
1680954 | #!/usr/bin/python
# Copyright (C) 2014-2020 Free Software Foundation, Inc.
# This file is part of the GNU C Library.
#
# The GNU C Library 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 Software Foundation; either
# versio... | StarcoderdataPython |
5156341 | """This module is for thread start."""
import state
from bitmessagemain import main
if __name__ == '__main__':
state.kivy = True
print("Kivy Loading......")
main()
| StarcoderdataPython |
3417539 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
import datetime
from datetime import timezone
import time
import json
import unittest
import os
from tests.common import async_test, TestHelper
from tests.adls_te... | StarcoderdataPython |
1601517 | import json
import random
import string
from paypal_client import PayPalClient
from paypalpayoutssdk.payouts import PayoutsPostRequest
from paypalhttp.serializers.json_serializer import Json
class CreatePayouts(PayPalClient):
""" Creates a payout batch with 5 payout items
Calls the create batch api (POST - /v... | StarcoderdataPython |
3481921 | <filename>vrd/dbhandler.py
import hashlib
import io
import sqlite3
from multiprocessing import Pool
import numpy as np
from tqdm import tqdm
from .image_preprocessing import process_image
class VRDDatabase:
"""A database containing the extracted fingerprints of a specific frame.
The database is based on sq... | StarcoderdataPython |
9613997 | import pytz
import datetime
def convert_utc_to_cst(utc_datetime: datetime.datetime) -> datetime.datetime:
return utc_datetime.replace(tzinfo=pytz.utc).astimezone(
pytz.timezone("Asia/Shanghai")
)
| StarcoderdataPython |
1741139 | <filename>core/connection/connection.py<gh_stars>0
import socket
import os
import tempfile
import glob
import json
import string
import zipfile
HEADER_SIZE = 10
CHUNK_SIZE = 4 * 1024
END_DELIMETER = "*END_OF_FILE*"
COMMAND_DELIMETER = "<END_OF_COMMAND>"
def zip_it(to_download):
# ziph is zipfile handle
i... | StarcoderdataPython |
3402343 | <reponame>jfthuong/pydpf-core
"""
to_elemental_fc
===============
Autogenerated DPF operator classes.
"""
from warnings import warn
from ansys.dpf.core.dpf_operator import Operator
from ansys.dpf.core.inputs import Input, _Inputs
from ansys.dpf.core.outputs import Output, _Outputs
from ansys.dpf.core.operators.specific... | StarcoderdataPython |
54284 | import string
from rt import *
from listener import Listener
import traceback
import pytz
from datetime import datetime
class Ticket:
def __init__(self, client):
self.client = client
Listener.register(self.on_ready, "on_ready")
Listener.register(self.on_message, "on_message")
Liste... | StarcoderdataPython |
5059974 | <gh_stars>1-10
import keras
import util
from datetime import datetime
def train(args, preprocess_manager):
util.llprint("Loading Data starts... \n")
X, y, sequence_max_length, num_features_all, num_features_activities = preprocess_manager.create_and_encode_training_set(
args)
util.llprint("Loading... | StarcoderdataPython |
4823118 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Component: YLPF
# Package : battm
# Name : UKF
# Author : NBIC
# License : BSD 2-Clause
# -------------------------------------------------------------------
#
# Copyright (C) 2019 NEC Brain Inspired Computing
# Research Alliance Laboratories
# ... | StarcoderdataPython |
252802 | # Using the root title function to change the title
# of the GUI
#? importing the tkinter files
from tkinter import *
#initialising the root window
root = Tk()
#using the title function to change the title
root.title("Simple Title ")
#A simple label
myLabel1 = Label(root, text="This the lable of the GUI")
myLabel1... | StarcoderdataPython |
133329 | <filename>week3/exercises/how-many.py<gh_stars>0
'''
write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary
'''
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
... | StarcoderdataPython |
8071905 | # -*- coding: utf-8 -*-
"""JSON-L parser plugin related functions and classes for testing."""
import json
from dfvfs.helpers import text_file
from plaso.storage.fake import writer as fake_writer
from tests.parsers import test_lib
class JSONLPluginTestCase(test_lib.ParserTestCase):
"""JSON-L parser plugin test c... | StarcoderdataPython |
1603342 | <reponame>mfkiwl/OpenCGRA-1<filename>fu/single/test/PhiRTL_test.py
"""
==========================================================================
PhiRTL_test.py
==========================================================================
Test cases for functional unit Phi.
Author : <NAME>
Date : November 27, 2019
"""... | StarcoderdataPython |
11339956 | <gh_stars>1-10
'''
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
'''
ip = input('Enter a sentence fow which u... | StarcoderdataPython |
11370620 | <gh_stars>1-10
import cx_Freeze
executables = [cx_Freeze.Executable("./src/RexRun.py")]
cx_Freeze.setup(
name="T-Rex Run",
options = {
"build_exe": {
"packages":["pygame"],
"include_files":[
"./src/ObstacleClass.py",
"./src/PlayerClass.py",
"./src/se... | StarcoderdataPython |
4995937 | # Copyright 2021 The WAX-ML 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | StarcoderdataPython |
40642 | <gh_stars>1-10
#!/usr/bin/python
import sys
import re
# Test application to check whether EMR pipeline and reading the data works
# This code is from the EMR example:
# https://s3.amazonaws.com/elasticmapreduce/samples/wordcount/wordSplitter.py
def main(argv):
pattern = re.compile("[a-zA-Z][a-zA-Z0-9]*")
for ... | StarcoderdataPython |
3356320 | <reponame>pchtsp/combiLima<filename>app/db.py
import json
import app.aux as aux
def search_company(company_id):
companies = get_companies()
company_name = [c[1] for c in companies if company_id == c[0]]
if len(company_name) > 0:
return company_name[0]
return ""
def get_companies():
with o... | StarcoderdataPython |
5054164 | n1 = int(input('\033[1;45mDigite um número: '))
n2 = int(input('\033[1;42mDigite outro número: '))
soma = n1 + n2
print('A soma de {} e {} é igual a {}'.format(n1, n2, soma)) | StarcoderdataPython |
1948759 | <gh_stars>1-10
# Create a camera at the pyvista module level.
#
import pyvista
camera = pyvista.Camera()
#
# Access the active camera of a plotter and get the position of the
# camera.
#
pl = pyvista.Plotter()
pl.camera.position
# Expected:
## (1.0, 1.0, 1.0)
| StarcoderdataPython |
1905775 | <reponame>RKalaj/moviebase
from flask_script import Manager
from moviebase import app, db, Director, Movie
manager = Manager(app)
@manager.command
def deploy():
db.drop_all()
db.create_all()
nolan = Director(name='<NAME>', about='<NAME> is an English film director, screenwriter, and producer who holds bo... | StarcoderdataPython |
5118103 | <reponame>startakovsky/docarray<gh_stars>100-1000
from .document import DocumentArray
from .storage.elastic import StorageMixins, ElasticConfig
__all__ = ['DocumentArrayElastic', 'ElasticConfig']
class DocumentArrayElastic(StorageMixins, DocumentArray):
"""This is a :class:`DocumentArray` that uses Elasticsearch... | StarcoderdataPython |
3499246 | import numpy as np
from torch import nn
from torch.nn.init import xavier_uniform_
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size()[0], -1)
class Reshape(nn.Module):
def __init__(self, *shape):
super(Reshape, self).__init__()
se... | StarcoderdataPython |
6646333 | <filename>pgen/gen_animation.py<gh_stars>0
import argparse
import pickle
import gym
from pgen import MLP
import pybullet
import pybullet_envs
import numpy as np
import skimage
import skimage.io
import matplotlib.pyplot as plt
def gen_animation(env_name, generator_file, latent_steps=10, save_figs=False,\
rend... | StarcoderdataPython |
115057 | """
Usefull tools for plotting with matplotlib
"""
| StarcoderdataPython |
4967549 | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 by appl... | StarcoderdataPython |
1821947 | #This has some success although not 100%
# import the necessary packages
import numpy as np
import argparse
import imutils
import glob
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--template", default="./test-images/logos/titleist.... | StarcoderdataPython |
67791 | <reponame>tf-encrypted/big-tensors
from typing import Optional
import numpy as np
import tensorflow as tf
from tensorflow.python.client import session as tf_session
from tensorflow.python.framework import ops as tf_ops
from tensorflow.python.keras.utils import tf_utils
import tf_big.python.ops.big_ops as ops
class ... | StarcoderdataPython |
1643881 | from setuptools import setup, find_packages
with open('README.md') as fp:
long_description = fp.read()
setup(
name='typeform',
version='1.1.0',
description='Python Client wrapper for Typeform API',
long_description=long_description,
long_description_content_type='text/markdown',
keywords=[... | StarcoderdataPython |
3300402 | from .base import Property
from .decorators import function_as_method, method_as_function
| StarcoderdataPython |
3473741 | <reponame>dohmatob/pytorch-playground
import argparse
import os
import time
from utee import misc
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import dataset
import model
from IPython import embed
parser = argparse.ArgumentParser(description='PyTorch C... | StarcoderdataPython |
213364 | <reponame>AlbertiPot/unnas<filename>pycls/models/nas/operations.py<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""NAS ops (adopted from DARTS)."""
im... | StarcoderdataPython |
3401128 | <gh_stars>1-10
# pytest --html=tests/report/test-report.html
# above command runs tests and test reports generates in tests/report location.
# nosetests --with-coverage --cover-html
# clean all the .pyc files
# find . -name \*.pyc -delete
# nosetests --with-coverage --cover-html
# pytest --cov=contentstack
# pytest -v... | StarcoderdataPython |
11317877 | <gh_stars>1-10
import abc
import os
from typing import List, Tuple
from bopt.basic_types import Hyperparameter
from bopt.hyperparam_values import HyperparamValues
from bopt.sample import SampleCollection
from bopt.models.parameters import ModelParameters
class Model(abc.ABC):
# @abc.abstractmethod
# def pred... | StarcoderdataPython |
287955 | <reponame>hkamran80/youtubedl-web
# youtube-dl Web Interface -- Threaded
from flask import Flask, render_template, redirect, request, url_for
import threading
import json
import os
app = Flask(__name__)
file = json.loads(open("web.json").read())
class dwnl(threading.Thread):
def __init__(self, dwnl_url, dwnl_type):... | StarcoderdataPython |
3275252 | # This Function formating the data to plot in Line Chart ...
def get_LineChartData(date_time,actualPower):
lineChartData = []
for i,j in zip(date_time,actualPower):
lineChartData.append(list((i,j)))
return lineChartData
# This Function formating the data to plot in Bar Chart ...
def get_BarChart... | StarcoderdataPython |
243475 | <reponame>iphilpot/DoE_Bloom_Filter
#!/usr/bin/env python
from model.bloom_filter import BloomFilter
from model.users import PresentUsers, AbsentUsers
import matplotlib.pyplot as plt
import numpy as np
import math
# This is the last experiment, a 2 factorial designed experiment. The goal is to understand
# the main... | StarcoderdataPython |
5017046 | <reponame>eltld/ezEngine<gh_stars>0
from DBAccess import DBAccess
import pysvn
import requests
from flask import Flask, json
class DBWriter:
"""Class that encapsulates the conversion of json build results into database records.
Also handles the retrival of revision information from the SVN server (commits mess... | StarcoderdataPython |
3396424 | <reponame>StichtingIAPC/swipe
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-29 18:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('sales', '... | StarcoderdataPython |
9774585 | from squeezeSeg import SqueezeSeg
| StarcoderdataPython |
9753326 | # example of training a final classification model
from sklearn.linear_model import LogisticRegression
from sklearn.datasets.samples_generator import make_blobs
# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
# fit final model
model = LogisticRegressi... | StarcoderdataPython |
11306287 | <reponame>rubasov/opensub-utils<gh_stars>1-10
import errno
import os
import sys
import tempfile
import unittest
from os.path import join
# Make it possible to run out of the working copy.
sys.path.insert(
0,
os.path.join(
os.path.dirname(__file__),
os.pardir,
"lib",
))
import ... | StarcoderdataPython |
8120467 | <gh_stars>100-1000
import multiprocessing
import os
import queue
import signal
import threading
import time
from rohmu import get_transfer
from rohmu.rohmufile import create_sink_pipeline
from pghoard.common import get_object_storage_config
from pghoard.config import key_lookup_for_site
class FileFetchManager:
... | StarcoderdataPython |
4977405 | import geonomics as gnx
import numpy as np
# FLAG DETERMINING WHETHER TO TEST TRAIT MUTATION OR DELETERIOUS MUTATION
mutate_trait = False
mod = gnx.make_model('./GNX_default_model_params.py')
mod.walk(10000, 'burn')
mod.walk(1)
spp = mod.comm[0]
ga = spp.gen_arch
re = ga.recombinations
trt = ga.traits[0]
off = [i.... | StarcoderdataPython |
4809894 | <reponame>suomesta/ken3
# -*- coding: utf-8 -*-
"""errortest does tests of an intended compile error.
run compiler with test code, which causes compile error.
"""
import glob
import os
import subprocess
import sys
__author__ = 'toda'
__version__ = '1.0.0'
# compile command
COMMAND = 'g++'
# options of compile comma... | StarcoderdataPython |
1716012 | <filename>flaskmovie/config.py
import os
# 用于连接数据的数据库。
# SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:ty158917@192.168.3.11:3306/movie"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:zw123456@127.0.0.1:3306/movie"
# 如果设置成 True (默认情况),Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
SQLALCHEMY_TRACK_MODIFICATIONS = True
REDIS_URL ... | StarcoderdataPython |
362131 | <filename>heimdall/models/__init__.py
"""Models package."""
from flask import Blueprint
from heimdall import db
bp = Blueprint("database", __name__)
@bp.after_app_request
def commit_session(response):
"""After each successful request commit the current database session."""
if response.status_code < 400:
... | StarcoderdataPython |
9671240 | <filename>pymir/Spectrum.py<gh_stars>100-1000
"""
Spectrum class
ndarray subclass for spectral data
Last updated: 17 December 2012
"""
from __future__ import division
import math
import numpy
from numpy import *
import scipy.stats
import scipy.stats.mstats
import matplotlib.pyplot as plt
import pymir
from pymir im... | StarcoderdataPython |
338786 | <reponame>hoostus/beancount-price-sources<filename>hoostus_sources/openexchange.py
"""Fetch prices from Morningstar's JSON 'api'
"""
import datetime
import logging
import re
import json
from urllib import parse
from urllib import error
from beancount.core.number import D
from beancount.prices import source
from beanc... | StarcoderdataPython |
6491689 | wallBlocks = {};
stairBlocks = {};
doorBlocks = {};
supportBlocks ={}
fenceBlocks = {}
slabBlocks = {}
def init():
#Tree
wallBlocks[17] = {};
wallBlocks[17][0] = [5,0]
wallBlocks[17][1] = [5,1]
wallBlocks[17][2] = [5,2]
wallBlocks[17][3] = [5,3]
wallBlocks[162] = {};
wa... | StarcoderdataPython |
11218135 | <gh_stars>0
import random
def main():
n=[random.randint(0,25)%25 for _ in range(5) ]
print('numbers ',n)
target=5;
hasmap={} #initial hasmap
for i in n:
if target-i in hasmap.keys():
return i,hasmap[target-i]
else:
hasmap[i]=i
return -1,-1
if __... | StarcoderdataPython |
8171174 | import logging
from .base import LitecordObject
from ..utils import dt_to_json
log = logging.getLogger(__name__)
class User(LitecordObject):
"""A general user object.
Parameters
----------
server: :class:`LitecordServer`
Server instance
raw: dict
Raw user data.
Attributes
... | StarcoderdataPython |
3467062 | <reponame>sfindeisen/skryba
#!/usr/bin/python3
import unittest
from collection import DictionaryCollection, ListCollection
class TestListCollection(unittest.TestCase):
def test_empty(self):
u = ListCollection(None, [])
self.assertEqual(u.all(), [])
def test_singleton(self):
u = List... | StarcoderdataPython |
25623 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | StarcoderdataPython |
6431204 | <reponame>fraunhoferfokus/WMAS<gh_stars>1-10
from __future__ import absolute_import
from ..data.session import Session, UNKNOWN
def deserialize_sessions(session_dicts):
sessions = []
for session_dict in session_dicts:
session = deserialize_session(session_dict)
sessions.append(session)
ret... | StarcoderdataPython |
8009412 | <filename>lstm_model.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, layer_size, output_size, dropout):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
... | StarcoderdataPython |
1847570 | import getpass
class IO:
"""Input/Output related utilities.
"""
@staticmethod
def input_secret(msg):
"""Prompt the user for an input using a given message. The input will
not be visible on the terminal.
Args:
msg: The message to display to the user prompting for an... | StarcoderdataPython |
5122491 | <reponame>xenein/froide<filename>froide/comments/__init__.py
def get_model():
from .models import FroideComment
return FroideComment
def get_form():
from .forms import CommentForm
return CommentForm
| StarcoderdataPython |
4849269 | <gh_stars>1-10
# -*- coding: UTF-8 -*-
# Copyright 2011-2016 <NAME>
# License: BSD (see file COPYING for details)
"""This module contains mainly a utility function :func:`html2odf`
which converts an ElementTree object generated using
:mod:`etgen.html` to a fragment of ODF.
.. This is part of the Lino test suite. To t... | StarcoderdataPython |
3453555 | <filename>wifi.py<gh_stars>0
import subprocess
import re
from colorama import init
from colorama import Fore, Style
init()
print(f"{Fore.RED}" +
"""
@@@@@@@ @@@@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@
@gam3@@@ @@fac3@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@... | StarcoderdataPython |
4946009 | # Problema 5 Project Euler. Mínim comú múltiple dels números de l'1 al 20
l = range(1, 21)
# Càlcul del mínim comú múltiple dels dos primers membres
num1 = l[0]
num2 = l[1]
if num1 > num2:
num = num1
den = num2
else:
num = num2
den = num1
rem = num % den
while rem != 0:
num = den
den = rem
... | StarcoderdataPython |
11300055 | <gh_stars>1-10
from precise_bbcode.bbcode import get_parser
from .models import Comment
def convert_all_comments():
parser = get_parser()
for comment in Comment.objects.exclude(text__exact=''):
comment.html_text = parser.render(comment.text)
comment.save() | StarcoderdataPython |
64551 | """The Applicants object is a container of Applicant objects."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable
if TYPE_CHECKING:
from .applicant_factory import ApplicantFactory
from .applicant_abc import Applicant
class ApplicantCollection(Iterable):
def __init__(self, app... | StarcoderdataPython |
8005899 | from ast_monitor.gps_sensor import GpsSensor
# Where to store data.
path = 'sensor_data/gps.txt'
gps = GpsSensor(gps_path=path)
gps.get_gps_data()
| StarcoderdataPython |
388009 | <reponame>ProhardONE/python_primer
# Exercise 9.1
# Author: <NAME>
class Line:
def __init__(self, c0, c1):
self.c0 = c0
self.c1 = c1
def __call__(self, x):
return self.c0 + self.c1 * x
def table(self, L, R, n):
"""Return a table with n points for L <= x <= R."""
... | StarcoderdataPython |
6568226 | #!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the ab... | StarcoderdataPython |
3546626 | from __future__ import print_function
import scipy
class ElectrodeModuleMaker(object):
def __init__(self,param):
self.param = param
self.template_lines = []
self.module_lines = []
def run(self):
self.load_template()
self.module_lines = list(self.template_lines)
... | StarcoderdataPython |
4989585 | def resolve_multiple_matches(matches):
max_index = len(matches) - 1
print(f"Multiple matches found, enter index of desired result (0 to {max_index}):")
print("\n".join(f"\t{i}: {v}" for i, v in enumerate(matches)))
while True:
index = input("")
if index.isnumeric() and 0 <= int(index)... | StarcoderdataPython |
3254913 | <gh_stars>1-10
def convert_statcan_xml_to_csv(infile, outfile):
import os
if os.path.isdir(infile):
data_dir = infile
else:
import tempfile
import zipfile
data_dir = tempfile.gettempdir() + "/data"
zip_ref = zipfile.ZipFile(infile, 'r')
zip_ref.extractall(data... | StarcoderdataPython |
3451788 | <reponame>suddrey-qut/armer
"""
Armer Class
.. codeauthor:: <NAME>
"""
from __future__ import annotations
from typing import List, Dict, Any, Tuple
import timeit
import importlib
import rospy
import tf2_ros
import yaml
import roboticstoolbox as rtb
from roboticstoolbox.backends.swift import Swift
from spatialmath.... | StarcoderdataPython |
1778281 | import numpy as np
#######################################
#######################################
ROOT_PATH = '/home/akeaveny/git/DenseFusion/'
# /home/akeaveny/git/DenseFusion/datasets/ycb_aff/
CLASSES_FILE = ROOT_PATH + 'datasets/ycb_aff/dataset_config/classes.txt'
CLASS_IDS_FILE = ROOT_PATH + 'datasets/ycb_aff... | StarcoderdataPython |
59459 | __import__('eigenpy').switchToNumpyArray()
| StarcoderdataPython |
11281688 | from virtualbox import library
from virtualbox.library_ext.progress import IProgress
class IHost(library.IHost):
__doc__ = library.IHost.__doc__
# Work around a bug where createHostOnlyNetworkInterface returns
# host_interface and progress in the wrong order
def create_host_only_network_interface(sel... | StarcoderdataPython |
11307566 | import os
import api_tmdb
import api_jellyfin
'''
tmdb -> jellyfin legend:
TV
id ProviderIds.Tmdb
name Name
release_date ProductionYear
media_type Type
Movies
id ProviderIds.Tmdb
title Name
... | StarcoderdataPython |
9633441 | from .settings import *
# Database
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "food_image",
"USER": "food_image",
"PASSWORD": "<PASSWORD>",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}
# settings
DEBUG = True
ALLOWED_HOSTS = ["*"]
... | StarcoderdataPython |
363856 | <gh_stars>10-100
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
from IPython.display import HTML
def data_point_creator(x_bound, y_bound, func, prec=.1):
x = np.arange(-5.12, 5.12, prec)
y = np.arange(-5.12, ... | StarcoderdataPython |
357493 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
from datawarehouse import load_higgs
def load_data():
data = load_higgs() # Load the full dataset and return it as a pandas.DataFrame
data = handle_missing_... | StarcoderdataPython |
20255 | import re
import pathlib
from clldutils.text import strip_chars
from cldfbench import Dataset as BaseDataset
from cldfbench import CLDFSpec
QUOTES = '“”'
class Dataset(BaseDataset):
dir = pathlib.Path(__file__).parent
id = "lapollaqiang"
def cldf_specs(self): # A dataset must declare all CLDF sets it ... | StarcoderdataPython |
11395553 | <filename>cooperhewitt/api/multiclient/__init__.py
# https://pythonhosted.org/setuptools/setuptools.html#namespace-packages
__import__('pkg_resources').declare_namespace(__name__)
import cooperhewitt.api.client
import grequests
class OAuth2(cooperhewitt.api.client.OAuth2):
def execute_methods(self, multi, size=1... | StarcoderdataPython |
5023331 | <gh_stars>1-10
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class ArrayLengthNode(Node, ArmLogicTreeNode):
'''Array length node'''
bl_idname = 'LNArrayLengthNode'
bl_label = 'Array Length'
bl_icon = 'GAME'
def init(self, context):
... | StarcoderdataPython |
1736488 | import gym
from gym import spaces
from gym.utils import seeding
def cmp(a, b):
return int((a > b)) - int((a < b))
# 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def draw_card(np_random):
return np_random.choice(deck)
def draw_hand(np_random):
re... | StarcoderdataPython |
3228255 | <filename>ping-command.py
@bot.command() #Ping command
async def ping(ctx):
await ctx.send(f"Pong 🏓")
| StarcoderdataPython |
3436665 | import argparse
import logging
import structlog
from dcicutils.es_utils import create_es_client
from dcicutils.ff_utils import get_health_page
log = structlog.getLogger(__name__)
EPILOG = __doc__
def main():
"""
Simple command to adjust settings on the Kibana index in ES, so that
searches against all ind... | StarcoderdataPython |
4947991 | # -*- coding: utf-8 -*-
from typing import Optional, Union
import pandas as pd
import typic
from standard_precip.spi import SPI
from tstoolbox import tsutils
def _nlarge_nsmall(pe_data, nlargest, nsmallest, groupby):
if nlargest is None and nsmallest is None:
return pe_data
nlarge = pd.Series()
... | StarcoderdataPython |
181906 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 17:38:58 2019
"""
from PyQt5.QtWidgets import (QPushButton, QDialog, QDialogButtonBox,
QLineEdit, QFormLayout, QMessageBox,
QFileDialog, QLabel)
import os
class FileBrowser(QDialog):
def __... | StarcoderdataPython |
8182920 | # ActivitySim
# See full license in LICENSE.txt.
from builtins import range
from builtins import object
import logging
import numpy as np
import pandas as pd
from activitysim.core.util import quick_loc_series
logger = logging.getLogger(__name__)
NOT_IN_SKIM_ZONE_ID = -1
NOT_IN_SKIM_NAN = np.nan
ROW_MAJOR_LAYOUT ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.