id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
188765 | class ImageGroupData:
def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset):
self.start_y = start_y
self.start_x = start_x
self.y_gear_offset = y_gear_offset
self.x_gear_offset = x_gear_offset
class ImageTypeData:
def __init__(self, size, rel_start_offset, rows=None, columns=None, p... | StarcoderdataPython |
3396626 | """ A pipeline that transfers data from sqlite to postgreSQL """
import sqlite3
import psycopg2
import queries as q
DBNAME = "czlilzkt"
USER = "czlilzkt"
PASSWORD = "<PASSWORD>"
HOST = "ziggy.db.elephantsql.com"
sqlite_rpg_db = "rpg_db.sqlite3"
# Make connection_______
# sqlite connector
def sqlite_connect(sqlite... | StarcoderdataPython |
3251721 | <reponame>nghia-tran/f5-common-python<filename>f5/bigip/tm/asm/signatures.py
# coding=utf-8
#
# Copyright 2015-2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# htt... | StarcoderdataPython |
1780432 | # Turns on debugging features in Flask
DEBUG = True
SERVER_NAME = "127.0.0.1:8080"
# Create dummy secrey key so we can use sessions
SECRET_KEY = '123456790'
# Create in-memory database
SQLALCHEMY_DATABASE_URI = 'mysql://:@localhost/inventory'
SQLALCHEMY_ECHO = True
# Flask-mail
MAIL_SERVER = ''
MAIL_PORT = 465
MAIL_... | StarcoderdataPython |
30965 | import requests
from teste_app import settigns
def google(q: str):
"""Faz uma pesquisa no google"""
return requests.get(settigns.GOOGLE, params={"q": q})
| StarcoderdataPython |
1624569 | """ Utility functions operating on operation matrices """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Govern... | StarcoderdataPython |
3351087 | from chainer_compiler.elichika.typing.types import *
__all__ = [ 'builtin_func_ty' ]
def ty_len(ty_args, ty_kwargs):
x_type, = ty_args
if isinstance(x_type, TyList):
return TyInt()
if isinstance(x_type, TyTuple):
return TyInt(x_type.size())
if isinstance(x_type, TyTensor):
... | StarcoderdataPython |
1640827 | <reponame>cmartinaf/rezpackages<gh_stars>1-10
name = 'ffmpeg'
version = '3.4'
authors = [
'FFmpeg Team'
]
description = \
'''
FFmpeg is the leading multimedia framework, able to decode, encode, transcode,
mux, demux, stream, filter and play pretty much anything that humans and
machines have creat... | StarcoderdataPython |
38776 | <filename>ch05/ch0501_convnet.py
# -*- encoding: utf-8 -*-
"""
@Author : zYx.Tom
@Contact : <EMAIL>
@site : https://zhuyuanxiang.github.io
---------------------------
@Software : PyCharm
@Project : deep-learning-with-python-notebooks
@File : ch0501_convnet.py
@Version : v0.1... | StarcoderdataPython |
3254404 | from pytanga.components import AbstractComponent
class ospfComponent(AbstractComponent):
def __init__(self,
process_id,
vrf=None,
router_id=None,
nsr=None,
maximum_paths=None,
domain_tag=None,
i... | StarcoderdataPython |
3271498 | <filename>source/utils/AttributeSelector.py<gh_stars>0
class AttributeSelector:
def __init__(self):
pass
def __call__(self, tweet):
t = {}
t["text"] = tweet["text"]
t["media"] = []
for m in tweet["extended_entities"]["media"]:
if "jpg" in m["media_url"]:
... | StarcoderdataPython |
1748465 | from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def hello():
return render_template('welcome.html')
@app.route('/enviar')
def envia():
return render_template('cadastrado.html')
| StarcoderdataPython |
169857 | <reponame>gabizinha12/CursoEmVideoPython<filename>Mundo_1/modulos_em_py/ex0022.py
nome = str(input("Digite seu nome: ")).strip()
print("Seu nome em maiusculas é {}".format(nome.upper()))
print("Seu nome em minusculas é {}".format(nome.lower()))
print("Seu nome tem ao todo {} letras".format(len(nome) - nome.count(' '))... | StarcoderdataPython |
3315464 | hyq_ref = [-1.652528468457493,
0.06758953014152885,
0.6638277139631803,
0.0,
0.0,
0.0,
1.0,
0.17905666752078864,
0.9253512562075908,
-0.8776870832724601,
0.11147422537786231,
-0.15843632504615043,
1.150049183494211,
-0.1704998924604114,
0.6859376445755911,
-1.1831277202117043,
0.06262698472369518,
-0.... | StarcoderdataPython |
1743023 | <filename>tf_agents/experimental/examples/ppo/train_eval_lib.py
# coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apac... | StarcoderdataPython |
1758186 | <filename>artifact_py/artifact.py<gh_stars>1-10
# artifact_py: the design documentation tool made for everyone.
#
# Copyright (C) 2019 <NAME> <github.com/vitiral>
#
# The source code is Licensed under either of
#
# * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LI... | StarcoderdataPython |
1667221 | from argparse import ArgumentParser
from loguru import logger
from weakly_supervised_parser.settings import TRAINED_MODEL_PATH
from weakly_supervised_parser.utils.prepare_dataset import DataLoaderHelper
from weakly_supervised_parser.utils.populate_chart import PopulateCKYChart
from weakly_supervised_parser.tree.evalua... | StarcoderdataPython |
1679841 | """
Axis class
==========
Axis is a named ordered collection of values.
For these doctests to run we are going to import numcube.Axis and numpy.
>>> from numcube import Axis
>>> import numpy as np
Creation
--------
To create an Axis object, you have to supply it with name and values. Name must be a string,
values mus... | StarcoderdataPython |
110466 | <filename>digsby/src/plugins/digsby_iq_version/__init__.py
from decimal import Decimal
from logging import getLogger
from peak.util.addons import AddOn
from pyxmpp.objects import StanzaPayloadObject
from pyxmpp.utils import to_utf8
from pyxmpp.xmlextra import get_node_ns_uri
import hooks
import libxml2
import traceback... | StarcoderdataPython |
3227747 | from .simple_type import SimpleTypePredictor
from .float_type import FloatType
from .nan_type import NaNType
class StringType(SimpleTypePredictor):
def __init__(self):
self._float_predictor = FloatType()
self._nan_predictor = NaNType()
def validate(self, candidate, **kwargs) -> bool:
... | StarcoderdataPython |
3294740 | """
A pattern to create a booking cluster description
The properties in this group are mostly from {region} region.
The properties are usually booked during {breakpoint} breakpoints by {adults} with {children} and {babies}.
These are {avg_spend_per_head} {detached} properties in the {complex} close to {close_to}.
The ... | StarcoderdataPython |
189962 | <reponame>udcymen/leetcode
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.getLeftMostNode(root)
def g... | StarcoderdataPython |
114009 | """Webapi views."""
from typing import Any, Dict, List, Iterable, Optional, cast, Tuple
from aiohttp import web
import time
from irisett import (
metadata,
bindata,
stats,
utils,
contact,
monitor_group,
object_models,
)
from irisett.webapi import (
errors,
)
from irisett.monitor.active... | StarcoderdataPython |
4821088 | <filename>biorxiv/publication_delay_experiment/02_publication_delay_experiment_figure_exploration.py
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.9.1+dev
# kernelspec:... | StarcoderdataPython |
4808332 | import epicbox
# import logging
# logging.basicConfig(
# format="%(levelname)-8s [%(asctime)s] %(message)s",
# level=logging.INFO,
# filename="app.log",
# )
PROFILES = {
"gcc_compile": {
"docker_image": "stepik/epicbox-gcc:6.3.0",
"user": "root",
},
"gcc_run": {
"docke... | StarcoderdataPython |
889 | <gh_stars>0
from binascii import hexlify
from functools import wraps
from logging import error
from os import urandom
from random import randint
from flask import make_response
from flask import render_template
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import Forbidden
from werkzeug.exception... | StarcoderdataPython |
3270844 | #!/usr/local/bin/python3
from Vagrant import Vagrant
import rumps
from apscheduler.schedulers.background import BackgroundScheduler
# Callbacks
def cb_vm_destroy(sender):
sender.vm.destroy()
def cb_vm_power_off(sender):
sender.vm.poweroff()
def cb_vm_power_on(sender):
sender.vm.poweron()
def cb_vm_provi... | StarcoderdataPython |
3303822 | import argparse
import stf_path
from trex_stf_lib.trex_client import CTRexClient
from pprint import pprint
import csv
import math
# sample TRex stateful to chnage active-flows and get results
def minimal_stateful_test(server,csv_file,a_active_flows):
trex_client = CTRexClient(server)
trex_client.start_tre... | StarcoderdataPython |
1660494 | <filename>tools/blender/md3_import.py
#!BPY
"""
Name: 'Quake3 (.md3)...'
Blender: 242
Group: 'Import'
Tooltip: 'Import from Quake3 file format. (.md3)'
"""
__author__ = "PhaethonH, <NAME>, Robert (Tr3B) Beckebans"
__url__ = ("http://xreal.sourceforge.net")
__version__ = "0.6 2006-11-12"
__bpydoc__ = """\
This script... | StarcoderdataPython |
3357765 | import pandas as pd
def row_to_tex(row):
if 'good_cand_ibata' in row.index:
flag = '' if pd.isnull(row['good_cand_ibata']) else row['good_cand_ibata']
else:
flag = ''
string = str(row['source_id']) + ' & '
string += "${0:.3f}$ & ".format(row['ra'])
string += "${0:.3f}$ & ".format(r... | StarcoderdataPython |
3348417 | _base_ = [
'../../_base_/models/deeppad_r50.py',
'../../_base_/datasets/cityscapes.py', '../../_base_/default_runtime.py',
'../../_base_/schedules/schedule_80k_warmup.py'
]
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
backbone=dict(
norm_cfg=norm_cfg,
),
decode_head=d... | StarcoderdataPython |
1652503 | <gh_stars>1-10
import pytest
from django.test import TestCase
@pytest.mark.builder_backend
class BuilderBackendTestCase(TestCase):
pass
@pytest.mark.builder
class BuilderTestCase(TestCase):
pass
| StarcoderdataPython |
1724563 | import dateutil.parser
from dateutil import tz
from datetime import timedelta
import time
import requests
from requests.auth import HTTPBasicAuth
from xui.solar_winds.solar_winds_scripts import TEST_SERVER_CONNECTION
from common.methods import generate_string_from_template
from utilities.models import ConnectionInfo
... | StarcoderdataPython |
40978 | from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "tax",
ext_modules = cythonize('tax.pyx'),
script_name = 'setup.py',
script_args = ['build_ext', '--inplace']
)
import tax
import numpy as np
print(tax.tax(np.ones(10)))
| StarcoderdataPython |
1724620 | import glob
import json
files = glob.glob("../docs/curation_bk/*.json")
for file in files:
with open(file) as f:
df = json.load(f)
print(file)
for selection in df["selections"]:
label = selection["within"]["label"]
attribution = "utokyo"
if "張交帖" in label:
a... | StarcoderdataPython |
3252005 | <filename>kickstart-menu/menu.py
#!/usr/bin/env python
# pylint: disable=too-many-ancestors
"""Menu system."""
import sys
import npyscreen
import classes
import datetime
import re
from kickstart import *
def str_ljust(_string):
"""Add padding to string."""
pad = 20
return str(_string.ljust(pad, ".") + ":"... | StarcoderdataPython |
1607035 | #!/usr/bin/env python
#
# Copyright (c) 2016-2021 InSeven Limited
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... | StarcoderdataPython |
3248849 | #!/usr/bin/env python3
import logging
from benchpress.lib.hook import Hook
logger = logging.getLogger(__name__)
class Emon(Hook):
"""Emon hook allows the benchmark to collect CPU utilization data across
execution time of application or system"""
emon_proc = None
def before_job(self, opts, job):
... | StarcoderdataPython |
1615357 | <gh_stars>1-10
import os
import json
import yaml
import logging
from .project import Project
from .plugin import PluginType, PluginInstall, PluginRef
from .plugin_discovery_service import PluginDiscoveryService
from .plugin.factory import plugin_factory
from .config_service import ConfigService
class PluginNotSuppor... | StarcoderdataPython |
3301225 | <gh_stars>1-10
import time
import datetime
import sys
import getopt, argparse
from collections import defaultdict
import json
import MySQLdb
import unicodecsv
import pprint
ITEM_MAP_VARCHAR_INSERT = "insert into item_map_varchar (item_id, attr_id, value) values ((select item_id from items where client_item_id = %(id)s... | StarcoderdataPython |
196012 | <reponame>Domepo/icalGenerator
from icalendar import Calendar, Event, Alarm
from datetime import date, datetime, timedelta
class addICS:
def __init__(self, file):
self.file = file
self.cal = Calendar()
self.cal.add("version", "2.0")
self.cal.add("prodid", "Technik-Kalender")
... | StarcoderdataPython |
3334092 | <gh_stars>1-10
"""Constants for the SENZ WiFi integration."""
DOMAIN = "senz"
VERSION = "0.0.6"
SENZ_API = "https://api.senzthermostat.nvent.com/api/v1"
OAUTH2_AUTHORIZE = "https://id.senzthermostat.nvent.com/connect/authorize"
OAUTH2_TOKEN = "https://id.senzthermostat.nvent.com/connect/token"
| StarcoderdataPython |
1698436 | # -*- coding: utf-8 -*-
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
import configs
class E... | StarcoderdataPython |
3398716 | #coding: utf-8
import unittest
from test_search import JOURNAL
from search import search_for
from tomd import parse_boldrow, entry2md, result2md, swedate
class TestBoldRowRegex(unittest.TestCase):
def test_no_math(self):
self.assertEqual(None, parse_boldrow('Hejsan hej'))
def test_math(self):
... | StarcoderdataPython |
3273178 | <filename>Misc/HiveMaker/solution_1.py
# The idea is that except if we have less than 11 sticks where the solution is trivial
# in every other case we create as much pairs of hexagons as possible. The addition of
# two pairs provides the best solution and also return to us 3 sticks. We repeat until
# no new pairs can b... | StarcoderdataPython |
3203110 | <reponame>noob20000405/casbin-cpp<gh_stars>100-1000
# Copyright 2021 The casbin Authors. 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... | StarcoderdataPython |
54440 | #!/usr/bin/env python
import aptx
import argparse
import textwrap
import os.path
parser = argparse.ArgumentParser(
description='Print schema version of .aptx files.',
epilog='example: aptx_schemaver.py *.aptx')
parser.add_argument('aptxfiles', nargs='+', help='aptx file specification')
args = parser.parse_arg... | StarcoderdataPython |
131137 | # coding=utf-8
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
import warnings
import numpy as np
from deslib.base import BaseDS
from deslib.util.aggregation import majority_voting_rule
from deslib.util.diversity import Q_statistic, ratio_errors, \
negative_double_fault, compute_pairwise_diversity
from sklea... | StarcoderdataPython |
152506 | <filename>rss_reader/database/redis/__init__.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
from .base_set import MySettings | StarcoderdataPython |
1784334 | <gh_stars>0
# A lot of this code exists to deal w/ the broken ECS connect_to_region
# function, and will be removed once this pull request is accepted:
# https://github.com/boto/boto/pull/3143
import logging
logger = logging.getLogger(__name__)
from boto.regioninfo import get_regions
from boto.ec2containerservice.l... | StarcoderdataPython |
69273 | import pytest
from .context import mock, builtin_str
@pytest.fixture(scope='function')
def func():
def dummy(*agrs, **kwargs):
pass
f = mock.create_autospec(spec=dummy, name='fixture_function_to_decorate')
return f
@pytest.fixture(scope='function', autouse=True)
@mock.patch('{builtin}.open'.forma... | StarcoderdataPython |
10018 | <reponame>Karoline0097/University-of-Michigan-Python-for-Everybody
## Problem 5: Extracting Data from JSON
# Example: http://py4e-data.dr-chuck.net/comments_42.json
# data consists of a number of names and comment counts in JSON
# {
# comments: [
# {
# name: "Matthias"
# count: 97
# },
# {
# ... | StarcoderdataPython |
3299646 | import xml.etree.ElementTree as ET
import pandas as pd
import datetime
import re
import pymongo
import csv
from time import time
import sys
import os
# This script parses the raw Stack Overflow data from a single giant >70 GB XML file,
# down into a MongoDB collection and a csv with the metadata.
def xml_iterator(fi... | StarcoderdataPython |
3286744 | """
A simple script to encode all the images the XRCed needs into a Python module
"""
import sys, os, glob
from wx.tools import img2py
def main(filemask, output):
# get the list of PNG files
files = glob.glob(filemask)
files.sort()
# Truncate the inages module
open(output, 'w')
# call img2py... | StarcoderdataPython |
3280067 | <filename>scripts/dpdk_setup_ports.py
#! /bin/bash
"source" "find_python.sh" "--local"
"exec" "$PYTHON" "$0" "$@"
# hhaim
import sys
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
import os
python_ver = 'python%s' % sys.version_info[0]
yaml_path = os.path.join('external_libs', 'pyyaml-3.11'... | StarcoderdataPython |
3229058 | #!/usr/bin/env python
import collections
import itertools
import json
import re
import ankipandas
from pypinyin import pinyin, Style
max_words = 10
MAX_RANK = 30_000
freq = json.load(open("global_wordfreq.release_UTF-8.json"))
freq = {word: rank for word, rank in freq.items() if rank <= MAX_RANK}
COLS = {
"1": ... | StarcoderdataPython |
3321864 | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
"""
SDA.py: Plots the probability of the SDA model generating a connection
based on different parameters for Figure 2.4.
"""
def prop(a, b, d):
return 1/(1+(1/b*d)**a)
n = 3
alphas = [2, 3, 8]
betas = [2, 3, 5]
colors = ['r', 'g', 'b']
d = ... | StarcoderdataPython |
3203814 | from flask import Flask, request, render_template, jsonify, url_for
from utils import clean_text
import pickle
import time
import os
app = Flask(__name__)
MODEL_VERSION = 'model_V0.pkl'
VECTORIZER_VERSION = 'vectorizer_V0.pkl'
# load model assets
vectorizer_path = os.path.join(os.getcwd(), 'model_assets', VECTORIZER... | StarcoderdataPython |
1751300 | import io
import json
import pandas as pd
from sachima.filter_enum import FilterEnum
from sachima.log import logger
def delfunc(sql, e):
buf = io.StringIO(sql)
temp = ""
for line in buf.readlines():
if "{" + e + "}" in line and "-- ifnulldel" in line:
# logger.debug("del sql line: " +... | StarcoderdataPython |
3235214 | from django.contrib import admin
from .models import *
from .forms import MultipleChoiceTestAnswerInlineFormset
from Test.models import Test
class MultipleChoiceTestAnswerInline(admin.TabularInline):
model = MultipleChoiceTestAnswer
formset = MultipleChoiceTestAnswerInlineFormset
extra = 0
verbose_nam... | StarcoderdataPython |
1651451 | <filename>examples/order_management/order/src/demo_data.py
import asyncio
from src.store import Base, create_order, engine
async def create_demo_data():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
await crea... | StarcoderdataPython |
178268 | from typing import Text, Any, Dict, List, Union, Optional, Tuple, Set
from anytree import Resolver
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from anytree.node.nodemixin import NodeMixin
from anytree.node.util import _repr
from anytree.search import findall, findall_by_attr, find
fr... | StarcoderdataPython |
4806255 | <gh_stars>1-10
import logging
from typing import Tuple
import torch
from torch import Tensor
from tqdm import tqdm
from . import optim
from .extrinsics import full_extrinsics, partial_extrinsics
from .geometry import check_origin, spiral, transform
from .orthonorm import orthonorm
from .plot import Scatter
from .poly... | StarcoderdataPython |
98186 | import json
import os
import random
import string
from math import asin
from math import ceil
from math import cos
from math import degrees
from math import pi
from math import radians
from math import sin
from math import sqrt
from math import tan
from pyaedt.generic.general_methods import _retry_ntimes
from pyaedt.g... | StarcoderdataPython |
1749726 | import os
import tensorflow as tf
import operator
from pathlib import Path
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, AutoConfig
from .config import model_params, model_location
from .get_weights import Download
from .label_mapping import LabelMapping
from . import __version__
cl... | StarcoderdataPython |
3278256 | <filename>docs/_mocked_modules/ctypes/__init__.py
"""Bare minimum mock version of ctypes.
This shadows the real ctypes module when building the documentation,
so that :mod:`rubicon.objc` can be imported by Sphinx autodoc even when no Objective-C runtime is available.
This module only emulates enough of ctypes to make... | StarcoderdataPython |
3290374 | """Shared exceptions for the august integration."""
from openpeerpower import exceptions
class RequireValidation(exceptions.OpenPeerPowerError):
"""Error to indicate we require validation (2fa)."""
class CannotConnect(exceptions.OpenPeerPowerError):
"""Error to indicate we cannot connect."""
class Invali... | StarcoderdataPython |
1626442 | # Execute a trajetory in a force mode.
# Author: <NAME>
# Force mode example
import robot_controller
# communicate with a robot
manipulator = robot_controller.Ur3("192.168.3.11", 30003, 30002)
force_traj = list()
pose = manipulator.get_pose()
pose[2] -= 0.1
for i in range(3):
pose[1] += 0.05
pt = manipulat... | StarcoderdataPython |
4834086 | <gh_stars>1-10
import numpy as np
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle"]
datasets_path = './datasets/jinnan2_round1_train_20190305/'
anchor_yolov2 = [[2.8523827,2.4452496 ],
[1.3892268,1.8958333 ],
[1.6490009,0.95596665],
[0.7680278,1.3883946 ],... | StarcoderdataPython |
1793086 | import os
GH_NAME = os.environ["GH_NAME"]
GH_EMAIL = os.environ["GH_EMAIL"]
print("GH_NAME:", GH_NAME, ",GH_EMAIL:", GH_EMAIL)
| StarcoderdataPython |
1739120 | <reponame>GilraGroup/baconian-project
from baconian.algo.algo import Algo
from baconian.algo.dynamics.dynamics_model import DynamicsModel
from baconian.core.core import EnvSpec
from baconian.common.logging import record_return_decorator
import numpy as np
class ModelFreeAlgo(Algo):
def __init__(self, env_spec: En... | StarcoderdataPython |
1645069 | # coding=utf-8
# Author: <NAME> Cruz <<EMAIL>>
#
# License: BSD 3 clause
"""
====================================================================
Dynamic selection with linear classifiers: XOR example
====================================================================
This example shows that DS can deal with non-lin... | StarcoderdataPython |
1617007 | <reponame>Formulka/django-GDPR<gh_stars>10-100
from typing import Callable
from django.contrib.contenttypes.models import ContentType
from django.db.models import Model
from django.test import TestCase
from gdpr.models import AnonymizedData
from germanium.tools import assert_false, assert_true
class NotImplementedM... | StarcoderdataPython |
1774304 | <reponame>PolicyStat/terrarium<filename>tests/tests.py
# new tests should be added to test_cli.py, not here
from __future__ import absolute_import
import copy
import hashlib
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
import unittest
class TerrariumTester(unittest.TestCase):
... | StarcoderdataPython |
1606951 | <reponame>vishalbelsare/h2o-3<filename>h2o-py/tests/testdir_algos/glm/pyunit_PUBDEV_7481_lambda_search_alpha_array_validation_large.py<gh_stars>1000+
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm
# with lambda_sea... | StarcoderdataPython |
3311598 | ################################################################
# Implemented by <NAME> (<EMAIL>) #
# #
# PyTorch-compatible implmentation of Integrated Gradients #
# proposed in "Axiomatic attribution for deep neuron networks" #
# (https://arxiv.org/a... | StarcoderdataPython |
1750404 | <reponame>nahidupa/grr
#!/usr/bin/env python
"""Tests for validating the configs we have."""
import glob
import os
import logging
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import test_lib
from grr.lib import utils
def ValidateConfig(config_file=None):
"""Iterate over all the sections ... | StarcoderdataPython |
3311434 | <reponame>pisskidney/leetcode
#!/usr/bin/python
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def kthSmallest(self, root, k):
res, cnt = self.inorder(root, k, 0)
return res
def inorder(self... | StarcoderdataPython |
79486 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | StarcoderdataPython |
3242761 | import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.utils.np_utils import to_categorical
from keras.optimizers import Adam
model = Sequential()
model.add(Dense(8, activation='relu', input_dim=4))
model.add(Dense(16, activation='relu'))
model.add(Dense(32, acti... | StarcoderdataPython |
1726577 | # coding=utf-8
# Author: <NAME> <<EMAIL>>
"""
The :mod:`perturbation_classifiers.subconcept` provides the implementation of
subconcept Perturbation-based Classifier (sPerC) algorithm.
"""
from .sperc import sPerC
__all__ = ['sPerC', 'clustering'] | StarcoderdataPython |
3366697 | import tensorflow as tf
import numpy as np
import callbacks
import pruning
import data
import os
import models
import argparse
from effective_masks import *
from utils import *
import logging
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
parser=argparse.ArgumentParser()
parser.add_argument('--sample',type=str,default='0',hel... | StarcoderdataPython |
3222075 | class CSVFileMixin(object):
"""
Mixin which allows the override of the filename being
passed back to the user when the spreadsheet is downloaded.
"""
def finalize_response(self, request, response, *args, **kwargs):
response = super().finalize_response(request, response, *args, **kwargs)
... | StarcoderdataPython |
46471 | import os
from hashlib import sha224
def search_duplicates(target, options=None):
digests = dict()
for root, dirs, files in os.walk(target):
for item in files:
path = '%s/%s' % (root, item)
hash_digest = _create_digest(path)
if hash_digest not in digests:
... | StarcoderdataPython |
1684132 | import json
from com.huawei.iotplatform.client.invokeapi.Authentication import Authentication
from com.huawei.iotplatform.client.invokeapi.BatchProcess import BatchProcess
from com.huawei.iotplatform.client.dto.AuthOutDTO import AuthOutDTO
from com.huawei.iotplatform.client.dto.BatchTaskCreateInDTO import BatchTaskCr... | StarcoderdataPython |
1629501 | """website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | StarcoderdataPython |
1709497 | <filename>SAR/Proyecto/SAR_indexer.py
from Compendium import *
import os
import sys
if __name__ == '__main__':
if len(sys.argv)>1:
path = sys.argv[1]
savedCompName = sys.argv[2]
else:
path = "./mini_enero"
savedCompName = "newsComp"
collection = sorted(os.listdir(p... | StarcoderdataPython |
3325683 | <filename>logics/upgrade_firmware.py<gh_stars>0
"""Reference: https://medium.com/@keagileageek/paramiko-how-to-ssh-and-file-transfers-with-python-75766179de73
"""
import os
from default_cfg import APP_CFG as dflt_cfg
from .app_constants import *
from logics.sessions import Session
# todo: cmd arguments 1:
# HOSTNAME ... | StarcoderdataPython |
1788283 | from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from .base import BaseTask
from ..encryption import EncryptionService
from ..exception import CryptographyKeysAlreadyCreated
class CryptographyKeysSetupTask(BaseTask):
"""Generates OpenGPG keys required for encryption.
Takes Bac... | StarcoderdataPython |
72477 | <reponame>zjzh/nova<filename>nova/notifications/objects/compute_task.py
# 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
#
# Un... | StarcoderdataPython |
3233857 | # -*- coding: utf-8 -*-
import pyvistaqt as pv
def plot_mesh(self, indices=[]):
"""Plot the mesh using pyvista plotter.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
Returns
-------
"""
mesh = self.... | StarcoderdataPython |
3393081 | <filename>QUIS SISTER 1/1194021_M. RIZKY_D4 TI - 3A/Semaphore.py
import logging
import threading
import time
import random
LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
semaphore = threading.Semaphore(0)
room = 0
exist_room = [1, 4... | StarcoderdataPython |
3277227 | import cv2
import numpy as np
img_path = "Resources/doctor strange.jpg"
width , height = 500,500
img = cv2.imread(img_path)
img_resized = cv2.resize(img ,(width,height) )
image_Cropped = img[0:900, 400:1000] # img[height, width] , y,x
print(img.shape) # (900,1600, 3)
cv2.i... | StarcoderdataPython |
1700036 | """Helpers to facilitate the creation of macros that instantiate rules.
When writing a macro that instantiates multiple rules, one common problem
is how to forward additional kwargs to each rule instantiated.
For example, how to correctly forward "//visibility", or how to forward
"tags" or exec environment.
Additiona... | StarcoderdataPython |
1617944 | __author__ = 'magus0219'
import re
import datetime
str_text = """
标签名:{name}
标签作者:{author}
标签作者email:{email}
标签commit:{commit_id}
标签时间:{tag_time}
标签描述:
{desc}
"""
class Tag():
def __init__(self, name, author, email, commit_id, desc, tag_time):
self.name = name
self.author = author
self.em... | StarcoderdataPython |
51614 | <reponame>le717/flask-google-fonts<filename>flask_google_fonts.py
from typing import Optional
from flask import Flask
from jinja2 import Markup
__all__ = ["GoogleFonts"]
class GoogleFonts:
"""Add fast-rendering Google Fonts to your Flask app.
Uses the techniques outlined in <NAME>'s post.
https://cssw... | StarcoderdataPython |
3389274 | <gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
x = np.arange(-1,9)
y = np.array([2, 1, .1, .05, .5, .1, -.15, .2, 1, 2])
xnew = np.linspace(x[0], x[-1], num=len(x)*100, endpoint=True)
f1 = interp1d(x, y)
f3 = interp1d(x, y, kind='cubic')
plt.figure(figsize=(5,... | StarcoderdataPython |
96827 | <filename>datasets/numeric_fused_head/numeric_fused_head.py
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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... | StarcoderdataPython |
1679283 | import logging
from os import environ
log = logging.getLogger(__name__)
class _Secrets:
"""Runtime abstraction exposing environment variables."""
def __init__(self) -> None:
"""Load attributes from environment."""
log.info("Loading secrets from environment")
keys = ("BOT_TOKEN", "TI... | StarcoderdataPython |
3377450 | <filename>per/migrations/0031_auto_20201106_1222.py
# Generated by Django 2.2.13 on 2020-11-06 12:22
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('per', '0030_auto_20201106_1205'),
]
operations = [
migrati... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.