id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1683165
<filename>pushservice/src/Controller/SendLog.py ####################################################################### # # Push Service for Enigma-2 # Coded by betonme (c) 2012 <glaserfrank(at)gmail.com> # Support: http://www.i-have-a-dreambox.com/wbb2/thread.php?threadid=167779 # # This program is free so...
StarcoderdataPython
154819
<filename>yeast/steps/summarize_step.py from pandas.core.groupby.generic import DataFrameGroupBy from yeast.step import Step from yeast.errors import YeastValidationError class SummarizeStep(Step): """ Create one or more numeric variables summarizing the columns of an existing group created by GroupBySte...
StarcoderdataPython
8296
""" Ocropus's magic PIL-numpy array conversion routines. They express slightly different behavior from PIL.Image.toarray(). """ import unicodedata import numpy as np from PIL import Image __all__ = ['pil2array', 'array2pil'] def pil2array(im: Image.Image, alpha: int = 0) -> np.array: if im.mode == '1': ...
StarcoderdataPython
3344379
""" WRITEME """ from __future__ import absolute_import, print_function, division import logging import warnings import theano from theano import gof import theano.gof.vm from theano.configparser import config from six import string_types from theano.compile.function_module import Supervisor _logger = logging.getLog...
StarcoderdataPython
1727078
import pytest from lhotse.cut import CutSet from lhotse.dataset import UnsupervisedDataset @pytest.fixture def libri_cut_set(): return CutSet.from_yaml('test/fixtures/libri/cuts.yml') def test_unsupervised_dataset(libri_cut_set): dataset = UnsupervisedDataset(libri_cut_set) assert len(dataset) == 1 ...
StarcoderdataPython
3306814
class node: def __init__(self,data,next = None ): ### Code Here ### self.value = data self.next = None def __str__(self): ### Code Here ### return self.value def createList(l=[]): ### Code Here ### for i in range(len(l)): l[i] = node(l[i]) if i > ...
StarcoderdataPython
58894
<filename>abstract_models/bisim/pick_puck.py import numpy as np class BisimPickPuckModel: @classmethod def get_state_block(cls, hand, layers, action_grid): num_positions = action_grid.shape[0] * action_grid.shape[1] action_grid = np.reshape(action_grid, (-1, 2)) if hand is not None:...
StarcoderdataPython
18655
<filename>eval.py<gh_stars>1-10 import torch from torch.utils.data import Dataset import numpy as np import os import pickle from madmom.features import DBNBeatTrackingProcessor import torch from model import BeatTrackingNet from utils import init_single_spec from mir_eval.beat import evaluate from data import Ball...
StarcoderdataPython
1774210
# -*- coding: utf-8 -*- # https://www.apache.org/licenses/LICENSE-2.0.html try: import traceback import re import BigWorld from gui.Scaleform.daapi.view.battle.shared.stats_exchage.vehicle import VehicleInfoComponent from gui.battle_control.arena_info.arena_dp import ArenaDataProvider from gu...
StarcoderdataPython
3286358
<reponame>NumberAI/python-bandwidth-iris<gh_stars>1-10 #!/usr/bin/env python from iris_sdk.models.maps.base_map import BaseMap class SubscriptionsMap(BaseMap): subscription = None
StarcoderdataPython
3392057
# pip install requests import abc import html import json import os import re import requests IMAGES_DIR = "../images/" image_storage = [] class ParsedImage: @abc.abstractclassmethod def get_image_src(self): pass class GoogleImage(ParsedImage): def __init__(self, json_ima...
StarcoderdataPython
52817
<reponame>XiYe20/VPTR import tensorflow as tf import numpy as np from PIL import Image from pathlib import Path import shutil import os from tqdm import tqdm #Requirements: tensorflow 2.6.0 def read_BAIR_tf2_record(records_dir, save_dir): """ Args: record_file: string for the BAIR tf record file path ...
StarcoderdataPython
3304325
<reponame>jfairf01/OrgoWebsite<filename>app/SnEMechs/errors.py<gh_stars>0 from flask import render_template from . import SnEMechs @SnEMechs.app_errorhandler(403) def forbidden(_): return render_template('errors/403.html'), 403 @SnEMechs.app_errorhandler(404) def page_not_found(_): return render_template('...
StarcoderdataPython
4806233
<reponame>TOXiNdeep2503/makeabilitylabwebsite #!/usr/bin/env python # -*- coding:utf-8 -*- """ Custom context processors that allows us to pass variables to every view See: https://docs.djangoproject.com/en/2.0/ref/templates/api/#subclassing-context-requestcontext https://stackoverflow.com/questions/28937...
StarcoderdataPython
150157
#! /usr/bin/env python3 import pygame from pygame import mixer from constants import DEFAULT_SAMPLE_RATE from decorated_gui import DecoratedGUI class AudioGUI (DecoratedGUI): def __init__ (self, sample_rate=DEFAULT_SAMPLE_RATE, *args, **kwargs): DecoratedGUI.__init__ (self, *args, **kwargs) self.sample_rate = ...
StarcoderdataPython
6352
<filename>hackathon/darkmattertemperaturedistribution/example.py<gh_stars>1-10 #!/usr/bin/env python from scipy import * from pylab import * #from pylab import imshow #! #! Some graphical explorations of the Julia sets with python and pyreport #!######################################################################### ...
StarcoderdataPython
87055
<reponame>WagnerNils/MMSplice_MTSplice # import tensorflow as tf import numpy as np import tensorflow.keras.backend as K from tensorflow.keras.layers import Layer from tensorflow.keras.layers import Conv1D from tensorflow.keras.regularizers import Regularizer from tensorflow.keras import initializers import scipy.inter...
StarcoderdataPython
197502
<reponame>gawainguo/Flask-AC<filename>flask_ac/ac_manager.py ''' This module provide ACManager class ''' from flask import g from flask_ac import ptree class ACManager(object): ''' ACManager is defination of access control manager, which hold the loaders and other configs for access control. Insta...
StarcoderdataPython
1734756
<gh_stars>10-100 #!/usr/bin/env python # Created by <NAME> on 18-2-13. class Solution: def convertToTitle(self, n): """ :type n: int :rtype: str """ ans = '' while n > 0: ans = chr((n-1) % 26 + 65) + ans n = (n - 1) // 26 return ans ...
StarcoderdataPython
60665
<filename>Hearthstone/test.py<gh_stars>0 from CardGenerator import CardGenerator test = CardGenerator() test.generate(2) #4 is how much mana should the card cost
StarcoderdataPython
1624573
<reponame>akinoriosamura/retinaface-tf2 import tensorflow as tf def MultiStepLR(initial_learning_rate, lr_steps, lr_rate, name='MultiStepLR'): """Multi-steps learning rate scheduler.""" lr_steps_value = [initial_learning_rate] for _ in range(len(lr_steps)): lr_steps_value.append(lr_steps_value[-1]...
StarcoderdataPython
1748927
<gh_stars>0 """ Test AS3 Client """ import json import tempfile import shutil from os import path from f5sdk import exceptions from f5sdk.utils import http_utils from ....global_test_imports import pytest, Mock, PropertyMock from ....shared import constants from ....shared import mock_utils REQUESTS = constants.MOC...
StarcoderdataPython
3300953
import time import microstats lst = [7, 4, 8, 6, 3.6, 8, 3, 3, 5, 2, 23, 9, 20, 7, 28, 22, 22, 6, 7, 7] def test_gauge_value(): g = microstats.GaugeValue() assert g.val == 0 g.set(20) g.set(25) g.set(10) assert g.val == 10 assert g.val_max == 25 assert g.val_min == 10 g.add(-5) ...
StarcoderdataPython
1661078
from flask import Blueprint, request, jsonify from app.handlers import service_handler as handler import logging """ service_router.py renders all of the backend routes that we are exposing in our application. All of these routes will be prefixed with `/api/v1/`, followed by the route These routes are as follows: /...
StarcoderdataPython
1739737
#!/usr/local/bin/python3 # https://data36.com/linear-regression-in-python-numpy-polyfit/ import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import numpy as np # {{{ n_sedov = [ 278, 288, 297, 306, 314, 318, 322, 330, 337, 344, 350, 363, 369, 375, 380, 386, 391, 396, 401, 406, 411, 416, 420, ] M...
StarcoderdataPython
1737906
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
StarcoderdataPython
1618749
#%% #%% import os import time import shutil import numpy as np import tensorflow as tf from PIL import Image import random import matplotlib.pyplot as plt import cv2 from cv2 import cv2 scal = 224 sampleModel = tf.keras.applications.ResNet50V2(weights='imagenet', include_top=F...
StarcoderdataPython
1760205
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/server/graphql/types/misc.py # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # ...
StarcoderdataPython
92310
<reponame>veeramanikandan0305/KA-UP import zipfile import sys import os import datetime import re from distutils.dir_util import copy_tree def zip_folder(folder_path, output_path): """Zip the contents of an entire folder (with that folder included in the archive). Empty subfolders will be included in the ar...
StarcoderdataPython
1685398
<filename>Python3/1133.py a = int(input()) b = int(input()) if a > b: a, b = b, a for i in range(a+1, b): if i % 5 in (2, 3): print(i)
StarcoderdataPython
80212
# -*- coding: utf-8 -*- """ @author : <NAME> @github : https://github.com/tianpangji @software : PyCharm @file : routing.py @create : 2020/7/29 20:21 """ import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drf_admin.settings.dev') from channels.routing import ProtocolTypeRouter, URLRo...
StarcoderdataPython
1757559
<reponame>pk-hackerrank/python # Importing phase and polar from cmath # Complex form a+bj, Polar coordinates (r,phi) from cmath import phase, polar # Reading input String given_input = input() # Converting given string into complex number i.e. a+bj format in_complex_format = complex(given_input) #calc_r = abs(in_comple...
StarcoderdataPython
86672
<reponame>3togo/skeleton-tracing import trace_skeleton import cv2 import random import os import sys def get_fname(fname): for i in range(5): if os.path.exists(fname): return fname fname = os.path.join("..", fname) print(fname) fname = get_fname("test_images/opencv-thinning-src-...
StarcoderdataPython
1639694
from os import error from instagrapi import Client from flask import Flask,jsonify import json import random print('Login in..') def write_file(data, filename): fh = open(filename, "w") try: fh.write(json.dumps(data)) finally: fh.close() def read_file(filename): fh = open(filename, "r...
StarcoderdataPython
64755
<filename>sbdata/tasks.py import ast import dataclasses import json import re import sys import typing from sbdata.repo import find_item_by_name, Item from sbdata.task import register_task, Arguments from sbdata.wiki import get_wiki_sources_by_title @dataclasses.dataclass class DungeonDrop: item: Item floor:...
StarcoderdataPython
63090
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: parser_funs Description : Author : <NAME> date: ------------------------------------------------- Change Activity: 2019/7/28: ------------------------------------------------- """ import ...
StarcoderdataPython
1667817
#!/usr/bin/env python3 # # Copyright (c) 2019, Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # import argparse import logging import time from damlassistant import get_package_id, start_trigger_service_in_background, kill_process, \ add_trigger_...
StarcoderdataPython
97089
<reponame>hoogamaphone/world-manager<filename>world_manager/blueprints/user/forms.py<gh_stars>0 from flask_wtf.form import FlaskForm class LoginForm(FlaskForm): pass
StarcoderdataPython
44575
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Contains a context manager for temporarily introducing an environment var. import os import contextlib @contextlib.contextmanager def use_environment_variable(key, value): """ Used to temporarily introduce a new environment variable as if it was set by th...
StarcoderdataPython
1684815
<reponame>reddit-pygame/minigolf-prototype """ The main function is defined here. It simply creates an instance of tools.Control and adds the game states to its dictionary using tools.setup_states. There should be no need (theoretically) to edit the tools.Control class. All modifications should occur in this module a...
StarcoderdataPython
3379208
#!/usr/bin/env python import argparse import datetime as dt import os.path import sys import ait.core.log as log ''' Convert MPS Seq files to AIT formatted sequence files ''' VALID_HEADER_KEYS = [ 'gap', 'on_board_filename', 'on_board_path', 'upload_type' ] def extract_seq_header(input_file): '...
StarcoderdataPython
64104
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.9.1+dev # kernelspec: # display_name: Python [conda env:annorxiver] # language: python # name: conda-env-annorxiver-...
StarcoderdataPython
1734591
<reponame>sikienzl/Teamprojekt #!/usr/bin/python3 # -*- coding: utf-8 -*- """Converts any files into txt-files""" import sys import getopt import logging import os.path import extractTxt import loggingModule def main(): NO_ARG_TXT="No argument" PUT_CORRECT_PARAM_TXT="Please put a correct parameter: error \n" ...
StarcoderdataPython
180248
<gh_stars>1-10 import wolframalpha WOLFRAM_ALPHA_APP_ID = "" # Put Wolfram Alpha App ID here fallback_response = "Sorry, I don't understand." greetings = ["hello", "hi", "howdy", "hey", "hola", "sup", "aloha"] farewells = ["bye", "goodbye", "adios"] client = wolframalpha.Client(WOLFRAM_ALPHA_APP_ID) def execute(in...
StarcoderdataPython
1785263
import math import time import arcade # Do the math to figure out our screen dimensions SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 SCREEN_TITLE = "Basic Renderer" class MyGame(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) # vsync must...
StarcoderdataPython
1642721
import os from _common_search_paths import charm_path_search, grackle_path_search is_arch_valid = 1 #python_lt_27 = 1 flags_arch = '-O3 -Wall -g' #flags_arch = '-Wall -g' flags_link = '-rdynamic' #optional fortran flag flags_arch_fortran = '-ffixed-line-length-132' cc = 'gcc' f90 = 'gfortran' #flags_prec_singl...
StarcoderdataPython
49313
"""Report generator for the error command. TODO: move reporting functionality out of the ErrorEstimator class. """ from itertools import repeat from atropos.commands.reports import BaseReportGenerator from atropos.io import open_output from atropos.commands.legacy_report import Printer, TitlePrinter class ReportGener...
StarcoderdataPython
3326120
import mafs import json fs = mafs.MagicFS() fs.add_argument('file', help='json file to read from') # read json file with open(fs.args.file) as f: items = json.load(f) def dig(d, parts): if parts: try: res = d.get(parts[0]) if res: return dig(res, parts[1:]) ...
StarcoderdataPython
3316719
import re subst = re.compile("(%\((\w+)\))") def substitute_str(text, vars): out = [] i0 = 0 for m in subst.finditer(text): name = m.group(2) if name in vars: out.append(text[i0:m.start(1)]) out.append(str(vars[name])) i0 = m.end(1) out.append(text[i...
StarcoderdataPython
1653040
#!/bin/env python3 # author: <NAME> # # Excel Sheet Column Title # # Given a positive integer, return its corresponding column title as appear in an Excel sheet. # For example: # 1 -> A # 2 -> B # 3 -> C # ... # 26 -> Z # 27 -> AA # 28 -> AB # Credits:Special thanks to @ifanchu for adding ...
StarcoderdataPython
3305567
# -*- coding: utf-8 -*- class ElementsInCurve: def __init__(self,filename_1, filename_2,sheet_name): """ Input the file containing the elements data :param filename_1: Trace elements total 700 + data :param filename_2: trace Standardized values (ppm) :param sheet_name: 0 = ...
StarcoderdataPython
1606166
from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from Autodesk.Revit import Exceptions uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document getselection = uidoc.Selection.GetElementIds from Autodesk.Revit.UI import TaskDialo...
StarcoderdataPython
1726031
##Question 23 ##Implement a stack class in Python. It should support 3 APIs: ##stack.top(): prints element at top of stack ##stack.pop(): takes out an element from top of stack ##stack.push(): adds a new element at top of stack class Stack(): def __init__(self): self.item = [] def size(self): ...
StarcoderdataPython
38228
<filename>beam.py import numpy as np import cv2 import wall SAME_LINE_THRESHOLD = 100 SAME_LEVEL_THRESHOLD = 8 SHORT_LINE_LENGTH = 10 BLEED_THRESHOLD = 10 def similar_line_already_found(line, found_lines): for fline in found_lines: x1, y1, x2, y2 = line fx1, fy1, fx2, fy2 = fline is_vertical_with_r...
StarcoderdataPython
3341085
class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.set = [] def add(self, key: int) -> None: if key not in self.set: self.set.append(key) def remove(self, key: int) -> None: if key in self.set: sel...
StarcoderdataPython
1715015
numerical_tokens = [] fully_numerical_tokens = [] with open("../../data-bin/wikitext-103/dict.txt", "r", encoding='utf-8') as f_r: for line in f_r: token, id = line.split() if any(char.isdigit() for char in token): numerical_tokens.append(token) if all(char.isdigit() for cha...
StarcoderdataPython
156284
class Solution: def wordPatternV1(self, pattern: str, str: str) -> bool: p2s, s2p, words = {}, {}, str.split() if len(pattern) != len(words): return False for p, s in zip(pattern, words): if p in p2s and p2s[p] != s: return False else: ...
StarcoderdataPython
3375845
import inspect import sys from typing import Any, NamedTuple, Type if sys.version_info < (3, 8): from typing_extensions import get_args else: from typing import get_args import msgpack # type: ignore[import] from pydantic import BaseModel from xpresso import Request from xpresso.binders.api import SupportsE...
StarcoderdataPython
1756395
class PDFColumn(object): def __init__(self, parent): self.parent = parent self.cells = [] self.max_width = 0 def _add_cell(self, cell): self.cells.append(cell) def _set_max_width(self, value): self.max_width = value def _get_max_width(self): for cell ...
StarcoderdataPython
3242867
# Generated by Django 3.0.4 on 2020-03-16 07:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Auto', fields=[ ...
StarcoderdataPython
1680162
<filename>app/mqtt_handler.py<gh_stars>1-10 import logging import time from queue import SimpleQueue import paho.mqtt.client as mqtt class MQTTHandler(object): def __init__(self, mqtt_broker_host, mqtt_broker_port=1883): self.logger = logging.getLogger("mqtt.client") self.mqtt_broker_host = mqtt_...
StarcoderdataPython
1684854
''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import import os import re import numpy as np from random import shuffle from collections import Counter from ..preprocessing.preprocessing import init_stopwords, tiny_tokenize_xml, tiny_tokenize, get_all_files, count_words from ..datasets.re...
StarcoderdataPython
3394936
from collections import Counter from itertools import combinations def part_one(words): two = 0 three = 0 for word in words: counter = Counter(word) occurences = set(elem[1] for elem in counter.most_common()) if 2 in occurences: two += 1 if 3 in occurences: ...
StarcoderdataPython
1745593
"""Utility Functions""" import logging from collections import namedtuple # pytype: disable=pyi-error def get_logger(logname): """Create and return a logger object.""" logger = logging.getLogger(logname) return logger def log_method(method): """Generate method for logging""" def wrapped(self, ...
StarcoderdataPython
1698469
<reponame>ishine/neurst from collections import namedtuple METRIC_REDUCTION = namedtuple( "metric_reduction", "SUM MEAN")(0, 1) REGISTERED_METRICS = dict() def register_metric(name, redution): if name in REGISTERED_METRICS: raise ValueError(f"Metric {name} already registered.") REGISTERED_METRIC...
StarcoderdataPython
28504
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # metrics namespaced under 'scylla' SCYLLA_ALIEN = { 'scylla_alien_receive_batch_queue_length': 'alien.receive_batch_queue_length', 'scylla_alien_total_received_messages': 'alien.total_received_me...
StarcoderdataPython
167686
from milight import MiLight, LightBulb, color_from_hex from . import LightController class MiLightController(LightController): VENDOR = "milight" def __init__(self, host, port, bulbs, *args, **kwargs): super(MiLightController, self).__init__(*args, **kwargs) self._milight = MiLight({'host':...
StarcoderdataPython
182987
# Generated by Django 3.1.2 on 2020-10-19 10:26 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import insta.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('inst...
StarcoderdataPython
1721845
<filename>leetcode/stamping_the_sequence/stamping_the_sequence.py class Solution: def movesToStamp(self, stamp: str, target: str) -> List[int]: ans = [] N = len(target) M = len(stamp) stamp = list(stamp) old_target = target target = list(target) def match(of...
StarcoderdataPython
140602
import unittest from tree import TreeNode # O(n). Recursive DFS. class Solution: def findSecondMinimumValue(self, root): """ :type root: TreeNode :rtype: int """ if not root: return -1 root_val = root.val def find_min(node): if not n...
StarcoderdataPython
63318
from twilio.rest import Client def sendotp(otpreci): account_sid = 'ACe8caad8112e2135294377d739ce3e9b9' auth_token = '<PASSWORD>' client = Client(account_sid, auth_token) msg='OTP for Login : ' + str(otpreci) message = client.messages.create( from_='whatsapp:+14155238886', body= msg ...
StarcoderdataPython
3359894
<gh_stars>0 from .....messaging.base_handler import ( BaseHandler, BaseResponder, HandlerException, RequestContext, ) from ..messages.credential_issue import CredentialIssue from ..messages.credential_request import CredentialRequest from aries_cloudagent.holder.base import BaseHolder, HolderError from ...
StarcoderdataPython
141593
<filename>dreamcoder/domains/logo/makeLogoTasks.py<gh_stars>1-10 # coding: utf8 import os import random import sys from dreamcoder.domains.logo.logoPrimitives import primitives, turtle from dreamcoder.task import Task from dreamcoder.program import Abstraction, Application, Index, Program from dreamcoder.type import ...
StarcoderdataPython
1678801
<reponame>compressore/metabolism-of-cities-platform<filename>src/core/migrations/0018_auto_20210107_1533.py # Generated by Django 3.1.2 on 2021-01-07 15:33 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0017_aut...
StarcoderdataPython
45199
#!_PYTHONLOC # # (C) COPYRIGHT 2014-2021 Ahasuerus # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from isfdb import * from common import * from isfdblib import * from ...
StarcoderdataPython
1687722
<reponame>arthurlewisbrown/altcoin_max_price_prediction<gh_stars>1-10 import shutil import pandas as pd import traceback import datetime import os from lib.model import model_info, predict_simulation from lib import mysql_helper from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activatio...
StarcoderdataPython
3249021
#!/usr/bin/env python # -*- encoding: utf-8 -*- __author__ = 'andyguo' from dayu_file_format.curve.data_structure import Point2D import pytest class TestPoint2D(object): def test___init__(self): p = Point2D(0, 1) assert p.x == 0 assert p.y == 1 assert type(p.x) is float a...
StarcoderdataPython
1667743
<gh_stars>10-100 import torch from torch.nn import Parameter, ParameterList import tntorch as tn class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): super(LinearNorm, self).__init__() self.linear_layer = torch.nn.Linear(in_dim, out_dim, bia...
StarcoderdataPython
3268234
<gh_stars>1-10 from django.apps import AppConfig class FetcherConfig(AppConfig): name = 'fetcher'
StarcoderdataPython
3234361
import numpy as np a = np.zeros((2,2,2)) reveal_type(a)
StarcoderdataPython
1621987
<reponame>Anchovee/dash_TA<filename>app/dashapp3/callbacks.py from datetime import datetime as dt import pandas_datareader as pdr from dash.dependencies import Input from dash.dependencies import Output from dash.exceptions import PreventUpdate def register_callbacks(dashapp): @dashapp.callback([ Output('g...
StarcoderdataPython
1624111
__all__ = ['Word', 'Line', 'Block', 'SourceFile'] from .component import Component class Word(Component): """ Represents immutable string. Provides content for: words """ templates = dict( string = '%(word)s' ) template_options = dict() def __init__(self, word): ...
StarcoderdataPython
95814
<filename>src/sfcparse/__xml/xmlbuildmanual.py<gh_stars>0 # xmlbuildmanual ######################################################################################################### # Imports import xml.etree.ElementTree as __xml_etree ####################################################################################...
StarcoderdataPython
1764916
from collections import OrderedDict, abc from enum import Enum from functools import reduce, wraps from typing import Callable, List, Optional, Sequence, TypeVar, Union, overload import torch from torch import Tensor, nn from .delay import Delay from .logging import getLogger from .module import CallMode, CoModule, P...
StarcoderdataPython
3217532
import sys import colorama class HascalError: def __init__(self, exception_message): colorama.init() sys.stderr.write(colorama.Fore.RED + "Error : ") sys.stderr.write(colorama.Style.RESET_ALL) sys.stderr.write(exception_message) sys.stderr.write("\n") sys.exit(1) ...
StarcoderdataPython
1646116
<reponame>jonrzhang/MegEngine<gh_stars>1-10 from functools import partial from megengine.quantization import QConfig, tqt_qconfig from megengine.quantization.fake_quant import TQT def test_equal(): qconfig = QConfig( weight_observer=None, act_observer=None, weight_fake_quant=partial(TQT, ...
StarcoderdataPython
153697
from functools import singledispatch from functools import update_wrapper class singledispatchmethod: """Single-dispatch generic method descriptor. Supports wrapping existing descriptors and handles non-descriptor callables as instance methods. """ def __init__(self, func): if not callabl...
StarcoderdataPython
1676540
<filename>ontask/action/tests/test_serializers.py # -*- coding: utf-8 -*- """Test the views for the scheduler pages.""" import os import test from django.conf import settings from ontask.action.serializers import ActionSelfcontainedSerializer class ActionTestSerializers(test.OnTaskTestCase): """Test stat view...
StarcoderdataPython
182100
<gh_stars>1000+ # Copyright 2019 Google LLC. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following...
StarcoderdataPython
3384290
<gh_stars>0 from app import create_app # Creating app instance app = create_app('development') def test(): """ Running unit tests """ import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': app.run()
StarcoderdataPython
3240218
<gh_stars>0 from django.contrib import admin from .models import Book, Borrower # Register your models here. admin.site.register(Book) admin.site.register(Borrower)
StarcoderdataPython
1701490
import lab9 from lab9 import Matrix A = Matrix(3, 3) B = Matrix(3, 3) C = A + B D = A - B E = A * 2 F = A * B print('Матрица А = ') A.outMat() print('Матрица В = ') B.outMat() print('C = A + B: ') if C != 1: C.outMat() else: print('Матрицы разных размеров!') print('D = A - B: ') if D != 1: ...
StarcoderdataPython
183418
<reponame>AutomataRaven/azaharTEA<filename>editorcontainer/rightclickmenu/__init__.py __all__ = ['rightclickmenu.RightClickMenu']
StarcoderdataPython
43093
import pandas as pd import matplotlib.pyplot as plt from src.utils.function_libraries import * from src.utils.data_utils import * from src.utils.identification.PI_Identifier import PI_Identifier from src.utils.solution_processing import * from differentiation.spectral_derivative import compute_spectral_derivative from ...
StarcoderdataPython
3231699
from flask import Blueprint api = Blueprint('api', __name__) from . import authentication from . import posts from . import users from . import comments from . import errors
StarcoderdataPython
1620696
import unittest from io import StringIO from unittest import mock, TestCase def get_test_dataframe(): import pandas as pd import numpy as np df = pd.DataFrame( { "one": [-1, np.nan, 2.5], "two": ["foo", "bar", "baz"], "three": [True, False, True], "f...
StarcoderdataPython
21660
""" Methods for user login """ from cgi import escape from google.appengine.ext import ndb def login_fields_complete(post_data): """ validates that both login fields were filled in :param post_data: :return: """ try: user_id = escape(post_data['user_id'], quote=True) except KeyErr...
StarcoderdataPython
182929
<reponame>lauramv1832/ship_it # coding=utf-8 from __future__ import unicode_literals import collections import os.path import mock import pytest from ship_it import fpm, cli, get_version_from_setup_py from ship_it.manifest import Manifest # not a fixture to make sure this is never passed down a module level __here__...
StarcoderdataPython
89395
import pygame from pygame.locals import * from sys import exit from random import * pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) screen.lock() for count in range(10): random_color = (randint(0,255), randint(0,255), randint(0,255)) random_pos = (randint(0,639), randint(0,479)) random...
StarcoderdataPython
38064
#Step 1 :- Importing dependancies and train test data generated from config import * train_data = pd.read_csv("data/train_data/train_feature.csv") test_data = pd.read_csv("data/test_data/test_feature.csv") #Step 2 :- Getting train data insights and drop unnecessary columns, Splitting data into input and target ...
StarcoderdataPython