id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
14304 | # encoding: utf-8
# module win32profile
# from C:\Python27\lib\site-packages\win32\win32profile.pyd
# by generator 1.147
# no doc
# no imports
# Variables with simple values
PI_APPLYPOLICY = 2
PI_NOUI = 1
PT_MANDATORY = 4
PT_ROAMING = 2
PT_TEMPORARY = 1
# functions
def CreateEnvironmentBlock(*args, **kwargs): # re... | StarcoderdataPython |
1695906 | <filename>trr265/gbe/participants.py
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/19_gbe.participants.ipynb (unless otherwise specified).
__all__ = []
# Cell
%load_ext autoreload
%autoreload 2
from .data_provider import GBEProvider
import pandas as pd | StarcoderdataPython |
6655774 | <reponame>bahp/python-spare-code
"""
Plotly - Weather
================
"""
# -------------------
# Main
# -------------------
# https://chart-studio.plotly.com/~empet/13748/sparklines/#/code
# https://omnipotent.net/jquery.sparkline/#s-about
# https://chart-studio.plotly.com/create/?fid=Dreamshot:8025#/
# Libraries
im... | StarcoderdataPython |
11375908 | __copyright__ = "Copyright (c) Microsoft Corporation and Mila - Quebec AI Institute"
__license__ = "MIT"
"""Constructors for MDP objects using pickleable dictionaries.
"""
import logging
from typing import Union
from segar.sim import Simulator
from segar.mdps import (
MDP,
RGBObservation,
ObjectStateObs... | StarcoderdataPython |
1736688 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
import socket
import time
import traceback
from kombu import Consumer
from easyjoblite import constants
from easyjoblite.consumers.base_rmq_consumer import BaseRMQConsumer
from easyjoblite.job import EasyJob
class RetryQueueConsumer(BaseRMQConsumer):
"""
... | StarcoderdataPython |
1894551 | def main():
year = int(input())
while True:
year = year + 1
if len(set(str(year))) == len(str(year)):
break
print(year)
if __name__ == "__main__":
main()
# def func(n):
# while True:
# n = n + 1
# if len(set(str(n))) == len(str(n)):
# bre... | StarcoderdataPython |
5016290 | from inspect import signature
from typing import Any, Tuple
from discord.ext.commands import Converter
def onoff(val: bool) -> str:
return "on" if val else "off"
def format_duration(seconds: int) -> str:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
dstr = f"{d}d " if d e... | StarcoderdataPython |
1621020 | from openpyxl import load_workbook
wb = load_workbook("성적목록.xlsx", data_only=True)
ws = wb.active
ws["H1"] = "총점"
ws["I1"] = "성적"
for col in ws.iter_cols(min_row=2, max_row= 11, min_col=4, max_col=4):
for cell in col:
cell.value = 10
for colu in ws.iter_cols(min_row=2, max_row= 11, min_col=8, max_col=8):
... | StarcoderdataPython |
114329 | """A module for demonstrating exceptions"""
import sys
def convert(s):
'''convert to a integer'''
try:
return int(s)
except (ValueError, TypeError):
raise | StarcoderdataPython |
1762829 | from itertools import accumulate
class Solution:
def numberOfArrays(self, diff, lower, upper):
A = list(accumulate(diff, initial=0))
return max(0, (upper - lower) - (max(A) - min(A)) + 1)
| StarcoderdataPython |
80864 | <filename>apptools/logger/agent/quality_agent_mailer.py
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforement... | StarcoderdataPython |
3297884 | <reponame>Tsukinome/Tesla-factory<filename>tesla/fabric.py
class Tesla:
"""
Defines car specs and actions
Parameters:
model: car model
color: car color
autopilot: autopilot present
efficiency: power consumption coefficient
battery_charge: battery ... | StarcoderdataPython |
5110859 | <filename>utils/config.py
"""
Common functionality for all sock-classifier programs.
"""
import argparse
import logging
from pathlib import Path
def logging_cli():
"""Provide the common CLI arguments for logging.
Returns a ArguemntParser.
"""
parser = argparse.ArgumentParser(add_help=False)
grou... | StarcoderdataPython |
1817488 | import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input as preprocess_input_resnet50
from tensorflow.keras.preprocessing import image
from numpy import linalg as LA
class Resnet50:
def __init__(self):
self.input_sha... | StarcoderdataPython |
8166445 | <filename>paradigma_funcional/roteiro8/main.py<gh_stars>0
from vector_operations import *
from matrix_operations import *
def main():
# Parte 1
v = [1,2,3]
w = [10,10,10]
print "v: ", v
print "w: ", w
print "\n||v||: ", norma(v)
print "2 * v: ", multiplyByScalar(v, 2)
print "v + w: ", a... | StarcoderdataPython |
1611600 | <reponame>MalcolmScoffable/openapi-generator
# coding: utf-8
# flake8: noqa
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: ... | StarcoderdataPython |
6575958 | from settings import api
class Command:
"""
A class that contains all the possible commands.
Note: every function documentation is used for help() command
"""
def __init__(self, commandline, message):
self.__message = message
self.__paramstr = commandline.get("args", "") ... | StarcoderdataPython |
5182263 |
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = []
for letter in s:
if not stack:
stack.append((letter, 1))
else:
prev_letter, count = stack[-1]
if letter == prev_letter:
if count... | StarcoderdataPython |
1982575 | import hoi4
import re
import copy
import hoi4
import json
default_year = 1918
techs = hoi4.load.get_technologies()
#
# folders = [ "land_doctrine_folder","naval_doctrine_folder","air_doctrine_folder" ]
folders = [ "land_doctrine_folder" ]
data = techs.raw_data();
tech_paths = {};
children = {};
parents = {};
doc... | StarcoderdataPython |
11314683 | """
This file constructs a dictionary of all of the station-codes/obs-codes
of artificial satellites for which wis.py knows how to get spice-kernels
The data for each obs-code is specified in a "KernelManager" object
Each KernelManager-Object is saved into an overall
obscodeDict
- The... | StarcoderdataPython |
6564241 | <filename>agile/plugins/labels.py
import asyncio
from .. import core
class Labels(core.AgileCommand):
description = 'Set labels in github issues'
async def run(self, name, config, options):
repositories = self.as_list(config.get('repositories'),
'No repositories g... | StarcoderdataPython |
4826418 | #imports
from PySide2 import QtWidgets, QtCore, QtGui, QtWebEngineWidgets
import hou
import pdg
import time
import math
import codecs
import os
import sys
import errno
import ast
import subprocess
from functools import partial
import pdg_mutagen
#info
__author__ = "<NAME>"
__copyright__ = "2019 All rights reserved... | StarcoderdataPython |
3333188 | <reponame>Dalkio/custom-alphazero
import os
tensorflow_log_level = "3"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = tensorflow_log_level
class ConfigGeneral:
game = "connect_n"
# -1 is used to disable the GPU
# other values should be used only once
self_play_gpu_index = "-1"
serving_gpu_index = "-1"
... | StarcoderdataPython |
8176881 | <gh_stars>0
expected_output = {
'lisp_id': {
0: {
'total_extranets': 1,
'max_allowed_ipv4_prefix': 4294967295,
'total_ipv4_prefix': 4,
'max_allowed_ipv6_prefix': 4294967295,
'total_ipv6_prefix': 0,
'extranet_name': {
'ext1': {
'provider_iid': 111,
'provider_ipv4_prefix_count': 0,
... | StarcoderdataPython |
8123439 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 10:33:55 2019
@author: ryder
"""
# import os
import pygsheets
import sheet_processing_functions as spf
import validation_logic
#%%
if __name__ == "__main__":
with open('keys/google_expenses_sheet_key.txt', 'r') as g_sheet_id_key_txt:
GOOG... | StarcoderdataPython |
9659936 | #!/usr/bin/env python
import commands
import re
import condor_config
from master_job import *
class CondorSubmitJob:
def __init__(self, results_dir, output_dir_list):
self.results_dir = results_dir
self.createSubmitScript(output_dir_list)
def createSubmitScript(self, output_dir_list):
submit... | StarcoderdataPython |
12838854 | from __future__ import annotations
from blox_old.core.engine.device import BlockDevice
from blox_old.btorch.module import TorchModule, TorchModuleError
import torch
from blox_old.utils import raise_if
from blox_old.core.block.base import Block
import typing as T
class TorchCudaError(TorchModuleError):
pass
def ... | StarcoderdataPython |
11286635 | import pytest
import jax
import jax.numpy as jnp
import netket as nk
import numpy as np
from functools import partial
@pytest.mark.parametrize("jit", [False, True])
@pytest.mark.parametrize("N", [1, 100])
def test_scan_append_reduce(jit, N):
def f(x):
y = jnp.sin(x)
return y, y, y**2
x = jnp... | StarcoderdataPython |
3237050 | <reponame>Bladez1753/lightning<gh_stars>1000+
from pyln.client import LightningRpc, RpcError, Millisatoshi, __version__, Plugin, monkey_patch
__all__ = [
"__version__",
"LightningRpc",
"RpcError",
"Millisatoshi",
"Plugin",
"monkey_patch",
]
| StarcoderdataPython |
6599643 | from .transporter import Transporter
from ..levels import Levels
from ..messages.log import Log
class Console(Transporter):
def __init__(self, level: Levels=None, same_level: bool=True, trans_id: str=None):
super().__init__(level, same_level, trans_id)
def transport(self, log: Log) -> None:
p... | StarcoderdataPython |
201303 | # coding: utf-8
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for /query api endpoint."""
import ddt
from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.... | StarcoderdataPython |
6551865 | #!/usr/bin/env python
from setuptools import find_packages, setup
import os
import subprocess
import sys
import time
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def make_cuda_ext(name, sources, sources_cuda=None):
if sou... | StarcoderdataPython |
139970 | <reponame>Jawayria/edx-analytics-data-api-client
import json
import httpretty
from analyticsclient.exceptions import NotFoundError
from analyticsclient.tests import ClientTestCase
class EngagementTimelineTests(ClientTestCase):
def setUp(self):
super(EngagementTimelineTests, self).setUp()
self... | StarcoderdataPython |
5058903 | <filename>tests/test_logger.py
import logging
from telemetry.telescope_ec2_age.logger import create_app_logger
def test_logger():
logger = create_app_logger(logging.CRITICAL)
assert isinstance(logger, logging.Logger)
assert logger.level == logging.CRITICAL
| StarcoderdataPython |
4810463 | <filename>var/spack/repos/builtin/packages/r-sn/package.py
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RSn(RPackage):
"""Build and man... | StarcoderdataPython |
1885564 | <reponame>gbr1/image_manipulator
from setuptools import setup
from os import path
package_name = 'image_manipulator'
here = path.abspath(path.dirname(__file__))
with open(path.join(here,'requirements.txt'),encoding='utf-8') as f:
requirements = f.read().splitlines()
setup(
name=package_name,
version='1.0... | StarcoderdataPython |
6495717 | import pytest
import re
# captures the server url and replaces IP or name with localhost-testing to help with cassette errors
def scrub_string(string, replacement=""):
def before_record_response(response):
regexp_http = "^https?://[^/]+/+[^/]+/+[^/]+/"
regexp_username = "_username=[a-zA-Z]+"
... | StarcoderdataPython |
3291992 | """
Helper functions for typo generation
"""
from aenum import Enum
class KeyboardEnum(str, Enum):
"""Available keyboards"""
be = "be"
class ModeEnum(str, Enum):
full = "full"
invert = "invert"
wrong = "wrong"
duplicate = "duplicate"
miss = "miss" | StarcoderdataPython |
9601542 | <reponame>cwegrzyn/records-mover<gh_stars>10-100
from typing import Optional
from .base import (SupportsMoveToRecordsDirectory,
SupportsToDataframesSource)
from ...db.quoting import quote_schema_and_table
from ...db import DBDriver
from ..records_directory import RecordsDirectory
from ..processing_in... | StarcoderdataPython |
9723415 | from scigateway_auth.common.config import Config, get_config_value
try:
with open(get_config_value(Config.PRIVATE_KEY_PATH), "r") as f:
PRIVATE_KEY = f.read()
except FileNotFoundError:
PRIVATE_KEY = ""
try:
with open(get_config_value(Config.PUBLIC_KEY_PATH), "r") as f:
PUBLIC_KEY = f.read(... | StarcoderdataPython |
8028963 | from chessServer.client import Client
class Admin(Client):
def __init__(self, hostname, port, admin_authentication):
super(Admin, self).__init__(hostname, port, admin_authentication, 'admin', '')
| StarcoderdataPython |
12823746 | <reponame>nikhase/statsmodels
import numpy as np
"""
Generate data sets for testing Cox proportional hazards regression
models.
After updating the test data sets, use R to run the survival.R script
to update the R results.
"""
# The current data may not reflect this seed
np.random.seed(5234)
# Loop over pairs conta... | StarcoderdataPython |
1985665 | from arago.actors.actor import Actor, Task, ActorStoppedError
from arago.actors.monitor import Monitor, Root, SHUTDOWN, RESTART, RESUME, ESCALATE, IGNORE, DEPLETE
from arago.actors.router import Router
from arago.actors.source import Source
from arago.actors.agent import Agent
| StarcoderdataPython |
243933 | <filename>actions/actions.py
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
import requests
from rasa_sdk import Action
from rasa_sdk.events import SlotSet
class ActionChitchat(... | StarcoderdataPython |
6519235 | import cv2, torch, torch.nn as nn
import numpy as np
import kornia as k, os, glob
from data.augmentation import Augmentation_random_crop
class Dataset(torch.utils.data.Dataset):
def __init__(self, opt, mode):
self.mode = 'train' if mode == 'train' else 'eval'
self.seq_length = opt.Data['sequence... | StarcoderdataPython |
353109 | <gh_stars>0
#-*- encoding: UTF-8 -*-
from django import forms
class NombreProductoWidget(forms.TextInput):
def __init__(self):
super(NombreProductoWidget,self).__init__(attrs={'class':'codigo_barra'})
class Media:
js = ( '/media/js/jquery.js',
'/media/js/jquery.capitalize.min.js',
... | StarcoderdataPython |
1636866 | #Imprimir del 1 al 10
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10, end="\n\n")
#range(5) -> [0,1,2,3,4]
#for variable in range(10):
#
#
#
#for (i=0; i<10; i++) {}
#range(start, end, step)
for i in range(1, 11, 1):
print(i)
print()
#Imprimir los datos de... | StarcoderdataPython |
5104554 | <filename>huxley/shortcuts.py
# Copyright (c) 2011-2013 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD License found in README.md.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simple... | StarcoderdataPython |
4974386 |
import testing
from testing import value_eq,object_eq,text_eq
def test_import():
from pwscf_analyzer import PwscfAnalyzer
#end def test_import
def test_empty_init():
from pwscf_analyzer import PwscfAnalyzer
PwscfAnalyzer()
#end def test_empty_init
def test_analyze():
import os
from numpy i... | StarcoderdataPython |
9795833 | <filename>config.py
import torch
class Config:
device = torch.device('cuda:0')
load_path = None
save_path = './'
num_classes = 2
rpn_sigma = 3.
roi_sigma = 1.
lr = 0.001
weight_decay = 0.1
epoch = 10
eval_iters = 100
config = Config()
| StarcoderdataPython |
1848541 |
from mxnet.gluon import nn
from mxnet import nd
from models.transform_nets import input_transform_net, feature_transform_net
class PointNetfeat_vanilla(nn.Block):
def __init__(self, num_points = 2500, global_feat = True, routing=None):
super(PointNetfeat_vanilla, self).__init__()
self.stn = input_... | StarcoderdataPython |
8107351 | <filename>notebooks/explore/load_years_data.py
from datetime import datetime as dt
import pickle
from yitian.datasource import load, preprocess, EQUITY
from yitian.datasource.file_utils import create_data_path, list_bucket_year_path, \
bucket_to_local, list_bucket_path
# required parameters
# | parameter | e... | StarcoderdataPython |
11350819 | def is_leap(year):
leap = False
# Write your logic here
return leap
year = int(input())
print(is_leap(year))
| StarcoderdataPython |
12863808 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 09:18:37 2019
@author: if715029
"""
import pandas as pd
import numpy as np
import sklearn.metrics as skm
import scipy.spatial.distance as sc
#%% Leer datos
data = pd.read_excel('../data/Test de películas(1-16).xlsx', encoding='latin_1')
#%% Seleccionar datos (a mi e... | StarcoderdataPython |
1786143 | import os
import re
import sklearn
import pandas as pd
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from deBERTa import deberta
import copy
import torch
import os
import json
from .ops import *
from .bert import *
from .config import Mo... | StarcoderdataPython |
372014 | import pytest
from unittest.mock import patch
from click.exceptions import MissingParameter
from rfidsecuritysvc.cli.permission import get, create, delete
from rfidsecuritysvc.exception import DuplicatePermissionError as DuplicateError, PermissionNotFoundError as NotFoundError
from rfidsecuritysvc.model.permission im... | StarcoderdataPython |
1666611 | <filename>xova/apps/xova/utils.py<gh_stars>0
# -*- coding: utf-8 -*-
import numpy as np
def _id(array, fill_value=0, dtype_=np.int32):
return np.full_like(array, fill_value, dtype=dtype_)
def id_full_like(exemplar, fill_value, dtype=np.int32):
""" full_like that handles nan chunk sizes """
return exem... | StarcoderdataPython |
1698238 | """DUL service testing"""
import logging
import socket
import threading
import time
import pytest
from pynetdicom import AE, debug_logger, evt
from pynetdicom.dul import DULServiceProvider
from pynetdicom.pdu import (
A_ASSOCIATE_RQ, A_ASSOCIATE_AC, A_ASSOCIATE_RJ,
A_RELEASE_RQ, A_RELEASE_RP, P_DATA_TF, A_AB... | StarcoderdataPython |
3499895 | <gh_stars>1-10
"""Creates the basic user system.
Revision ID: cee3ba551880
Revises:
Create Date: 2020-09-19 17:03:37.354440
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cee3ba551880'
down_revision = None
branch_labels = None
depends_on = None
def upgrade... | StarcoderdataPython |
4809003 | <filename>mykits/cmds_fstk.py<gh_stars>10-100
#!/usr/bin/env python3
import fnmatch
from mylib.ext import fstk
from mylib.ext.console_app import *
from mylib.easy import logging
_logger = logging.ez_get_logger(__name__)
FILE_DIR_CHOICES = {'f', 'd', 'fd'}
ON_EXIST_CHOICES = {'error', 'overwrite', 'rename'}
apr = Ar... | StarcoderdataPython |
1834446 | <reponame>apple/ml-cvnets
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch import nn, Tensor
from typing import Tuple
class PixelShuffle(nn.PixelShuffle):
"""
Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)`
to a te... | StarcoderdataPython |
4959233 | #!/usr/bin/env python
import sys
sys.path.append('../')
from ore_examples_helper import OreExample
oreex = OreExample(sys.argv[1] if len(sys.argv)>1 else False)
oreex.print_headline("Run ORE with flat vols")
oreex.run("Input/ore_flat.xml")
oreex.print_headline("Run ORE with smiles")
oreex.run("Input/ore_smile.xml")... | StarcoderdataPython |
11318055 | <reponame>MikeFalowski/taurus
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or mo... | StarcoderdataPython |
322446 | <gh_stars>1-10
from django.contrib.auth.models import Group
from django.core.management import call_command
from profiles.models import Profile
from services.models import AllowedDataField, Service
from subscriptions.models import SubscriptionType, SubscriptionTypeCategory
from users.models import User
from utils.util... | StarcoderdataPython |
389721 | <gh_stars>1-10
__version__ = "0.2.0"
from . import exc # noqa: F401
from .base import Auditor # noqa: F401
from .base import CommonColumnValues # noqa: F401
from .base import alembic_supports_callback # noqa: F401
| StarcoderdataPython |
365097 | <filename>ramona/server/__main__.py<gh_stars>10-100
'''
This code is stub/kickstarted for ramona server application
'''
# This code can be used to enable remote debugging in PyDev
#Add pydevd to the PYTHONPATH (may be skipped if that path is already added in the PyDev configurations)
#import sys;sys.path.append(r'/op... | StarcoderdataPython |
3318896 | #! /usr/bin/env python
# coding=utf-8
import tensorflow as tf
def convolutional(input_data, filters_shape, trainable, name, downsample=False, activate=True, bn=True):
with tf.variable_scope(name):
if downsample:
pad_h, pad_w = (filters_shape[0] - 2) // 2 + 1, (filters_shape[1] - 2) // 2 + 1
... | StarcoderdataPython |
9702630 | import numpy as np
import subprocess, os, sys
class Saver:
def __init__(self, grid, outputPath, basePath, extension, fileName="Results"):
self.grid = grid
self.fileName = fileName
self.extension = extension
self.outputPath = os.path.join( outputPath , f"{fileName}.{extension}" )
self.basePath = basePath
... | StarcoderdataPython |
11359585 |
import configparser
import logging
import os
import subprocess
import uuid
from parameters import get_parameter
config = configparser.RawConfigParser()
config.read([
'worker.cfg',
'/etc/py_gpac_worker/worker.cfg'
])
class GPAC_worker:
def get_parameter(self, key, param):
key = "GPAC_" + key
... | StarcoderdataPython |
1830865 | import re
import json
from okdata.sdk.team.client import TeamClient
def test_get_teams(requests_mock):
teams = [
{"team_id": "abc", "name": "Team Foo"},
{"team_id": "123", "name": "Team Bar"},
]
requests_mock.register_uri(
"GET", re.compile("teams"), text=json.dumps(teams), status... | StarcoderdataPython |
3465220 | <reponame>NeoBoy/tarteel-ml<filename>training/architectures/seq2seq.py
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense
def lstm_encoder_decoder_with_teacher_forcing_training(
latent_dim, num_encoder_tokens, num_decoder_tokens):
# Define an input sequence an... | StarcoderdataPython |
25972 | import random
import torch
import numpy as np
import time
import os
from model.net import Net
from model.loss import Loss
from torch.autograd import Variable
import itertools
import pandas as pd
from main.dataset import LunaDataSet
from torch.utils.data import DataLoader
from configs import VAL_PCT, TOTAL_EPOCHS, DEFA... | StarcoderdataPython |
1771588 | class DavidStrategyLevel2:
def __init__(self, player_index):
self.player_index = player_index
self.name = 'berserk'
self.first_location=False
def decide_ship_movement(self, ship_index, game_state):
ship_coords = game_state['players'][self.player_index]['units'][ship_index]['coo... | StarcoderdataPython |
4894099 | <reponame>Atharva-Phatak/torchflare<filename>torchflare/datasets/text_data.py
import pathlib
from typing import List, Union
import pandas as pd
from pandas import DataFrame
from torchflare.datasets.core_utils import get_iloc_cols, to_tensor
from torchflare.datasets.data_core import ItemReader
class TextDataset(Item... | StarcoderdataPython |
8040164 | from pathlib import Path
import matplotlib.pyplot as plt
def ensure_dir(path):
path = Path(path)
if not path:
return False
if not path.is_dir():
path.mkdir(parents=True, exist_ok=True)
return path.is_dir()
def save_figure(path, fig=None, dpi=300, enabled=True):
if not enabled:
... | StarcoderdataPython |
5128855 | import h5py
from versioned_hdf5 import VersionedHDF5File
import numpy
import tempfile
import shutil
import os
filename = 'delete_versions_bench.h5'
try:
from versioned_hdf5 import delete_versions
except ImportError:
from versioned_hdf5.replay import recreate_dataset, tmp_group, swap
def delete_versions(... | StarcoderdataPython |
299648 | from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
class AddForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
| StarcoderdataPython |
9730635 | from rest_framework import serializers
from . models import Client, Order
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
fields = [
'pk',
'name',
]
class OrderSerializer(serializers.ModelSerializer):
client_obj = ClientSerial... | StarcoderdataPython |
4841629 | from wagtail.contrib.modeladmin.options import (
ModelAdmin, modeladmin_register)
from origins.models import Nomen
class NomenAdmin(ModelAdmin):
model = Nomen
menu_label = 'Nomen' # ditch this to use verbose_name_plural from model
menu_icon = 'pilcrow' # change as required
menu_order = 200 # wi... | StarcoderdataPython |
24208 | <gh_stars>0
""" A Python Class
A simple Python graph class to do essential operations into graph.
"""
import operator
import math
from random import choice
from collections import defaultdict
import networkx as nx
class ProA():
def __init__(self, graph):
""" Initializes util object.
"""
se... | StarcoderdataPython |
164742 | <filename>venv/lib/python3.6/site-packages/ansible_collections/cisco/mso/plugins/modules/mso_rest.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, <NAME> (@anvitha-jain) <<EMAIL>>
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import abs... | StarcoderdataPython |
1967743 | <reponame>google/aiyprojects-raspbian-tools
import subprocess
if __name__ == '__main__':
output = subprocess.check_output(['uname', '-a'])
print(output.decode('UTF-8'), end='')
output = subprocess.check_output(['cat', '/etc/aiyprojects.info'])
print(output.decode('UTF-8'), end='')
| StarcoderdataPython |
12866551 | <filename>apps/recurring_donations/management/commands/process_monthly_donations.py
import csv
import os
import math
import logging
import traceback
import requests
import sys
from collections import namedtuple
from optparse import make_option
from django.conf import settings
from django.contrib.contenttypes.models imp... | StarcoderdataPython |
6595049 | <reponame>VincentTide/vincenttide
from app import app
from flask import request, render_template, redirect, url_for, flash, abort
from flask.ext.login import login_required, current_user, login_user, logout_user
from models import *
from forms import *
from sqlalchemy import desc
import random
from utility import bbpar... | StarcoderdataPython |
6419387 | <reponame>dineshkumar2509/learning-python<filename>trips/nan.py
a = float('nan')
print(a) // nan
print('a is a:', a is a) // True
print('a == a:', a == a) // False
| StarcoderdataPython |
9779908 | <reponame>Ayrx/screenshot_ninja
import time
from typing import Optional
from binaryninja import (
BinaryView,
MessageBoxButtonSet,
MessageBoxIcon,
PluginCommand,
get_int_input,
get_save_filename_input,
show_message_box,
)
from .core import get_active_view_image, get_active_window_image
d... | StarcoderdataPython |
6462678 | <reponame>M-Hayhurst/Python-Arduino-LED-Cube<filename>SerialTest.py
import serial
from time import sleep
ser = serial.Serial('COM3', 9600, timeout=1)
print(ser.name)
sleep(0.1)
ser.write(b'G')
sleep(0.1)
msg = ser.read()
print('Arduino replied: %s'%msg)
| StarcoderdataPython |
279743 | # Run visualization of the output of inference
#
# <NAME> <<EMAIL>>
import cv2
import numpy as np
import json
import os
from detectron2.config import get_cfg
import argparse
colors = [(129, 0, 70), (220, 120, 0), (255, 100, 220), (6, 231, 255), (89, 0, 130), (251, 221, 64), (5, 5, 255)]
parser = argparse.ArgumentPars... | StarcoderdataPython |
1835775 | <reponame>arvinddoraiswamy/ThickClientScripts
#Get server header from every response and dump it into a file
#Search response bodies for a set of common versions
from burp import IBurpExtender
from burp import IHttpListener
from burp import IProxyListener
import re
import sys
import os
unique_banners={}
list_of_platf... | StarcoderdataPython |
117566 |
nome = str(input('Informe seu nome: ')).strip()
dividido = nome.split()
print('Seu primeiro nome é: {}'.format(dividido[0]))
print('Seu último nome é: {}'.format(dividido[len(dividido) - 1]))
| StarcoderdataPython |
9721357 | import os
from rdkit import Chem
from frag_gt.fragstore_scripts.generate_fragstore import FragmentStoreCreator
from frag_gt.src.fragstore import fragstore_factory
from frag_gt.tests.utils import SAMPLE_SMILES_FILE
def test_create_gene_table(tmp_path):
# Given
sample_smiles_file = SAMPLE_SMILES_FILE
frag... | StarcoderdataPython |
97059 | # -*- coding: utf-8 -*-
import re
from os import path
class JstlPathResolver:
def __init__(self, view, str_lookup, current_dir, roots, lang, settings):
self.view = view
self.import_line_regex = settings.get('import_line_regex', {})[lang]
prog = re.compile(self.import_line_regex[0])
... | StarcoderdataPython |
9798051 | <reponame>chulchultrain/FriendLeague
import psycopg2
import json
import leagreq.match_detail as match_detail
conn = psycopg2.connect(host='localhost',database='FriendLeague',user='thomas',password='<PASSWORD>')
cursor = conn.cursor()
name = '333asd'
#cursor.execute('select account_id from analytics_account where name =... | StarcoderdataPython |
3225964 | # MIT License
#
# Copyright (c) 2018 <NAME>, <EMAIL>
#
# 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, modify, mer... | StarcoderdataPython |
3448607 | <filename>tbCrawlerUrlSpider/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json
import os
from hashlib import md5
from scrapy import signa... | StarcoderdataPython |
11298349 | <filename>CHAPTER 10 (maps, hash tables and skip lists)/cyclic_shift_hash_code.py
def hash_code(s):
mask = (1 << 32) - 1 # limit to 32-bit integers
h = 0
for character in s:
h = (h << 5 & mask) + (h >> 27) # 5 bit cyclic shift of running sum
h += ord(character) # a... | StarcoderdataPython |
1725295 | """
MVP activity stream. To be extended appropriately as requirements are drawn up.
"""
import time
from datetime import datetime
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from api.applications.models import CountryOnApplication
from ... | StarcoderdataPython |
5039491 | <gh_stars>0
"""CS 5033: Machine Learning Reinforcement Learning Project
Package wordle
This package contains:
game: The class that plays the game from the Wordle side, to be callable by the
agents.
"""
__version__ = '1.0.0'
__all__ = []
__author__ = '<NAME> <<EMAIL>>'
| StarcoderdataPython |
9709337 | <gh_stars>1-10
from hashlib import pbkdf2_hmac
from collections import namedtuple
from Crypto.Cipher import AES
from Crypto import Random
import paramiko
def to_hex(_bytes):
"""Encode `_bytes` as a colon-delemeted hexidecimal representation of each byte"""
if type(_bytes) is str:
_bytes = _bytes.enco... | StarcoderdataPython |
1706175 | import unittest
from simplex_method import *
import numpy as np
from scipy import optimize
class TestSimplexMethod(unittest.TestCase):
def test_simplex_method(self):
m = np.array([[-2.0, 1.0, -10.0],
[1.0, 1.0, 20.0],
[-5.0, -10.0, 0.0]])
res = {'x0': 1... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.