id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1678695 | <reponame>delapiero/pyads
# reserved - 2 bytes - 0
# length - 4 bytes - od ams
# ams_target_adr - 6 bytes
# ams_target_port - 2 bytes
# ams_source_adr - 6 bytes
# ams_source_port - 2 bytes
# command - 2 bytes:
# 0 - invalid
# 1 - read device info
# 2 - read
# 3 - write
# 4 - read state
# 5 - wr... | StarcoderdataPython |
179472 | # Copyright 2017 FUJITSU LIMITED
#
# 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 writ... | StarcoderdataPython |
4826576 | import requests
from consome_api import BuscaEndereco
cep = "02410010"
objeto_cep = BuscaEndereco(cep)
print(objeto_cep.formata_cep())
| StarcoderdataPython |
194030 | import os
from string import Template
from .base import GnuRecipe
class PaleMoonRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(PaleMoonRecipe, self).__init__(*args, **kwargs)
self.sha256 = 'b2ad32daf6b83474a77f9c56e18a0e92' \
'82bf2af34a8d9ace581f0583545fd375'
... | StarcoderdataPython |
1653598 | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(Grap... | StarcoderdataPython |
152919 | # Roll no.:
# Registration no.:
# Evaluate fibonacci numbers and calculate the limit of the numbers.
def fibo(n):
"""Returns nth fibonacci number."""
a, b = 0, 1
for i in range(1, n):
a, b = b, a+b
return b
def calc_ratio():
"""Calculates the limit of the ratio of fibonacci numbers correct to 4th decimal place... | StarcoderdataPython |
129008 | <reponame>Rachneet/BERT-MLM
from transformers import (BertTokenizer, BertForMaskedLM, Trainer, TrainingArguments,
DataCollatorForLanguageModeling, pipeline)
import torch
import numpy as np
import math
import collections
import urllib
import itertools
from torch.utils.data import DataLoader
imp... | StarcoderdataPython |
3384090 | <filename>model.py
import os
import cv2
import csv
import numpy as np
from PIL import Image
#from numpy.testing import verbose
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import math
# path to generated images
data_path = '../data/'
# csv file generated
csv_file = 'driving_lo... | StarcoderdataPython |
152004 | from datetime import datetime
from pretty_timedelta import pretty_timedelta
__author__ = 'gautam'
def pretty_time(datetime_value):
now = datetime.now()
delta = datetime_value - now
return pretty_timedelta(delta)
| StarcoderdataPython |
85438 | <filename>cgi-bin/request/isusm.py<gh_stars>1-10
#!/usr/bin/env python
"""Download interface for ISU-SM data."""
import cgi
import datetime
import sys
import os
from io import StringIO
import pandas as pd
import psycopg2.extras
from pyiem.datatypes import temperature, distance
from pyiem.util import get_dbconn, ssw
... | StarcoderdataPython |
134382 | <reponame>cosmic119/DiscoGAN
# -*- coding:utf8 -*-
# File : helper.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 12/31/16
#
# This file is part of TensorArtist.
from ..graph.env import get_default_env, reuse_context
from ..graph.node import as_varnode, as_varnode_or_register, as_tftensor
from ...core.logger im... | StarcoderdataPython |
185158 | import numpy as np
from math import inf as infinity
import itertools
import random
import pdb
import matplotlib.pyplot as plt
class TicTacToe(object):
def __init__(self):
self.game_state = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
self.agent_state = np.zeros((3,3)) #actual agent obs... | StarcoderdataPython |
56881 | <reponame>egochao/transformer_with_einsum
"""
@author : Hyunwoong
@when : 2019-10-22
@homepage : https://github.com/gusdnd852
"""
import torch
# GPU device setting
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# model parameter setting
batch_size = 64
max_len = 256
d_model = 512
n_layers = 6... | StarcoderdataPython |
28889 | <reponame>meyskens/lookout-sdk
"""Lookout - Assisted Code Review"""
import pkg_resources
pkg_resources.declare_namespace(__name__)
| StarcoderdataPython |
3224 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
4821699 | <gh_stars>1-10
from girl.common import *
from girl.typehelpers import *
class Area(object):
@property
def offset(self):
raise NotImplementedError("Please implement the offset property")
@property
def size(self):
raise NotImplementedError("Please implement the size property")
@property
de... | StarcoderdataPython |
122152 | """
Utility function for ultisnips
"""
from typing import Any, Iterable, List
from pprint import pformat
from nayvy.function.func import get_current_func
from nayvy.importing.import_statement import ImportStatement
from nayvy.importing.utils import get_first_line_num, get_import_block_indices
from nayvy_vim_if.utils... | StarcoderdataPython |
3311790 | <gh_stars>1-10
##################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2019 #
# ADAPTED VERSION #
##################################################
import os, sys, hashlib, torch
import numpy as np
from PIL import Image
import torch.utils.data as data
fr... | StarcoderdataPython |
1606773 | <gh_stars>1-10
import os
from collections import OrderedDict
from confuse import Configuration as ConfSuper
class Configuration(ConfSuper):
def __init__(self, appname: str):
super().__init__(appname)
def _recursive_parse(self, node: OrderedDict, dynasty: list = None):
dynasty = dynasty or []... | StarcoderdataPython |
3250228 | <gh_stars>0
from django.test import TestCase
from rest_framework.test import APIClient
from django.urls import reverse
from django.contrib.auth import get_user_model
class PrivateApiTests(TestCase):
"""Holds all API Tests which will doesn't require authenticated Users"""
API_ENDPOINT_WEBSITE = reverse("webap... | StarcoderdataPython |
174900 | #!python
##############
# HOW TO RUN #
##############
# 1. Install Pytest
"pip install pytest"
# 2. Run Tests
"pytest -v test_airlines.py"
# NOTE: if "pytest" is not found, run "python -m pytest ..."
##############
import pytest
from typing import Dict, List, Any
from airlines import Airline, get_delay
try:
from... | StarcoderdataPython |
74168 | import winrm
import os
print('\n********************************\n')
print(os.environ['winrm_endpoint'])
print(os.environ['domain_username'])
print('\n********************************\n')
s = winrm.Session(os.environ['winrm_endpoint'], auth=(os.environ['domain_username'], os.environ['domain_password']), transport='nt... | StarcoderdataPython |
187001 | <reponame>xiashuqin89/bk-chatbot
"""
TencentBlueKing is pleased to support the open source community by making
蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available.
Copyright (C) 2017-2018 THL A29 Limited,
a Tencent company. All rights reserved.
Licensed under the MIT License (the "License");
you may not use this f... | StarcoderdataPython |
1689007 | from mayan.apps.documents.permissions import permission_document_view
from mayan.apps.documents.search import document_search
from mayan.apps.documents.tests.literals import DEFAULT_DOCUMENT_STUB_LABEL
from mayan.apps.documents.tests.mixins.document_mixins import DocumentTestMixin
from mayan.apps.tags.tests.mixins impo... | StarcoderdataPython |
1673415 | <gh_stars>0
import os
def main():
folder_name = "./Surgeon Tracing/"
directory_name = "C:/Users/Abdul/OneDrive - Newcastle University/Stage 3/Obsidian Vault/EEE3095-7 Individual Project and Dissertation/Tremor ML/data/" + folder_name[2:]
directory = os.fsencode(directory_name)
file = ""
filenames... | StarcoderdataPython |
1713294 | import os
import yaml
import cv2
import json
import requests
class Params :
def __init__( self, config_file ):
with open( config_file, 'r' ) as ff :
self.params = yaml.load( ff, yaml.FullLoader )
def set( self, key, value ):
self.params[key] = value
def __getattr__( self, item... | StarcoderdataPython |
3251888 | # -*- coding: utf-8 -*-
import sys
sys.path.append('.')
CODE_DIRECTORY='aws_role_credentials'
from paver.easy import task, consume_args
@task
@consume_args
def run(args):
"""Run the package's main script. All arguments are passed to it."""
# The main script expects to get the called executable's name as
... | StarcoderdataPython |
3235598 | from datetime import datetime, timedelta
from nose.tools import eq_, ok_
from mock import Mock, patch
from django.core.exceptions import ObjectDoesNotExist
import amo
import amo.tests
from addons.models import Addon
from market.models import AddonPremium, Price
from users.models import UserProfile
from devhub.model... | StarcoderdataPython |
3275701 | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def analyse(outfolder, df, feature_names):
print("Analysing data ...")
color1 = "#0F2F8C"
color2 = "#A60303"
color3 = "#AAAAAA"
# Create a plot showing attribute distributions
plt.gcf().subplots_adjust(bottom=0.25)
... | StarcoderdataPython |
84173 | import pytest
from eth_utils import ValidationError
from hypothesis import (
given,
settings,
strategies as st,
)
from trinity._utils.tree_root import Tree, RootTracker
@given(st.permutations(range(10)))
def test_tree_linking(add_order):
# node and parent id
nodes = (
('A0', '_'),
... | StarcoderdataPython |
1757590 | # pylint: disable=g-bad-file-header
# Copyright 2021 DeepMind Technologies Limited. 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/... | StarcoderdataPython |
126930 | <reponame>arcunliffe/physics_deep_learning
"""
Utility functions for training deep learning models using pytorch.
<NAME>
2020-10-18
"""
import random
def train_network(model, data, epochs, loss_function, optimizer, display_loss=True):
"""
Train a pytorch model.
Inputs:
model: torch model, e.g.,... | StarcoderdataPython |
4819112 | <reponame>ThBlitz/Medical-Diagnositcs-Tool
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home_url'),
path('about', views.about, name='about_url'),
path('run', views.run, name='run_url'),
path('real_time', views.real_time, name='real_time_url')
]
| StarcoderdataPython |
85410 | import time
from bynge import app
class AudioFileProcessor:
def __init__(self, uuid):
self.uuid = uuid
app.logger.info('processing task started')
def process(self):
app.logger.info(self.uuid)
time.sleep(10)
def store(self):
print(self.uuid)
def normalize(sel... | StarcoderdataPython |
1793185 | <reponame>olegenov/yatube
# Generated by Django 2.2.6 on 2020-09-18 14:33
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0010_profilephoto'),
]
... | StarcoderdataPython |
3395948 | <filename>src/users/views.py
from aiohttp import web
from ..auth.mixins import TokenRequiredMixin
class UsersView(TokenRequiredMixin, web.View):
"""View to get users."""
async def get(self):
"""Get list of users.
Method allows to get all users, active or inactive.
Example:
... | StarcoderdataPython |
3294811 | <filename>environments/setup.py
from setuptools import setup
setup( name="light_safety_gym", version="0.1.0", install_requires=["gym"] ) | StarcoderdataPython |
1631639 | <gh_stars>1-10
from .ce import CE, load_model, similarity, get_example, get_examples_path
from .embed_align import align
__version__ = '0.1.2' | StarcoderdataPython |
4825985 | <filename>polynomials_over_Zp.py
# -*- coding: utf-8 -*-
"""
"""
# =============================================================================
from sympy.polys import galoistools as gt
from sympy.ntheory import isprime
from sympy.polys.domains import ZZ
# ===========================================================... | StarcoderdataPython |
1796901 | <filename>books/booksdatasourcetests.py
'''
booksdatasourcetest.py
10/2/2021
<NAME>, <NAME>
Revised by <NAME>
'''
import booksdatasource
import unittest
class BooksDataSourceTester(unittest.TestCase):
def setUp(self):
self.data_source = booksdatasource.BooksDataSource('books1.csv')
... | StarcoderdataPython |
9329 | <filename>rllib/agents/ppo/tests/test_appo.py
import unittest
import ray
import ray.rllib.agents.ppo as ppo
from ray.rllib.utils.test_utils import check_compute_single_action, \
framework_iterator
class TestAPPO(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
... | StarcoderdataPython |
196219 | <filename>elasticemailbackend/backend.py
from email.mime.base import MIMEBase
from urllib3.exceptions import HTTPError
try:
import rfc822
except ImportError:
import email.utils as rfc822
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import Email... | StarcoderdataPython |
1608854 | '''
System tests for authentication functionality
'''
import pytest
from jenkinsapi.utils.requester import Requester
from six.moves.urllib.error import HTTPError
from requests import HTTPError as REQHTTPError
from jenkinsapi.jenkins import Jenkins
def test_normal_uthentication(jenkins_admin_admin):
# No problem ... | StarcoderdataPython |
3396241 | <reponame>daicang/Leetcode
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
def bisearch(left, right):
if left == right:
return left
middle = (left+right) / 2
pivot = pow(middle, 2)
... | StarcoderdataPython |
3272843 | test = { 'name': 'q2_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': ">>> # Check your column labels and spelling;\n>>> recent_poverty_total.labels==('geo', 'poverty_percent','population_total','poverty_total')\nTrue",
'hidden': False,
... | StarcoderdataPython |
3381837 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
DEFAULT_THEME = 'lumen'
# Boolean: True if you == <NAME>; False otherwise :)
FLASK_PRACTICE_ADMIN = os.getenv('true')
# Activates the cross-site request forgery prevention.
WTF_CSRF_ENABLED = True
# Used to create cr... | StarcoderdataPython |
1727323 | <reponame>vschule/adventcode
def first(str_input):
count = 0
for line in str_input.splitlines():
if isNice(line):
count += 1
return count
# A nice string is one with all of the following properties:
# It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaei... | StarcoderdataPython |
3263200 | from __future__ import absolute_import, print_function
import re
from django.db import models
from django.utils import timezone
from sentry.db.models import (
BoundedPositiveIntegerField, FlexibleForeignKey, Model, sane_repr
)
from sentry.utils.cache import memoize
_fixes_re = re.compile(r'\b(?:Fix|Fixes|Fixed|... | StarcoderdataPython |
157879 | from abc import ABC, abstractmethod
from typing import Union
import pandas as pd
from sklearn.feature_selection import VarianceThreshold
from .abstract import ReducerAbstract
class LowVariance(ReducerAbstract):
reducer: VarianceThreshold
def transform(self,
df: pd.DataFrame,
... | StarcoderdataPython |
18295 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
class MrpSubProduct(models.Model):
_name = 'mrp.subproduct'
_description = 'Byproduct'
product_id = fi... | StarcoderdataPython |
1789161 | """Main SDGym benchmarking module."""
import io
import logging
import multiprocessing as mp
import os
import types
from datetime import datetime, timedelta
import humanfriendly
import psutil
import tqdm
from sdgym.data import load_dataset
from sdgym.evaluate import compute_scores
from sdgym.results import make_leade... | StarcoderdataPython |
1674594 | <filename>tests/baggers/test_bag.py<gh_stars>1-10
import bagit
import filecmp
import os
import pytest
import tempfile
from baggins.baggers.bag import Baggee
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), '..', 'fixtures')
# extend with test subclasses, to test functionality
class SampleBaggee(Baggee):
... | StarcoderdataPython |
1761686 | def MinDivisor(n):
d = 2
while d <= n ** (1 / 2):
if n % d == 0:
return d
d += 1
return n
print(MinDivisor(int(input())))
| StarcoderdataPython |
1637957 | import asyncio
from time import time
def throttle(wait):
"""Second order decorator for rate-limiting a function within an asyncio concurrent app
- The first call will always happen *without* delay.
- Subsequent calls, within wait seconds, are dropped, even if argurments differ.
- The final call will ... | StarcoderdataPython |
191012 | <gh_stars>0
#改变Excel的样式
import openpyxl
from openpyxl.styles import Font
from openpyxl.styles import colors #如果你要用Hex,就用Color这个库
# 打算在一个wb 里面生成5个sheet,分别demo
# 新建一个WB
wb = openpyxl.Workbook()
# Font 默认的字体是Calibri
ws_name_font = "Font_Demo"
ws_font = wb.active
ws_font.title = ws_name_font
# 生成一个字体 例如 斜体24
italic24 = ... | StarcoderdataPython |
1778289 | <reponame>Darumin/arachne<filename>arachne_test/nouns_test.py
import unittest
from arachne import nouns as n
from arachne import utils as u
class NounsTestCase(unittest.TestCase):
def setUp(self) -> None:
self.doo = n.Door('doo')
self.con = n.Container('con')
self.ite = n.Item('boo')
... | StarcoderdataPython |
168413 | from output.models.nist_data.list_pkg.id.schema_instance.nistschema_sv_iv_list_id_white_space_1_xsd.nistschema_sv_iv_list_id_white_space_1 import (
NistschemaSvIvListIdWhiteSpace1,
Out,
)
__all__ = [
"NistschemaSvIvListIdWhiteSpace1",
"Out",
]
| StarcoderdataPython |
3234054 | <filename>appdaemon/lib/core/monitored_callback.py
import traceback
from base_automation import BaseAutomation
def monitored_callback(callback):
def inner(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception as e:
app: BaseAutomation = args[0]
... | StarcoderdataPython |
1681638 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 13:37:39 2019
@author: gsolana
https://python.swaroopch.com/modules.html
"""
class TidalGauge:
""" Module examplo
"""
__version__=0.1
def __init__(self, filepath=True):
""" Tidal Gauge data set a... | StarcoderdataPython |
3304364 | n = int(input())
l = list(map(int,input().split()))
c = {}
for i in l:
if i in c:
c[i]+=1
else:
c[i]=1
ans,anss=0,0
x = max(l)
for i in set(l):
for j in range(1,32):
a = 2**j - i
if a>x:
break
if a in c:
if i==a:
anss += c[a]*(c... | StarcoderdataPython |
3290718 | <filename>stackvm/device.py
class Device(object):
def write(self, value):
raise NotImplementedError
def read(self):
raise NotImplementedError
| StarcoderdataPython |
154848 | <reponame>nariya/pychatwork<filename>pychatwork.py
# -*- coding: utf-8 -*-
# https://github.com/nariya/pychatwork
from __future__ import print_function
import requests
class Chatwork:
def __init__(self, token):
self.token = token
self.apiurl = u'https://api.chatwork.com/v2/'
def send(self, ro... | StarcoderdataPython |
3226204 | <reponame>dimas-b/nessie
# -*- coding: utf-8 -*-
"""Use AWS4Auth and botocore to fetch credentials and sign requests."""
from botocore.credentials import get_credentials
from botocore.session import Session
from requests_aws4auth import AWS4Auth
def setup_aws_auth(region: str, profile: str = None) -> AWS4Auth:
""... | StarcoderdataPython |
3207301 | <reponame>wangvei/pydefect<filename>pydefect/core/supercell_calc_results.py
# -*- coding: utf-8 -*-
import json
from pathlib import Path
from pprint import pformat
from typing import Union, Optional
import numpy as np
from monty.json import MontyEncoder, MSONable
from monty.serialization import loadfn
from pydefect... | StarcoderdataPython |
78788 | # -*- coding: utf-8 -*-
""""
ニューラルネットワーク・サンプル
"""
import os
import sys
import numpy as np
def main():
sys.path.append(os.path.join(os.getcwd(), 'src', 'lib'))
from neuralnetwork import NeuralNetwork
import utils
seed_value = 8976
# 学習データの作成 (評価にも利用)
X_train = np.array([
... | StarcoderdataPython |
22165 | from django.contrib import admin
from .models import (Dish, Payments, Order, Delivery, OrderItem)
admin.site.register(Dish)
admin.site.register(Payments)
admin.site.register(Order)
admin.site.register(Delivery)
admin.site.register(OrderItem)
| StarcoderdataPython |
1778727 | <filename>HackerRank/Abbreviation.py
# Enter your code here. Read input from STDIN. Print output to STDOUT
q = int(raw_input())
for qq in xrange(q):
a = raw_input()
b = raw_input()
dic = {}
result = False
for i in b:
if i not in dic:
dic[i] = 0
dic[i] += 1
for i in a:... | StarcoderdataPython |
44647 | import os, sys, matplotlib
import faulthandler; faulthandler.enable()
mpl_v = 'MPL-8'
daptype = 'SPX-MILESHC-MILESHC'
os.environ['STELLARMASS_PCA_RESULTSDIR'] = '/Users/admin/sas/mangawork/manga/mangapca/zachpace/CSPs_CKC14_MaNGA_20190215-1/v2_5_3/2.3.0/results'
manga_results_basedir = os.environ['STELLARMASS_PCA_RESU... | StarcoderdataPython |
1624652 | <gh_stars>10-100
import cv2
import datetime, time
from pathlib import Path
def capture_and_save(im):
s = im.shape
# Add a timestamp
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,s[0]-10)
fontScale = 1
fontColor = (20,20,20)
lineType = 2
cv2.putText(im,datetime.datetime.n... | StarcoderdataPython |
1695764 | from .core import Ioc
from .impl import IocImpl
__all__ = [
"ioc"
]
ioc = IocImpl()
| StarcoderdataPython |
63426 | <reponame>ecosoft-odoo/mh-doodba
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
#... | StarcoderdataPython |
48082 | """
Module For the ScreenOptionsParser
"""
from conjur.version import __version__
from conjur.argument_parser.parser_utils import conjur_copyright
# pylint: disable=too-few-public-methods
class ScreenOptionsParser:
"""Partial class of the ArgParseBuilder.
This class add the ScreenOptions subparser to the ArgP... | StarcoderdataPython |
3285343 | <gh_stars>0
from flask import render_template, session, redirect
from flask_dance.contrib import azure, github
import flask_dance.contrib
from CTFd.auth import confirm, register, reset_password, login
from CTFd.models import db, Users
from CTFd.utils import get_config, set_config
from CTFd.utils.logging import log
fro... | StarcoderdataPython |
3378223 | ''' This module contains class ParamsFrame which is responsible for
all operations with parameters.
Attributes:
MAX_FILE_LBL_LENGTH (int): maximum length of the label with
file name.
TEXT_FOR_PARAMS_LBL (str): text displayed on one of the labels.
'''
import os
from tkinter import W... | StarcoderdataPython |
198541 | # coding=utf-8
# Copyright 2019 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | StarcoderdataPython |
3371911 | <filename>hooks/tests/test_integration/test_validate_django_model_field_names/samples/package_a/models.py<gh_stars>1-10
from django.db import models
from django.db.models import CharField, DateField, DateTimeField, Model
class MyDateTimeExtraField(DateTimeField):
pass
class ModelA(models.Model):
ok_date = m... | StarcoderdataPython |
187863 | import tensorflow as tf
from tensorflow.python.framework import ops
import numpy as np
import functools
from keras import backend as K
from keras.engine import Layer, InputSpec
from keras import activations
from keras import initializers
from keras import regularizers, constraints
def noisy_dense(inputs, units, bias... | StarcoderdataPython |
3224829 | #import sys
#file = sys.stdin
file = open( r'.\data\sets.txt' )
data = []
for line in file:
data.append(line.strip().split())
print(data)
set1 = set(data[1])
set2 = set(data[3])
print(set1, set2)
symdif = set1.symmetric_difference(set2)
symdif = list(map(int, symdif))
symdif.sort()
[print(n) for n in sorted(symdif)]... | StarcoderdataPython |
181922 | import copy
import unittest
import testlib
import json
import random
from ddt import file_data, ddt, data, unpack
import program03 as program
@ddt
class Test(testlib.TestCase):
def do_test(self, parole, testo, expected):
'''Implementazione del test
- parole: la lista di parole
... | StarcoderdataPython |
113084 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import yaml
import logging
logger = logging.getLogger(__name__)
CONFIG_FILE = "./utils/load_balancer/config.yaml"
LB_KUSTOMIZE_PATH = "../../deployment/add-ons/load-balancer/"
| StarcoderdataPython |
1603262 | """
@file
@brief Modification to doxypy.py
(which you can found here: http://code.foosel.org/doxypy).
The main tweaks are:
- the documentation is not moved before the function or class definition
- it uses a function to modify every line of documentation to use rst syntax.
"""
from __future__ import print_function
i... | StarcoderdataPython |
18867 | <filename>OrangeInstaller/OrangeInstaller/Testing.py
from Functions import functions, systemTools
import unittest
import sys
class systemToolsTests(unittest.TestCase):
"""
Class for testing
"""
def test_checkSystemTools(self):
check = False
if systemTools.isWindows() == True:
... | StarcoderdataPython |
1688704 | import cv2 , os, time
from PIL import Image
import numpy as np
key = cv2. waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
try:
check, frame = webcam.read()
print(check) #prints true as long as the webcam is running
print(frame) #prints matrix values of each framecd
cv2.imshow("C... | StarcoderdataPython |
3309135 | import tornado.ioloop
import tornado.web
import os
import os.path
import tornado.tcpserver
import ssl
import logging
import flickr_api
import pprint
import uuid
import json
flickr_auth_info = {
"api_key" : "<KEY>",
"secret" : "69003acec0548150"
}
flickr_api.set_keys(
api_key = flickr_auth_info['... | StarcoderdataPython |
184750 | #!/usr/bin/python2.4
# Copyright 2009 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 ... | StarcoderdataPython |
1672821 | # Copyright © 2019 <NAME>.
import random
import engine
from battleships.players.Player import Player
class AIPlayer(Player):
def start_game(self):
pass
def start_turn(self):
pass
def end_turn(self):
pass
def request_shot(self):
self.current_cell += 1
self.f... | StarcoderdataPython |
195487 | <gh_stars>0
"""
Simple PyWren example using one single function invocation
"""
import pywren_ibm_cloud as pywren
def my_function(x):
return x + 7
if __name__ == '__main__':
pw = pywren.ibm_cf_executor()
pw.call_async(my_function, 3)
print (pw.get_result())
| StarcoderdataPython |
3387560 | <reponame>poojasakhalkar/ankLekhan<filename>NumToWordConvertor.py
import json
with open("data.json",'r', encoding='utf8') as words:
valueDict = json.load(words)
class NumberToWord():
def getPositionValue(self,number):
listOfNumbers = []
while number != 0:
listOfNumbers.app... | StarcoderdataPython |
4818376 | import datetime
import numpy as np
from numpy import nan
import pandas as pd
import pytest
from pandas.util.testing import assert_frame_equal
from numpy.testing import assert_allclose
from pvlib.location import Location
from pvlib import tracking
SINGLEAXIS_COL_ORDER = ['tracker_theta', 'aoi',
... | StarcoderdataPython |
12752 | #! /usr/bin/python
import requests
import re
from bs4 import BeautifulSoup
import colors
class FindingComments(object):
def __init__(self, url):
self.url = url
self.comment_list = ['<!--(.*)-->']
self.found_comments = {}
def get_soure_code(self):
resp_text = requests.get(sel... | StarcoderdataPython |
1713960 | """Serializers for the sequencers app."""
from rest_framework import serializers
from ..models import SequencingMachine
class SequencingMachineSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
validated_data["project"] = self.context["project"]
return super().u... | StarcoderdataPython |
1625075 | <filename>tests/FrameBuilder/eigenstepsbuilder.py
import numpy as np
def get_eigensteps_random(mu_vector,lambda_vector,N,d):
''' Construct a valid random point in the GT polytope.
Parameters
----------
mu_vector : array_type
The vector of lengths
lambda_vector : array_type
... | StarcoderdataPython |
1661692 | <filename>hls4ml/converters/onnx/convolution.py
import math
from hls4ml.converters.onnx_to_hls import onnx_handler, get_onnx_attribute, get_onnx_input_name, compute_pads_1d, compute_pads_2d
from hls4ml.converters.utils import compute_padding_1d, compute_padding_2d
@onnx_handler('Conv')
def parse_conv_layer(reader, nod... | StarcoderdataPython |
4838137 | <filename>creator.py
#!/usr/bin/env python3
import os
import sys
import tempfile
import uuid
from sh import kolibri, zip as zip_files
from envcontext import EnvironmentContext as EnvContext
from shutil import copyfile
import hashlib
import urllib.request
import configparser
import json
import oss2
DATA_ROOT = os.envir... | StarcoderdataPython |
3396972 | <gh_stars>0
import argparse
import datetime
import os
import sys
import time
EXIT_ARGUMENT_NUMBER = 1
EXIT_FILE_EXISTS = 2
tags = []
categories = []
term = 'p'
now = time.localtime()
force = False
id = 0
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--gist', help='create gist', action='store_true')
p... | StarcoderdataPython |
67596 | from constance import config
from django.conf import settings
from portal.selection.models import Selection
from portal.users.models import User
def user_has_payment(user: User) -> bool:
try:
return user.selection.payment_value is not None
except Selection.DoesNotExist:
return False
def adm... | StarcoderdataPython |
17267 | <gh_stars>100-1000
"""
模板语言:
{{ 变量 }}
{% 代码段 %}
{% 一个参数时:变量|过滤器, Book.id | add: 1 <= 2 当前id+1来和2比较
两个参数时:变量|过滤器:参数 %}, 过滤器最多只能传2个参数,过滤器用来对传入的变量进行修改
{% if book.name|length > 4 %} 管道|符号的左右不能有多余的空格,否则报错,其次并不是name.length而是通过管道来过滤
{{ book.pub_date|date:'Y年m月j日' }} 日期的转换管道
"""
"""
... | StarcoderdataPython |
1680798 | """ tests which dictate the specs for the module node """
import sys
sys.path.pop(0) # remove the path for the test directory
import json
import unittest
import unittest.mock
import node
from drivers.sensors import sensor_base
'''
mock for the config manager class
'''
exec_methods = [] # keep track of the methods ... | StarcoderdataPython |
1706950 | from lxml import etree
import lxml.html
import elist.elist as elel
| StarcoderdataPython |
3398373 | """
Input independence rate:
Percentage of images where difference in attribution between original scene image and image
with added object is imperceptible. Image with added object is created using optimization
procedure to ensure the logit output stays the same (computationally expensive).
1 - IIR can be interpreted a... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.