id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3275549 | import pandas as pd
# return dictionary of distribution of array's elements
def get_distribution(iterable):
iterable = pd.Series(iterable)
counts_dict = iterable.value_counts().to_dict()
percent_list = []
for count in list(counts_dict.values()):
percent = (count/len(iterable))*100
pe... | StarcoderdataPython |
3397303 | from foo import Bar, MoveOnlyFoo, UMapStringCopyableMember as UMSCM
import foo
def test_copyable():
copybar = Bar(UMSCM({"foo": 42, "bar": -1}))
assert dict(copybar.m_map) == {"foo": 42, "bar": -1}
copybar.m_map["foo"] = -1
copybar.m_map["baz"] = 1337
assert dict(copybar.m_map) == {"foo": -1, "bar"... | StarcoderdataPython |
3273185 | <reponame>pylhc/submitter<filename>pylhc_submitter/autosix.py
"""
AutoSix
-------
``AutoSix`` is a wrapper to automatically perform the necessary setup and steps needed for ``SixDesk`` use.
The functionality is similar to the ``pylhc_submitter.job_submitter`` in that the inner product of a ``replace_dict`` is u... | StarcoderdataPython |
3395710 | # coding: utf-8
# This file is imported from __init__.py and exec'd from setup.py
__version__ = "1.0.0"
| StarcoderdataPython |
198119 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Psi4(CMakePackage):
"""Psi4 is an open-source suite of ab initio quantum chemis... | StarcoderdataPython |
1615176 | <reponame>betonr/cube-builder
#
# This file is part of Python Module for Cube Builder.
# Copyright (C) 2019-2020 INPE.
#
# Cube Builder is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Define Brazil Data Cube main package executor.... | StarcoderdataPython |
3232790 | <gh_stars>1-10
import pytest
from worker_images import logger, config
def load_conf():
"""
Load configuration from config file
:return:
"""
conf = config.load_config("tests/config/config_tests.ini")
return conf
@pytest.mark.parametrize("log_level", [
load_conf().get('LOGGING', 'level'),... | StarcoderdataPython |
3354624 | <gh_stars>0
"""Functions for plotting."""
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
import numpy as np
from matplotlib import axes, figure
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from htma_py.htma_plots.plot_helpers import (
make_axis_pretty,
make_lege... | StarcoderdataPython |
1721184 | <reponame>SebastianSeltmann/yeoboseyo
# coding: utf-8
"""
여보세요 Run
"""
# std lib
from __future__ import unicode_literals
# starlette
from starlette.config import Config
from logging import getLogger
from mastodon import Mastodon
# create logger
logger = getLogger('yeoboseyo.yeoboseyo')
config = Config('.env')
fr... | StarcoderdataPython |
23329 | <gh_stars>1-10
import unittest
from ape.load_bin_log import LoadBinLog
class LoadBinTestCase(unittest.TestCase):
def test_LoadBinLogAll(self):
data = LoadBinLog("../tests/log_0_2020-5-1-14-53-42.bin")
self.assertGreater(len(data), 0, "no data")
def test_LoadBinLogString(self):
data =... | StarcoderdataPython |
3288669 | <gh_stars>0
# -*- encoding: utf-8 -*-
from celery import Celery
from django.conf import settings
# Working through:
# http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django
app = Celery('example_checkout')
# Config in one of three ways:
# 1) settings on the app
# app.co... | StarcoderdataPython |
1672539 | <filename>src/crypto/crypto_sample.py
from fastquant import get_crypto_data, backtest
from src.utils.strategies import *
ticker = "ETH/USDT"
cashToTrade = 10000
stock_data = get_crypto_data(ticker,
"2021-12-01",
"2022-03-07",
time_resol... | StarcoderdataPython |
1644028 | #!/usr/bin/env python
# coding: utf-8
# Author: <NAME> <<EMAIL>>
from tempfile import NamedTemporaryFile
from lxml import etree
from rstconverter.tree import debug_root_label, DGParentedTree, t
import rstconverter as rstc
EXPECTED_SVG_TREE = """<?xml version="1.0" encoding="utf-8" ?>
<svg baseProfile="full" height... | StarcoderdataPython |
22361 | <gh_stars>0
class ScreenLogger:
def __init__(self, loghandler=None, verbose = True):
self.LogMessage = None
self.LogHandler = loghandler
self.Verbose = verbose
return
def Log(self, message):
if self.LogMessage != message:
self.LogMessage = message
... | StarcoderdataPython |
3284974 | from pathlib import Path
from glue.app.qt.application import GlueApplication
from glue.core import Data, DataCollection
from glue.core.data_factories import load_data
from glue.plugins.wcs_autolinking.wcs_autolinking import wcs_autolink
from glue_solar.instruments.iris import _parse_iris_raster
from irispy.spectrograp... | StarcoderdataPython |
3365838 | """Monte Carlo Tree Search for stochastic environments."""
import asyncio
import random
import gin
import gym_open_ai
from alpaca.alpacka import data
from alpaca.alpacka.agents import base
from alpaca.alpacka.agents import core
@gin.configurable
def rate_new_leaves_with_rollouts(
leaf,
observation,
mod... | StarcoderdataPython |
3297124 | <gh_stars>0
# -*- coding: utf-8 -*-
import psycopg2
from openapi.config.config import NirvanaConfig
class Postgres(object):
def __init__(self):
nirvana_config = NirvanaConfig()
pg_provider, pg_host, pg_user, pg_password, pg_database = nirvana_config.postgres_config()
self.conn = psycopg2.... | StarcoderdataPython |
36742 | from Sort.Example import Example
class Merge(Example):
def __init__(self) -> None:
super().__init__()
def sort(self, a):
# create aux just once
self.aux = [None for i in range(len(a))]
self._sort(a, 0, len(a) - 1)
def _sort(self, a, lo, hi):
if lo >= hi:
... | StarcoderdataPython |
1650795 | <reponame>NeCTAR-RC/aardvark
# Copyright (c) 2018 European Organization for Nuclear Research.
# 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:... | StarcoderdataPython |
3310451 | <gh_stars>1-10
from bitcoin.core.script import *
from bitcoin.core import Hash160
import bitcoin.base58
import struct
import unittest
from hashlib import sha256
def payment_script(time_lock, secret_hash, pub_0, pub_1):
"""
this function making payment script for mm2 atomic swap
ported from mm2 rust code
... | StarcoderdataPython |
1745938 | <gh_stars>0
#!/usr/bin/env python
"""
In an earlier exercise we looked at the cities dataset and asked which region in India contains
the most cities. In this exercise, we'd like you to answer a related question regarding regions in
India. What is the average city population for a region in India? Calculate your answ... | StarcoderdataPython |
94726 | <filename>mail.py
from __future__ import print_function
import httplib2
from apiclient import discovery
from oauth2client import tools
from library.gmail import sendemail
import argparse
import os
import os
from oauth2client.file import Storage
from oauth2client import client
try:
flags = argparse.ArgumentParser(... | StarcoderdataPython |
175802 | <filename>equadratures/distributions/recurrence_utils.py<gh_stars>10-100
"""Recurrence coefficients class."""
import numpy as np
from scipy.special import erf, erfinv, gamma, beta, betainc, gammainc
def laguerre_recurrence_coefficients(a, order):
"""
Returns the Laguerre recurrence coefficients.
:param dou... | StarcoderdataPython |
3330986 | <reponame>ubsicap/dbl-metadata-as-json
from .name_like_fields import process_name_like_field
def process_identification_section(dom, json_dict):
identification_sections = dom.xpath("identification")
if len(identification_sections) > 0:
identification_section = identification_sections[0]
json_di... | StarcoderdataPython |
1728202 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio-RDM-Records is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Marshmallow utility functions."""
import pycountry
from flas... | StarcoderdataPython |
3264728 | #
# stm32_serialbuffer.py
#
import pioutil
if pioutil.is_pio_build():
Import("env")
# Get a build flag's value or None
def getBuildFlagValue(name):
for flag in build_flags:
if isinstance(flag, list) and flag[0] == name:
return flag[1]
return None
# Get an overriding buffer size for RX or TX from the b... | StarcoderdataPython |
3206814 | def unilabel(y_true, y_pred):
"""Compute relevance(s) of predicted labels.
This version of the relevance function works only for the queries
(problems) with a single groud truth label.
It is provided mainly for two reasons: there is a slight speedup (order of
seconds for the large `n_samples`) and ... | StarcoderdataPython |
154091 | <reponame>awasilyev/dd-agent
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# std
import logging
import re
# project
from utils.singleton import Singleton
log = logging.getLogger(__name__)
class AbstractSDBackend(object):
"""Singleton for service disco... | StarcoderdataPython |
195889 | <reponame>CrtomirJuren/python-delavnica
"""
Python program to remove an empty element from a list.
"""
list_in = ['Hello', 34, 45, '', 40]
# result = ['Hello', 34, 45, 40]
for item in list_in:
if not item:
list_in.remove(item)
print(list_in) | StarcoderdataPython |
52720 | import appdaemon.plugins.hass.hassapi as hass
import datetime
import pytz
import requests
import json
class SyncGTasksAndGrocy(hass.Hass):
tl_name = 'Corvées'
tl_id = None
tl_main = None
debug = False
gr_cl = None
service = None
tl_lastup = None
google_oauth_tasks = None
grocyapi = ... | StarcoderdataPython |
1774758 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 13:19:12 2020
@author: Amirh
"""
from hyperopt import hp
from hyperopt import fmin, tpe, space_eval
#%%
class ParamTuner():
def __init__(self, opt_model,
x,y,
decor=None, scale=False,
cv=None, tes... | StarcoderdataPython |
58384 | <reponame>hitachinsk/DataStructure
import Assoc as As
class DictList():
def __init__(self, elem = None):
"""
:type elem: As.Assoc
"""
if elem is None:
elem = []
for i in range(len(elem)):
if not isinstance(elem[i], As.Assoc):
... | StarcoderdataPython |
3389137 | <reponame>diegoaguilartaio/tf-ssd
import tensorflow as tf
from tensorflow.keras.layers import Layer, Input, Conv2D, MaxPool2D
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
from .header import get_head_from_outputs
class L2Normalization(Layer):
"""Normalizing different scale... | StarcoderdataPython |
1725796 | <filename>doors/inout.py
import json
import os
import pickle
import pandas as pd
def append_csv(data, path):
""" append to a csv """
assert path.endswith(".csv")
to_log = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)
if "~" in path:
print("Dont include the user path as ~!, us... | StarcoderdataPython |
3229576 | import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from linear_interpolate import linear_interpolate, k_value_linear_interpolate
# linear interpolate.py exists in the same directory and is code written for piecewise linear interpolation
# of blasisus velocity ratios and K values.
im... | StarcoderdataPython |
24370 | from flask import Blueprint, abort, request, jsonify
from prediction_utils import *
prediction_page = Blueprint('prediction_page', __name__)
@prediction_page.route('/map', methods=['GET'])
def get_map_data():
offset = int(request.args['offset'])
country = request.args['country'] if 'country' in request.args e... | StarcoderdataPython |
1794585 | <filename>soap/program/graph.py<gh_stars>10-100
import itertools
import networkx
from matplotlib import pyplot
from soap.common import base_dispatcher, cached_property, Flyweight
from soap.expression import (
InputVariable, External, InputVariableTuple, AccessExpr, UpdateExpr,
operators
)
from soap.semantics ... | StarcoderdataPython |
3206739 | <gh_stars>1-10
def fab(max):
n, a, b = 0, 0, 1
while n<max:
yield b
a, b = b, a + b
n = n + 1
print "first"
for n in fab(10):
print n
print "second"
f = fab(100)
for n in range(10):
print n, f.next()
print "third"
f0 = fab(5)
f1 = fab(10)
f = "f0"
while True:
f = "f1" if ... | StarcoderdataPython |
1643382 | from opera.parser.utils.location import Location
class Node:
def __init__(self, value, loc=None):
self.value = value
self.loc = loc or Location("", 0, 0)
def _dump_header(self):
return "{}({})".format(type(self.value).__name__, self.loc)
def _dump_map(self, pad):
children... | StarcoderdataPython |
3382262 | import datetime
import uuid
from rasa_core.channels import CollectingOutputChannel, UserMessage
from rasa_core.dispatcher import Button, Dispatcher
from rasa_core.events import (
ReminderScheduled, UserUttered, ActionExecuted,
BotUttered, Restarted)
from rasa_nlu.training_data import Message
from rasa_core.pro... | StarcoderdataPython |
3388444 | <filename>main/api.py
"""View functions for API endpoints."""
from typing import Dict, Any
from urllib.parse import unquote_plus
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from pydantic import ValidationError
from relaton.serializers.bibxml.anchor import get_suitable_anchor
from comm... | StarcoderdataPython |
3364638 | import os
srcdir = os.path.dirname(__file__) | StarcoderdataPython |
3342670 | '''LSST JupyterHub utilities and helpers.
These implement the LSST-specific tooling for the LSST Science
Platform Notebook Aspect. The repo scanner looks for Docker images in
a repository with a particular tag format; the prepuller pulls a
subset of those images to each node. The reaper removes images past a
certain... | StarcoderdataPython |
8170 | <filename>app/__init__.py
import connexion, os
from connexion.resolver import RestyResolver
from flask import json
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Globally accessible libraries
db = SQLAlchemy()
mm = Marshmallow()
def init_app():
"""Initialize the Connexion ap... | StarcoderdataPython |
1777052 | # !/usr/bin/python
# -*- coding: utf-8 -*-
"""myds - A Data Science Package (https://github.com/augustomatheuss/myds)
Module ctl from myds for central limit theorem (CLT).
Copyright 2020 <NAME>
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following c... | StarcoderdataPython |
1777027 | # -*- coding: utf-8 -*-
"""
.. wikisection:: overview
:title: (5) Seeds (exactly matching kmers)
The :mod:`biseqt.seeds` module provides tools for storing and analyzing
exactly matching kmers, aka seeds.
>>> from biseqt.seeds import SeedIndex
>>> from biseqt.sequence import Sequence, Alphabet
... | StarcoderdataPython |
1738421 | <filename>Modulo_1/semana2/Entrada_Datos/entrada_datos.py
# Demostración de entrada de datos.
nombre = input("Buen día me podía decir su nombre por favor : ")
print("Bienvenido al sistema ",nombre," Gracias por usar mi programa.", sep="'")
| StarcoderdataPython |
1717986 | <filename>tests/test_equilibrium.py
import pytest
import numpy as np
import numpy.linalg as la
import attr
from thermo import Chemical
from gibbs.mixture import Mixture
from gibbs.models.ceos import PengRobinson78, PengRobinson
from gibbs.equilibrium import calculate_equilibrium
from gibbs.minimization import PygmoSel... | StarcoderdataPython |
3386572 | # Copyright 2020 The AutoKeras 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 applicable law or agreed to i... | StarcoderdataPython |
1766887 | <filename>binding.gyp
{
"targets": [
{
"target_name": "geos",
"sources": [
"src/cpp/binding.cpp",
"src/cpp/geometry.cpp",
"src/cpp/wktreader.cpp",
"src/cpp/wkbreader.cpp",
"src/cpp/wktwriter.cpp",
"src/cpp/wkbwriter.cpp",
"src/cpp/geometryfactory... | StarcoderdataPython |
1644585 | <gh_stars>1-10
import network
import socket
import time
SSID="yourSSID"
PASSWORD="<PASSWORD>"
host="192.168.3.147"
port=100
wlan=None
s=None
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF) #create a wlan object
wlan.active(True) ... | StarcoderdataPython |
3235522 | # Copyright (c) 2018, Stellapps Technologies Private Ltd.
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import has_common
def execute(filters=None):
columns, data = get_columns(), get_data(filters)
return columns ,data ... | StarcoderdataPython |
3352210 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import genpy
import pymongo # https://api.mongodb.org/python/2.6.3/
import json
import copy
from bson import json_util
from bson.objectid import ObjectId
from datetime import *
from tms_msg_db.msg import TmsdbStamped, Tmsdb
import tms_db_manager.tms_db_util as... | StarcoderdataPython |
100510 | <filename>base_app/functional_tests/test_product_delete.py<gh_stars>0
''' functional test to delete product '''
from django.urls import reverse
from mixer.backend.django import mixer
import pytest
from .base import FunctionalTest
pytestmark = pytest.mark.django_db
class ProductDeleteTest(FunctionalTest):
""" tes... | StarcoderdataPython |
1642569 | <gh_stars>10-100
from PIL import Image, ImageDraw
import io
IMAGE_WIDTH = 60
IMAGE_HEIGHT = 24
file = open("output.h", "w")
img = Image.open('usb_small.png') #.convert('1')
#img = img.convert('L')
#img = img.resize((IMAGE_WIDTH,IMAGE_HEIGHT))
#img.save('usb_small.png')
pixelData = img.getdata()
outputArray = []
fo... | StarcoderdataPython |
1794586 | <filename>malaysiaflights/airline.py
import datetime
class Airline(object):
def __init__(self):
pass
def main(self, from_, to, date):
results = []
try:
response = self.search(from_, to, date)
data = self.preprocess(response)
number_of_results = s... | StarcoderdataPython |
137727 | <filename>tests/test_nfkb_pathway.py
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
from biomass import Model, run_simulation
from biomass.models import nfkb_pathway
model = Model(nfkb_pathway.__package__).create()
for dir in ["figure", "simulation_data"]:
if os.path.is... | StarcoderdataPython |
3327564 | #!/usr/bin/env python
# coding: utf-8
from collections import defaultdict
class RegexTable(object):
def __init__(self, l_tpl, l_regex):
assert len(l_tpl) == len(l_regex)
self._table = self._make_table(l_tpl, l_regex)
def _make_table(self, l_tpl, l_regex):
return [(tplid, reobj) for... | StarcoderdataPython |
1694232 | # MULTIPLE IMAGE SAMPLES FOR FACE_DETECTION WITH "FACE RECOGNITION MODULE" APPROACH
# Built-int imports
import os
import time
# External imports
import cv2 as cv
import numpy as np
# My own imports
import face_detect_fr as fdfr
import get_assets_folder as gaf
def process_one_image_face():
# Sample 1
image_r... | StarcoderdataPython |
4816546 | <filename>summary_maps/maps/selection_if_apply.py
import pandas as pd
base = pd.read_csv("./index_select_assign/access_data_1/census.csv")
def remean_points(row):
if row.age >=30:
return "Legal"
return "novo"
# axis = index teríamos que passar uma função para transformar cada coluna
x = base.apply(... | StarcoderdataPython |
3271809 | <filename>intensio/test/python/multiplefiles/basic/output/basicRAT/basicRAT_client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import subprocess
import struct
import sys
try:
from core.crypto import sUdzqtLgbOHLwwhpgZAqnWQnkYcohXdZ, rupicluuYAUuPXtZzzprBLFiIHrFbgdx, GZwddfwOTaBNFKKNcZkODnEKpIiNMM... | StarcoderdataPython |
3385243 | <reponame>jacruzsdev/pytax<filename>pytax/pytax.py
# -*- coding: utf-8 -*-
def calc_tax(price, tax):
full_price = (price*tax)+price
return full_price
| StarcoderdataPython |
191794 | # Language: Python 3
n = int(input())
if (n % 2 != 0):
print("Weird")
elif (2 <= n <= 5):
print("Not Weird")
elif (6 <= n <= 20):
print("Weird")
else:
print("Not Weird")
| StarcoderdataPython |
3363667 | <reponame>Lauszus/socketsocketcan
from socketsocketcan import TCPBus
import can
from datetime import datetime
from time import sleep
bus = TCPBus(5000)
print("socket connected!")
#create a listener to print all received messages
listener = can.Printer()
notifier = can.Notifier(bus,(listener,),timeout=None)
try:
... | StarcoderdataPython |
3241240 | <gh_stars>0
from django import forms
from django.forms import ModelForm
from .models import Carro, Color, Marca, Modelo, Ciudad, Provincia, Persona
class PersonaForm(ModelForm):
exclude = ('id')
import re
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import... | StarcoderdataPython |
4831556 | """Components of lexer implementations."""
'''
zlib License
(C) 2020-2021 DeltaRazero
All rights reserved.
'''
# ***************************************************************************************
from ._abst_matcher import *
from ._abst_lexer import *
from ._implementations import *
from ._profiler import ... | StarcoderdataPython |
1713103 | <reponame>RAGNAROSaa/-<gh_stars>1-10
from django.contrib import admin
from forum.models import Category, Question, Answer
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('name',)
list_display = ('name',)
class QuestionAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'category', 'invit... | StarcoderdataPython |
93785 | r"""
Check for SageMath Python modules
"""
from . import PythonModule
from .join_feature import JoinFeature
class sage__combinat(JoinFeature):
def __init__(self):
# sage.combinat will be a namespace package.
# Testing whether sage.combinat itself can be imported is meaningless.
# Hence, w... | StarcoderdataPython |
141894 | <gh_stars>1-10
import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
from QCDAnalysis.Skimming.QCDHLT1jetPE1EventContent_cff import *
QCDHLT1jetPE1OutputModule = cms.OutputModule("PoolOutputModule",
AODSIMEventContent,
#using QCDHLT1jetPE1EventContent
QCDHLT1jet... | StarcoderdataPython |
112831 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
WorkflowClientConfig = namedtuple(
'WorkflowClientConfig',
'domain task_list execution_start_to_close_timeout task_start_to_close_timeout',
)
"""An immutable object that s... | StarcoderdataPython |
64865 | <filename>tools/nntool/quantization/float32/kernels/ssd_postprocess.py
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3... | StarcoderdataPython |
1679415 | # 236. Lowest Common Ancestor of a Binary Tree
# Runtime: 72 ms, faster than 66.64% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Memory Usage: 18.2 MB, less than 90.52% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Definition for a binary tree node.
# c... | StarcoderdataPython |
1617901 | <reponame>xtommy-1/FundSystem
from abc import ABC
import scrapy
import re
import json
from copyheaders import headers_raw_to_dict
from ..items import HistoricNetValueItem, FundStockItem
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.err... | StarcoderdataPython |
78371 | <filename>nontology/live_similarity_functions.py
import numpy as np
import pandas as pd
def make_live_x_y_matrix(x_data, xcol, y_data, ycol, n_components):
x_numeric = np.array(x_data[x_data.columns[0:n_components]])
y_numeric = np.array(y_data[y_data.columns[0:n_components]])
x_y_matrix = pd.DataFrame(
... | StarcoderdataPython |
3643 | <filename>promt_tr/__main__.py
''' __main__, to run:
python -m promt_tr
'''
import sys
from random import randint
from promt_tr import promt_tr, LANG_CODES
# pragma: no cover
def main():
'''main'''
from_lang = 'auto'
to_lang = 'zh'
text = 'test ' + str(randint(0, 10000))
if not sys.argv[1:]:
... | StarcoderdataPython |
4842876 | #!/usr/bin/env python
# coding: utf-8
import click
@click.group()
def main():
pass
@main.command()
@click.option(
'--port', type=int,
default=9000, show_default=True,
help='The port number used by the server.',
)
@click.option(
'--text', type=str, required=True,
help='The input string to be... | StarcoderdataPython |
1795128 | names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
# Rewrite the for loop to use enumerate
indexed_names = []
for i,name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name[1])
print(indexed_names)
# Rewrite the above for loop using list comprehension
indexed_names_comp = [(i,na... | StarcoderdataPython |
1663997 | <gh_stars>0
from api.methods.messages import Messages
from api.utils.http import Http
class VkApi(object):
def __init__(self, access_token):
self._access_token = access_token
self._http = Http(access_token)
self._messages = Messages(self._http)
@property
def messages(self):
... | StarcoderdataPython |
4810318 | <gh_stars>0
'''
Booking.com Interview Question for Software Engineer / Developers
https://www.careercup.com/question?id=5739532692488192
Given number N, Find the least number of perfect square number sum needed to get N.
Example :
n=5 (4+1) i.e. 2
n=7 (4+1+1+1) i.e. 4
n=12 (4+4+4) i.e 3
n=20 (16+4) i.e. 2
'''
impo... | StarcoderdataPython |
4819185 | <gh_stars>1-10
import os
from collections import defaultdict, deque
from addict import Dict
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
import torch.jit
from speedrun import (
BaseExperiment,
IOMixin,
TensorboardMixin,
register_default_dispatch,
)
from speedrun.logg... | StarcoderdataPython |
1638926 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from modules.integer_utilities import sort_int
sort_int()
| StarcoderdataPython |
1659314 | <gh_stars>0
import csv
def read_csv(file):
input_csv = open('{}'.format(file), 'r')
reader_csv = csv.reader(input_csv, delimiter=',')
repos = [{'url': r[1], 'owner': r[2], 'repo': r[3]} for r in reader_csv]
input_csv.close()
return repos
def read_csv_repos(file):
input_csv = open('{}'.format(... | StarcoderdataPython |
3308985 | """Python related tools."""
import os
from . import package
from . import utils
def get_path(cmd, venv=None):
"""Return path to cmd."""
path = cmd
if venv:
path = os.path.join(venv, "bin", path)
return path
def get_pip_path(venv):
"""Return the full path to pip command."""
binpath ... | StarcoderdataPython |
1680907 | import os
import html
import aiohttp
from plugin import Plugin
from decorators import command
from xml.etree import ElementTree
from bs4 import BeautifulSoup
from collections import OrderedDict
MAL_USERNAME = os.getenv('MAL_USERNAME')
MAL_PASSWORD = os.getenv('MAL_PASSWORD')
IMGUR_ID = os.getenv('IMGUR_ID')
GOOGLE_A... | StarcoderdataPython |
4803729 | <reponame>jessicaleete/numerical_computing
import numpy as np
from scipy import linalg as la
from math import copysign
def hqr(A):
"""Finds the QR decomposition of A using Householder reflectors.
input: A, mxn array with m>=n
output: Q, orthogonal mxm array
R, upper triangular mxn array
... | StarcoderdataPython |
1687284 | <filename>core/mongo/connection.py
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Mongo connection setup
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------... | StarcoderdataPython |
1603697 | <reponame>OmalleyTomas98/graphTheoryProject
# Author : <NAME>
# Student ID : G00361128 (@gmit.ie)
# Course : Software Development GA_KSOAG_H08 Y3
# Module : Graph Theory -(48901)
# Program : NFA Builder
# Due Date : 03/04/2020
import Regex
import argparser
print("************************************... | StarcoderdataPython |
103992 |
# -*- coding:utf-8 -*-
from .. import utils
from sqlalchemy.sql import text
def mostViewTaxon(connection):
sql = "SELECT * FROM atlas.vm_taxons_plus_observes"
req = connection.execute(text(sql))
tabTax = list()
for r in req:
if r.nom_vern != None:
nom_verna = r.nom_v... | StarcoderdataPython |
1695855 | ################################################################################
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import tornado
from functoo... | StarcoderdataPython |
1633154 | """
将原来的数据库,变成一个stock id一个文件的数据库
"""
import os
import pandas as pd
import numpy as np
import pickle
# 导入行情数据
file_path = 'C:/Users/Administrator/Desktop/program/data/hangqing/'
file_list = os.listdir(file_path)
columns_name = pd.read_csv(file_path+file_list[0]).columns
hangqing_record = []
temp_r... | StarcoderdataPython |
1794097 | #!/usr/bin/python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
import sys
from catapult_build import module_finder
from catapult_build import temp_deployment_dir
def DevAppserver(pa... | StarcoderdataPython |
1692798 | <gh_stars>0
# -*- coding: UTF-8 -*-
"""
emoji.core
~~~~~~~~~~
Core components for emoji.
"""
import re
import sys
import warnings
from emoji import unicode_codes
__all__ = [
'emojize', 'demojize', 'get_emoji_regexp',
'emoji_lis', 'distinct_emoji_lis', 'emoji_count',
'replace_emoji', 'is_emoji', 'vers... | StarcoderdataPython |
80770 | from __future__ import print_function
from __future__ import division
import sys
import math
import os
import numpy
# ***** readme *****
# 这个代码从结果文件AllResults_filtered.txt中提取出概率低、p值低的出来
# 并且做出筛选
resultfile = open(sys.argv[1])
Pvaluethres = float(sys.argv[2])
probthres = float(sys.argv[3])
totalcellnum = min(int(sys.a... | StarcoderdataPython |
3394761 | <reponame>KunyuHe/Hacker-Rank-Practice<filename>ProblemSolving/BetweenTwoSets.py<gh_stars>0
def getTotalX(a, b):
count = 0
for num in range(max(a), min(b) + 1):
if all([num % elem == 0 for elem in a]) and \
all([elem % num == 0 for elem in b]):
count += 1
return count
| StarcoderdataPython |
3294877 | # -*- coding: utf-8 -*-
import sys
from datetime import datetime
from xbmcplugin import addDirectoryItems, endOfDirectory
from resources.lib.common import build_list
from resources.lib.onschedule import getcollectionid
"""
List what's on Eurosport 1 first
"""
def channel_schedule_key(video):
attrs = video... | StarcoderdataPython |
144807 | import tweepy
import logging
import time
from newsplease import NewsPlease
from newspaper import Article
from newspaper import fulltext
import requests
from lxml import html
import requests
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
# text to image
import numpy as np
import textwrap
impo... | StarcoderdataPython |
3384708 | <gh_stars>10-100
import paddle.nn as nn
class Identity(nn.Layer):
def __init__(self):
super(Identity, self).__init__()
def forward(self, inputs):
return inputs
class EncoderBlock(nn.Layer):
def __init__(self, n_in, n_out, n_layers):
super(EncoderBlock, self).__init__()
n... | StarcoderdataPython |
3336584 | <filename>discord_i18n/__init__.py<gh_stars>1-10
from .type_hints import *
from .locale import *
from .locale_manager import LocaleManager | StarcoderdataPython |
3266849 | """
County Classes
Module Description
==================
This module contains the CountyData and CountyDataset classes.
Copyright Information
===============================
This file is Copyright (c) 2021 <NAME>, <NAME>, <NAME>, <NAME>.
"""
from dataclasses import dataclass
from typing import Any, Iterable, Union
i... | StarcoderdataPython |
4817616 | import random
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import distance
import pandas as pd
#def generate_point(radius_sq):
# #https://stackoverflow.com/questions/30564015/how-to-generate-random-points-in-a-circular-distribution
# r_squared, theta = [random.randint(1, rad... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.