id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1665298 | <filename>InstagramBotComment/bot.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random
class InstagramBot:
def __init__(self, username, password):
# ------------------------
# Inicialização do firefox
# ------------------------
... | StarcoderdataPython |
1612697 | from unittest import TestCase
import unittest
import pkgutil
from os import walk
from os import path
class TestPackage(TestCase):
def test_import_ez_1(self):
import ezyrb as ez
fh = ez.filehandler.FileHandler('inexistent.vtk')
def test_import_ez_2(self):
import ezyrb as ez
mh ... | StarcoderdataPython |
9658301 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyenhancer",
version="1.0dev1",
author="<NAME>",
author_email="<EMAIL>",
description="A tiny NumPy-based library for image color enhancement",
long_description=long_description,
lo... | StarcoderdataPython |
8309 | <filename>SelfTests.py
import os
import unittest
from Logger import Logger
class TestLogger(unittest.TestCase):
def test_file_handling(self):
testLog = Logger("testLog")
## Check if program can create and open file
self.assertTrue(testLog.opened)
returns = testLog.close()
##... | StarcoderdataPython |
9614161 | #script to find three letter words which have the same two last letters
fp = open('C:/Users/dennis/Desktop/test2.txt', 'r')
words = [line.rstrip() for line in fp.readlines() if len(line) > 2 and line[1] == line[2]]
print str(len(words))+ " results"
for w in words :
print w
| StarcoderdataPython |
11277256 | <filename>software/python/basics/L1_motors.py
# This example drives the right and left motors.
# Intended for Beaglebone Blue hardware.
# This example uses rcpy library. Documentation: guitar.ucsd.edu/rcpy/rcpy.pdf
# Import external libraries
import rcpy
import rcpy.motor as motor
import time ... | StarcoderdataPython |
63562 | <reponame>deepparrot/vision
import PIL
import torch
import torchvision
import tqdm
from torchbench.image_classification import ImageNet
import torchvision.transforms as transforms
import PIL
import torchvision.models as models
# DEEP RESIDUAL LEARNING
# Define the transforms need to convert ImageNet data to expecte... | StarcoderdataPython |
6510938 | <filename>gensim2/pearson.py
"""
@Project : DuReader
@Module : pearson.py
@Author : Deco [<EMAIL>]
@Created : 5/17/18 10:25 AM
@Desc :
"""
import os
import numpy as np
import pandas
import scipy.stats
import tensorflow as tf
def load_sts_dataset(filename):
# Loads a subset of the STS dataset into... | StarcoderdataPython |
330068 | #!/usr/local/bin/python3
import os
import logging
import json
import time
import signal
from pprint import pformat
from http import client
from urllib.parse import urlparse
from pddns import providers
from pddns.pddns import get_ip
CACHE_PATH = os.getenv('CACHE_PATH', '/var/lib/dyndns.cache')
CONSOLE_AUTH_TOKEN = o... | StarcoderdataPython |
3523398 | """ UI Controller interaction between the UI and the core """
import numpy as np
from PyQt5.QtCore import pyqtSignal, QThread, pyqtSlot
from torpido.controller import Controller as MainController
class Controller(QThread):
"""
Middleware between the UI and the main core, all interactions reside here. with s... | StarcoderdataPython |
1751131 | <filename>trainer/show.py
import matplotlib.pyplot as plt
#-------Immagini di esempio---------------#
def show_data(X_train,Y_train,datagen):
plt.figure(figsize=(15,6))
for i in range(40):
plt.subplot(4, 10, i+1)
X_train2, Y_train2 = datagen.flow(X_train,Y_train).next()
plt.imshow(X_train2[0].reshap... | StarcoderdataPython |
296791 | import forum
from forum.tests.auth import *
from forum.tests.models import * | StarcoderdataPython |
5111615 | <filename>RobustART/metrics/imageneto_evaluator.py
import json
import yaml
import numpy as np
from .base_evaluator import Evaluator, Metric
import RobustART.metrics.calibration_tools as calibration_tools
class ImageNetOEvaluator(Evaluator):
def __init__(self):
super(ImageNetOEvaluator, self).__init__()
... | StarcoderdataPython |
11268421 | <reponame>labomics/MetaLogo<gh_stars>1-10
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_bio as dashbio
from dash.dependencies import Input, Output, State
from dash.exceptions import Pr... | StarcoderdataPython |
208247 | <filename>release/stubs/System/ComponentModel/Design/Serialization.py
# encoding: utf-8
# module System.ComponentModel.Design.Serialization calls itself Serialization
# from System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
# by generator 1.145
""" NamespaceTracker represent a CLS namespace.... | StarcoderdataPython |
3324671 | <reponame>jameshensman/deepGPy
# Copyright <NAME> and <NAME> 2014
# Licensed under the GNU GPL version 3.0
import numpy as np
from scipy import weave
try:
from scipy.linalg.lapack import dpotri
except:
from scipy import linalg
dpotri = linalg.lapack.clapack.dpotri
import GPy
def safe_root(N):
i = np.... | StarcoderdataPython |
54521 | class RobotPlayer(object):
def __init__(self, rc):
self.rc = rc
def run(self):
while True:
print 'DO RE ME'
self.rc.yield_execution()
| StarcoderdataPython |
9662487 | import torch
from pepper_variant.modules.python.models.simple_model import TransducerGRU
class ModelHandler:
@staticmethod
def save_checkpoint(state, filename):
torch.save(state, filename)
@staticmethod
def get_new_gru_model(image_features, gru_layers, hidden_size, num_classes, num_classes_ty... | StarcoderdataPython |
1952941 | # Copyright 2013 IBM Corp.
#
# 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 |
5196789 | <reponame>jkpubsrc/python-module-jk-php-version-parser<gh_stars>0
#from __future__ import annotations
import typing
import jk_typing
import jk_version
from .ComposerToken import ComposerToken
class _ComposerTokenPattern(object):
###############################################################################... | StarcoderdataPython |
3571044 | from office365.entity_collection import EntityCollection
from office365.onedrive.listitems.field_value_set import FieldValueSet
from office365.onedrive.versions.base_item_version import BaseItemVersion
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.resource_pa... | StarcoderdataPython |
8173374 | # -*- coding: utf-8 -*-
from pyecore.ecore import EClassifier, EAnnotation, EClass, EPackage, EAttribute
import pyecore.ecore as ecore
from pyecore.innerutils import ignored
from .uml import Element
UML_20_URI = "http://www.eclipse.org/uml2/2.0.0/UML"
EXTENSION_PREFIX = "base_"
def patch_ecore_metamodel():
pass... | StarcoderdataPython |
8147870 | <reponame>yandong2023/The-sword-pointing-to-offer-code<gh_stars>1-10
# -*- coding:UTF-8 -*-
import functools
# Python3.x和Python2.x对于map、reduce、filter的处理变得不同
# Python3.x中map和filter的输出是一个map型和filter型, 需要从里面取出需要的值
# Python2.x中map和filter输出的直接是一个list
# Python3.x中使用reduce需要引入functools
# 使用map把list中的int变为str
map(str, [1, 2, ... | StarcoderdataPython |
1878110 | <gh_stars>10-100
"""Miscellaneous utils."""
import os
import re
import subprocess
import signal
import fnmatch
from contextlib import contextmanager
from anytree import PreOrderIter
import numpy as np
import pandas as pd
import vtk
import psutil
from tqdm import tqdm
try:
from credentials import TNAV_LICENSE_URL
e... | StarcoderdataPython |
71760 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" ib.ext.cfg.CommissionReport -> config module for CommissionReport.java.
"""
| StarcoderdataPython |
1856229 | #!/usr/bin/python
#: ----------------------------------------------------------------------------
#: Copyright (C) 2017 Verizon. All Rights Reserved.
#: All Rights Reserved
#:
#: file: transform.py
#: details: memsql pipline transform python script
#: author: <NAME>
#: date: 04/27/2017
#:
#: Licensed under the ... | StarcoderdataPython |
6562496 | from tests.common_tests.ether import (
listening_to_node,
ether_block_number
)
def test_parity_listening_to_node(parity_settings):
listening_to_node(parity_settings)
pass
def test_parity_ether_block_number(parity_settings):
ether_block_number(parity_settings)
pass
| StarcoderdataPython |
6485481 | from datetime import datetime
from contextlib import contextmanager
from functools import wraps
from sqlalchemy import create_engine
from sqlalchemy.engine.row import Row
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, cla... | StarcoderdataPython |
3239997 | <filename>online_judge/blueprints/auth.py
import json
from flask import (render_template, Blueprint, request, session, current_app, redirect, url_for)
from online_judge.db.user import User
from online_judge.helpers.session import redirect_if_authenticated
auth = Blueprint('auth', __name__)
def validate_form():
u... | StarcoderdataPython |
9798913 | <filename>PyMOTW/source/tempfile/tempfile_TemporaryFile_binary.py
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 <NAME> All rights reserved.
#
"""
"""
#end_pymotw_header
import os
import tempfile
with tempfile.TemporaryFile() as temp:
temp.write(b'Some data')
temp.seek(0)
print(temp.rea... | StarcoderdataPython |
3458180 | from hyperopt import fmin, tpe, space_eval, hp, Trials, STATUS_OK, STATUS_FAIL
from hyperopt.pyll import stochastic, scope
from os.path import join
import os
import pandas as pd
import numpy as np
@scope.define
def round_n(x, n=3):
return np.round(x, n)
def monitor_callback(params, scores, name=''):
tmp = {'N... | StarcoderdataPython |
196543 | # NOTIFY CODE
OBSCURE_WHITESPACE = (
'\u180E' # Mongolian vowel separator
'\u200B' # zero width space
'\u200C' # zero width non-joiner
'\u200D' # zero width joiner
'\u2060' # word joiner
'\u00A0' # non breaking space
'\uFEFF' # zero width non-breaking space
)
uk_prefix = '44'
clas... | StarcoderdataPython |
9631668 | <reponame>Tanmoy741127/Intellup<gh_stars>1-10
# Generated by Django 3.2.5 on 2021-07-04 13:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('datahandler', '0004_contesthistory_points'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
9785855 | <reponame>7Rocky/plantilla-informe-LaTeX
import re
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Comment, Generic, Keyword, String, Text
__all__ = ['DockerfileLexer']
class DockerfileLexer(RegexLexer):
name = 'Dockerfile'
aliases = ['']
filenames = ['*']
# Text: black
... | StarcoderdataPython |
3372649 | <gh_stars>0
# -*- coding: utf-8 -*
from __future__ import print_function, unicode_literals, division
from eight import *
import numpy as np
def gini_coefficient(x):
"""
Return computed Gini coefficient.
See https://en.wikipedia.org/wiki/Gini_coefficient
Adapted from econpy library.
copyright: 2... | StarcoderdataPython |
5120506 | <gh_stars>1-10
"""
Common pytest configuration for the test suites
"""
import os
import sys
import pytest
from docutils.parsers.rst.states import RSTStateMachine, Struct, Inliner, state_classes
from docutils.parsers.rst.languages import en
from docutils.statemachine import StringList
from docutils.utils import new_d... | StarcoderdataPython |
11316776 | <filename>tests/line_break_test.py
from unicodedata_reader.reader import UnicodeDataReader
from unicodedata_reader import *
# This function tests reading property values using the actual data.
# Please see `entry_test.py` for tests using test data.
def test_line_break_value():
# Entries for testing, copied from:
... | StarcoderdataPython |
8045072 | <reponame>kiss2u/google-research
# coding=utf-8
# Copyright 2020 The Google Research 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.... | StarcoderdataPython |
134933 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#import tensorflow as tf
import numpy as np
import math
try:
import cPickle as pickle
except:
import pickle
import os
class BlockScramble:
def __init__( self, blockSize_filename ):
if( isinstance( blockSize_filename, str ) ):
self.load( block... | StarcoderdataPython |
60975 | <filename>application.py
# Dependencies
import argparse
import requests
from datetime import datetime
from bs4 import BeautifulSoup
# Argparse description
parser = argparse.ArgumentParser(description="Enter Ticker To Receive Prices")
parser.add_argument('ticker', type=str)
args = parser.parse_args()
ticker = args.tick... | StarcoderdataPython |
3349499 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | StarcoderdataPython |
11316550 | def metade(preco = 0):
return preco/2
def dobro(preco = 0):
return preco * 2
def aumentar(preco = 0,r = 0):
return preco * (100 + r)/100
def diminuir(preco = 0,r = 0):
return preco * (100 - r)/100
def moeda(preco = 0, moeda = 'R$'):
return (f'{moeda}{preco:.2f}'.replace('.',','))
| StarcoderdataPython |
175344 | <filename>practice_problems/prog1_vi.py
#!/usr/bin/env python3
#
# Author: <NAME>
# Email: <EMAIL>
#
# Script to Program to find Sum, Diff, Prod, Avg, Div
num1 = input("Enter the first Number: ")
num2 = input("Enter the second Number: ")
# Check if the user has entered the number itself
try:
# Convert the numbers... | StarcoderdataPython |
1908402 | # coding: utf-8
import re
import datetime
def money2float(money):
# Remove comma(,)
money = money.replace(',', '')
g = re.match('([0-9\.]+)', money)
if not g:
return money
num = float(g.group(1))
pos = 0
while True:
pos = money.find('万', pos+1)
if pos != -1:
... | StarcoderdataPython |
6559131 |
import os, fnmatch, string
from . import iterutils, model as flmd
from .source import Source, SourceFile
import anyconfig
from collections import OrderedDict
DEFAULT_EXCLUDE_PATTERNS = ['*.tar','*.jar','*.zip','*.gz','*.swp','node_modules','target','.idea','*.hide','*save']
DEFAULT_FILE_PATTERNS = ['*.yml','*cfg','*... | StarcoderdataPython |
380324 | <filename>setup.py
from setuptools import setup
setup(
name='Trading-algorithm',
version='1.0.0',
packages=[''],
url='www.linkedin.com/in/luca-pedersoli-820009202',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='A trading algorithm that helps the trader to predict ... | StarcoderdataPython |
4825143 | <gh_stars>10-100
'''
Mixin for publishing messages to a topic's listeners. This will be
mixed into topicobj.Topic so that a user can use a Topic object to
send a message to the topic's listeners via a publish() method.
Note that it is important that the PublisherMixin NOT modify any
state data during message sending, ... | StarcoderdataPython |
11273382 | # Enter your code for "Degree Distribution" here.
import csv
degrees = []
students = []
for l in csv.DictReader(open("degrees.csv")):
degrees.append(l)
for l in csv.DictReader(open("students.csv")):
students.append(l)
students = sorted(students, key=lambda x: float(x["score"]))
students.reverse()
print(st... | StarcoderdataPython |
286317 | <gh_stars>0
from os.path import join, abspath, relpath, isdir
from os import mkdir, chmod, pardir
import shutil
from glob import glob
import pickle
import numpy as np
from time import time
from datetime import datetime
from ..simulation.environment import ConditionSimulation
class Batch:
"""
Class defines a ... | StarcoderdataPython |
6602684 | <reponame>glwhart/autoGR
import os
for i in list(range(50,1001,50)):
with open("struct_enum.in","w+") as f:
f.write("System \n")
f.write("bulk \n")
f.write("1 0 0 \n")
f.write("0 1 0 \n")
f.write("0 0 2 \n")
f.write("2 \n")
f.write("1 \n")
f.write("0.... | StarcoderdataPython |
1777997 | # Copyright 2017 Google Inc. 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 law or a... | StarcoderdataPython |
3357915 | <gh_stars>0
from IRCParser import parseIRC
import json
import pprint
pp = pprint.PrettyPrinter(indent=4, compact=False, depth=100000)
with open("src/parseTests.json", "r") as f:
tests = json.load(f)
# yes i know its scuffed idc :)
for test in tests:
# get expected values & print them before calculating real ... | StarcoderdataPython |
3481969 | #!/usr/bin/env python
import codecs
import os
import re
import xml
import xml.sax.saxutils as saxutils
from lib.core.common import getUnicode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import SqlmapFilePathException
from lib.core.settings impo... | StarcoderdataPython |
11336688 | from django.contrib import admin
# from .models import related models
from .models import *
# Register your models here.
# CarModelInline class
class CarModelInline(admin.StackedInline):
model = CarModel
extra = 5
# CarMakeAdmin class with CarModelInline
class CarMakeAdmin(admin.ModelAdmin):
inlines = [C... | StarcoderdataPython |
6508961 | <reponame>Mstoned/Data-Structures
# python3
class HeapBuilder:
def __init__(self):
self._swaps = [] #array of tuples or arrays
self._data = []
def ReadData(self):
n = int(input())
self._data = [int(s) for s in input().split()]
assert n == len(self._data)
def WriteR... | StarcoderdataPython |
267463 | """ ImageNet Validation Script
Hacked together by / Copyright 2020 <NAME> (https://github.com/rwightman)
"""
import time
import argparse
import fnmatch
import jax
from absl import logging
import objax
import jeffnet.data.tf_imagenet_data as imagenet_data
from jeffnet.common import correct_topk, AverageMeter, get_mode... | StarcoderdataPython |
1997751 | <reponame>maeotaku/leaf_recognition_sdk<filename>src/Features/Texture.py
import cv2
from mahotas.features import lbp
from ImageCoreManipulation import *
class Texture(object):
def __init__(self, img):
self.img = img#threadsHolding(img)
#self.pixels = pixels
print("Extracting LBP...")
... | StarcoderdataPython |
38191 | <reponame>rmomizo/Ubiqu-Ity
import copy
from unittest import TestCase
import TestResults
__author__ = 'zthomae'
class TestArgumentParser(TestCase):
def setUp(self):
self.parser = TestResults.make_parser()
def test_type_should_not_be_optional(self):
try:
TestResults.parse_args(sel... | StarcoderdataPython |
3518375 | #!/usr/bin/python
""" Autor: <NAME>
Universidad Icesi 2017
Proyecto de grado: Sistema open source para la deteccion paginas web maliciosas
Este script tiene como funcion la abstracion de caracteristicas
de un trafico de red obtenido del conjunto de urls.
Toda las caracteristicas obtenidas para el tr... | StarcoderdataPython |
1806152 | <filename>tests/test_choices.py
import valleydeight as vd
import pytest
def test_choice_static():
choice_t = vd.Choice("one", 4, True)
assert choice_t("one") == "one"
assert choice_t(True) is True
assert choice_t(4) == 4
with pytest.raises(vd.ValidatorException):
choice_t(8)
with pyte... | StarcoderdataPython |
5066393 | from copy import deepcopy
import random
from abc import abstractmethod
class abstract_cascade:
def __init__(self, G, itterations=10000):
self.G = deepcopy(G)
self.cascase_id = 1
self.step = 1
self.d = {}
self.activated = ""
self.numberOfNodes = len(self.G.nodes())
... | StarcoderdataPython |
1791107 | """Data Provider implementation module for constructing data based on standard stock indicators
The data provider in this module is not indented to be instantiated outside of this module. Instead, upon the importing
of this module, the provider will create an instance of itself and register itself with the global D... | StarcoderdataPython |
3250371 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
print re.match('www', 'www.runoob.com').span()
print re.match('com', 'www.runoob.com')
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M | re.I)
if matchObj:
print "matchObj.group(): ", matchObj.group()
print "matchObj... | StarcoderdataPython |
3237354 | # -*- coding: utf-8 -*-
"""Main module."""
def LargeIfFactual(s):
```returns the word big if the input says the word true
```
if "true" in s:
return "big"
else:
return "small"
a="true"
b="false"
c="anything else"
x=LargeIfFactual(a)
y=LargeIfFactual(b)
z=LargeIfFactual(c)
| StarcoderdataPython |
5003027 | import sys
import pyaudio
from struct import unpack
import numpy as np
# from Adafruit_LED_Backpack import BicolorMatrix8x8
# Create BicolorMatrix display instance with default settings
# display = BicolorMatrix8x8.BicolorMatrix8x8()
# display.begin()
# display.clear()
# display.set_brightness(7)
spectrum = [1,1,1,3... | StarcoderdataPython |
3478673 | from NewsSummaryDataset import NewsSummaryDataset
import pandas as pd
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from transformers import (
T5TokenizerFast as T5Tokenizer
)
# News Summary Dataset Module containing the main
# train, test and validation dataloaders to be used
# in model f... | StarcoderdataPython |
3359234 | from nbox import plug, PRETRAINED_MODELS
import nbox
import torch
import numpy as np
class DoubleInSingleOut(torch.nn.Module):
def __init__(self):
super().__init__()
self.f1 = torch.nn.Linear(2, 4)
self.f2 = torch.nn.Linear(2, 4)
self.logit_scale = torch.nn.Parameter(torch.ones([]... | StarcoderdataPython |
1960675 | <reponame>lucaparisi91/qmc4<gh_stars>0
import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns
from scipy.optimize import curve_fit
import numpy as np
if __name__ == "__main__":
datas=pd.read_csv("2bDistancesTimings_2.dat",sep=" ",index_col=False)
print(datas)
cutOff=0;
for... | StarcoderdataPython |
1738509 | <reponame>czyczyyzc/Compressed_Self-Attention
from __future__ import absolute_import
from .duke import Duke
from .market import Market
from .cuhk import CUHK
__factory = {
'market': Market,
'duke': Duke,
"cuhk": CUHK,
}
def names():
return sorted(__factory.keys())
def create(name, root, *args, **kw... | StarcoderdataPython |
8169362 | """Test Node Child Base model."""
import pytest
from openzwavemqtt.models.node import OZWNode
from openzwavemqtt.models.node_child_base import OZWNodeChildBase
class MockDescendant(OZWNodeChildBase):
"""Mock a descendant."""
EVENT_CHANGED = "mock-changed"
def test_node():
"""Test a node."""
node =... | StarcoderdataPython |
8036081 | import io
from typing import Optional
import pytest
from helpers import unhex
from unblob.file_utils import round_up
from unblob.handlers.filesystem.squashfs import (
SquashFSv3Handler,
SquashFSv4BEHandler,
SquashFSv4LEHandler,
)
SQUASHFS_V4_LE_NO_PAD_CONTENTS = unhex(
"""\
00000000 68 73 71 73 05 0... | StarcoderdataPython |
4886861 | <filename>examples/blender/eventTiming.py
#!/usr/bin/env python3
"""
eventTiming helps when timing events
"""
# standard library modules
import datetime
class eventTiming(object):
'''stores name and beginning and ending of an arbitrary "event"'''
def __init__(self, eventName, startDateTime=None, endDateTime=N... | StarcoderdataPython |
6634237 | from .child import Child
from typing import Dict, Optional
from config import Config
from os.path import join, abspath, exists
from os import remove
class Action(Child):
def __init__(self, service, type: str, vnfd, token):
super().__init__(f"{service.id}_{type}")
self.service = service # type: "N... | StarcoderdataPython |
3249720 | from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... | StarcoderdataPython |
12820972 | <filename>NRUtil/constants.py<gh_stars>0
""" Declaring constants used by the archive script. """
import os
import dotenv
import sys
envPath = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(envPath):
print("loading dot env...")
dotenv.load_dotenv()
OBJ_STORE_BUCKET = os.environ['OBJ_STORE_B... | StarcoderdataPython |
6685736 | <filename>server/app/request.py
from flask import jsonify, abort
def api_error(code, message=""):
resp = jsonify({"message": message})
resp.status_code = code
return abort(resp)
def bad_credentials():
return api_error(403, "Wrong username or password")
def get_json_key(data, key):
if not isins... | StarcoderdataPython |
1926233 | # Copyright 2022 The Symanto Research Team 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... | StarcoderdataPython |
312883 | #Calcula o volume de uma fossa sépica para estabelecimentos residenciais em conformidade com a NBR 7229/1993
'''
Entre com os dados da Fossa Séptica
'''
print(' Dimensionamento de uma Fossa Séptica pra estabelecimentos residenciais em conformidade com a NBR 7229/1993:')
N = 1
while N != 0:
N = int(input('Digite... | StarcoderdataPython |
3440843 | """Weather plugin for the VO simulations."""
# ----------------------------------------------------------------------------!
import openclsim.model as model
# ----------------------------------------------------------------------------!
class HasDelayPlugin:
"""Mixin forActivity to initialize WeatherPluginActivit... | StarcoderdataPython |
381624 | <filename>cells/TC_mdPul.py
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 08:38:28 2019
@author: <NAME>
"""
from brian2 import *
defaultclock.dt = 0.01*ms
prefs.codegen.target = 'numpy'
eq_TC_mdPul='''
dV/dt=(-INa-IK-IL-IKL-IH-ITLT-J-Isyn-Iapp-Itheta)/Cm_TC : volt
J : amp * meter ** -2
Ith... | StarcoderdataPython |
4965202 | <gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
def exp_moving_average(values, window):
""" Numpy implementation of EMA
"""
if window >= len(values):
sma = np.mean(np.asarray(values))
a = [sma] * len(values)
else:
weights = np.exp(np.linspace(-1., 0., window))
... | StarcoderdataPython |
3238131 | print('''Existe uma sequência que se repete indefinidamente com as figuras
de um triângulo, árvore, losângulo, espada, coração e um quadrado, nesse padrão.
Ou seja, há um padrão de repetição das 6 primeiras figuras.\n''')
n = int(input("Digite o número de elmentos que a sequência vai ter.\n"))
padroes = n / 6
resto = ... | StarcoderdataPython |
6583277 | # This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2020 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if yo... | StarcoderdataPython |
11284234 | import os
import argparse
import random
from statistics import mean
import xml.etree.ElementTree as ET
random.seed(42)
#
# config
#
parser = argparse.ArgumentParser()
parser.add_argument('--train-dir', action='store', dest='train_dir',
help='train directory location', required=True)
... | StarcoderdataPython |
8075570 | <gh_stars>10-100
# Schema Version 3
# Canvas course and student IDs are now cached
V3 = {
"$schema": "http://json-schema.org/schema#",
"type": "object",
"properties": {
# Config version
"version": {
"type": "integer",
},
# Backend type (gitlab / mock)
"... | StarcoderdataPython |
4920661 | <filename>entities/health.py
import pygame
from random import randint
gros = 4
long = 8
class Health():
def __init__(self, w, h, min_life, max_life, screen):
self.x = randint(0 + w, screen.get_width() - w)
self.y = randint(0 + h, screen.get_height() - h)
self.w = w
self.h = h
... | StarcoderdataPython |
6457917 | <gh_stars>10-100
"""Installation file for ansys-dpf-post module"""
import os
from io import open as io_open
from setuptools import setup
install_requires = ["ansys.dpf.core>=0.3.0", "scooby"]
# Get version from version info
filepath = os.path.dirname(__file__)
__version__ = None
version_file = os.path.join(filepath,... | StarcoderdataPython |
9707675 | <reponame>wudinaonao/FlaskMark12306Captcha<filename>constants/ImagePositionCoordinates.py<gh_stars>1-10
IMAGE_POSITION_COORDINATES = [
[(5, 12 + 30), (72, 79 + 30)],
[(5, 84 + 30), (72, 151 + 30)],
[(77, 12 + 30), (142, 79 + 30)],
[(77, 84 + 30), (142, 151 + 30)],
[(147, 12 + 30), (214, 79 + 30)],
... | StarcoderdataPython |
11354365 | <filename>setup.py
import os.path
import re
import setuptools
def find_version(filename):
with open(filename) as f:
text = f.read()
match = re.search(r"^_version_str = '(.*)'$", text, re.MULTILINE)
if not match:
raise RuntimeError('cannot find version')
return match.group(1)
tld = os... | StarcoderdataPython |
11305839 | <filename>bot/service/network_service.py
import requests
def is_syncing(node_ip):
response = requests.get(f'{node_ip}/syncing')
if not response.ok:
raise ConnectionError
syncing = response.json().get('syncing', False)
if syncing is bool and syncing:
return True
else:
ret... | StarcoderdataPython |
6684149 | from django.shortcuts import redirect, render
from django.views.generic import TemplateView, ListView
from django.db.models import Q
from jobs.models import Job
from events.models import Event
from meetups.models import Meetup
from communities.models import Community
class HomePageView(TemplateView):
template_nam... | StarcoderdataPython |
4834954 | from prettytable import PrettyTable
def is_symmetric (A, n):
for i in range(n):
for j in range(i-1):
if A[i][j] != A[j][i]:
return False
return True
def LU (A, n):
for k in range(n):
for i in range(k+1, n):
if A[k][k] == 0:
print("ER... | StarcoderdataPython |
1658511 | """
Migration script to add the post_job_action_association table.
"""
import logging
from sqlalchemy import (
Column,
ForeignKey,
Integer,
MetaData,
Table,
)
from galaxy.model.migrate.versions.util import (
create_table,
drop_table,
)
log = logging.getLogger(__name__)
metadata = MetaDat... | StarcoderdataPython |
6620186 | <filename>Linux-Operation0605/app/core/templatetags/tags.py<gh_stars>0
# coding=utf-8
import datetime
from django import template
from app.core.models import Domain
from app.utils.domain_session import get_domainid_bysession
register = template.Library()
@register.filter
def int2datetime(t):
try:
return ... | StarcoderdataPython |
3465285 | <reponame>MarvinT/ephys-analysis
from __future__ import absolute_import
import h5py
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from . import core
def kwik2rigid_pandas(block_path):
'''
loads data in a manner that is very useful for acute experiments
Param... | StarcoderdataPython |
1639364 |
from requests.exceptions import ConnectionError
from coreapi import exceptions, utils
from coreapi.transports.base import BaseTransport
from coreapi.document import Document, Error
from coreapi.transports.http import (
BlockAll,
_get_params,
_get_url,
_get_headers,
_decode_result,
_handle_inpla... | StarcoderdataPython |
5177126 | from unittest import TestCase, main
from project.folder_reader import KillerFolder, KillerFile, FolderStore, RootDoesNotExist
class KillerFolderTestCase(TestCase):
def setUp(self):
self.folder = KillerFolder('king', 'C:\\user\\main')
self.folder_1 = KillerFolder('queen', 'C:\\user\\main\\queen', ... | StarcoderdataPython |
8164356 | <gh_stars>0
"""Helper classes and functions to wrap the zeroconf-library"""
try:
import zeroconf as zc
zeroConfOK=True
except ImportError:
zeroConfOK=False
from PyFoam.Infrastructure.Logging import foamLogger
from PyFoam.Error import warning
from PyFoam.ThirdParty.six import print_,b
from PyFoam.Infrastru... | StarcoderdataPython |
6507984 | #!/usr/bin/env python
# wfrun.pi.py - Sample script for WFRUN. It runs "pi" (calculates pi)
# many times. This is the master part WFRUN. It is interpreted by a
# Python interpreter invoked by "wfrun", and the interpreter marker at
# the first line (#!) is meaningless. For running this script, see
# the comment in ... | StarcoderdataPython |
1621794 | <filename>setup.py<gh_stars>0
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="ietfdata",
version="0.5.0",
author="<NAME>",
author_email="<EMAIL>",
description="Access the IETF Data Tracker and RFC Index",
long_description=long_descr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.