id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1696855 | <filename>boxcox_lm/model/numpyro.py
import time
from functools import partial
from typing import Optional
import jax.numpy as jnp
import numpyro as pyro
import numpyro.distributions as dist
from jax import grad, random, vmap
from numpy import float32
from numpyro.infer import MCMC, NUTS, Predictive
from .base import... | StarcoderdataPython |
194900 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Common Python library imports
# Pip package imports
import pytest
from flask import url_for
from flask_security import AnonymousUser, current_user
# Internal package imports
from backend.farm.models import Production, Farm, Template
TASK_GENERAL_1 = {
'title': 'tas... | StarcoderdataPython |
63761 | class EngIndexBiMap:
def __init__(self):
self.char2index_dict = dict()
self.index2char_dict = dict()
for i in range(0, 25):
self.char2index_dict[chr(ord('a') + i)] = i
self.index2char_dict[i] = chr(ord('a') + i)
def char2index(self, ch):
return self.char2... | StarcoderdataPython |
1627250 | <reponame>logan-connolly/mychef<filename>api/app/schemas/source.py
from typing import Optional, Union
from pydantic import AnyUrl, BaseModel
class SourceBase(BaseModel):
"Shared properties acrosse all schemas"
name: Optional[str]
url: Optional[Union[str, AnyUrl]]
class SourceCreate(SourceBase):
"Pr... | StarcoderdataPython |
3363862 | <gh_stars>0
from sympy import Matrix, zeros
class ShortestPath(object):
"""
:type path_matrix:Matrix
:type vertex_quantity:Matrix
"""
def __init__(self, path_matrix):
assert path_matrix.shape[0] == path_matrix.shape[1]
self.path_matrix = path_matrix
self.vertex_quantity = ... | StarcoderdataPython |
1785396 | <gh_stars>0
# Generated by Django 2.0.13 on 2019-04-18 16:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hotel', '0005_auto_20190417_2133'),
]
operations = [
migrations.RemoveField(
model_name='feedback',
name='autho... | StarcoderdataPython |
3385374 | import bpy
import json
import math
import mathutils
import os
from math import radians
import bmesh
from mathutils import Matrix, Euler, Vector
import numpy as np
from MaterialFactory import MaterialFactory
class RenderCore:
def __init__(self, config):
self.config = config
self.MaterialFactory = M... | StarcoderdataPython |
164451 | def helper(N):
if (N <= 2):
print ("NO")
return
value = (N * (N + 1)) // 2
if(value%2==1):
print ("NO")
return
s1 = []
s2 = []
if (N%2==0):
shift = True
start = 1
last = N
while (start < last):
if (shift):
... | StarcoderdataPython |
3259861 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import xlrd
import logging
import pdfkit
import simplejson as json
from difflib import get_close_matches
import xlwt
from lxml import etree as ElementTree
from datetime import datetime, timedelta, time, date
from bs4 import BeautifulSoup
from django.htt... | StarcoderdataPython |
85754 | # Copyright 2018, <NAME> LLC
# License: Apache License Version 2.0 + Commons Clause
# ---------------------------------------------------------------------------
# workers.py - configuration related to worker setup. This file *CAN* be
# different per worker.
# --------------------------------------------------------... | StarcoderdataPython |
4822782 | <reponame>Robpol86/sphinx-carousel
"""Sphinx directives."""
from typing import List, Optional, Tuple
from docutils.nodes import caption, Element, image as docutils_image, legend, reference
from docutils.parsers.rst.directives import flag, unchanged
from sphinx.util import logging as sphinx_logging
from sphinx.util.doc... | StarcoderdataPython |
62319 | <reponame>mustard-seed/SparseNN_training
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.quantization import QuantStub, DeQuantStub
import torch.optim as optim
import horovod.torch as hvd
from torchvision import datasets, transforms
import torch.utils.data.distributed as distributed
import... | StarcoderdataPython |
3212399 | <filename>test_aiodataloader.py<gh_stars>100-1000
import pytest
from asyncio import gather
from functools import partial
from pytest import raises
from aiodataloader import DataLoader
pytestmark = pytest.mark.asyncio
async def do_test():
return True
def id_loader(**options):
load_calls = []
async def ... | StarcoderdataPython |
3266324 | from django.contrib.auth import get_user_model
from rest_framework import generics, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from api.permissions import SuperUserCr... | StarcoderdataPython |
1710701 | from .actor import Actor, EnvelopeTracker, register_handler
from .actlet import Actlet
from .messages import ShutdownMessage, ActletDoneMessage, TimerDoneMessage
from .proxy import ActorProxy
from .router import Router
__all__ = [
'Actlet',
'Actor',
'ActorProxy',
'EnvelopeTracker',
'Router',
'r... | StarcoderdataPython |
3274562 | <gh_stars>0
from Sim import *
from Singleton import *
import json
import matplotlib.pyplot as plt
import numpy as np
import pyfits
import os
import shutil
import random
import sys
class ValidateModel(Singleton):
## Manager object for xspec model validation and visualization of data
## (This is a singleton object ... | StarcoderdataPython |
164637 | <gh_stars>0
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
#学習用データが足りない時に使う
def dilution_img(input_img):
#画像のサイズ
img_size = input_img.shape
filter_one = np.ones([3,3])
#回転用
mat_1 = cv2.getRotationMatrix2D(tuple(np.array(input_img.shape[:2])/2),23,1)
mat_2 = cv2.getRotationM... | StarcoderdataPython |
45299 | <gh_stars>0
import re
import random
TEMPLATE_RE = re.compile(r"\{(.+?)\}")
class TextGenerator(object):
def __init__(self, templates, parts, default_templates=None, variables=None):
self.templates = templates
self.default_templates = default_templates
self.parts = parts
self.varia... | StarcoderdataPython |
3361217 | # -*- coding: utf-8 -*-
import re
from collections import OrderedDict
from . import noteparser
class Jianpu(noteparser.NoteParser):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.CHROMATIC_SCALE_DICT = {'1': 0, '1#': 1, '2b': 1, '2': 2, '2#': 3, '3b': 3, '3': 4, '4': 5, '4#': 6,
... | StarcoderdataPython |
135442 | import setuptools
import re
VERSIONFILE = "alchemyml/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
with o... | StarcoderdataPython |
1139 | <reponame>smokedpirate/Encryption-hash-generator<gh_stars>1-10
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtGui, QtCore
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(577, 341)
palette = QtGui... | StarcoderdataPython |
13766 | #!/usr/bin/env python
# -*- coding: utf-8 -*-,
from __future__ import absolute_import
from __future__ import print_function
from . import logging as xAH_logging
try:
from .config import Config
except:
xAH_logging.logger.warning("xAH::Config could not be imported.")
__version__ = "1.0.0"
__all__ = ["utils", "... | StarcoderdataPython |
3271569 | <gh_stars>0
"""
==========================
Discrete Fourier Transform
==========================
This example shows how you can approximate a time series using only some of its
Fourier coefficients using :class:`pyts.approximation.DFT`.
"""
import numpy as np
import matplotlib.pyplot as plt
from pyts.approximation im... | StarcoderdataPython |
1706013 | import pytest
from freezegun import freeze_time
import datetime
from io import BytesIO
from aerofiles.igc import Writer
@pytest.fixture()
def output():
return BytesIO()
@pytest.fixture()
def writer(output):
return Writer(output)
def test_write_line(writer):
writer.write_line('line')
assert writ... | StarcoderdataPython |
125897 | <filename>tests/test_experiment/test_local_load/test_local_model_load.py
import os
import unittest
import shutil
from collections import OrderedDict
import torch.nn as nn
from tests.utils import *
from aitoolbox.experiment.local_load.local_model_load import PyTorchLocalModelLoader
from aitoolbox.experiment.local_save... | StarcoderdataPython |
1643104 | <filename>main.py
from http.server import HTTPServer
from src.http import httpHandler
PORT_NUMBER = 8082
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), httpHandler)
print('Started httpserver on port ' , PORT_NUMBER)
#Wai... | StarcoderdataPython |
23026 | from .mdp_value_iteration import value_iteration | StarcoderdataPython |
3239288 | <reponame>mashton/policyk
import logging
from django.db import models
from policyengine.models import CommunityPlatform, CommunityUser
from policyengine.utils import default_boolean_vote_message
logger = logging.getLogger(__name__)
class GithubUser(CommunityUser):
pass
class GithubCommunity(CommunityPlatform)... | StarcoderdataPython |
3280183 | <filename>tests/pint_enable.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Zinc dumping and parsing module
# (C) 2016 VRT Systems
#
# vim: set ts=4 sts=4 et tw=78 sw=4 si:
# If `pint` is not installed or available, skip the relevant tests.
try:
import pint
import hszinc
from hszinc.pintutil import to_pint
... | StarcoderdataPython |
3261275 | <reponame>SlothKun/Trello_SuperTemplate_Prototype
import sys
import dboperations
import restapioperations as apiop
import pprint
pp = pprint.PrettyPrinter(indent=4)
#db = dboperations.dboperations()
#db.connect()
class baseoperations():
def __init__(self):
self.username = ""
self.key =... | StarcoderdataPython |
130586 | <gh_stars>100-1000
#!/usr/bin/env python
# <NAME> for bowtie2
# Modified by <NAME> for homer
from __future__ import print_function
import json
import optparse
import os
import subprocess
import sys
DEFAULT_DATA_TABLE_NAME = "homer_preparse"
def get_id_name(params, dbkey, fasta_description=None):
# TODO: ensure ... | StarcoderdataPython |
1706129 | import unittest
from . import filter_tests
from . import query_tests
from . import formatter_tests
from . import performance_tests
def run_tests():
suite = unittest.TestLoader().loadTestsFromModule(filter_tests)
suite.addTests(unittest.TestLoader().loadTestsFromModule(query_tests))
suite.addTests(unittest... | StarcoderdataPython |
69150 | <filename>screenshots/Part-4/ext/table.py
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
class Table(QtGui.QDialog):
def __init__(self,parent = None):
QtGui.QDialog.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
# Rows
... | StarcoderdataPython |
1681478 | <filename>enrichers/sentence_splitter.py
from enrichers.base import Enricher
from nltk.data import load as nltk_load
import json
import regex
from itertools import chain
class SentenceSplitter(Enricher):
name = 'sentence_splitter'
persistent = False
requires = ('cleaner',)
def __init__(self, *args, *... | StarcoderdataPython |
3388682 | from datetime import datetime, timedelta
from django.urls import reverse
from django.test import TestCase
from django.utils.crypto import get_random_string
from prometheus_client.parser import text_string_to_metric_families
from zentral.contrib.munki.models import ManagedInstall, MunkiState
from zentral.conf import set... | StarcoderdataPython |
3350338 | <filename>asyncapi/_tests/__init__.py
from dataclasses import dataclass
from asyncapi import AutoSpec
spec = AutoSpec(
title='Fake API',
description='Faked API',
version='0.0.1',
development='kafka://fake.fake',
)
@dataclass
class FakeMessage:
faked: int
@spec.subscribe(
channel_name='fak... | StarcoderdataPython |
145832 | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import glob
import logging
import re
import subprocess
import tempfile
from datetime import datetime as dt
from string import Template
class TaskFailedException(Exception):
pass
class TempDirIsFileException(Exception):
pass
class Tas... | StarcoderdataPython |
3321839 | <gh_stars>10-100
import hashlib
import uuid
mac = uuid.getnode()
def make_id(code: str) -> uuid.UUID:
"""Make a pseudo-random ID that is constant on a particular machine.
When the same `code` is specified, this ID should always be the same for a
particular machine, but it should differ between different machi... | StarcoderdataPython |
1677380 | import os
import urllib.parse
from django.contrib.auth.models import User
from django.test import TestCase
from dfirtrack.settings import BASE_DIR
from dfirtrack_config.models import SystemImporterFileCsvConfigModel
from dfirtrack_main.tests.system_importer.config_functions import (
set_csv_import_filename,
s... | StarcoderdataPython |
3233824 | """Forex Controller."""
__docformat__ = "numpy"
import argparse
import difflib
from datetime import timedelta, datetime
from typing import List, Union
import pandas as pd
from colorama import Style
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal import feature_flags as gtff
from gamesto... | StarcoderdataPython |
1730881 | # AUTOGENERATED! DO NOT EDIT! File to edit: 02_oo_hp.ipynb (unless otherwise specified).
__all__ = ['SEED', 'auto_assign', 'HypsterBase', 'HpExpression', 'HYPSTER_TYPES', 'SubExpression', 'AddExpression',
'MulExpression', 'DivExpression', 'PowExpression', 'set_init_name', 'HpInt', 'HpFloat', 'HpFunc',
... | StarcoderdataPython |
1625291 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import re
import sys
from pathlib import Path
from typing import List
import humanize
import pandas as pd
from llvm_rl.model import Model
from... | StarcoderdataPython |
1686857 | <reponame>unseenme/mindspore
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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 re... | StarcoderdataPython |
3334988 | import pandas as pd
import difflib
import random
from estimators import utils
random.seed(1)
class NaiveEstimator:
def __init__(self, args):
if 'Sept' in args.experiment_name:
trace_range = ('2020-09-01 00:00:00', '2020-09-26 23:59:00')
elif 'July' in args.experiment_name:
... | StarcoderdataPython |
65182 | import os
import time
import urllib, json
from random import randint
from flask import Flask
from flask_ask import Ask, statement, question
app = Flask(__name__)
ask = Ask(app, '/')
MAGIC_SEAWEED_KEY = 'e96ca9b1f03a627aaab136eafe4f83ee'
SPOT_ID = '1449'
@ask.launch
def launched():
return question("This is a sur... | StarcoderdataPython |
3220138 | # Generated by Django 3.2 on 2021-05-05 20:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20210505_1718'),
]
operations = [
migrations.RenameField(
model_name='card',
old_name='card_num',
... | StarcoderdataPython |
1610071 | <reponame>sunjc53yy/chromium
# Copyright 2014 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.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class AndroidAcceptancePa... | StarcoderdataPython |
5278 | """
Defines the basic objects for CORE emulation: the PyCoreObj base class, along with PyCoreNode,
PyCoreNet, and PyCoreNetIf.
"""
import os
import shutil
import socket
import threading
from socket import AF_INET
from socket import AF_INET6
from core.data import NodeData, LinkData
from core.enumerations import LinkTy... | StarcoderdataPython |
3276951 | import os
import numpy as np
import torch
from torchvision import datasets, transforms
from datasets.sbmnist import load_sbmnist_image
class StackedMNIST(datasets.MNIST):
def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
super().__init__(root=root, transform=tran... | StarcoderdataPython |
1705353 | <reponame>phrb/orio_experiments<gh_stars>0
"""
Rewritten from original version by mac
@author: norris
"""
from orio.main.util.globals import *
import time
class Stats:
def __init__(self, params={}):
pass
def record(self, x, y, extra="", progress=""):
""" record x and y coordinates -- subcl... | StarcoderdataPython |
147053 | from django.urls import path
from .views import ContractListView, ContractDetailView
from django.conf import settings
app_name = 'contract'
urlpatterns = [
path('', ContractListView.as_view(), name='contract_list'),
path('<uuid:pk>', ContractDetailView.as_view(),
name='contract_detail'),
]
| StarcoderdataPython |
3278822 | <reponame>lewisjnewman/blog<filename>migrations/versions/be3c2d8a314f_.py
"""empty message
Revision ID: <PASSWORD>
Revises: <PASSWORD>
Create Date: 2020-09-07 01:33:35.832994
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = '<PASSWOR... | StarcoderdataPython |
3359378 | <reponame>jimbarnesrtp/pf2<gh_stars>10-100
# -*- coding: utf-8 -*-
import unittest
from buildItems import ItemBuilder
import os
class TestBuildItems(unittest.TestCase):
line_break = "++++++++++++++++++++++++++++++++++"
data = []
norm_data = []
def load_items(self) -> list:
if len(self.da... | StarcoderdataPython |
4815569 | <filename>adobe_no_of_1_bits.py
'''
Number of 1 Bits
Asked in: Adobe, Yahoo
https://www.interviewbit.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of 1 bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so ... | StarcoderdataPython |
1638227 | <filename>ironic/tests/unit/conductor/test_steps.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
#
# Unless required by app... | StarcoderdataPython |
3383510 | <filename>actions/action_decorator.py
from functools import wraps
def action(label):
"""Decorator to convert a function to a callable usable by the Action
class.
Args:
label (str): The label to show before executing the action.
"""
def wrapper(f):
"""
Returns:
... | StarcoderdataPython |
3260199 | import json
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.http import request
from django.shortcuts imp... | StarcoderdataPython |
3241815 | from typing import List
from urllib.parse import quote
from buffpy.models.update import Update
PATHS = {
"GET_PENDING": "profiles/{}/updates/pending.json",
"GET_SENT": "profiles/{}/updates/sent.json",
"SHUFFLE": "profiles/{}/updates/shuffle.json",
"REORDER": "profiles/{}/updates/reorder.json",
"C... | StarcoderdataPython |
1736639 | <filename>utilities/png_seq_to_gif.py<gh_stars>1-10
"""
Convert a png sequence of a animated gif used for presenting the experiments
"""
import os
import sys
import imageio
def main():
png_dir = sys.argv[1]
images = []
for i, file_name in enumerate(sorted(os.listdir(png_dir))):
if i % 10 == 0:
... | StarcoderdataPython |
4839617 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from typing import Dict, List, Any
from recc.core.mixin.context_base import ContextBase
from recc.template.v1 import keys as v1k
class ContextStorage(ContextBase):
async def get_templates_v1(self) -> List[Dict[str, Any]]:
result = list()
for k, v in self.sto... | StarcoderdataPython |
41756 | <reponame>menghao2015/MyBlog<filename>myapp/decorators.py
from functools import wraps
from flask import abort
from flask.ext.login import current_user
from .models import Permission
def permission_required(permission):
def decorators(f):
@wraps(f)
def decorators_function(*args, **kwargs):
if not current_user.... | StarcoderdataPython |
1731369 | <gh_stars>0
from Bio.PDB import *
def CheckingNewChains(chains_movil, chains_fixed, equivalences, stoich):
"""Takes the list of chains that are already in the complex and two chains that are evaluating for being added to the complex. Return a
Arguments:
chains_movil -- list of chains objects that are evaluating f... | StarcoderdataPython |
1740037 | from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import cross_val_score
from hyperactive import Hyperactive
def test_issue_29():
data = load_diabetes()
X, y = data.data, data.target
def model(para):
gbr = GradientBoost... | StarcoderdataPython |
159791 | <filename>Programming Fundamentals/Mid exam prep/froggy_squad.py
frogs = input().split(' ')
while True:
token = input().split(' ')
length = len(frogs) - 1
command = token[0]
if command == 'Join':
name = token[1]
frogs.append(name)
elif command == 'Jump':
name = token[1]
... | StarcoderdataPython |
1717858 | from ThesisAnalysis.plotting.setup import ThesisPlotter
from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader
import os
import numpy as np
from matplotlib.ticker import MultipleLocator, FuncFormatter
from target_calib import CalculateRowColumnBlockPhase, GetCellIDTCArray
def setup_cells(df, camera):
fci... | StarcoderdataPython |
3216742 | import os
from pipeline.backend.pipeline import PipeLine
pipeline_upload = PipeLine().set_initiator(role='guest', party_id=9999).set_roles(guest=9999)
partition = 4
dense_data_guest = {"name": "breast_hetero_guest", "namespace": f"experiment"}
dense_data_host = {"name": "breast_hetero_host", "namespace": f"experiment... | StarcoderdataPython |
3384446 | <filename>besspin/cwesEvaluation/PPAC/vulClassTester.py
#! /usr/bin/env python3
""" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
This file has the custom PPAC methods to for runTests
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # """
from besspin.cwesEvaluation.compat ... | StarcoderdataPython |
1735720 | # Import necessary libraries
from fastai.basics import *
from fastai.data.all import *
from fastai.vision.all import *
from fastai.callback.all import *
from fastai.metrics import *
from fastai.callback.wandb import *
from pathlib import Path
from tqdm import tqdm
from math import ceil
import wandb
# wandb.login()
... | StarcoderdataPython |
145517 | <gh_stars>1000+
"""
Parameter retrieval exceptions
"""
class GetParameterError(Exception):
"""When a provider raises an exception on parameter retrieval"""
class TransformParameterError(Exception):
"""When a provider fails to transform a parameter value"""
| StarcoderdataPython |
1703810 | name = "custom-search"
| StarcoderdataPython |
3323446 | # -*- coding: utf-8 -*-
#pylint: skip-file
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import io
import csv
import os
_ver = sys.version_info
is_py2 = (_ver[0] == 2)
is_py3 = (_ver[0] == 3)
is_py33 = (... | StarcoderdataPython |
1770121 | <reponame>larryweya/dry-pyramid
from passlib.context import CryptContext
from pyramid.security import has_permission
pwd_context = CryptContext()
def permission_check_func(context, request):
""" Attach a function for has_permission checks within templates.
For example:
.. code-block:: python
... | StarcoderdataPython |
188050 | __version__ = '9.2.3' | StarcoderdataPython |
1696306 | import os
import time
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import ray
from ray.util.sgd import TorchTrainer
from ray.util.sgd.utils import AverageMeterCollection
from ray.util.sgd.torch import TrainingOperator
import dgl
from dgl.data import RedditData... | StarcoderdataPython |
49697 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version':... | StarcoderdataPython |
9144 | <reponame>chandrashekar-cohesity/management-sdk-python
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.continuous_schedule
import cohesity_management_sdk.models.daily_schedule
import cohesity_management_sdk.models.monthly_schedule
import cohesity_management_sdk.models.rpo_s... | StarcoderdataPython |
3278195 | import unittest
from main import one, two
instructions = [
"forward 5",
"down 5",
"forward 8",
"up 3",
"down 8",
"forward 2",
]
class TestOne(unittest.TestCase):
def test_simple(self):
self.assertEqual(150, one(instructions))
class TestTwo(unittest.TestCase):
def test_simpl... | StarcoderdataPython |
111718 | <reponame>pitkanenlauri/questoffununlimited<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012-2017, <NAME> <<EMAIL>>
This file is part of pytmx.
pytmx is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Founda... | StarcoderdataPython |
1600016 | '''
Date: 2021-05-19 09:50:09
LastEditors: Liuliang
LastEditTime: 2021-05-19 09:51:25
Description:
'''
#叶子节点可以理解成不依赖其他tensor的tensor
import torch
a=torch.tensor([1.0])
print(a.is_leaf)
b=a+1
print(b.is_leaf) | StarcoderdataPython |
151142 | <gh_stars>0
from dataclasses import dataclass, field
from typing import Optional
from bindings.csw.abstract_positional_accuracy_type import (
AbstractPositionalAccuracyType,
)
from bindings.csw.result import Result
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class AbsoluteExternalPositionalAccuracyTy... | StarcoderdataPython |
12734 | # flake8:NOQA
"""Python asteroid airburst calculator"""
from .solver import *
from .damage import *
from .locator import *
from .mapping import *
| StarcoderdataPython |
3244546 | v = 2
validador = contador = 0
lista = []
N = int(input('Quantos números primos deseja mostrar? '))
while contador != N:
for c in range(1, v):
if v % c == 0:
validador += 1
if validador == 1:
lista.append(v)
contador +=1
validador = 0
v +=1
for i,v in enumerate(lista)... | StarcoderdataPython |
1796483 | import ataxx
import unittest
class TestMethods(unittest.TestCase):
def test_pass(self):
tests = [
["x5o/7/7/7/7/7/o5x x 0 1", False],
["x5o/7/2-1-2/7/2-1-2/7/o5x x 0 1", False],
["x5o/7/3-3/2-1-2/3-3/7/o5x x 0 1", False],
["7/7/7/7/4ooo/4ooo/4oox x 0 1", True... | StarcoderdataPython |
189618 | <gh_stars>1-10
# ==============================================================================
# Copyright 2018 <NAME>. 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
#... | StarcoderdataPython |
1747526 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
pcaptomsc
~~~~~~~~~~~~~~~~~~~~
converting wireshark packet capture (pcap) into message sequence chart for sequencediagram.net, hackmd.io, or mscgen (png, svg, and eps format).
See the README file for details.
:author: Jonathan <<EMAIL>>... | StarcoderdataPython |
3259488 | import mwclient
import mwparserfromhell
import logging
import re
import sys
def fix(page):
text = page.text()
p = mwparserfromhell.parse(text)
has_bad_link = False
for link in p.filter_wikilinks():
if "File:" in link.title:
print("Fixing link", link.title, "in", page.name)
... | StarcoderdataPython |
153857 | <filename>gcAPI/event.py
from __future__ import print_function
import datetime
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import os
def addEvent(EVENT):
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argpar... | StarcoderdataPython |
3244391 | <filename>venv/Lib/site-packages/jsonpickle/version.py
try:
import importlib_metadata as metadata
except ImportError:
metadata = None
def _get_version():
try:
version = metadata.version('jsonpickle')
except (AttributeError, ImportError):
version = __default_version__
return version... | StarcoderdataPython |
3222732 | import os
os.system("sudo ln -s /dev/ttyUSB0 /dev/ttyS35")
os.system("sudo ./MotorControllerCode/HelloEposCmd") | StarcoderdataPython |
84281 | # 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
# distributed under t... | StarcoderdataPython |
89885 | <gh_stars>1-10
def send_email(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#fl... | StarcoderdataPython |
1769471 | <gh_stars>1-10
from org.meteothink.table import TableUtil
from org.meteothink.layer import LayerTypes, VectorLayer, ChartSet
from org.meteothink.projection import ProjectionUtil
from org.meteothink.common.projection import KnownCoordinateSystems
from org.meteothink.shape import PolygonShape, ShapeTypes
from org.meteot... | StarcoderdataPython |
187075 | #!/usr/bin/python3
import pyperclip
'''
String puras
Podemos inserir um r antes das pastas de inicio em uma string para
transofrmá-la em uma string pura (raw string), com isso a string
ignorará todos os caracteres de scape
'''
print('Exemplo de um string pura:')
print(r'\n\t That is Carlos \'s cat.')
'''
Strings em m... | StarcoderdataPython |
33337 | from typing import List
import pytest
from cfn_lint_ax.rules import (
CloudfrontDistributionComment,
CloudfrontDistributionLogging,
)
from tests.utils import BAD_TEMPLATE_FIXTURES_PATH, ExpectedError, assert_all_matches
@pytest.mark.parametrize(
"filename,expected_errors",
[
(
"c... | StarcoderdataPython |
173947 | <gh_stars>10-100
# coding: utf-8
import numpy as np
import pandas as pd
import os
import networkx as nx
from utils import get_nx_graph, check_and_make_path
def get_graph_from_nodes(file_path, node_file, output_node_dir, output_edge_dir, sep='\t'):
import random
df_edges = pd.read_csv(file_path, sep=sep, heade... | StarcoderdataPython |
122146 | # -*- coding:utf-8 -*-
from django.db import models
# Create your models here.
from article.models import Post
class Comment(models.Model):
STATUS_NORMAL = 1
STATUS_DELETE = 0
STATUS_ITEMS = [
(STATUS_NORMAL, '正常'),
(STATUS_DELETE, '删除')
]
target = models.CharField(max_length=5... | StarcoderdataPython |
1675919 | def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
| StarcoderdataPython |
3390373 | # -*- coding: utf-8 -*-
import numpy as np
import torch
from torch import Tensor
from ctp.clutrr.base import Instance
from ctp.util import make_batches
from typing import Callable, List, Optional, Tuple, Any, Dict
def accuracy(scoring_function: Callable[[List[Instance], List[str]], Tuple[Tensor, Any]],
... | StarcoderdataPython |
1734030 | <gh_stars>1-10
def Caesar(text, sdv):
text = text.lower()
s = ''
for c in text:
if 'а' <= c <= 'я':
ot_sm = ord(c) - ord('а')
new_ot_sm = (ot_sm + sdv) % 32
abs_sm = ord('а') + new_ot_sm
c = chr(abs_sm)
s += c
return s
s = Caesar(input(),... | StarcoderdataPython |
4818420 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 14:00:33 2021
@author: <EMAIL>
"""
import os, subprocess, platform
import xarray, datetime
import numpy as np
from eclipse import utils, eio
from dateutil import parser
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from argparse import ArgumentPars... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.