id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3372737 | from ftfy import bad_codecs, guess_bytes
def test_cesu8():
cls1 = bad_codecs.search_function('cesu8').__class__
cls2 = bad_codecs.search_function('cesu-8').__class__
assert cls1 == cls2
test_bytes = (b'\xed\xa6\x9d\xed\xbd\xb7 is an unassigned character, '
b'and \xc0\x80 is null')
... | StarcoderdataPython |
3446537 | <filename>tests/test_robustats.py
import unittest
import robustats
class TestWeightedMedian(unittest.TestCase):
def test_same_weights(self):
x = [1., 2., 3.]
weights = [1., 1., 1.]
weighted_median = robustats.weighted_median(x, weights)
self.assertEqual(weighted_median, 2.)
d... | StarcoderdataPython |
6442113 | import wtforms_widgets
from wtforms import ValidationError
from pycroft.model.user import User
class UserIDField(wtforms_widgets.fields.core.StringField):
"""A User-ID Field """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(self, **kwargs):
return s... | StarcoderdataPython |
346750 | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from lookup.api import views as lv
app_name = "lookup"
router = DefaultRouter()
router.register(r"lookup", lv.LookupViewSet, app_name)
urlpatterns = [
path("", include(router.urls)),
] | StarcoderdataPython |
3552052 | # (c) Copyright [2018-2021] Micro Focus or one of its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | StarcoderdataPython |
1789023 | <filename>GUnicornConfig.py
import logging
import sys
from GServerHooks import ServerHooks
from gunicorn import glogging
from pythonjsonlogger import jsonlogger
class CustomLogger(glogging.Logger):
"""Custom logger for Gunicorn log messages."""
def _set_handler(self, log, output, fmt, stream=None):
... | StarcoderdataPython |
5166361 | #Gets data export
#(c) Leanplum 2015
import urllib2
import re
import json
import time
startDate = raw_input('Enter the startDate you want data for: ')
appId = raw_input('Enter your appId: ')
clientKey = raw_input('Enter your clientKey: ')
# Optional Entries - make sure to uncomment out urlTwo
# endDate = raw_input('... | StarcoderdataPython |
11390143 | <gh_stars>0
#!/usr/bin/env python
import asyncio
import random
import websockets
class WebsocketClient:
def __init__(self):
self.clientID = random.randint(0, 100)
self.event = asyncio.Event()
async def eventGenerator(self):
while True:
await asyncio.sleep(1.5)
... | StarcoderdataPython |
8071067 | """
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | StarcoderdataPython |
396307 | import os
import sys
from pathlib import Path
ROOT_PATH = Path(__file__).resolve().parent.parent
if str(ROOT_PATH) not in sys.path:
sys.path.insert(1, str(ROOT_PATH))
import numpy as np
import re
from frequency_response import FrequencyResponse
from biquad import peaking, low_shelf, high_shelf, digital_coeffs
from ... | StarcoderdataPython |
5067989 | """
Module contains the state machine runner itself.
Implements the following functions:
* __init__ - Constructor accepts path to properties file and
then calls get_properties() to load the YAML.
* get_properties - Read the properties file into the properties attribute.
* run - Iterates over the array ... | StarcoderdataPython |
6456833 | <filename>createfiles.py<gh_stars>0
import os
cwd = os.getcwd()
names = ("fivemb", "fiftymb", "fivehundredmb", "onegb", "twogb")
nums = (5, 50, 500, 1024, 2048)
multi = 1024 * 1024
sizes = [num * multi for num in nums]
for name, size in zip(names, sizes):
with open(name, "wb") as out:
out.seek(size - 1)
... | StarcoderdataPython |
160833 | <reponame>RenaKunisaki/GhidraScripts<filename>FindStruct.py
#Find structs by field type.
#@author Rena
#@category Struct
#@keybinding
#@menupath
#@toolbar
StringColumnDisplay = ghidra.app.tablechooser.StringColumnDisplay
AddressableRowObject = ghidra.app.tablechooser.AddressableRowObject
TableChooserExecutor = ghidra... | StarcoderdataPython |
11237158 | <reponame>abrahammurciano/nextcord
from nextcord.ext.abc.context_base import ContextBase
from .id_converter import IDConverter
from .errors import MessageNotFound, ChannelNotFound
from nextcord.abc import MessageableChannel
from typing import Optional
import nextcord
import re
class PartialMessageConverter(IDConverte... | StarcoderdataPython |
9685267 | <filename>pcapkit/all.py
# -*- coding: utf-8 -*-
# pylint: disable=unused-import, unused-wildcard-import, bad-continuation,wildcard-import
"""index for the library
:mod:`pcapkit` has defined various and numerous functions
and classes, which have different features and purposes.
To make a simple index for this library,... | StarcoderdataPython |
1919897 | <reponame>karpiq24/django-klima-kar
from django.contrib import admin
from apps.invoicing.models import (
SaleInvoice,
SaleInvoiceItem,
Contractor,
RefrigerantWeights,
ServiceTemplate,
CorrectiveSaleInvoice,
)
admin.site.register(SaleInvoice)
admin.site.register(SaleInvoiceItem)
admin.site.regi... | StarcoderdataPython |
6646432 | <filename>src/examples/utils_PyKinectV2.py<gh_stars>0
##############################################################
### Set of useful utilities function related to PyKinectV2 ###
##############################################################
import cv2
import ctypes
import numpy as np
from open3d import *
from pykinec... | StarcoderdataPython |
1763823 | """Unit tests for the SonarQube commented-out code collector."""
from .base import SonarQubeTestCase
class SonarQubeCommentedOutCodeTest(SonarQubeTestCase):
"""Unit tests for the SonarQube commented-out code collector."""
METRIC_TYPE = "commented_out_code"
async def test_commented_out_code(self):
... | StarcoderdataPython |
9705919 | <gh_stars>0
#!/usr/bin/python
# --------------------------------------------------------------------------------------------------
# Convert all Preferences from many separate tables per semester to a
# single table with additional semester Id.
#
#------------------------------------------------------------------------... | StarcoderdataPython |
4980888 | <gh_stars>1-10
"""
Task using configuration to get the subscriptions then
- Does not collect groups with no alias as they will be deleted
- Collect groups that have an alias not found in AAD
- Collect groups by age that meet certain thresh holds
- 30 days old - initial warning
- 60 days old - second warning
... | StarcoderdataPython |
3494025 | import time
import random
import board
import adafruit_pyportal
# Get wifi details and more from a settings.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Set up where we'll be fetching data from
DATA_SOURCE = "http... | StarcoderdataPython |
12849485 | <filename>app/gws/server/spool.py
import gws
import importlib
def add(job):
uwsgi = importlib.import_module('uwsgi')
gws.log.info("SPOOLING", job.uid)
d = {b'job_uid': gws.as_bytes(job.uid)}
uwsgi.spool(d)
| StarcoderdataPython |
1675874 | <reponame>rob-opsi/freight<filename>freight/hooks/github.py
from __future__ import absolute_import
__all__ = ['GitHubHooks']
from flask import request, Response
from .base import Hook
class GitHubHooks(Hook):
def ok(self):
return Response()
def deploy(self, app, env):
payload = request.get... | StarcoderdataPython |
1951113 | #!/usr/bin/env python3
import json
import os
import math
# Should we run commands that are generated (to escape and convert)
run_commands = True
release = True
workers = 14;
print_commands = True
recolor = False
gen_gif = False
reverse_gif = False;
rotate_gif_degrees = 0
gif_intermediate = "zoom_rotated.gif"
gif_outp... | StarcoderdataPython |
5048148 | from setuptools import find_packages
from setuptools import setup
readme = open('README.rst').read()
history = open('CHANGES.txt').read()
long_description = readme + '\n\n' + history
setup(name='Products.mcdutils',
version='3.3.dev0',
description=('A Zope product with memcached-backed ZCache and '
... | StarcoderdataPython |
1746894 | <reponame>gadgetlabs/reinforcementlearningrobot
#!/usr/bin/env python3
import os
import asyncio
import json
class SensorNotFound(Exception):
pass
class ActuatorNotFound(Exception):
pass
class BehaviourNotFound(Exception):
pass
def main(config):
loop = asyncio.get_event_loop()
sensor_queue =... | StarcoderdataPython |
3408987 | """
DESAFIO 063: Sequência de Fibonacci v1.0
Escreva um programa que leia um número n inteiro qualquer e mostre
na tela os n primeiros elementos de uma Sequência de Fibonacci.
Ex: 0 → 1 → 1 → 2 → 3 → 5 → 8
"""
"""
# Feito com for
x = 1
y = 0
n = int(input('Digite quantos primeiros elementos da Sequência de Fibonacc... | StarcoderdataPython |
9697744 | <reponame>pkingpeng/-python-
"""
https://stackoverflow.com/questions/36721232/importerror-cannot-import-name-get-column-letter
"""
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
print(get_column_letter(1))
print(get_column_letter(2))
print(get_column_letter(27))
print(get_colum... | StarcoderdataPython |
3526310 | import requests
import json
import logging
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.resource import ResourceManagementClient
from dku_utils.access import _is_none_or_blank
AZURE_METADATA_SERVICE="http://169.254.169.254"
INSTANCE_API_VERSION = "2019-04-30"
def run_and_process_cloud_error(fn... | StarcoderdataPython |
3340431 | <filename>safe_transaction_service/tokens/clients/zerion_client.py
from dataclasses import dataclass
from typing import List, Optional
from eth_typing import ChecksumAddress
from web3.exceptions import ContractLogicError
from gnosis.eth import EthereumClient
from gnosis.eth.constants import NULL_ADDRESS
@dataclass
... | StarcoderdataPython |
179701 | # Generated by Django 2.2.1 on 2019-05-16 20:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('IoT_DataMgmt', '0069_auto_20190514_1740'),
]
operations = [
migrations.AlterModelOptions(
name='equipmentfacility',
options=... | StarcoderdataPython |
4847176 | <filename>course_project/K33401/Kumpan_Viktor/Django_Note_service/src/api/tests/tests_views.py<gh_stars>1-10
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from notes.models import Note
User = get_user_model()
... | StarcoderdataPython |
3547915 | import sys
from awsglue.dynamicframe import DynamicFrame
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame
data_sheets = ['volts', 'amps', 'watts', 'power_factor', 'watt_... | StarcoderdataPython |
85414 | # Django settings for example project.
import os
from django.contrib.messages import constants as message_constants
PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split(
os.path.dirname(os.path.abspath(__file__))
)
def env(name, default):
return os.environ.get(name, default)
DEBUG = True
SECRET_KEY = <KEY>'
... | StarcoderdataPython |
4895356 | <reponame>Tomcli/kfp-tekton
# Copyright 2021 kubeflow.org
#
# 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... | StarcoderdataPython |
5023256 | #entrada
while True:
try:
entrada = str(input()).split()
#processamento
binN1 = bin(int(entrada[0]))[2:]
binN2 = bin(int(entrada[1]))[2:]
tamBinN1 = len(binN1)
tamBinN2 = len(binN2)
result = ''
resto = '' #completando o numero ... | StarcoderdataPython |
4853385 | from pos_parameters import filename_parameter, value_parameter, \
string_parameter, list_parameter,\
vector_parameter
import pos_wrappers
class preprocess_slice_volume(pos_wrappers.generic_wrapper):
_template = """pos_slice_volume \
-i {input_image... | StarcoderdataPython |
1653716 | <filename>tests/test_users.py<gh_stars>10-100
# pylint: disable=redefined-outer-name,unused-variable
from unittest import mock
import pytest
from tinkoff.invest.services import UsersService
@pytest.fixture()
def users_service():
return mock.create_autospec(spec=UsersService)
def test_get_accounts(users_servi... | StarcoderdataPython |
3594433 | import subprocess
def audiveris(input_path, output_path):
subprocess.call(["sudo","docker","run","--rm",\
"-v", output_path+":/output",
"-v", input_path+":/input",\
"toprock/audiveris"]) | StarcoderdataPython |
5199467 | <gh_stars>0
from scipy.spatial import distance
import imutils
from imutils import face_utils
import dlib
import cv2 as cv
def eye_aspect_ratio(eye):
A = distance.euclidean(eye[1], eye[5])
B = distance.euclidean(eye[2], eye[4])
C = distance.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
... | StarcoderdataPython |
3424732 | # Desenvolva um programa que leia as duas notas de um aluno e calcule e mostre sua média
Nome = (input('Digite seu nome:'))
nota1 = float(input('Digite o valor da nota 1:'))
nota2 = float(input('Digite o valor da nota 2:'))
media = (nota1 + nota2) / 2
print('A média do aluno \033[32m{}\033[m \033[36m{}\033[m'.format(No... | StarcoderdataPython |
6600643 | <reponame>braincodercn/OpenStock<filename>RoadMap/graph.py
import graphviz
from graphviz import Digraph
from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
def make_graph():
g = Digraph("Roadmap_of_Task_based_Framework")
g.node('System')
g.node('Data Sources')
g.n... | StarcoderdataPython |
106471 | <reponame>dpopadic/ml-res<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import re
from nltk import PorterStemmer
def plotData(X, y):
# PLOTDATA(x,y) plots the data points with + for the positive examples
# and o for the negative examples. X is assumed to be a Mx2 ma... | StarcoderdataPython |
3380309 | <reponame>pathtoknowhere/warden
import requests
import os
from flask import (Blueprint, flash, redirect, render_template, request,
url_for, current_app)
from flask_login import current_user, login_required, login_user
from werkzeug.security import generate_password_hash
from forms import Registratio... | StarcoderdataPython |
1864559 | <filename>src/cosmosdb-preview/azext_cosmosdb_preview/commands.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --... | StarcoderdataPython |
1937193 | import time
for x in range(-30, 30):
for y in range(13, -13, -1):
if ((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.05) ** 2 * (y * 0.1) ** 3 <= 0 :
print('\n'.join([''.join(['love'[(x - y) % len('love')]])]))
#else: print(' ')
| StarcoderdataPython |
4970986 | """Structure change
Revision ID: bd1b5f1bc8ff
Revises: <PASSWORD>
Create Date: 2019-08-05 09:27:15.358485
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bd1b5f1bc8ff'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# #... | StarcoderdataPython |
1856080 | # Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
384649 | from flask import Flask
app = Flask(__name__)
app.config.from_object('wsgi.settings')
from wsgi import route
| StarcoderdataPython |
8132924 | # -*- coding: utf-8 -*-
# author: itimor
from django.db.models import Q
from dry_rest_permissions.generics import DRYPermissionFiltersBase
from users.models import User
from django.shortcuts import get_object_or_404
class ReportFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, query... | StarcoderdataPython |
9727215 | import numpy as np
class DeltaDist:
def __init__(self, vals):
self.val = np.max(vals)
self.b = self.val
self.a = self.val
def cdf(self, samples):
if isinstance(samples, (list, np.ndarray)):
return [1.0 if self.val <= k else 0.0 for k in samples]
else:
... | StarcoderdataPython |
6680045 | from tkinter import *
pencere = Tk()
def fonksiyon():
print("Test")
etiket = Label(pencere, text="<NAME>")
etiket.pack()
buton = Button(pencere, text="Butona Tıkla!", command=fonksiyon)
buton.pack()
pencere.mainloop() | StarcoderdataPython |
6613744 | from pydantic import BaseModel
from tracardi.domain.entity import Entity
class PushOverAuth(BaseModel):
token: str
user: str
class PushOverConfiguration(BaseModel):
source: Entity
message: str
| StarcoderdataPython |
284218 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from ftplib import FTP
import os
import sys
import time
import socket
class MyFTP:
def __init__(self, host, port=21):
""" 初始化 FTP 客户端
参数:
host:ip地址
port:端口号
"""
# print("__init__()---> hos... | StarcoderdataPython |
1858684 | # Copyright (c) 2005-2013 Simplistix Ltd
#
# This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details.
from AccessControl import ModuleSecurityInfo
from App.FactoryDispatcher import FactoryDispatcher
from bdb import Bdb
from cmd import Cmd... | StarcoderdataPython |
6584484 | <gh_stars>0
from hashlib import sha1
import constants
from message import Message, MessageType
"""Handles pieces, which divisions of the file being passed by the torrent."""
class PieceError(Exception):
pass
def piece_factory(total_length, piece_length, hashes):
"""Creates the piece divisions for a given ... | StarcoderdataPython |
12850031 | <filename>My Tools/Number Reverse/numberReverse.py
num = int(input("Enter a number: "))
temp = num
reverse = 0
while(temp):
reverse = (reverse * 10) + (temp % 10)
temp = int(temp / 10)
print("Reversed: " + str(reverse)) | StarcoderdataPython |
4983200 | <gh_stars>1-10
"""The tests for the climate component."""
import asyncio
import pytest
import voluptuous as vol
from homeassistant.components.climate import SET_TEMPERATURE_SCHEMA
from tests.common import async_mock_service
@asyncio.coroutine
def test_set_temp_schema_no_req(hass, caplog):
"""Test the set temper... | StarcoderdataPython |
6533713 | <reponame>yaseralnajjar/hackcyprus-hitup
import datetime
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
from rest_framework import viewsets, generics, status
from rest_framework.response import Response
from . import models
from . import serializers
from rest_fram... | StarcoderdataPython |
3475478 | from django.shortcuts import render,redirect
from django.http import HttpResponse, Http404,HttpResponseRedirect
import datetime as dt
from .models import Image, PhotosLetterRecipients
from .forms import PhotosLetterForm,NewImageForm,ProfileUploadForm
from .email import send_welcome_email
from django.contrib.auth.decora... | StarcoderdataPython |
12848279 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import web
from bson.objectid import ObjectId
from config import setting
import helper
db = setting.db_web
url = ('/online/batch_job')
# - 批量处理订单
class handler:
def GET(self):
if helper.logged(helper.PRIV_USER,'BATCH_JOB'):
render = helper.create_render()
#use... | StarcoderdataPython |
353022 | from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rdynload import dlopen, dlsym, DLOpenError
from pypy.interpreter.gateway import unwrap_spec
from pypy.interpreter.error import raise_import_error
from pypy.interpreter.error import OperationError, oefmt
from pypy.module._hpy_universal import llapi... | StarcoderdataPython |
3243265 | # Generated by Django 2.1.7 on 2019-03-12 09:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizational_area', '0009_auto_20190305_1843'),
]
operations = [
migrations.AddField(
model_name='organizationalstructureoffic... | StarcoderdataPython |
4219 | <reponame>klemenkotar/dcrl<filename>projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py<gh_stars>10-100
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.imitation i... | StarcoderdataPython |
3347400 | from __future__ import division
import numpy as np
import pycuda.driver as drv
from pycuda.compiler import SourceModule
import pycuda.autoinit
kernel_code_div_eigenenergy_cuda = """
#include<stdio.h>
#include<stdlib.h>
__global__ void calc_XXVV_gpu(float *nm2v_re, float *nm2v_im, int nm2v_dim1, int nm2v_dim2,
fl... | StarcoderdataPython |
5086380 | <filename>scrapers/scrape_matrix.py
#!/usr/bin/env python3
import sys
# This file contains expectations of what data is provided by each scraper.
# It is used by the parser to verify no expected field is missing,
# which would indicate broken parser, or change to a website.
#
# It is to track and detect regressions.
... | StarcoderdataPython |
11306047 | <reponame>drewbrew/advent-of-code-2020
from typing import Deque, List, Set, Tuple
from collections import deque
TEST_INPUT = """Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10""".split(
"\n\n"
)
with open("day22.txt") as infile:
REAL_INPUT = infile.read().split("\n\n")
def build_hands(puzzle_input: List[str]) ->... | StarcoderdataPython |
1668514 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''Unit tests for shoplift.scrapers
Test the scraping APIs exposed by the different
scraping methods.
'''
import unittest
from shoplift.web import Resource
from shoplift.scrapers import *
class TestScrapers(unittest.TestCase):
def testResourceInputSupport(se... | StarcoderdataPython |
136938 | <gh_stars>0
#!/usr/bin/env python
# (C) Copyright 2016, NVIDIA CORPORATION.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without li... | StarcoderdataPython |
11348657 | import math
import torch
from torch import nn
from torch.nn import functional as F
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)
class BasicBlock(nn.Module):
expansion = 1
d... | StarcoderdataPython |
1977134 | <gh_stars>0
"""Enumerations.py: NeoPixel Indicator Module."""
from enum import Enum, auto, unique
from typing import Tuple
ColorType = Tuple[int, int, int]
class Color:
"""This is a doctring."""
# Color.BLACK is used in npin module code, and should not be modified.
BLACK = (0, 0, 0)
# WHITE, RED, ... | StarcoderdataPython |
1773925 | <filename>deferpy/defer.py<gh_stars>1-10
from functools import partial, update_wrapper
import wrapt
def defer(name='_'):
return partial(DeferDecorated, return_name=name)
class DeferDecorated():
def __init__(self, f, return_name='_'):
update_wrapper(self, f)
self.underscore = wrapt.ObjectProxy(... | StarcoderdataPython |
4859001 | <gh_stars>1-10
# 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, software
# dist... | StarcoderdataPython |
8030063 | <gh_stars>10-100
#!/usr/bin/env python
#
# Title: docker-mount.py
# Author: <NAME>
# Date: 2021-01-07
# Version: 1.0.2
#
# Purpose: Allow the mounting of the AUFS layered/union filesystem from
# a docker container to be mounted (read-only) for the purposes
# of forensic examination
#
# Copyright (c) 2016-2021... | StarcoderdataPython |
3259370 | from netaddr import *
from scapy.all import *
WPS_QUERY = {
b"\x00\x10\x18": "Broadcom", # Broadcom */
b"\x00\x03\x7f": "AtherosC", # Atheros Communications */
b"\x00\x0c\x43": "RalinkTe", # Ralink Technology, Corp. */
b"\x00\x17\xa5": "RalinkTe", # Ralink Technology Corp */
b"\x00\xe0\x4c": "RealtekS", # R... | StarcoderdataPython |
6635446 | <filename>pyzoo/zoo/automl/model/VanillaLSTM.py
#
# Copyright 2018 Analytics Zoo 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
#
... | StarcoderdataPython |
1601352 | MOUNT_JS = \
"""
if (typeof {var}.React === 'undefined') throw new Error('Cannot find `React` variable. Have you added an object to your JS export which points to React?');
if (typeof {var}.router === 'undefined') throw new Error('Cannot find `router` variable. Have you added an object to your JS export which points to... | StarcoderdataPython |
6646593 | <filename>pyserverlessdb/__main__.py
from pyserverlessdb.db import DB
import json
import textwrap
BANNER = textwrap.dedent('''
+==============================================+
| ╔═╗┬ ┬╔═╗┌─┐┬─┐┬ ┬┌─┐┬─┐┬ ┌─┐┌─┐┌─┐╔╦╗╔╗ |
| ╠═╝└┬┘╚═╗├┤ ├┬┘└┐┌┘├┤ ├┬┘│ ├┤ └─┐└─┐ ║║╠╩╗ |
| ╩ ┴ ╚═╝└─┘┴└─ └┘ └─┘┴└─┴─┘└─┘└─┘└─┘═╩╝... | StarcoderdataPython |
3392996 | <reponame>CarbonDDR/al-go-rithms
def squareRoot(n):
x = n
y = 1
e = 0.000001
while (x - y > e):
x = (x + y) / 2
y = n/x
return x
print(squareRoot(50)) | StarcoderdataPython |
6635213 | <reponame>gerryjenkinslb/cs22-slides-and-py-files
import turtle
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
size = 300
myWin.setup(width=size, height=size, startx=30, starty=30)
myTurtle.speed(10) # speed from 1 to 10
def drawSpiral(myTurtle, lineLen):
if lineLen > 0:
myTurtle.forward(lineLen)
... | StarcoderdataPython |
4921156 | #!/usr/bin/env python
from datetime import date, time
from sagescrape.dpw.timemanagement import TimeManagement
if __name__ == "__main__":
# datetime.time() gives the current time
my_enter = time(9,23)
my_exit = time(17,42)
tm = TimeManagement()
tm.launch()
tm.fill_times(date.today(), my_enter... | StarcoderdataPython |
3404743 | <filename>app.py
from datetime import datetime
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'this is secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:/... | StarcoderdataPython |
3353012 | <filename>scripts/prepare_megadepth_valid_list.py
import os
import json
import tables
from tqdm import tqdm
import numpy as np
def read_all_imgs(base_dir):
all_imgs = []
for cur, dirs, files in os.walk(base_dir):
if 'imgs' in cur:
all_imgs += [os.path.join(cur, f) for f in files]
all_... | StarcoderdataPython |
8186339 | # -*- coding: utf-8 -*-
###
# (C) Copyright [2019] Hewlett Packard Enterprise Development LP
#
# 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
#... | StarcoderdataPython |
127291 | import gym
from gym.wrappers import TimeLimit
env = TimeLimit(gym.make('gym_custom:pomdp-mountain-car-episodic-easy-v0'), max_episode_steps=15)
print(env.observation_space.shape)
print(env.action_space.shape)
print(env.action_space.high)
rewards = []
for i in range(1):
state = env.reset()
done = False
ep... | StarcoderdataPython |
11357496 | name = input("Enter your name: ")
age = input("Enter your age: ")
print("User name is", name, "and your age is",age)
#other example:
print("\t Calculate average")
num1 = int(input("Enter the first number "))
num2 = int(input("Enter the second number "))
average = (num1 + num2) / 2
print("Average is =", average) | StarcoderdataPython |
11230423 | # Copyright (c) 2012 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | StarcoderdataPython |
5119115 | import numpy as np
import sys
import numpy as np
from numpy import float32, int32, uint8, dtype, genfromtxt
N = len( sys.argv )
direction = sys.argv[ 1 ]
cx = float(sys.argv[ 2 ])
cx = float(sys.argv[ 2 ])
cy = float(sys.argv[ 3 ])
cz = float(sys.argv[ 4 ])
t=np.array([[1.0,0.0,0.0,cx],[0.0,1.0,0.0,cy],[0.0,0.0,1.0... | StarcoderdataPython |
3599078 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 11:54:58 2019
@author: <NAME>
If you are using free search api then it only has access to 7 days old data so you might get nothing on older tweets
But using this method you can make a better reply network
"""
import tweepy
from tweepy import ... | StarcoderdataPython |
389875 | <reponame>amirhossein-bayati/pre-processing-dibets-dataset<filename>Final.py
# Import Libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
from fitter import Fitter, get_common_distributions
# Read File Function
def read_file(name):
data = pd.read_excel(name)
return dat... | StarcoderdataPython |
1762337 | from surveytoolbox.config import EASTING, NORTHING, ELEVATION, BEARING
# Import functions
from surveytoolbox.SurveyPoint import NewSurveyPoint
from surveytoolbox.bdc import bearing_distance_from_coordinates
from surveytoolbox.fmt_dms import format_as_dms
point_1 = NewSurveyPoint("JRR")
point_2 = NewSurveyPoint("JayA... | StarcoderdataPython |
1911348 | <reponame>SimenKH/DataDrivenModelling<filename>core/__init__.py
# this lstm core module implementation provides an implementation
# of time series prediction using a lstm approach. It is provided
# as is with no warranties or support.
__author__ = "<NAME>"
__altered_by___="<NAME>"
__copyright__ = "<NAME> 2018"
__versi... | StarcoderdataPython |
14298 | """
Entry point for the CLI
"""
import logging
import click
from samcli import __version__
from .options import debug_option
from .context import Context
from .command import BaseCommand
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %... | StarcoderdataPython |
64391 | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.modules.admin.views import WPAdmin
from indico.util.i... | StarcoderdataPython |
12860463 | from django.apps import AppConfig
class ConnectConfig(AppConfig):
name = 'Connect'
| StarcoderdataPython |
6415686 | # -*- coding: utf-8 -*-
from mimes.image import IMAGE_MIMES
from mimes.audio import AUDIO_MIMES
from mimes.video import VIDEO_MIMES
| StarcoderdataPython |
11221190 | # coding: utf-8
from abc import ABCMeta, abstractmethod
##################################################
# 学習・評価・予測 実行クラスの基底クラス
##################################################
class AbsRunner(metaclass=ABCMeta):
"""学習・評価・予測 実行クラス
Attributes:
run_name (string) : ランの名称
model (Abs... | StarcoderdataPython |
6563570 | <reponame>JordanMilne/Redhawk<filename>redhawk/test/test_common_xml_writer.py<gh_stars>0
#!/usr/bin/env python
import redhawk.common.writers.xml_writer as X
from . import common_test_utils as T
import nose.tools
import random
import itertools
import tempfile
import os
class TestXMLWriter:
def __init__(self):
... | StarcoderdataPython |
165658 | from services.recommendation import Recommendation
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log = logging.getLogger(__name__)
def start_recommendation(elk_rec=False, **kwargs):
"""This f... | StarcoderdataPython |
6490957 | class Solution:
def trap(self, height: list) -> int:
left_to_right = [0 for _ in range(len(height))]
right_to_left = [0 for _ in range(len(height))]
max_value = 0
for i in range(len(height)):
max_value = max((max_value, height[i]))
left_to_right[i] = ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.