id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3530755
from unittest import TestCase from bs4 import BeautifulSoup from tools.lib.capitalization import check_capitalization, get_safe_text, is_capitalized class GetSafeTextTestCase(TestCase): def test_get_safe_text(self) -> None: string = "Zulip Zulip. Zulip some text!" safe_text = get_safe_text(strin...
StarcoderdataPython
1649318
from openpyxl.reader.excel import load_workbook from re import sub from NLP5 import getDirectResourceUrl, databaseWrapper, getRedirectedResourceURL, isLocation, checkDisambiguates __author__ = '<NAME>' def isLocationBool(keyword): locationString = keyword locationString = locationString.replace("_"," ") ...
StarcoderdataPython
4856380
# Do NOT edit this file! # It was generated by IdlC class idl.json.python.ProxyAsnVisitor. # # Section generated from "/home/nb/builds/MEGA/px2-3.0.0-3.0.9-branch-20140613-none-release-none-pdu-raritan/fwcomponents/mkdist/tmp/px2_final/libidl_client/topofw/peripheral/idl/PeripheralDeviceSlot.idl" # import raritan.rpc...
StarcoderdataPython
72424
<filename>autofit/graphical/factor_graphs/factor.py<gh_stars>0 from abc import ABC from functools import lru_cache from inspect import getfullargspec from itertools import chain, repeat from typing import \ ( Tuple, Dict, Union, Set, Callable, List ) import numpy as np from autofit.graphical.factor_graphs.abs...
StarcoderdataPython
248400
# coding: utf-8 from gae_mini_profiler import profiler from gae_mini_profiler import templatetags import flask import flask_debugtoolbar import config import util app = flask.Flask(__name__) app.config.from_object(config) app.jinja_env.line_statement_prefix = '#' app.jinja_env.line_comment_prefix = '##' app.jinja_en...
StarcoderdataPython
107401
<filename>src/resources/base_resource.py from typing import Type from flask_restful import Resource from flask import request from src.dao.base_dao import BaseDao class BaseResource(Resource): def __init__(self, dao: BaseDao, type_model: Type): self.__dao = dao self.__model_type = type_model ...
StarcoderdataPython
4992808
<gh_stars>10-100 """Removed unique constraint from topics Revision ID: db25f23bffc8 Revises: <PASSWORD> Create Date: 2021-08-23 17:16:20.389142 """ from alembic import op revision = '<KEY>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.create_index(op.f('ix_repos_topics_...
StarcoderdataPython
132941
<reponame>pakit/test_recipes """ Formula that requires cyclea recipe. """ from pakit import Dummy, Recipe class Cycleb(Recipe): """ Dummy recipe does nothing special but have dependency. """ def __init__(self): super(Cycleb, self).__init__() self.homepage = 'dummy' self.repos =...
StarcoderdataPython
3474946
<filename>src/train.py #!/usr/bin/env python """ Main training workflow """ from __future__ import division import argparse import os from others.logging import init_logger from train_abstractive import validate, train, test_text, baseline model_flags = ['hidden_size', 'ff_size', 'heads', 'emb_size', 'enc_layers...
StarcoderdataPython
6562557
TARGETS = { 'a001': "a001.wav", # 굵은 여성 'p112': "p112_003.wav", # 견자희 'p226': "p226_049-22k.wav", # 중년 남자 'p234': "p234_009-22k.wav", # 젊은 여성 'p237': "p237_007-22k.wav", # 중후한 남성 'p345': "p345_009-22k.wav", # 허스키한 남성 "p277": "p277_034-22k.wav", # 어린 여성 "p286": "p286_010-22k.wav", # 얉은 남성 "p300": "p300...
StarcoderdataPython
379787
<gh_stars>10-100 # coding=utf-8 from flask import url_for from psi.app import const from psi.app.utils import db_util from tests import fixture from tests.base_test_case import BaseTestCase from tests.object_faker import object_faker from tests.views.organization.base_organization_test import BaseOrganizationTestCase ...
StarcoderdataPython
1655757
<filename>tests/@proxyTest/makeOpMethods.py #!/bin/env python # 2007-03-27 generate boilerplate matlab methods from awmstools import spitOut BINARY_ARITH = '''plus minus mtimes times mpower power mldivide mrdivide ldivide rdivide eq ne lt gt le ge horzcat vertcat '''.split() UNARY_ARITH=''' uminus uplus transpose ctr...
StarcoderdataPython
8150917
<reponame>adwaita1/ALGORITHMMS<gh_stars>1-10 memo={} def DP(x,y,i,j): if i>=len(x): memo[(i,j)]=len(y)-j return len(y)-j if j>=len(y): memo[(i,j)]=len(x)-i return len(x)-i if (i,j) in memo: return memo[(i,j)] if x[i]==y[j]: memo[(i,j)]=min(DP(x,y,i,j+1),D...
StarcoderdataPython
3428045
<reponame>nasa/fmdtools<gh_stars>1-10 """ Description: Translates simulation outputs to pandas tables for display, export, etc. Uses methods: - :meth:`hist`: Returns formatted pandas dataframe of model history - :meth:`objtab`: Make table of function OR flow value attributes - objtype = 'func...
StarcoderdataPython
3346309
<gh_stars>0 from django.shortcuts import render from django.views.generic import TemplateView, CreateView, UpdateView, DetailView, ListView from utils.decorators import has_dashboard_permission_required from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from d...
StarcoderdataPython
6622771
<reponame>TomohikoK/PyCat<gh_stars>0 def double(arg: int) -> int: return arg * 2 x: List[str] = ['a', 'bb'] x1 = list(map(double @ length_of_str, x)) x2 = list(map(double, list(map(length_of_str, x)))) assert x1 == x2 # どちらの値も[2, 4]
StarcoderdataPython
5116047
<gh_stars>0 #!/bin/python3 S = input().strip() try: i = int(S) print(S) except: print('Bad String')
StarcoderdataPython
3245094
<gh_stars>1-10 import logging import coreapi from django.http import QueryDict from django.conf import settings from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly from rest_framework.views import APIView from rest...
StarcoderdataPython
9713713
<gh_stars>0 from athanor.commands.command import AthanorCommand class CmdStaff(AthanorCommand): key = '@staff' admin_switches = ('add', 'order', 'duty', 'vacation', 'notes', 'createcat', 'deletecat', 'renamecat', 'ordercat') def switch_createcat(self): if not self.lhs: ...
StarcoderdataPython
12814791
#!/usr/bin/env python3 from typing import Any, Generic, List, Optional, TypeVar, cast import rospy from std_msgs.msg import Bool, Float32, Int16 import time class Watchdog: def __init__(self, timeout: float): self._timeout = timeout self.pet() def pet(self): self._lastTime = time.clo...
StarcoderdataPython
3345828
<filename>bhpm/jax_code/models/kernels.py # File: matrix.py # Created Date: 2020-04-18 # Author: <NAME> (<EMAIL>) """ Kernels that are meant to produce matrices of values. We use the vectorized squared-distance algorithm for speed. As a trade-off, We avoid doing kernel grads on these. This is a reasonable place for "...
StarcoderdataPython
11279675
<reponame>relikd/lektor-groupby-plugin<gh_stars>0 from lektor.db import Page # isinstance from lektor.pluginsystem import Plugin # subclass from typing import TYPE_CHECKING, Iterator, Any from .backref import GroupByRef, VGroups from .groupby import GroupBy from .pruner import prune from .resolver import Resolver fro...
StarcoderdataPython
4847261
<reponame>zhengkai15/pytorch-examples import torch import matplotlib.pyplot as plt w = 2 b = 1 noise = torch.rand(100, 1) x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # 因为输入层格式要为(-1, 1),所以这里将(100)的格式转成(100, 1) y = w*x + b + noise # 拟合分布在y=2x+1上并且带有噪声的散点 model = torch.nn.Sequential( torch.nn.Linear(1, 16)...
StarcoderdataPython
4871778
from oauth2_provider.signals import app_authorized """ Why are we doing this? The reason is because ``django-oauth-toolkit`` does not attach the user object to the authorized token when user specific "client credentials" application gets authorized. """ def handle_app_authorized(sender, request, token, **kwargs): ...
StarcoderdataPython
3528184
<gh_stars>1-10 from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType import factory from cart.models import CartItem, Cart class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ('username',) ...
StarcoderdataPython
5194493
"""Utility functions used throughout the package. Attributes: use_colorlog (bool): Whether the logging should use colorlog or not. """ import os import sys import logging import logging.handlers import logging.config import matplotlib.markers import matplotlib.lines import numpy as np import pandas as pd import sc...
StarcoderdataPython
1873138
from pygen.cgen import * from arithgen import ArithGen, gen_max_int_gen import iterables from utils import eval_branches, FunctionGenerator import pgen import random class ClassGenerator(FunctionGenerator): def __init__(self, module, stats, opts, rng=None): self.opts = opts self.module = module...
StarcoderdataPython
1872895
<reponame>marktiu7/Web<filename>myweb/pub_form/form_login.py from django import forms from django.forms import ModelForm from login.models import * #login class UserForm(ModelForm): class Meta: model = login fields = '__all__' labels ={ 'username':'yonghuming', 'p...
StarcoderdataPython
5194631
<gh_stars>0 from prettytable import PrettyTable from prettytable import PLAIN_COLUMNS """ SAÍDA PARA CALCULOS SIMPLES: print("bin| 1100 + 0011 = 1111") print("dec| 12 + 3 = 15") print("hex| C + 3 = F") print("oct| 1100 + 0011 = 1111") print("asc| - + - = -") """ table = PrettyTa...
StarcoderdataPython
3221049
<reponame>gabrielcervante/live-sharer<filename>venv/Lib/site-packages/PySide6/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py ############################################################################ ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2016 The Qt Company Ltd. ## Contact...
StarcoderdataPython
1654013
# Copyright (c) 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
StarcoderdataPython
4998597
# MIT License # Copyright (c) 2022 Muhammed # 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, merge, publi...
StarcoderdataPython
11325133
#!/usr/bin/env python """ .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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
11269706
<reponame>scottwittenburg/vcs<gh_stars>10-100 import basevcstest class TestVCSPatterns(basevcstest.VCSBaseTest): def testLargePatterns(self): fillarea = self.x.createfillarea() fillarea.x = [[0, .33, .33, 0], [.33, .67, .67, .33], [.67, 1, 1, .67]] fillarea.y = [[0, 0, 1, 1]] * 3 f...
StarcoderdataPython
12846923
from django.views import View class PostOnlyView(View): form_class = None def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(se...
StarcoderdataPython
8016825
# Enter your code here. Read input from STDIN. Print output to STDOUT import cmath r=complex(input()) print(cmath.polar(r)[0]) print(cmath.polar(r)[1])
StarcoderdataPython
6694458
<reponame>caomingpei/smart-contract-vulnerability-detector<gh_stars>1-10 """ Module detecting deprecated standards. """ from slither.core.cfg.node import NodeType from slither.core.declarations.solidity_variables import ( SolidityVariableComposed, SolidityFunction, ) from slither.detectors.abstract_detector im...
StarcoderdataPython
8036578
<reponame>parkun-by/broadcaster import logging import aio_pika import config import asyncio from typing import Callable from asyncio.events import AbstractEventLoop logger = logging.getLogger(__name__) class Rabbit: async def start(self, loop: AbstractEventLoop, callback:...
StarcoderdataPython
6552317
<reponame>HoeYeon/Image_Captioning # All paths are relative to train_val.py file config = { 'images_path': 'train_val_data/Flicker8k_Dataset/', #Make sure you put that last slash(/) 'train_data_path': 'train_val_data/Flickr_8k.trainImages.txt', 'val_data_path': 'train_val_data/Flickr_8k.devImages.txt', 'captions_pa...
StarcoderdataPython
11351735
<reponame>anju24/liftover_helper<gh_stars>0 import setuptools setuptools.setup( name='LiftoverHelper', version='0.1.0', author='<NAME>', author_email='<EMAIL>', url='https://github.com/anju24/liftover_helper', license='LICENSE.txt', description='Pre and post processing of VCF files for lift...
StarcoderdataPython
1822028
<reponame>USF-GT-Molecular-Modeling/hoomd-blue # Copyright (c) 2009-2022 The Regents of the University of Michigan. # Part of HOOMD-blue, released under the BSD 3-Clause License. """Test the C++ internal wall data structures.""" import numpy as np import pytest from hoomd.md import _md class _TestCounter: def...
StarcoderdataPython
1710056
<reponame>An00bRektn/CTF #!/usr/bin/python3 from pwn import * from hashlib import sha256 BLOCK_SIZE = 32 def decrypt_block(block, secret): dec_block = b'' for i in range(BLOCK_SIZE): val = (block[i]-secret[i]) % 256 dec_block += bytes([val]) return dec_block r = remote('172.16.17.32',3085...
StarcoderdataPython
3331814
import unittest import numpy as np from toptim.optimizer import ParametersSet, create_engine class ParametersSetTest(unittest.TestCase): def test_Create_DataProvided_StoreValuesAsArray(self): data = [1., 2., 3.] _set = self._create_set(data) self.assertTrue(isinstance(_set.values, np.n...
StarcoderdataPython
6440066
<reponame>cglewis/snakebite<gh_stars>0 # -*- coding: utf-8 -*- # Copyright (c) 2013 Spotify AB # # 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 #...
StarcoderdataPython
4932470
# # @lc app=leetcode id=229 lang=python3 # # [229] Majority Element II # import collections # @lc code=start class Solution: def majorityElement(self, nums): if not nums: return [] mi = len(nums)/3 d = collections.defaultdict(int) ans = [] for item in nums: ...
StarcoderdataPython
11347450
n = int(input()) m = int(input()) k = int(input()) if k < n * m and ((k % n == 0) or (k % m == 0)): print("YES") else: print("NO")
StarcoderdataPython
1622934
<filename>sac/sac_wrapper.py import os import random from collections import deque from itertools import count from typing import Tuple import gym import numpy as np import torch from torch import nn from torch.distributions.independent import Independent from torch.utils.tensorboard import SummaryWriter import sac_c...
StarcoderdataPython
11383617
# -*- coding: utf-8 -* # Author: <NAME> # File: li.py # Create Date: 2017-01-18 class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ n = numRows if n == 1: return s jumpSum = 2 * n - 2 ret = "" for i in ...
StarcoderdataPython
9632127
<gh_stars>0 import numpy as np import torch import torch.utils.data as data import data.util as util import random class LDRs_dataset(data.Dataset): '''Read LQ images only in the test phase.''' def __init__(self, opt): super(LDRs_dataset, self).__init__() self.opt = opt self.paths_LDRs...
StarcoderdataPython
242474
<gh_stars>0 # -*- coding: utf-8 -*- import numpy as np import math from scipy.stats.qmc import Sobol, Halton, LatinHypercube from src.functions.particle import Particle from src.functions.moment_matching import shift_samples class Samples: """ Class for generating list of Particles given various initial condi...
StarcoderdataPython
8131192
<reponame>Mateus224/pytransform3d-1 """ ========================================== Construct Rotation Matrix from Two Vectors ========================================== We compute rotation matrix from two vectors that form a plane. The x-axis will point in the same direction as the first vector, the y-axis corresponds...
StarcoderdataPython
3201762
#Write your code below this row 👇 sum = 0 for i in range(2 , 101 , 2): sum += i print(sum) total = 0 for j in range(1, 101): if(j % 2 == 0): total += j print(total)
StarcoderdataPython
1860149
''' Created on 05.04.2021 @author: michael ''' from os.path import basename from reportlab.pdfgen.canvas import Canvas from Asb.ScanConverter.ImageOperations import ImageFileOperations from Asb.ScanConverter.Services import JobDefinition, FormatConversionService from Asb.ScanConverter.Ocr.OCR import OcrRunner from ...
StarcoderdataPython
11305793
<gh_stars>10-100 #!/usr/bin/env python ''' A script to convert variant output from the ncov pipeline. ''' import os import os.path import sys import csv import argparse import vcf import re class Variant(object): def __init__(self, var): ''' A class to handle variants from the variants.tsv file. ...
StarcoderdataPython
8101309
<gh_stars>1-10 import os import time from binary_tree import BinaryTree, HuffmanTree from graph import DirectedGraph, UndirectedGraph, DirectedNetwork, UndirectedNetwork def flash_message(message=None, keep_time=3): if message: # 如果消息有效则先清屏再打印消息,否则先等待,再清屏 i = os.system("cls") print(message) ...
StarcoderdataPython
31800
<gh_stars>1-10 import cupy as cp import numpy as np import pandas as pd import itertools import math import networkx as nx from gpucsl.pc.kernel_management import get_module function_names = [ "compact<6,6>", ] module = get_module("helpers/graph_helpers.cu", function_names, ("-D", "PYTHON_TEST")) def test_compac...
StarcoderdataPython
5077968
<reponame>MattTaylorDLS/pymalcolm import unittest from mock import patch, ANY from malcolm.core import call_with_params from malcolm.modules.ca.parts import CAActionPart class caint(int): ok = True @patch("malcolm.modules.ca.parts.caactionpart.CaToolsHelper") class TestCAActionPart(unittest.TestCase): ...
StarcoderdataPython
3415753
<filename>client/src/dolbyio_rest_apis/media/models/result_error.py<gh_stars>1-10 """ dolbyio_rest_apis.media.models.result_error ~~~~~~~~~~~~~~~ This module contains the Result Error model. """ from dolbyio_rest_apis.core.helpers import get_value_or_default class ResultError(dict): """The :class:`ResultError` o...
StarcoderdataPython
6601519
<gh_stars>0 # output parameterized data for a country from covid_package.libs.aggregate_data import fetch_latest_data_date def get_data_items(this_data, iso_list, param_list): # get the last date that data is available this_date = fetch_latest_data_date(this_data, iso_list) # two items: gdp_per_capita...
StarcoderdataPython
4828080
from django.apps import apps from django.conf import settings from django.core.validators import MinValueValidator from django.db.models import ( Model, PositiveSmallIntegerField, TextField, FloatField, ForeignKey, OneToOneField, ManyToManyField, BooleanField, DateTimeField, QuerySet, Max, Sum, F, SET_NULL...
StarcoderdataPython
3260558
from unittest.mock import patch from nose.tools import eq_ from pyecharts.charts import Gauge @patch("pyecharts.render.engine.write_utf8_html_file") def test_gauge_base(fake_writer): c = Gauge().add("", [("完成率", 66.6)]) c.render() _, content = fake_writer.call_args[0] eq_(c.theme, "white") eq_(c...
StarcoderdataPython
8174558
import os from spanner import system def retrieve_satellite_image_for_lat_lon_grid(df, filename, size=640): if os.path.exists(filename): return filename regions = [] for lat, lon in set([tuple(row.tolist()) for row in df[['lat_int', 'lon_int']].values]): regions.append([lat - 0.5, lat + 0...
StarcoderdataPython
8140891
<gh_stars>0 fatorial = int(input("Digite o valor de n:")) x = 2 total = 1 while x <= fatorial: total = total * x x = x + 1 print(total)
StarcoderdataPython
316097
<gh_stars>1-10 __all__ = ['genome_fetch']
StarcoderdataPython
11371216
<gh_stars>0 __all__ = ["client", "excs", "resource", "utils", "validate"] from .__version__ import ( # noqa: F401 imported but unused __name__, __about__, __url__, __version_info__, __version__, __author__, __author_email__, __maintainer__, __license__, __copyright__, ) from ....
StarcoderdataPython
3548410
<gh_stars>0 from tkinter import * HEIGHT = 500 WIDTH = 800 window = Tk() window.title('DISTRUGATORUL DE BULE') c = Canvas(window, width=WIDTH, height=HEIGHT, bg='darkblue') c.pack() ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill='red') ship_id2 = c.create_oval(0, 0, 30, 30, outline='red') SHIP_R = 15 MID_X = WID...
StarcoderdataPython
11379861
import cv2 import time import numpy as np import pickle with open('range.pickle','rb') as f: t = pickle.load(f) lower_red = np.array([t[0],t[1],t[2]]) upper_red = np.array([t[3],t[4],t[5]]) cap = cv2.VideoCapture(0) time.sleep(3) background = 0 #initial capture for i in range(50): ret,background = cap.r...
StarcoderdataPython
1843730
from honeybee_schema.energy.construction import OpaqueConstructionAbridged, \ WindowConstructionAbridged, WindowConstructionShadeAbridged from copy import copy from pydantic import ValidationError import pytest import os import json # target folder where all of the samples live root = os.path.dirname(os.path.dirna...
StarcoderdataPython
3347284
"""""" import sys import importlib import traceback from typing import Sequence, Any from pathlib import Path from datetime import datetime from threading import Thread from pandas import DataFrame from trader.setting import SETTINGS from vnpy.event import Event, EventEngine from vnpy.trader.engine import BaseEngine...
StarcoderdataPython
288100
<filename>src/util.py<gh_stars>1-10 from src.structures import client from discord.colour import Colour import discord class Util: def __init__(self, bot: "client.MusicBot") -> None: self.bot = bot def embed(self, **kwargs) -> discord.Embed: return discord.Embed(colour=Colour.blurple(), **kwar...
StarcoderdataPython
6697523
<gh_stars>0 import sys from lib.automaton import Ean if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError('Need a EAN size as argument') n = int(sys.argv[1]) dfa = Ean(n) print(dfa.regular_expression())
StarcoderdataPython
3358672
<gh_stars>1-10 import numpy as np import pygame as pg from numba import njit def main(): size = np.random.randint(20,60) # size of the map posx, posy, posz = 1.5, np.random.uniform(1, size -1), 0.5 rot, rot_v = (np.pi/4, 0) lx, ly, lz = (size*20, size*30, 1000) mr, mg, mb, maph, mapr...
StarcoderdataPython
5016845
<gh_stars>0 with open('Jeanette_c.txt','w',encoding='utf-8') as f: f.write('''我会给你电话,我们一起生个火,喝点小酒,在属于我们的地方辨认彼此。 别等待,别把故事留到后面讲,生命如此之短。这一片海和沙滩,这海滩上的散步,在潮水将我们所做的一切吞噬之前。 我爱你。 这是世上最难的三个字。 可除此以外。我还能说什么。''') with open('Jeanette_c.txt','r',encoding='utf-8') as f: s = f.read() print(s)
StarcoderdataPython
6425261
""" Module with class for cell types in vtkUnstructuredGrid """ __copyright__ = "Copyright © 2018-2021 <NAME>" __license__ = "SPDX-License-Identifier: MIT" from enum import Enum, unique import numpy as np from .data_array import DTYPE_TO_VTK @unique class CellType(Enum): """ Enumerates the VTK cell types....
StarcoderdataPython
223725
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: <EMAIL> ## ## This file is part of VisTrails. ## ## "Redistributio...
StarcoderdataPython
5094099
import elegy import jax import jax.numpy as jnp import typing as tp import einops import optax class MixerBlock(elegy.Module): def __init__(self, elements: int, channels: int): self.elements = elements self.channels = channels super().__init__() def call(self, x): transpose = ...
StarcoderdataPython
5025646
<gh_stars>10-100 import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") print("##### RECORDS #####") for hooman in client["mi-db"].hoomans.find(): print(hooman)
StarcoderdataPython
5137439
<reponame>deepakrana47/RNN-attention-network from bs4 import BeautifulSoup import re, numpy as np import pandas as pd from _text import Tokenizer # from keras.preprocessing.sequence import pad_sequences stopwrds = open('stopword.txt').read().split('\n') def html2text(review): """Return extracted text string fro...
StarcoderdataPython
386935
<filename>dask_mpi/tests/test_cli.py from __future__ import print_function, division, absolute_import import os from time import sleep import pytest pytest.importorskip("mpi4py") import requests from distributed import Client from distributed.comm.addressing import get_address_host_port from distributed.metrics i...
StarcoderdataPython
6571861
from flask import current_app from flask_mail import Message from . import celery, mail from .inception import execute_final @celery.task() def execute_task(id): app = current_app._get_current_object() return execute_final(app, id) @celery.task() def send_mail(subject, body, receiver): msg = Message(s...
StarcoderdataPython
9752677
def polybius(text): res="" for i in text: if i.isalpha(): temp=ord(i)-ord("A") if ord(i)>=ord("J"): temp-=1 res+=f"{temp//5+1}{temp%5+1}" else: res+=i return res
StarcoderdataPython
359725
<reponame>justin-sayah/Friendable from firebase_admin import credentials, firestore, initialize_app from generate_suggestion import gen_result cred = credentials.Certificate("google_auth_creds.json") # initialize_app(cred) db = firestore.client() def get_group_object(user_number): print('getting the group for ' +...
StarcoderdataPython
1940337
<reponame>pponnuvel/hotsos<filename>plugins/storage/pyparts/ceph_daemon_checks.py from core.checks import DPKGVersionCompare from core.issues import ( issue_types, issue_utils, ) from core.utils import sorted_dict from core.plugins.storage import ( bcache, ceph, ) from core.plugins.kernel import KernelC...
StarcoderdataPython
1777668
""" testing API from game.py """ from data.game import Game def main(): gm = Game(api_use=True) gm.new_game() flip_stock = ['S0', 0, 'S0'] gm.api_make_move(flip_stock) gm.api_make_move(flip_stock) gm.api_make_move(flip_stock) gm.api_make_move(flip_stock) gm.api_make_move(flip_stock) gm.api_undo_move() prin...
StarcoderdataPython
3257296
<filename>ldap2sql.py #!/usr/bin/python import inspect import os import sys import urllib import urllib2 import hashlib import logging from sqlalchemy import create_engine reload(sys) sys.setdefaultencoding('UTF8') cmd_folder = os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], "c...
StarcoderdataPython
4864093
<reponame>tyranus-project/steganography-telegram-bot from aiogram import Dispatcher from loguru import logger from .common import register_common_handlers from .decryption import register_decryption_handlers from .encryption import register_encryption_handlers from .exception import register_exception_handlers def ...
StarcoderdataPython
8190569
<reponame>SpeagleYao/2048-api<filename>2048_api_final/evaluate.py<gh_stars>0 from game2048.game import Game from game2048.displays import Display from game2048.agents import Agent from keras.models import load_model import keras import tensorflow as tf import numpy as np def single_run(size, score_to_win, Agen...
StarcoderdataPython
6695799
#!/usr/bin/env python3 import sys def make_crc_table(polynomial): table = [] for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ polynomial else: crc = crc >> 1 byte = byte >> 1 table.append(crc) return table def calc_crc32(table, crc, data): i...
StarcoderdataPython
1936940
<reponame>BodhiTechnology/PythonLib class SimpleFlyWeight(): """ principle: predefined the values and reuse it for time to time """ def __init__(self): self.grades = [letter + suffix for letter in 'ABCD' for suffix in ('+', '', '-')] + ['F'] def compute_grade(self, percent): percen...
StarcoderdataPython
6550334
<gh_stars>10-100 #!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from subprocess import Popen lyrics = """Installation is complete. You need to restart the computer in order to use the new installation. You can continue to use this live media, although any changes you ma...
StarcoderdataPython
4940380
<filename>setup.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='gitflow_linter', version='0.0.5', descriptio...
StarcoderdataPython
1909903
class ExternalTaskFinished: def __init__(self, external_task_id, result): self.__external_task_id = external_task_id self.__result = result async def send_to_external_task_api(self, external_task_api, identity, worker_id): await external_task_api.finish_external_task( id...
StarcoderdataPython
5060272
<reponame>vijaykumawat256/Prompt-Summarization<gh_stars>0 def interpret(code):
StarcoderdataPython
1973470
from enum import Enum, auto from state import State from constants.upgrades import upgrades as u_data class StateModifier(): class Action(Enum): PURCHASE_BUILDING = auto() PURCHASE_UPGRADE = auto() PURCHASE_COOKIE = auto() def __init__(self, state: State): self.base_state = ...
StarcoderdataPython
11286305
#! /usr/bin/python import math import sys def set_correct_normal(possible_internal_points,plane): #Make the orientation of Normal correct for point in possible_internal_points: dist = dotProduct(plane.normal,point - plane.pointA) if(dist != 0) : if(dist > 10**-10): plane.normal.x = -1*plane.normal.x p...
StarcoderdataPython
3527610
import json import os import multiprocessing import time import scipy.io as scio from utils import * base_dir = '~/' name_path = os.path.join(base_dir, 'trainval.txt') thread_num = 8 name_list = [] with open(name_path, 'r') as f: for line in f: line = line.strip('\n') name_list.append(line) data_pa...
StarcoderdataPython
11202699
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2020 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
StarcoderdataPython
281258
from .table import table from .split import split from .dataset import dataset from .cache import cache
StarcoderdataPython
8066517
<reponame>Ascend/modelzoo<gh_stars>10-100 # Copyright (c) <NAME> 2016, # All rights reserved # # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https...
StarcoderdataPython
8078952
from flask import current_app as app class Sellproduct2: def __init__(self, seller_id, product_id, current, category, name, descrip, img_link, price, available): self.seller_id = seller_id self.product_id = product_id self.current = current self.category = category self.nam...
StarcoderdataPython