id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
110570 | # -*- coding: utf-8 -*-
# vim: set ft=python ts=4 sw=4 expandtab:
import datetime
from unittest.mock import MagicMock, patch
import pytest
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
from busypie import SECOND, wait
from tzlocal import get_localzone
from vplan.... | StarcoderdataPython |
3379472 | listOriginal = [1,2,3,4,5,6,7,8,9,10]
result = list(map(lambda x: x**2, filter(lambda y: y%2==0, listOriginal)))
print(result)
print([x**2 for x in [y for y in listOriginal if y%2==0]])
print([x+y+z for x in range(1, 3) for y in range(11, 13) for z in range(101, 103)]) | StarcoderdataPython |
4823015 | """Problem 1002 from URI Judge Online"""
# pylint: disable-msg=C0103
r = input()
PI = 3.14159
area = pow(r, 2)*PI
print "A={0:.4f}".format(area)
| StarcoderdataPython |
3354126 | """Regression tests from real-world examples"""
import pytest
import pymergevcd.io_manager
@pytest.mark.manual
def test_regression_two_files(record_property):
"""Trying to merge two files
Currently not publicly available source files, hence no good test.
"""
record_property('req', 'SW-AS-nnn-deadbe... | StarcoderdataPython |
3333122 | """
Some useful functions
"""
from __future__ import division
import numpy as np
# A series of variables and dimension names that Salem will understand
valid_names = dict()
valid_names['x_dim'] = ['west_east', 'lon', 'longitude', 'longitudes', 'lons',
'xlong', 'xlong_m', 'dimlon', 'x', 'lon_3... | StarcoderdataPython |
52657 | <filename>tools/cp.py<gh_stars>100-1000
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Copy a file.
This module works much like the cp posix command - it takes 2 arguments:
(... | StarcoderdataPython |
161703 | """
This module has simple examples of multicore programs.
The first few examples are the same as those in
IoTPy/IoTPy/tests/multicore_test.py
"""
import sys
import os
import threading
import random
import multiprocessing
import numpy as np
sys.path.append(os.path.abspath("../multiprocessing"))
sys.path.append(os.path... | StarcoderdataPython |
180003 | import arpy
# from subprocess import Popen
# auto push to git
arpy.task("push", ["git add .", "git commit -m 'updates'", "git push origin master"], ".", ignorelist=[".git"])
| StarcoderdataPython |
1674888 | <reponame>tcchrist/renku-python
# -*- coding: utf-8 -*-
#
# Copyright 2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may no... | StarcoderdataPython |
1676006 | import json
import logging
import os
import shutil
import socket
from os.path import join
from hacksport.operations import execute
from shell_manager.bundle import get_bundle, get_bundle_root
from shell_manager.util import (BUNDLE_ROOT, DEPLOYED_ROOT, get_problem,
get_problem_root, HACK... | StarcoderdataPython |
1737569 | <reponame>kagemeka/atcoder-submissions<filename>jp.atcoder/typical90/typical90_s/26013390.py
import sys
import typing
import numba as nb
import numpy as np
@nb.njit((nb.i8[:], ), cache=True)
def solve(a: np.ndarray) -> typing.NoReturn:
n = len(a)
inf = 1 << 60
dp = np.full((n, n), inf, np.int64)
... | StarcoderdataPython |
1742936 | """evaluate.py
Script to create a system response for a given gold standard and then compare
the system response to that gold standard.
USAGE:
$ python evaluate.py --run --gold DIR1 --system DIR2 [OPTIONS]
$ python evaluate.py --comp --gold DIR1 --system DIR2 [OPTIONS]
$ python evaluate.py --diff --gold DIR... | StarcoderdataPython |
3215456 | <filename>lib/ansible/modules/cloud/alicloud/_ali_eni_facts.py
#!/usr/bin/python
# Copyright (c) 2017 Alibaba Group Holding Limited. <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redis... | StarcoderdataPython |
3291124 | <filename>small/GCD.py
#calcolare il massimo comune divisore alcuni numeri
import sys
def Split(str, a):
if len(a)== 1: return str.split(a[0])
else: return Split(a[1].join(str.split(a[0])), a[1:])
def MCD(primo_numero, secondo_numero):
if primo_numero % secondo_numero== 0: return secondo_numero
else: ... | StarcoderdataPython |
3284157 | import model
import dataclasses
import asyncio
import struct
import typing
import ujson
import time
@dataclasses.dataclass
class Response:
"""The format of a Minecraft server response packet."""
version_name: str
version_protocol: int
player_max: int
players_online: int
sample: list[dict[str, ... | StarcoderdataPython |
1624627 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2018-05-06 09:25
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('rango... | StarcoderdataPython |
4822243 | # Django settings for expression_data project.
try:
from localsettings import *
except ImportError:
pass
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django wil... | StarcoderdataPython |
4836233 | #!/usr/bin/python3
import re
from app.views import debug, PARSER_DEBUG
PARSER_DEBUG = False
NMAP_PORTS = re.compile(".*Ports:\s")
NMAP_TAB = re.compile("\t")
NMAP_HOST = re.compile("Host:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+\((.*?)\)")
# Parses nmap greppable format in an object
class NMService():
def __init... | StarcoderdataPython |
124402 | n = int(input())
# n = 3
sum1 = 0
sum2 = 0
for i in range(1, n + 1):
# print("i = ", i)
if i % 2 == 0:
sum1 += i
else:
sum2 += i
if sum1 == 0:
print(sum2)
else:
print(sum2 - sum1)
| StarcoderdataPython |
5302 | <reponame>waschag-tvk/pywaschedv
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import (
User,
)
from wasch.models import (
Appointment,
WashUser,
WashParameters,
# not models:
AppointmentError,
StatusRights,
)
from wasch im... | StarcoderdataPython |
1714941 | <reponame>lyric-com/idol<gh_stars>0
# DO NOT EDIT
# This file was generated by idol_py, any changes will be lost when idol_py is rerun again
from typing import MutableMapping
from .test_atleast_one import (
TestsBasicTestAtleastOne as CodegenTestsBasicTestAtleastOne,
)
from ...__idol__ import Map
TestsBasicTestMap... | StarcoderdataPython |
4825333 | <gh_stars>0
from datetime import datetime
from typing import Optional
from bson import ObjectId
from pydantic import BaseModel, EmailStr, Field
from .pyobject_id import PyObjectId
class UserModel(BaseModel): # pylint: disable=too-few-public-methods
"""
User model for database
"""
id: PyObjectId = F... | StarcoderdataPython |
197721 | <gh_stars>100-1000
"""
An example using both tensorflow and numpy implementations of viterbi
replicating example on wikipedia
"""
from __future__ import print_function
__author__ = '<NAME> <<EMAIL>>'
import tensorflow as tf
import numpy as np
from tensorflow_hmm import HMMNumpy, HMMTensorflow
def dptable(V, pathS... | StarcoderdataPython |
75358 | <filename>tests/unit/injector/test_injector.py
from dataclasses import dataclass, field
import pytest
from predico.field_types import injected
from predico.injector import inject, InvalidInjectable
@dataclass
class Shoe:
size: int = 77
@dataclass
class Athlete:
shoe: Shoe = Shoe()
def test_injector_prop... | StarcoderdataPython |
1793732 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Create config file to run evaluation"""
__author__ = '<NAME>, <NAME>, <NAME>, <NAME>, <NAME> '
__email__ = '<EMAIL>, <EMAIL>, <EMAIL>, <EMAIL>, <EMAIL>'
import os
import argparse
import xml.etree.ElementTree as ET
from xml.dom import minidom
import copy
de... | StarcoderdataPython |
4819375 | from core.protocol import TopicProtocol
from core.map_report import MapReport
import argparse
import os
def find_topics():
result = {}
topic_dir = os.path.join(os.path.dirname(__file__), 'map')
for module in os.listdir(topic_dir):
if module[0:2] == '__':
continue
elif module[-... | StarcoderdataPython |
3284423 | <reponame>grammatek/regina_normalizer
from regina_normalizer import unicode_maps as um
from regina_normalizer import dict_data
"""
Handles Unicode cleaning and Unicode normalizing of text. To simplify further processing, text normalizeing and
grapheme-to-phoneme conversion, we clean the text of most unicode characters... | StarcoderdataPython |
3227178 | <reponame>tingiskhan/pyfilter
import torch
from torch.distributions import Distribution
from torch.nn import Module
from abc import ABC
class BaseApproximation(Module, ABC):
"""
Abstract base class for constructing variational approximations.
"""
def __init__(self):
super().__init__()
de... | StarcoderdataPython |
93855 | <filename>super_laser_gui.py
import sys, os, serial, datetime, time
import numpy as np
from configparser import ConfigParser
import scipy
from scipy.interpolate import interp1d
import fileinput
from simple_pid import PID
from wlm import *
# shouldn't need this -> from Fiber import *
from PyQt5.QtWidgets import *
from... | StarcoderdataPython |
96003 | class InvalidateEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.Control.Invalidated event.
InvalidateEventArgs(invalidRect: Rectangle)
"""
def Instance(self):
""" This function has been arbitrarily put into the stubs"""
return InvalidateEventArgs()
@staticmethod
def __new... | StarcoderdataPython |
4841065 | <filename>ppcls/arch/backbone/model_zoo/repvgg.py
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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/l... | StarcoderdataPython |
3378573 | <reponame>michaelgundlach/7billionhumans
# Generated from SBHasm.g4 by ANTLR 4.7.1
# encoding: utf-8
import sys
from io import StringIO
from antlr4 import *
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3)")
... | StarcoderdataPython |
3290483 | <reponame>Shchusia/gen_doc
"""
Setup module for install lib
"""
import os
import re
from os import path
from pathlib import Path
from typing import List, Optional
from setuptools import setup
LIB_NAME = 'gen_doc'
HERE = Path(__file__).parent
this_directory = path.abspath(path.dirname(__file__))
with o... | StarcoderdataPython |
90959 | <reponame>pepsipepsi/nodebox_opengl_python3
import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
# Generate compositions using random text.
font('Arial Black')
def rndText():
"""Returns a random string of up to 9 characters."""
t = u... | StarcoderdataPython |
3358972 | <reponame>dhimmel/serg-pycode<filename>bioparser/efo.py
import os
import csv
import networkx
import data
import networkx_ontology
import obo
class EFO(obo.OBO):
def __init__(self, directory=None):
if directory is None:
directory = data.current_path('efo')
obo_filename = 'efo.obo'... | StarcoderdataPython |
3308377 | <filename>Util.py<gh_stars>0
import time
import os
import sys
def formatTime(t):
return time.strftime('%H:%M:%S', time.gmtime(t))
def formatTimeHM(t):
return time.strftime('%H:%M', time.gmtime(t))
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
... | StarcoderdataPython |
1752727 | import pandas as pd
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
import folium
import pprint
pp = pprint.PrettyPrinter(indent =4)
general_directory = os.path.split(os.getcwd())[0]
data_location = os.path.join(general_directory, "data")
dat... | StarcoderdataPython |
1747154 | <reponame>fossabot/bili-bonus<gh_stars>1-10
# -*- coding: utf-8 -*-
from src.luckydraw.main import start
| StarcoderdataPython |
3293247 | #idade para se alistar com acrescimo de sexo criado por mim
from datetime import date
atual = date.today().year
print(' Alistamento obrigatório Militar')
print('Para sexo MASCULINO digite [1]\n Para sexo FEMININO digite [2] ')
sexo = int(input('Qual é o seu sexo? '))
if sexo == 1:
nasc = int(input('Digite seu... | StarcoderdataPython |
106713 | from discord.ext import commands
from xml.etree import ElementTree
import discord, os, requests, time, re, random
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials
tts_subscription_key = '<KEY>'
text_analytics_subscription_key ... | StarcoderdataPython |
28698 | """This module contains helper functions used in the API"""
import datetime
import json
import re
import string
import random
from functools import wraps
from flask import request
from api_v1.models import User
def name_validalidation(name, context):
"""Function used to validate various names"""
if len(name... | StarcoderdataPython |
1600251 | import appdirs
from pkg_resources import Requirement, resource_filename
import shutil
import os
from plico.utils.addtree import mkdirp
class ConfigFileManager():
def __init__(self, appName, appAuthor, pythonPackageName):
self._appName = appName
self._appAuthor = appAuthor
self._packageNam... | StarcoderdataPython |
18005 | <filename>controllers/rcj_soccer_referee_supervisor/rcj_soccer_referee_supervisor.py
from math import ceil
from referee.consts import MATCH_TIME, TIME_STEP
from referee.referee import RCJSoccerReferee
referee = RCJSoccerReferee(
match_time=MATCH_TIME,
progress_check_steps=ceil(15/(TIME_STEP/1000.0)),
progr... | StarcoderdataPython |
1680353 | import json
from sys import exit
class Disassembler:
"""
A class used to represent Disassembler
Attributes
----------
_opcodes: list[int]
_instructions: dict[int, dict()]
_registers: dict[str, str]
_opcode: str
_r_type_format: dict[str, str]
_j_type_format: dict[str, str]
... | StarcoderdataPython |
80251 | <reponame>dmulyalin/ttp<filename>test/pytest/test_answers_and_docs.py
import sys
sys.path.insert(0, "../..")
import pprint
import pytest
import logging
logging.basicConfig(level=logging.DEBUG)
from ttp import ttp
def test_answer_1():
"""https://stackoverflow.com/questions/63522291/parsing-blocks-of-text-within... | StarcoderdataPython |
3355161 | from war import War
WAR_STATS_FILE_PATH = "./data/war_stats.tsv"
def load_data(file_path):
"""
Loads war data from given file path
Args:
file_path (str): path to .tsv file with war data
"""
# open war stats data in read mode
wars = []
file = open(file_path, "r")
# CSV colum... | StarcoderdataPython |
3288760 | <filename>third_party/chromite/lib/chrome_util.py
# -*- coding: utf-8 -*-
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Library containing utility functions used for Chrome-specific build tasks... | StarcoderdataPython |
3371883 | # -*- coding: utf-8 -*-
"""Flux Calculation class tests.
This script tests the operation of the Background Image Class.
Created on Thu Apr 22 13:44:35 2021
@author: denis
"""
import numpy as np
import pytest
from AIS.Background_Image import Background_Image
ccd_operation_mode = {
"em_mode": 0,
"em_gain": ... | StarcoderdataPython |
1735810 | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test that the wallet can send and receive using all combinations of address types.
There are 5 nodes-under-... | StarcoderdataPython |
156706 |
import tensorflow as tf
from capsule.norm_layer import Norm
layers = tf.keras.layers
models = tf.keras.models
import matplotlib.pyplot as plt
class ReconstructionNetwork(tf.keras.Model):
def __init__(self, in_capsules, in_dim, name="", out_dim=28, img_dim=1):
super(ReconstructionNetwork, self).__init... | StarcoderdataPython |
3379872 | from .fc import FC as FullyConnectedClassifier
from .rnn import RNNClassifier
from .bert_hf import BERT
__all__ = ["FullyConnectedClassifier", "RNNClassifier", "BERT"]
| StarcoderdataPython |
161110 | import os
import re
import logging
import pandas as pd
from googleapiclient.discovery import build
import yaml
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
# load personal websites
with open("_data/websites.yml", "r") as f:
WEBSITES = yaml.load(f, Loader=yaml.BaseLoader)
def membe... | StarcoderdataPython |
151071 | from rest_framework.test import APITestCase
# Create your tests here.
class BaseTestCase(APITestCase):
pass
| StarcoderdataPython |
46697 | """
Django settings for webDe project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from... | StarcoderdataPython |
57220 | # copied from https://github.com/probml/pyprobml/blob/master/scripts/sgmcmc_nuts_demo.py
# Compare NUTS, SGLD and Adam on sampling from a multivariate Gaussian
from collections import namedtuple
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union
import jax.numpy as jnp
import optax
from ... | StarcoderdataPython |
132326 | <gh_stars>0
import cv2
import pandas as pd
import numpy as np
import argparse
#Creating argument parser to take image path from command line
ap = argparse.ArgumentParser()
ap.add_argument('-i','--image', required=True,help='Image Path')
args = vars(ap.parse_args())
img_path = args['image']
#Reading image w... | StarcoderdataPython |
183244 | """Utils
"""
import json
__all__ = ['MyException', 'nedb_parser', 'python_data_to_lua_table']
LUA_INDENT = ' ' * 4
class MyException(Exception):
"""My Exception
I don't want to check the return value of every function.
Raise an exception, just easier to programming.
"""
def __init__(self, msg):
... | StarcoderdataPython |
96918 | <gh_stars>100-1000
from __future__ import print_function
import re
import os
import sys
import argparse
import collections
import subprocess
import json
from poline.utilfuncs import *
from poline.fields import Fields
from itertools import islice
from operator import itemgetter, attrgetter
if sys.version_info >= (3,0... | StarcoderdataPython |
3238148 | import pandas as pd
import json
import numpy as np
import yfinance as yf
import datetime
import time
BLACKLIST = ['IBTB','FDM']
if input('Override Close Wait?') == 'n':
print("Waiting for market close...")
while True:
now = datetime.datetime.now()
current_time = int(now.strftime("%H%M"))
print(current... | StarcoderdataPython |
3269368 | import unittest
import pyperclip
from accounts import User
from accounts import Credentials
class TestAccounts(unittest.TestCase):
"""
Test class that define test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"... | StarcoderdataPython |
3270435 | <gh_stars>1-10
import logging
import re
import time
from collections import deque
from datetime import datetime
from operator import itemgetter
import pyrclib
from pyrclib.channels import Channel
from pyrclib.connection import IRCConnection
from pyrclib.events import EventDispatcher
from pyrclib.user import User
cla... | StarcoderdataPython |
4810771 | <gh_stars>0
from django.db import models
from django.utils.text import slugify
from utils.base_models import BaseModel
class Category(BaseModel):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.slug)
s... | StarcoderdataPython |
3322342 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import colorlog
import pprint
from utils.pycocoevalcap.eval import COCOEvalCap
from utils.pycocotools.coco import COCO
from utils.utils import nostdout
pp = pprint.PrettyPrinter().pprint
class... | StarcoderdataPython |
162543 | <reponame>ndjuric/dscaler
#!/usr/bin/env python3
DOCTL = "/usr/local/bin/doctl"
PK_FILE = "/home/ndjuric/.ssh/id_rsa.pub"
SWARM_DIR = TAG = "swarm"
OVERLAY_NETWORK = "swarmnet"
DOCKER_REGISTRY = {
'master': 'private.docker.registry.example.com:5000/master',
'worker': 'private.docker.registry.example.com:5000/w... | StarcoderdataPython |
1756855 | <filename>docker_ws/src/ai_model/get_io_tensors.py
###############################################################################################################
# Source : https://newbedev.com/given-a-tensor-flow-model-graph-how-to-find-the-input-node-and-output-node-names
##########################################... | StarcoderdataPython |
3303166 | #!/usr/bin/env python
"""
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBU... | StarcoderdataPython |
3289458 | from mrjob.job import MRJob
from mrjob.step import MRStep
from heapq import nlargest
from operator import itemgetter
import re
WORD_RE = re.compile(r"[\w']+")
class MRMostUsedWord(MRJob):
def mapper_get_words(self, _, row):
data = row.split('\t')
for word in WORD_RE.findall(data[2]):
y... | StarcoderdataPython |
3272962 | <filename>fastapi/{{ cookiecutter.project_name }}/app/core/config.py
from typing import Literal
from pydantic import AnyHttpUrl, BaseSettings, Field
class CustomBaseSettings(BaseSettings):
"""Configure .env settings for all our setting-classes"""
class Config:
env_file = '.env'
env_file_enco... | StarcoderdataPython |
26061 | <reponame>algon-320/tenki.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import datetime
import pickle
import lxml.html
import urllib.request, urllib.error
import re
from modules.weather import Weather
from modules.print_util import String
class WeatherForecastManager:
PICKLE_DUMP_FILE = '... | StarcoderdataPython |
197572 | """
Views of core application.
"""
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.shortcuts import render
from django.utils.translation import gettext as _
from rest_framework.authto... | StarcoderdataPython |
3270329 | from Errors import CacheKeyError
import functools
predefinedCacheKeyHints = {
"test": "This is a test hint.",
"outputFolder": "A folder path(string) for logger file and figures: Auto provided when Discoverer is initiated.",
"groupName": "A string of the group name: Should be defined by hand.",
"friendL... | StarcoderdataPython |
165019 | from .casing import * | StarcoderdataPython |
1602493 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2019-04-25 15:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content', '0049_auto_20181009_1410'),
]
operations = [
migrations.AlterFiel... | StarcoderdataPython |
3379202 | class SBLError(Exception):
"""SBL Exception"""
pass
| StarcoderdataPython |
4838359 | import tensorflow as tf
x = [[1,2,3],[4,5,6]]
x = tf.convert_to_tensor(x)
xtrans = tf.transpose(x)
y=([[[1,2,3],[6,5,4]],[[4,5,6],[3,6,3]]])
y = tf.convert_to_tensor(y)
ytrans = tf.transpose(y, perm=[0, 2, 1])
with tf.Session() as sess:
print(sess.run(xtrans))
print(sess.run(ytrans)) | StarcoderdataPython |
1613445 | import datetime
import pytest
import os
from batimap.app import create_app
from batimap.extensions import db
from batimap.db import Base, Boundary, Cadastre, City
@pytest.fixture
def app():
test_db_uri = os.environ.get(
"POSTGRES_URI", "postgresql://test:batimap@localhost:15432/testdb"
)
test_red... | StarcoderdataPython |
1617239 | <filename>lib/pytaf/tafdecoder.py
import re
from .taf import TAF
class DecodeError(Exception):
def __init__(self, msg):
self.strerror = msg
class Decoder(object):
def __init__(self, taf):
if isinstance(taf, TAF):
self._taf = taf
else:
raise DecodeError("Argument... | StarcoderdataPython |
1604054 | <reponame>nunulong/algorithms
class Solution:
def two_sum(self, nums, target):
result = []
for index in range(0, len(nums), 1):
sec = target - nums[index]
if sec in nums:
result.append(index)
result.append(nums.index(sec))
return result
| StarcoderdataPython |
1614987 | <reponame>nicholas-miklaucic/nmiklaucic-updated-emacs
"""Glue for the "black" library.
"""
import sys
from pkg_resources import parse_version
import os
try:
import toml
except ImportError:
toml = None
from elpy.rpc import Fault
BLACK_NOT_SUPPORTED = sys.version_info < (3, 6)
try:
if BLACK_NOT_SUPPORT... | StarcoderdataPython |
3218123 | <reponame>zconnect-iot/zconnect-django
# pylint: disable=wildcard-import,unused-wildcard-import
from .base import ModelBase
from .activity_stream import * # noqa
from .device import * # noqa
from .event import * # noqa
from .location import * # noqa
from .organization import * # noqa
from .product import * # noqa
from... | StarcoderdataPython |
36696 | <reponame>zopefoundation/grokcore.component
"""
Imported model and adapter won't be grokked:
>>> import grokcore.component as grok
>>> grok.testing.grok(__name__)
>>> from grokcore.component.tests.adapter.adapter import IHome
>>> cave = Cave()
>>> home = IHome(cave)
Traceback (most recent call last):
.... | StarcoderdataPython |
24974 | <filename>test.py<gh_stars>1-10
#!/usr/bin/env python
"""
Test the Inspector
"""
import os.path, sys
sys.path.append(os.path.dirname(__file__))
import unittest
import inspector
########################################################
#
# Inspector test
#
########################################################
de... | StarcoderdataPython |
131353 | """Chapter 5: Question 4.
A simple condition to check if a number is power of 2: n & (n-1) == 0
Example:
n = 1000
1000 & (1000 - 1)) = 1000 & 0111 = 0000 = 0
"""
def is_power_of_two(n):
"""Checks if n is a power of 2.
Args:
n: Non-negative integer.
"""
if n < 0:
raise Valu... | StarcoderdataPython |
3297620 | <gh_stars>0
lista = [ ]
k = 0
n = 0
while k < 10:
consoante = input ('Digite uma letra: ')
lista.append(consoante)
if consoante not in 'aeiou':
n = n + 1
k = k + 1
print(n)
print(lista)
| StarcoderdataPython |
1733671 | <reponame>nrser/nansi.collections<filename>wireguard/plugins/action/package.py<gh_stars>0
from __future__ import annotations
from typing import Literal, Optional
import splatlog as logging
from nansi.plugins.action.os_resolve import OSResolveAction
from nansi.plugins.action.args.all import Arg, ArgsBase
LOG = loggin... | StarcoderdataPython |
3236325 | <reponame>JohannesBuchner/pystrict3
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os
import re
import smtplib
class... | StarcoderdataPython |
4806532 |
while True:
try:
numInput=int(input("Please Enter a number:"))
break
except ValueError:
print("Try Again")
if numInput%2==0:
print("even")
else:
print("odd")
| StarcoderdataPython |
3325319 | import spacy
nlp = spacy.load("de_core_news_sm")
text = "Apple wurde 1976 von <NAME>, <NAME> und <NAME> gegründet."
# Verarbeite den Text
doc = ____
# Iteriere über die vorhergesagten Entitäten
for ent in ____.____:
# Drucke den Text und das Label der Entität
print(ent.____, ____.____)
| StarcoderdataPython |
1633165 | <reponame>NatholBMX/coursera_partical_rl
import sys
import numpy as np
sys.path.append("..")
import grading
def submit_bandits(scores, email, token):
epsilon_greedy_agent = None
ucb_agent = None
thompson_sampling_agent = None
for agent in scores:
if "EpsilonGreedyAgent" in agent.name:
... | StarcoderdataPython |
1760797 | # Copyright 2018 <NAME>
# 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
... | StarcoderdataPython |
3316825 | #coding:utf8
# rest
from rest_framework import serializers
# my model
from models import WXUser
class WXUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = WXUser
fields = ('openid','nickname','avatar','gender','city','province','country','language')
| StarcoderdataPython |
1630802 | <reponame>alexrudy/tox-server<gh_stars>1-10
# type: ignore
from invoke import task
@task
def lock(c, sync=True):
"""Lock dependencies"""
c.config["run"]["echo"] = True
c.run("pip-compile requirements/test-requirements.in")
c.run("pip-compile requirements/dev-requirements.in")
if sync:
sync... | StarcoderdataPython |
3377291 | # -*- coding: utf-8 -*-
import lib.requests as requests
import conf.config as conf
base = conf.read_config(conf.path, 'API', 'baseUrl')
class Shot(object):
def __getShot(self,uid,project_id,start,length):
api = conf.read_config(conf.path, 'API', 'getShotApi')
url = base + api + '?uid=' ... | StarcoderdataPython |
1616110 | <filename>parallel-pytest.py
import argparse
import re
import subprocess
import threading
import fnmatch
import os
import sys
import six.moves.queue as queue
class Collector(threading.Thread):
def __init__(self):
self.__output = queue.Queue()
self.is_failure = False
super(Collector, self).... | StarcoderdataPython |
4826787 | <filename>scripts/prepare_nil_dataset.py
import numpy as np
import pandas as pd
import textdistance
import json
import os
import statistics
import pickle
scores_path = './data/scores'
datasets_path = './data/BLINK_benchmark'
dataset_output_path = './data/nil_dataset.pickle'
datasets = [
('AIDA-YAGO2_testa_ner',... | StarcoderdataPython |
1778348 | # -*- coding: utf-8 -*-
import math
import os
import random
import time
import src.hyperka.et_funcs.utils as ut
from src.hyperka.ea_funcs.train_funcs import find_neighbours_multi
from src.hyperka.et_apps.util import generate_adjacent_graph
# 根据相应参数初始化模型
def get_model(folder, kge_model, args):
print("data folder:... | StarcoderdataPython |
1739069 | from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from . import views
APP_SLUGS = {
'chrono': 'Chrono',
'face_value': 'Face_Value',
'podcasts': 'Podcasts',
'roller': 'Roller',
'webfighter': 'Webfighter',
'generalnotes': 'General_Notes',
'rtcamera': '... | StarcoderdataPython |
166333 | <gh_stars>0
import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper
from baselines.common.vec_env.vec_env import clear_mpi_env_vars
def worker(remote, parent_remote, env_fn_wrappers):
def step(env, action):
ob, reward, done, info = env.step(action)
if done:... | StarcoderdataPython |
158752 | <reponame>ry755/ryfs
#!/usr/bin/env python3
# ryfs.py
# manage RYFS disk images
import os
import sys
import struct
import argparse
version_info = (0, 2)
version = '.'.join(str(c) for c in version_info)
# create new RYFSv1 disk image
def ryfs_create():
if not quiet:
if use_boot_sector:
print("... | StarcoderdataPython |
1697905 | <filename>code/blastn_all_v_all.py
'''
For blastn searches we are going to calculate the percent coverage of
the phage genome and score the longest coverage as the best hit. It
doesn't matter where the hits are on the bacterial genome.
We are going to use a cutoff of 0.001 E value
'''
import sys,os,re
from phage i... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.