id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5170993 | <reponame>zhanghanchong/text2sql-hansql<gh_stars>0
#coding=utf8
import os
EXP_PATH = 'exp'
def hyperparam_path(args):
if args.read_model_path and args.testing:
return args.read_model_path
exp_path = hyperparam_path_text2sql(args)
if not os.path.exists(exp_path):
os.makedirs(exp_path)
r... | StarcoderdataPython |
194678 | import smbus
from enum import Enum
class MCP23017(object):
OUTPUT = 0
INPUT = 1
PORT_A = 0
PORT_B = 1
IODIR_A = 0x00 # Controls the direction of the data I/O for port A.
IODIR_B = 0x01 # Controls the direction of the data I/O for port B.
IPOL_A = 0x02 ... | StarcoderdataPython |
6406203 | <filename>example/polls/viewsets.py
from django.shortcuts import get_object_or_404
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from drf_react_template.mixins import FormSchemaViewSetMixin
from example.polls import models, serializers
class PollViewSet(
ListModelMixin,
RetrieveModelMi... | StarcoderdataPython |
3292050 | import os
class Filename(object):
"""
Filename class used to manipulate image filenames.
Used by the exposure tool.
"""
def __init__(self, parent=None):
"""
Creates a filename instance.
param object parent: reference to parent image object
"""
# self.pare... | StarcoderdataPython |
288349 | <reponame>piyueh/zoteroutils
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Distributed under terms of the BSD 3-Clause license.
"""A class that represents the SQLite database."""
class Database:
"""A class that represents a Zotero's SQLite database."""
... | StarcoderdataPython |
8168637 | n1 = int(input('Digite um número: '))
d = n1 * 2
t = n1 * 3
r = n1 ** 0.5
print(f'\033[7;30mSeu dobro é {d}, triplo {t} e raiz quadrada {r:.3f}.\033[m') | StarcoderdataPython |
6635005 | <reponame>williamsdoug/timeseries_fastai
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_data.ipynb (unless otherwise specified).
__all__ = ['TSBlock', 'stack_train_valid', 'TSDataLoaders']
# Cell
from .imports import *
from .core import *
from fastai.basics import *
from fastai.torch_core import *
from fastai.vis... | StarcoderdataPython |
8046647 | from flair.data import Corpus
from flair.embeddings import TokenEmbeddings, WordEmbeddings, StackedEmbeddings, CharacterEmbeddings, FlairEmbeddings, \
CamembertEmbeddings, BertEmbeddings, PooledFlairEmbeddings
from typing import List
import torch
from src.utils.monitoring import Monitor
torch.manual_seed(42)
torc... | StarcoderdataPython |
6555945 | <gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: 05_performance.ipynb (unless otherwise specified).
__all__ = ['load_pred_model', 'inference']
# Cell
from .imports import *
from .data_processing import *
from .anomaly import *
# Cell
import warnings
warnings.filterwarnings(action='once')
# Cell
def load_pre... | StarcoderdataPython |
6538807 | """
17362 : 수학은 체육과목 입니다 2
URL : https://www.acmicpc.net/problem/17362
Input #1 :
3
Output #1 :
3
Input #2 :
1000
Output #2 :
2
"""
n = int(input())
n = n % 8
if n == 1:
print(1)
elif (n == 0) or (n == 2):
print(2)
elif (n == 3) or (n == 7):
print(3)... | StarcoderdataPython |
9616618 | <filename>test_tools/OperateInterface.py<gh_stars>10-100
#!/usr/bin/python
#-*-coding:utf-8-*-
class OperateInterface(object):
def initiate(self,planes,bases,region_size,max_plane_battery,intruder_exposed_time, plane_sight, max_semo_intruder, target_move):
assert 0, 'Must choose an algorithem to test!'
... | StarcoderdataPython |
1610478 | <gh_stars>0
# RT - AutoMod
from typing import TYPE_CHECKING, Optional, Union, Dict, List
from discord.ext import commands, tasks
import discord
from collections import defaultdict
from time import time
from .modutils import check, assertion_error_handler
from .constants import CACHE_TIMEOUT
from .datacl... | StarcoderdataPython |
12811838 | <filename>config.py
import os
from dotenv import load_dotenv
from setup import basedir
try:
load_dotenv()
except FileNotFoundError:
pass
class BaseConfig(object):
"""
Base Configuration for placeholder
"""
SECRET_KEY = "SO_SECURE"
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv('DATABA... | StarcoderdataPython |
4877398 | from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
handler400 = '{{ cookiecutter.repo_name }}.errors.bad_request'
handler403 = 'django.views.defaults.permission_denied'
handle... | StarcoderdataPython |
8063038 | <reponame>msrb/nvdlib
import datetime
import cpe
import typing
from collections import namedtuple
from enum import Enum
from itertools import chain
from nvdlib.utils import AttrDict
VERSION = '4.0'
class CVE(object):
"""Representation of a CVE entry from the NVD database."""
def __init__(self, cve_id: st... | StarcoderdataPython |
9643406 | # Generated by Django 3.1.1 on 2020-11-21 10:58
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='HealthEmergency',
fields=[
('id', models.Au... | StarcoderdataPython |
52815 | <filename>embutils/utils/version.py<gh_stars>0
#!/usr/bin/python
# -*- coding: ascii -*-
"""
Version number implementation.
:date: 2021
:author: <NAME>
:contact: <EMAIL>
:license: The MIT License (MIT)
"""
import re
import attr
from ..utils.common import TPAny, TPText
# -->> Tunables <<----------------... | StarcoderdataPython |
3318976 | <reponame>gkluber/Sub-Riemannian-Quantum-Circuits
from subriemannian_qc.discrete import DiscreteApproximator
import numpy as np
# Use the discrete approximator to find an approximation to the identity matrix
for n in range(1, 4):
gate_approx = DiscreteApproximator(n, 10, 10, 1, 100)
approximation, _ = gate_a... | StarcoderdataPython |
11344053 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^user/$", views.UserManagementView.as_view()),
url(r"^user/logout/$", views.UserLogOutView.as_view()),
url(r"^super/$", views.SupermanagementView.as_view()),
url(r"^super/(?P<userkind>\d+)/$", views.SupermanagementView.as_view(... | StarcoderdataPython |
11379434 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from tempfile import mkdtemp
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3... | StarcoderdataPython |
12801984 | import os
import logging.config
from typing import Dict
from omegaconf import DictConfig
import pandas as pd
import hydra
from src.data import split_train_val_data
from src.entities.train_pipeline_params import TrainingPipelineParams, TrainingPipelineParamsSchema
from src.features.build_features import get_target, bu... | StarcoderdataPython |
8197521 | from django.apps import AppConfig
class MytodoConfig(AppConfig):
name = 'MyTodo'
| StarcoderdataPython |
5000187 | import numpy as np
import json
def smooth_raman_json(
min_freq: float,
max_freq: float,
points: int,
width: float,
num_acoustic: int,
filename: str,
) -> np.ndarray:
frequency = []
intensity = []
file = json.loads(open(filename).read())
# Load the json ... | StarcoderdataPython |
3245663 | import unittest
from django.test import Client, TestCase
from django.contrib.auth.models import User
import string
import random
from django.test.utils import override_settings
from django.urls import reverse
from .models import Reviews, UserInformation, Request
from django.contrib.auth import get_user_model
class Te... | StarcoderdataPython |
4946043 | <reponame>EEDDRV/Alert-Grade<filename>Main.py
import API, Config, time, sys, json
from email import message
import smtplib
from email.message import EmailMessage
def send_email(subject, body, to):
msg = EmailMessage()
msg.set_content(body)
msg['subject'] = subject
msg['to'] = to
user = Config.Send_Email
msg['fro... | StarcoderdataPython |
9642987 | #!/usr/bin/python3
import asyncio
import argparse
import krpc
import time
import datetime
import os
import sys
from ksppynet.flight_plan_node import ManeuverNode
__all__ = (
"FlightPlan",
)
class KStream(object):
def __init__(self, conn, item, attr):
self.stream = conn.add_stream(getattr, item, attr)
... | StarcoderdataPython |
8050513 | <reponame>viuipan/ironsmslib
from .base import APIException
class ServiceException(APIException):
message = "SERVICE_ERROR"
description = "service problems"
def __init__(self, response):
super(ServiceException, self).__init__(description=self.description)
| StarcoderdataPython |
3400223 | """
" License:
" -----------------------------------------------------------------------------
" Copyright (c) 2018, <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. Redistr... | StarcoderdataPython |
9701516 | <reponame>texx00/sandypi
from queue import Queue
import json
from threading import Thread
import time
import random
from server.utils import settings_utils
from server.database.playlist_elements import ShuffleElement, TimeElement
TIME_CONVERSION_FACTOR = 60*60 # hours to seconds
class QueueManager():
def __... | StarcoderdataPython |
1877355 | <reponame>zhique-design/zhique-service<filename>blog/urls.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from .views import CategoryBreadcrumbView
from .viewsets import ArticleViewSet, CategoryViewSet, HotArticleViewSet, TagViewSet, Recomm... | StarcoderdataPython |
12830462 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Trying to gin up a human-readable, simple-minded (bilinear interpolation) algorithm for de-mosaicing a
# sensor readout that has an RGGB color filter array (CFA).
# Red filters lie over cells whose x coordinate is even and whose y coordinate is even: eve... | StarcoderdataPython |
1659644 | from zc.buildout.easy_install import script_header, _safe_arg
script_templates = {
"wsgi": script_header + """
%(relative_paths_setup)s
import os
import sys
sys.path[0:0] = [
%(path)s,
]
%(initialization)s
os.chdir(path)
if not os.path.isdir('applications'):
raise RuntimeError('Running from the wrong fold... | StarcoderdataPython |
5029638 | <reponame>ItamarHavenstein/Python<filename>Exercicio51a60/ex055.py
maiorPeso = 0.0
menorPeso = 0.0
for c in range(1, 6, 1):
peso = float(input('Pesso da {}° pessoa: '.format(c)))
if c == 1:
maiorPeso = peso
menorPeso = peso
else:
if peso > maiorPeso:
maiorPeso = peso
... | StarcoderdataPython |
6538870 | <gh_stars>1-10
# Generated by Django 3.2.6 on 2021-08-21 21:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reactbackend', '0002_votes_applied_change'),
]
operations = [
migrations.AlterField(
model_name='votes',
... | StarcoderdataPython |
6543480 | <filename>pkgs/robots/bdsim/robots/test_robots.py
import bdsim.np
import math
import matplotlib.pyplot as plt
import time
from bdsim.blocks.robots import *
import unittest
import numpy.testing as nt
class RobotBlockTest(unittest.TestCase):
def test_quadrotor(self):
from quad_model import quadrotor a... | StarcoderdataPython |
352397 | <reponame>IBM/gcat-assets
import sys, os, ibm_boto3
from ibm_botocore.client import Config
from pprint import pprint
cos = ibm_boto3.client(
service_name="s3",
ibm_api_key_id=os.environ["COS_APIKEY"],
ibm_service_instance_id=os.environ["COS_RESOURCE_INSTANCE_ID"],
ibm_auth_endpoint="https://iam.cloud.i... | StarcoderdataPython |
11352129 | <gh_stars>1-10
"""empty message
Revision ID: 84102fbdb0f8
Revises:
Create Date: 2021-11-12 15:28:34.421620
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands a... | StarcoderdataPython |
5039679 | # Character width information for PostScript font `Times Bold Italic'
# generated from the Adobe Font Metric file `../../../../adobe/tibi____.afm'. Adobe
# copyright notice follows:
#
# Copyright (c) 1985, 1987, 1989, 1990 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype AG and/or its ... | StarcoderdataPython |
9653111 | """
Django settings for e_shop project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | StarcoderdataPython |
317457 | from blockchain import*;
from time import time;
import pprint
pp = pprint.PrettyPrinter(indent=4)
blockchain = Blockchain();
transactions = [];
block = Block(transactions, time(), 0);
blockchain.addBlock(block);
block = Block(transactions, time(), 1);
blockchain.addBlock(block);
block = Block(transa... | StarcoderdataPython |
220479 | import numpy as np
from surfinpy import plotting
from surfinpy import utils as ut
def calculate_excess(adsorbant, slab_cations, area, bulk,
nspecies=1, check=False):
r"""Calculates the excess of a given species at the surface.
Depending on the nature of the species, there are two ways to ... | StarcoderdataPython |
3226530 | <reponame>machinalis/alfajor
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.localflavor.ar.forms import ARPostalCodeField
from django.contrib.localflavor.ar.forms import ARProvinceSelect
from django.forms.util import ErrorList
from ventas.models import DatosDeEnvio, GastosDeEnvio, ARP
class Dum... | StarcoderdataPython |
3429557 | import numpy as np
import torch
import copy
from ..utils.utils_data import nasbench2graph, nasbench2graph2
from .acquisition_functions import acq_fn
from ..eigen.trainer_predictor import NasBenchGinPredictorTrainer
from ..eigen.trainer_uncertainty_predictor import NasBenchGinGaussianTrainer
from nas_lib.utils.corr impo... | StarcoderdataPython |
9637822 | <reponame>Alecto3-D/testable-greeter
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... | StarcoderdataPython |
6579668 | <reponame>michaelarg/clAIre
# import the necessary packages
from __future__ import print_function
from imutils.video import WebcamVideoStream
from imutils.video import FPS
import argparse
import imutils
import sys
import numpy as np
import cv2
#opencv2 uses BGR
#Order: Red, Orange, Green in HSV
colour = [ ([0,100,10... | StarcoderdataPython |
3501575 | # coding:utf-8
from flask import Flask
from flask import render_template, request
app = Flask(__name__)
@app.route('/', methods=['get', 'post'])
def login_view():
# the methods that handle requests are called views, in flask
msg = ''
# form is a dictionary like attribute that holds the form data
if... | StarcoderdataPython |
1806702 | """ This is the Bokeh charts testing interface.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with thi... | StarcoderdataPython |
9673175 | <reponame>DianQK/my_slack_bot_demo
import os
from bilibili.testv import fetchLatestTestVideos
import sys
RUN_TASKS = os.environ["RUN_TASKS"]
tasks = RUN_TASKS.split(',')
if 'testv' in tasks:
fetchLatestTestVideos()
if 'sspai' in tasks:
print('TODO')
| StarcoderdataPython |
4862713 | <gh_stars>0
import pandas as pd
# Buat dataframe df1 dan df2
df1 = pd.DataFrame({
'key':['k1','k2','k3','k4','k5'],
'val1':[200, 500, 0, 500, 100],
'val2':[30, 50, 100, 20, 10]
})
df2 = pd.DataFrame({
'key':['k1','k3','k5','k7','k10'],
'val3':[1,2,3,4,5],
'val4':[6,7,8,8,10]
})
# Merge yang ekivalen d... | StarcoderdataPython |
8130613 | from robocorp_ls_core.ep_providers import * # Kept for backward compatibility
| StarcoderdataPython |
3427606 | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author <NAME> <<EMAIL>>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api, _
import odoo.addons.decimal_precision as dp
class CreateRent... | StarcoderdataPython |
221042 | <reponame>bjpop/blip<gh_stars>100-1000
print(2 not in [1,2,3])
print(2 not in [4,5])
print(1 not in [1] not in [[1]])
print(3 not in [1] not in [[1]])
| StarcoderdataPython |
9645129 | <filename>app/models.py<gh_stars>0
from . import db
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from . import login_manager
@login_manager.user_loader
def load_user(user_id):
return Admin.query.get(int(user_id))
class Admin(UserMixin,db.Model):
... | StarcoderdataPython |
4913920 | <gh_stars>1000+
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 requ... | StarcoderdataPython |
12843787 | #!/usr/bin/python
"""
I wrote this in a couple afternoons while watching Netflix, so it can probably be better.
-jmag
"""
from slackclient import SlackClient
import sys, json, sqlite3, time, re, datetime
MENTION_REGEX = "^<@(|[WU][A-Z0-9]+?)>(.*)"
class ConfigException(Exception):
pass
class Connection... | StarcoderdataPython |
5092815 | <gh_stars>1-10
"""
cloudalbum/__init__.py
~~~~~~~~~~~~~~~~~~~~~~~
Environment configuration how to run application.
:description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course
:copyright: © 2019 written by <NAME>, <NAME>.
:license: MIT, see LIC... | StarcoderdataPython |
3404502 | <reponame>4dn-dcic/tibanna_ff
from tibanna_ffcommon.portal_utils import (
TibannaSettings,
FormatExtensionMap,
)
from tibanna_cgap.zebra_utils import (
FourfrontStarter,
FourfrontUpdater,
ProcessedFileMetadata,
)
import pytest
from dcicutils import ff_utils
from tests.tibanna.zebra.conftest import (... | StarcoderdataPython |
198055 | <reponame>gruiick/pyRogue<filename>chapters/rogue_test01.py
#!/usr/bin/env python3
# coding: utf-8
#
# $Id: rogue_test01.py 894 $
# SPDX-License-Identifier: BSD-2-Clause
#
"""
from http://www.roguebasin.com/index.php?title=Roguelike_Tutorial,_using_python3%2Btdl,_part_1
"""
import tdl
SCREEN_WIDTH = 80
SCREEN_HE... | StarcoderdataPython |
8173205 | <reponame>BehaviorPredictionTestingPlatform/VerifAI
import carla
import sys
from agents.navigation.agent import *
from agents.navigation.controller import VehiclePIDController
from agents.tools.misc import distance_vehicle, draw_waypoints
import numpy as np
'''This agent doesn't move.'''
class BrakeAgent(Agent):
... | StarcoderdataPython |
6424305 |
import fasteners, json, os, threading
thread_lock = threading.Lock()
def write(filename, content):
with open(filename, 'w+') as f:
f.write(content)
def read(filename):
content = '{}'
if os.path.exists(filename):
with open(filename, 'r') as f:
content = f.read()
... | StarcoderdataPython |
1895916 | """
Copyright 2015 - <NAME> <<EMAIL>>
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 t... | StarcoderdataPython |
1751033 | print('this is two/c.py')
| StarcoderdataPython |
6677225 | from datetime import datetime
from resourse.error_log import ERROR_LOG
class MountJson:
def putDateTime(self):
now = datetime.now()
return self.putTag("dateTime",str(now.date()) + "T" + str(now.time()) + "Z")
def putTag(self,tag,value):
self.jsonBuffer[tag] = value
... | StarcoderdataPython |
3230619 | <filename>REM/Tool/IDA 7.3/python/ida_diskio.py
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
"""
IDA Plugin SDK API wrapper: diskio
"""
from sys import vers... | StarcoderdataPython |
222065 | from argparse import ArgumentParser
from pathlib import Path
from sys import (
exit,
stderr,
)
from typing import List
from src import (
Dataset,
MCV,
UrbanSound8k,
)
_DESCRIPTION = """
Generate noised audio for noise reduction models training.
Based on UrbanSound8k and Mozilla Common Voice datase... | StarcoderdataPython |
6507515 | <gh_stars>0
"""
Copyright (C) 2019-2020 Zilliz. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable l... | StarcoderdataPython |
5087701 | <gh_stars>1-10
list=[1,2,3,4]
i=0
while(i<3):
list[i]=list[i]+1
i=i+1;
| StarcoderdataPython |
3559041 | <gh_stars>1-10
#
# laaso/appmanager.py
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
'''
Module that provides application classes that depend on laaso.azure_tool.
'''
import laaso.azure_tool
import laaso.common
import laaso.identity
import laaso.util
class ManagerMix... | StarcoderdataPython |
11318643 | # Copyright (c) 2017 The Verde Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Generators of synthetic datasets.
"""
import warnings
from ..synthetic import CheckerBoard... | StarcoderdataPython |
1915455 | <reponame>anthonyeden/pypco
"""PCO Services endpoints.
Generated by pypco_generator tool. Manual changes not recommended.
"""
#pylint: disable=C0304,R0903,C0111,C0321
from .base_endpoint import BaseEndpoint
# The base Services endpoint
class ServicesEndpoint(BaseEndpoint): pass
# All Services endpoints
class Attac... | StarcoderdataPython |
3353948 | from klpyastro.plot import plottools
#from nose.tools import assert_equal
#### Not clear how to test plots
class TestPlot:
@classmethod
def setup_class(cls):
pass
@classmethod
def teardown_class(cls):
pass
def setup(self):
pass
def teardown(self):
... | StarcoderdataPython |
3442020 | <filename>niphlem/input_data.py
import numpy as np
import json
import matplotlib.pyplot as mpl
import warnings
def get_lines(filename):
"""
Read in lines from file, stripping new line markers
Parameters
----------
filename : str, pathlike
Path to file.
Returns
-------
lines :... | StarcoderdataPython |
8068253 | <filename>fourier.py
"""
Calculates the Fourier coefficients for a given set of data points
"""
import matplotlib.pyplot as plt
import numpy as np
class Fourier:
def __init__(self, points, N):
# self.c stores all coefficients of the fourier series
# self.n stores the value of n that each coefficient corresponds... | StarcoderdataPython |
8103775 |
from glob import glob
from shutil import move, rmtree
from os import listdir, path, walk, unlink
from subprocess import check_output, STDOUT, CalledProcessError
def run(*args, **kwargs):
try:
return check_output(*args, **kwargs, stderr=STDOUT)
except CalledProcessError as e:
raise Exception(e... | StarcoderdataPython |
4964972 | <filename>IRRemote/listener/irservice.py
#!/usr/bin/env python
#-- @author: Makin, August 2015
from RPi import GPIO
import time
import os
import subprocess
import re
SAMPLE_SIZE = 256
IRpin = 14
GPIO.setmode(GPIO.BCM)
GPIO.setup(IRpin, GPIO.IN)
def kill():
proses = "omxplayer"
hasiltm = os.popen("ps -ef | grep "+pro... | StarcoderdataPython |
5070535 | import requests
print(f"requests version: {requests.__version__}")
print()
req_google = requests.get("https://www.google.com")
req_myfile = requests.get("https://raw.githubusercontent.com/Andrewjjj/CMPUT404Lab/main/Lab1/lab1.py")
print(req_myfile.content) | StarcoderdataPython |
93075 | <reponame>overholts/tuner
import os
import shutil
from pathlib import Path
def copy(source: Path, destination: Path):
os.makedirs(destination.parent, 0o755, exist_ok=True)
shutil.copy(str(source), str(destination))
def remove(target: Path):
os.remove(target)
| StarcoderdataPython |
9602251 | <gh_stars>0
import math
__all__ = ['sito', 'fact', 'tot', 'primes', 'nwd', 'primo', 'nTyFibb',
'mniejszyRownyFibb', 'isPrime', 'nextPrime', 'tableOfPrimes']
def sito(u):
tab = [0 for i in range(u+1)]
for i in range(2, u+1):
tab[i] = i
for i in range(4, u+1, 2):
tab[i] = 2
... | StarcoderdataPython |
124816 | <reponame>matthewb66/blackduck-scan-directguidance
import re
import os
import tempfile
# import semver
import xml.etree.ElementTree as ET
from bdscan import globals, classComponent
class MyTreeBuilder(ET.TreeBuilder):
def comment(self, data):
self.start(ET.Comment, {})
self.data(data)
sel... | StarcoderdataPython |
138587 | #! /usr/bin/env python
'''Make sure the Riak client is sane'''
import unittest
from test import BaseTest
from simhash_db import Client
class RiakTest(BaseTest, unittest.TestCase):
'''Test the Riak client'''
def make_client(self, name, num_blocks, num_bits):
return Client('riak', name, num_blocks, nu... | StarcoderdataPython |
4933707 | import threading
from configHandler import loadConfigData
from clientClass import Client
def main():
mainConfig = loadConfigData("../config.json")
PORT = mainConfig["PORT"]
SERVER_IP = mainConfig["SERVER_IP"]
DISCONNECT_MESSAGE = mainConfig["DISCONNECT_MESSAGE"]
SERVER_ADDRESS = (SERVER_IP, PORT)
... | StarcoderdataPython |
3279692 | import sys
import argparse
import warnings
from processing.data_pipeline import DataPipeline
if __name__ == "__main__":
warnings.simplefilter("ignore")
parser = argparse.ArgumentParser(description="Implement the data pipeline")
parser.add_argument(
"--filename",
"-input",
default="... | StarcoderdataPython |
1724255 | <reponame>StevenHuang2020/ML
import matplotlib.pyplot as plt
import numpy as np
from distributions import Binomial_distribution, Discrete_uniform_distribution
def plotDistributeBar(ax, data, label='', width=0.3, offset=0, title='Probability Distribution of true'):
ax.bar(np.arange(len(data))+offset,data,width=widt... | StarcoderdataPython |
1805036 | <gh_stars>0
#!/usr/bin/env python3
from functools import partial, reduce
from itertools import compress, count, cycle, islice, starmap
from operator import mul
def get_input(filename):
with open(filename, "r") as input_file:
# returning list not a generator because I'll need to go through
# it sev... | StarcoderdataPython |
1849840 | <reponame>cyware-labs/ioc-analyzer<filename>ioc_analyzer/py_whois/query.py
import socket
from ioc_analyzer.py_whois.parser import RawTextWhoIsParser
from ioc_analyzer.py_whois.tld import tld_whois_dict
DEFAULT_WHOIS_PORT = 43
class SocketWrapper(object):
NEW_LINE_CHAR = '\n'
def __init__(self, server, port... | StarcoderdataPython |
6603195 | <gh_stars>0
r"""
>>> import sys
>>> import pretext
>>> myrepr = pretext.PrefixRepr()
>>> repr = myrepr.repr
>>> def _displayhook(value):
... if value is not None:
... sys.stdout.write(myrepr.repr(value))
>>> sys.displayhook = _displayhook
>>> u''
u''
>>> b''
b''
>>> bytes()
b''
>>> b'\0'
b'\x00'
>>> b"'"
b"... | StarcoderdataPython |
5162070 | <filename>src/Client/View/MainFrame/TabFrame/FirstTabFrame/subWindows/viewAllWindow.py<gh_stars>10-100
# -*- coding:utf-8 -*-
from src.Client.Conf.config import *
from src.Client.MissionSystem import missionSystem
from src.Client.SystemTools.ConfFileRead import configFileRead
class ViewAllWindow():
"""
显示全部任... | StarcoderdataPython |
5056729 | <reponame>thanhn9/prometheus-workshop
from fastapi import FastAPI
from starlette.responses import PlainTextResponse
import prometheus_client
app = FastAPI(title="Python Service")
CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')
@app.get("/")
def read_root():
return {"Hello": "World"}
@app... | StarcoderdataPython |
3212983 |
from cpc_api.api import CPCApi
import matplotlib.pyplot as plt
def main():
api = CPCApi(legislature='2017-2022')
meluche = api.search_parliamentarians('Melenchon')
arr_face_de_meluche = api.picture(meluche.slug, pixels=512)
plt.imshow(arr_face_de_meluche)
plt.show()
if __name__ == "__main__":
... | StarcoderdataPython |
11243434 | DATE_TIME_STRINGS = ("year", "month", "week", "day", "hour", "minutes", "tomorrow")
CASHTAG = "$"
CRYPTO_CURRENCIES = (
"BTC",
"ETH",
"ADA",
"SOL",
"DOT",
"XRP",
"LTC",
"NEO",
"EOS",
"BNB",
"HT",
"LINK",
"BCH",
"TRX",
"XTZ",
)
NASDAQ_TRADING_HOURS = ["09:30... | StarcoderdataPython |
96547 | import json
import requests
import logging
from datetime import date, timedelta
logging.basicConfig(level=logging.ERROR)
class EODAPI:
BASE_URL = "https://eodhistoricaldata.com/api/"
def __init__(self, apiToken):
self.apiToken = apiToken
# Do basic API call to EOD API and retry if fail
def doRequest(self, url,... | StarcoderdataPython |
6443617 | #-*- coding: utf-8 -*-
#!/usr/bin/python3
"""
Copyright (c) 2020 LG Electronics Inc.
SPDX-License-Identifier: MIT
"""
__version__ = "0.4.7"
| StarcoderdataPython |
273590 | """This module contains the meta information of OrgGetNumImpactedDomains ExternalMethod."""
from ..ucscentralcoremeta import MethodMeta, MethodPropertyMeta
method_meta = MethodMeta("OrgGetNumImpactedDomains", "orgGetNumImpactedDomains", "Version142b")
prop_meta = {
"cookie": MethodPropertyMeta("Cookie", "cookie"... | StarcoderdataPython |
11362331 |
# _read_h5ad.py
__module_name__ = "_read_h5ad.py"
__author__ = ", ".join(["<NAME>"])
__email__ = ", ".join(["<EMAIL>",])
# package imports #
# --------------- #
from anndata import read_h5ad
def _read_h5ad(h5ad_path, silent=False):
"""Wraps anndata.read_h5ad"""
adata = read_h5ad(h5ad_path)
... | StarcoderdataPython |
3492638 | <reponame>nsteins/crash-model<filename>src/showcase/app.py
import os
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
CONFIG_FILE = os.path.join('static', 'config.js')
@app.route('/data/<path:path>')
def static_files(path):
return send_from_directory('data', path)
@app.rou... | StarcoderdataPython |
11331884 | """
Parser for the Telnet protocol. (Not a complete implementation of the telnet
specification, but sufficient for a command line interface.)
Inspired by `Twisted.conch.telnet`.
"""
import struct
from typing import Callable, Generator
from .log import logger
__all__ = [
"TelnetProtocolParser",
]
def int2byte(n... | StarcoderdataPython |
11397919 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'UserProfile'
db.delete_table(u'report_userprofile')
... | StarcoderdataPython |
5163735 | import time
import argparse
import sys
class Auxiliar:
dp = [[]]
def readFile(v):
try:
file = args.folder
except Exception as e:
print(e)
sys.exit("Directory Not Found, for help use the -h option")
try:
f = open(file, 'r')
N = int (f.readline())
for j in range (N):
element = f.re... | StarcoderdataPython |
5111832 | <reponame>13thProgression/gold-blockchain<filename>chia/util/service_groups.py
from typing import Generator, KeysView
SERVICES_FOR_GROUP = {
"all": "gold_harvester gold_timelord_launcher gold_timelord gold_farmer gold_full_node gold_wallet".split(),
"node": "gold_full_node".split(),
"harvester": "gold_harv... | StarcoderdataPython |
1623154 | # Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='top2']/div[@id='productName']|//div[@class='top2']/div[@class='name']",
'price' : "//div[@class='pm-2']/div[@class='deta... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.