id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
100328 | <reponame>joshmaglione/SingularZeta
#
# Copyright 2020 <NAME>
#
# Distributed under MIT License
#
from rationalPoints import _guess_polynomial
from globalVars import _DEFAULT_VERBOSE as _verbose
# A useful function for multiple lines
_cat_with_space = lambda x, y: x + "\n" + y
# Get the name of the atlas, whic... | StarcoderdataPython |
84254 | <filename>nz_covid_pass_verifier.py
#!/usr/bin/env python3
import argparse
import base64
import json
import sys
import uuid
import yaml
import cwt
import requests
import PIL.Image
import pyzbar.pyzbar
from datetime import datetime, timezone
DID_URL = 'https://nzcp.identity.health.nz/.well-known/did.json'
def get_... | StarcoderdataPython |
3337462 | #!/usr/bin/env python3
# coding: utf-8
# author: alice12ml
import config
import requests
import logging
from handler import Handler
from handler.timestamp import TimeStampHandler
from handler.video import VideoHandler
from handler.sticker import StickerHandler
from handler.user_info import UserInfoHandler
from concurr... | StarcoderdataPython |
1606505 | <reponame>coll-gate/collgate<filename>server/accession/accessionbatch.py
# -*- coding: utf-8; -*-
#
# @file accessionbatch.py
# @brief coll-gate accession batch rest handler
# @author <NAME> (INRA UMR1095)
# @date 2017-01-03
# @copyright Copyright (c) 2017 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
from ... | StarcoderdataPython |
1737458 | import re
import sys
class Cart:
def __init__(self, x, y, direction):
global g_id
self.x = x
self.y = y
self.position = (x, y)
self.last_position = (x, y)
self.direction = direction
self.next_turn = 'l'
self.id = g_id
g_id += 1
def set_x... | StarcoderdataPython |
28513 | <filename>jupyterlab-mlops/jupyter_server_config.py
import os
import requests
import time
c = get_config() # noqa: F821
c.ServerApp.ip = "0.0.0.0"
c.ServerApp.port = 8888
c.ServerApp.open_browser = False
def get_gooogle_instance_attribute(attribute_name):
try:
response = requests.get(
f'h... | StarcoderdataPython |
3352892 | from pushservices.fcm import FCMClient
import unittest
import sys
from unittest.mock import MagicMock, patch
from util import json_decode
def mocked_tornado_http(*args, **kwargs):
class HTTP:
async def fetch(self, url, **kwargs):
body = kwargs["body"]
return body
return HTTP()... | StarcoderdataPython |
151164 | from __future__ import division
from annotypes import Anno, add_call_types
from malcolm.core import Part, NumberMeta, Widget, config_tag, APartName, \
PartRegistrar, Display
from ..infos import ExposureDeadtimeInfo, ParameterTweakInfo
from ..util import exposure_attribute
from ..hooks import ReportStatusHook, Val... | StarcoderdataPython |
23751 | import json
from django.urls import reverse
from django.shortcuts import render
from django.db.models import Q
from django.views.generic.base import View
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
... | StarcoderdataPython |
4807660 | <filename>py/agentflow/loggers/print_logger.py
# Copyright 2020 DeepMind Technologies Limited.
#
# 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-... | StarcoderdataPython |
1679527 | <gh_stars>0
import json
import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from openslides.mediafiles.models import Mediafile
from tests.count_queries import count_queries
from tests.te... | StarcoderdataPython |
1750594 | #!/usr/bin/env python
import time
import os
import sys
from systemd.daemon import notify, Notification
if os.environ.get('SYSTEMD_NOTIFY_ENABLE') == 'true':
notify(Notification.STOPPING)
notify(Notification.STATUS, "Service stopping...")
time.sleep(3)
print("Finished prestart")
sys.exit(0)
| StarcoderdataPython |
1720491 | <filename>legacy/ABC_111/D2.py
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: mo-mo-
#
# Created: 29/09/2018
# Copyright: (c) mo-mo- 2018
# Licence: <your licence>
#---------------------------------------------------... | StarcoderdataPython |
1705772 | <gh_stars>0
from unittest import expectedFailure
from ..utils import TranspileTestCase
class MathModuleTests(TranspileTestCase):
# Trigonometric functions
def test_sin(self):
self.assertCodeExecution("""
import math
print(math.sin(1))
""")
def test_cos(self):
... | StarcoderdataPython |
4829680 | <reponame>coryMosaicML/composer<filename>composer/algorithms/agc/__init__.py
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""`Adaptive gradient Clipping <https://arxiv.org/abs/2102.06171>`_ Clips all gradients in model based on ratio of
gradient norms to parameter norms.
See the :d... | StarcoderdataPython |
3393319 | """Unit test for AdaLossBatchNormalization """
import unittest
import numpy as np
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import testing
from ada_loss.chainer_impl.functions.loss_scaling import loss_scaling
from ada_loss.chainer_impl.functions.ada_loss_batch_normalization i... | StarcoderdataPython |
3384404 | from ._magnetizationModel import MagnetizationModel
from fortMag import langevin
class Langevin(MagnetizationModel):
'''
Model to describe a linear function
'''
def __init__(self, parent):
super().__init__(parent)
self.kB = 1.3806485e-23 # J/K
self.muB = 9.274009994e-24 # J/T
def initParameters(... | StarcoderdataPython |
3380252 | <gh_stars>1-10
'''Module for admin-only commands in guilds'''
import disnake
from disnake.ext import commands
from src.utils import guild_functions
class AdminCommands(commands.Cog):
'''Cog for admin-only commands'''
@commands.slash_command()
async def admin(self, inter: disnake.CommandInteraction, *args... | StarcoderdataPython |
3351367 | import requests
class RandomUser:
def __init__(self):
self.url = "https://randomuser.me/api/"
def get_random_user(self):
result = requests.get(self.url)
data = result.json()["results"][0]
return data
def get_multiple_users(self, number):
if type(number) is not in... | StarcoderdataPython |
1708725 | <reponame>hellsayenci/ats
# Generated by Django 2.0.1 on 2019-12-21 02:57
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('utils', '__first__'),
('company', '0001_i... | StarcoderdataPython |
1798321 | from z3 import Int
from generativemagic.spelling import Language
def create_card_variables(language: Language):
names = map(language.card_name, range(1, 53))
our_vars = map(Int, names)
return list(our_vars)
| StarcoderdataPython |
158884 | cont = contIdade = contHomens = contMulher20 = 0
print('-=' * 15, '\nCadastro de Pessoas')
print('-=' * 15)
while True:
idade = int(input('\033[1mDigite a idade:\033[m '))
if idade >= 18:
contIdade += 1
sexo = ' '
while sexo not in 'MmFf':
sexo = str(input('\033[1mDigite o sexo [M/F]:\03... | StarcoderdataPython |
1751033 | print('this is two/c.py')
| StarcoderdataPython |
132786 | # ADVENT OF CODE 2021
# Challenge #{day:02}
# <NAME>
SAMPLE_INPUT = """\
\
"""
PT1_SAMPLE_ANS = None
def pt1(input: str):
input = input.splitlines()
return input
PT2_SAMPLE_ANS = None
def pt2(input: str):
input = input.splitlines()
return input
# ===============================... | StarcoderdataPython |
1782440 | # -*- coding: utf-8 -*-
# dcf
# ---
# A Python library for generating discounted cashflows.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.4, copyright Saturday, 10 October 2020
# Website: https://github.com/sonntagsgesicht/dcf
# License: Apache License 2.0 (see LICENSE f... | StarcoderdataPython |
3243138 | import os
# Checking the Path is valid or not
def isDir(file_path):
if os.path.isdir(file_path):
return True
else:
return False
#Checking the path containes any files
def isContains(file_path):
files = os.listdir(file_path)
if files == []:
return False
else:
retur... | StarcoderdataPython |
4836507 | <filename>src/Sastrawi/StopWordRemover/StopWordRemoverFactory.py
from Sastrawi.Dictionary.ArrayDictionary import ArrayDictionary
from Sastrawi.StopWordRemover.StopWordRemover import StopWordRemover
class StopWordRemoverFactory(object):
"""description of class"""
def create_stop_word_remover(self):
sto... | StarcoderdataPython |
232 | # Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
22351 | <gh_stars>0
#!/usr/bin/env python3
import asyncio, entity, io, json, logging, queue, random, threading, time, websockets, whale
from bot import bot
from random import randrange
logging.basicConfig()
log = logging.getLogger('tweetx')
log.setLevel(logging.DEBUG)
class Event:
def __init__(self):
self.callba... | StarcoderdataPython |
3295588 | <filename>felz.py
import skimage.segmentation
from matplotlib import pyplot as plt
import scipy
import numpy as np
from collections import defaultdict, namedtuple
import cv2
from random import randint
from skimage import io, draw, transform
import argparse
from subprocess import call
ap = argparse.ArgumentParser()
ap.... | StarcoderdataPython |
3394640 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 15:43:29 2019
@author: jamie.ross
"""
ratings = [beer.ratings for beer in receps]
ratings = pd.concat(ratings)
ratings = ratings[[x in ['10', '20', '30', '40', '50'] for x in ratings.Rating]]
ratings['Char'] = pd.to_numeric(ratings['Char'])
ratings['Rating'] = pd.t... | StarcoderdataPython |
1768387 | __all__ = [
"ewma",
"gbdt",
"statistic",
"isolation_forest",
"xgboosting",
"polynomial_interpolation",
"ewma_and_polynomial",
]
| StarcoderdataPython |
1796273 | import logging
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
from hdrbp._util import (
basic_repr,
basic_str,
compute_correlation,
compute_diversification_ratio,
compute_drawdowns,
compute_gini,
compute_prices,
compute_risk_contributions,
compute_turnov... | StarcoderdataPython |
17861 | import requests
import re
import time
import random
import pprint
import os
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3858.0 Safari/537.36"}
def youdict(threadName, q):
res = []
index = 0
url = q.get(timeout = 2)
... | StarcoderdataPython |
1723414 | <filename>services/dsrp-api/app/api/services/object_store_storage_service.py
import boto3
import io
import asyncio
from flask import Response
from pathlib import Path
from app.config import Config
class ObjectStoreStorageService():
_client = None
def __init__(self):
session = boto3.session.Session(... | StarcoderdataPython |
51310 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
INITIAL_PICKS = [
{"user_id": 1, "event_id": 1, "team": "home", "week": 1},
{"user_id": 2, "event_id": 7, "team": "home", "week": 1},
{"user_id": 3, "event_id": 8, "team": "away", "week": 1},
{"user_id": 4, "event_id": 6, "t... | StarcoderdataPython |
96939 | import torch
import torch.nn as nn
import torch.optim as optim
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from data_loader import *
def get_iou(predict, label):
predict_f = torch.flatten(predict)
label_f = torch.flatten(label)
intersection = torch.sum(predict_f*lab... | StarcoderdataPython |
3355698 | <gh_stars>0
#---------------------------------------------------------------------------
# predict.py
#
# Author : <NAME>
# Date : July 10, 2015
# School : Harvard University
#
# Project : Master Thesis
# An Interactive Deep Learning Toolkit for
# Automatic Segmentation of Images
#
# Summary : ... | StarcoderdataPython |
6184 | <gh_stars>0
import typing as t
from http.server import HTTPServer, BaseHTTPRequestHandler
from . import response as resp
class WsgiServer(HTTPServer):
pass
class WsgiHandel(BaseHTTPRequestHandler):
def handle(self) -> None:
handle_response = SimpleHandler(self.wfile)
handle_response.send()... | StarcoderdataPython |
3355356 | import http.client
import os
import tempfile
import wave
import numpy as np
import json
import time
def transcribeAudio(path_to_audio_file, samplerate=16000):
headers = {"Content-type": "audio/wav; codec=\"audio/pcm\"; samplerate=" + str(samplerate)}
with open(path_to_audio_file, 'rb') as audio_file:
... | StarcoderdataPython |
1739747 | # dagparser.py - parser and generator for concise description of DAGs
#
# Copyright 2010 <NAME> <<EMAIL>>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import re, string
import util
from i18n import _
def parsedag(desc):
''... | StarcoderdataPython |
1721933 | <reponame>cooomma/mayday-ticketing-bot
import logging
import time
from telegram.error import BadRequest
from telegram.ext.dispatcher import run_async
import mayday
from mayday.constants import TICKET_MAPPING, conversations, stages
from mayday.constants.replykeyboards import KEYBOARDS
from mayday.controllers.redis imp... | StarcoderdataPython |
3263519 | from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView, QQuickItem
from mind_mapper.controllers import Controller
import sys
import os
class View(object):
shapes = ["rectangle", "ellipse", "image"]
edgetypes = ["line", "curve"]
def __init__(self):
... | StarcoderdataPython |
4810502 | conj_A = {1, 2, 3}
conj_B = {3, 4, 5}
#Conjuntos Comuns ás duas listas
print(conj_A & conj_B)
#Valores que existem na primeira listas
print(conj_A - conj_B)
#Valores que existem na Segunda listas
print(conj_B - conj_A)
res = conj_A | conj_B
print(res) | StarcoderdataPython |
197257 | # Optical Character Recognition or optical character reader (OCR) is the electronic or mechanical conversion of images of typed, handwritten or printed text into machine-encoded text, whether from a scanned document, a photo of a document.
# pip install edenai
from edenai import OCR
# Get your API key here: https://... | StarcoderdataPython |
160153 | <filename>example/helloworld/test.py
import unittest
import grpc
from homi.test_case import HomiTestCase
from .app import app
from .helloworld_pb2 import HelloRequest, _GREETER
class GreeterTestCase(HomiTestCase):
app = app
def test_hello_say(self):
server = self.get_test_server()
name = "t... | StarcoderdataPython |
1673796 | #!user/bin/python
import os
import subprocess
import env
env_object = env.MyEnv()
cmd_rm_ansible_container = [
'docker', 'rm', '-f', 'ans'
]
cmd_rm_apache2_container = [
'docker', 'rm', '-f', 'web'
]
cmd_rm_mariadb_container = [
'docker', 'rm', '-f', 'db'
]
cmd_rmi_ansible_image = [
'docker', 'rmi', '... | StarcoderdataPython |
1790692 | <gh_stars>10-100
import json
import os
import glob
import pickle
import re
import time
import wget
import tarfile
import numpy as np
import tensorflow as tf
import matplotlib.image as mpimg
from skimage.transform import resize
from sklearn.decomposition import PCA
from tensorflow.python.keras.preprocessing.image impor... | StarcoderdataPython |
1655319 | nome = str(input('Qual seu nome? '))
if nome == 'Gustavo':
print('Que nome lindo voce tem!')
else:
print('Seu nome é tão normal!')
print('Bom dia, {}!'.format(nome))
| StarcoderdataPython |
86765 | <filename>lib/doekbase/data_api/tests/nose_plugin_wsurl.py
"""
Nose testing plugin for configuring Workspace URL during tests.
"""
# Imports
# Stdlib
import os
# Third-party
from nose.plugins import Plugin
# Local
from doekbase.data_api import core
from doekbase.data_api.util import get_logger
# Logging
_log = get_lo... | StarcoderdataPython |
3238252 | class NoDbtPathSupplied(Exception):
"""Thrown when no argument for dbt path has been supplied"""
class NoDbtSchemaSupplied(Exception):
"""Thrown when using folder parser without supplying a schema"""
class MetabaseUnableToSync(Exception):
"""Thrown when Metabase cannot sync / align models with dbt model... | StarcoderdataPython |
131257 | <filename>kongming/api/controllers/v1/hosts.py
# Copyright 2018 Huawei Technologies Co.,LTD.
# 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:/... | StarcoderdataPython |
96471 | <filename>misc_functions.py
import csv
def do_transpose(some_2Dlist):
y = zip(*some_2Dlist)
z = []
for i in y:
z.append(list(i))
return z
def write_2dlist_to_csv(some_2Dlist, some_file_name):
fp = open(some_file_name, 'wb')
writer = csv.writer(fp)
writer.writerows(some_2Dlist)
| StarcoderdataPython |
3346925 | from aiohttp import web
from timer_data.api import api
def create_routes():
return [
web.get('/api/ping', api.ping),
web.post('/api/register', api.create_user),
web.post('/api/login', api.login),
web.get('/api/logout', api.logout),
# timer
web.post('/api/timer', api... | StarcoderdataPython |
53620 | #!/usr/bin/env python
# Author: <NAME>
# email: <EMAIL>
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open(('README.md'), encoding='utf-8') as readme:
bdescription = readme.read()
setup(
name='sparkdataset',
description=("Provides instant access to ... | StarcoderdataPython |
4815056 | <reponame>clearbluejar/cve-markdown-charts
from urllib import response
import requests
import datetime
import json
from bs4 import BeautifulSoup
import os
from mdutils.tools.Table import Table
from html import escape
import argparse
msrc_api_url = "https://api.msrc.microsoft.com/"
cve_url = "https://cve.mitre.org/cgi... | StarcoderdataPython |
1686954 | import torch
import torch.nn as nn
import subprocess
import sys
import os
def is_distributed():
return torch.distributed.is_initialized()
def get_world_size():
if not torch.distributed.is_initialized():
return 1
return torch.distributed.get_world_size()
def get_rank():
if not t... | StarcoderdataPython |
164283 | #g = r.Graph()
#g.load("cdTriplestore.rdf")
#print time.time()-T
# mais de 4 minutos para carregar
#ss=set([s for s in g.subjects()])
#len(ss)
#oo=set([s for s in g.objects()])
#len(ss)
#len(oo)
#pp=set([s for s in g.predicates()])
#classes=g.objects(predicate=r.RDF.type)
# classes que apareceram na triplificacao dos... | StarcoderdataPython |
148821 | <filename>modules/routers/service/dependencies.py<gh_stars>0
from fastapi import HTTPException
from .models import AchievementTemplate
from ..user.models import User
from ...database import MongoDbWrapper
DB = MongoDbWrapper()
async def get_achievement_template(achievement_template_id: str) -> AchievementTemplate:
... | StarcoderdataPython |
3210433 |
from pyteal import *
from validator import *
from utils import *
from config import *
tc = TemplateContract(configuration)
print(tc.get_blank_hash()) | StarcoderdataPython |
3378927 | <gh_stars>0
"""Allows using emdp as a gym environment."""
import gym
import numpy as np
from gym import spaces
import emdp.utils as utils
def gymify(mdp, **kwargs):
return GymToMDP(mdp, **kwargs)
class GymToMDP(gym.Env):
def __init__(self, mdp, observation_one_hot=True):
"""
:param mdp: The... | StarcoderdataPython |
1777447 | from onlinejudge_verify.online_submission.submissions import *
from requests import session
import requests
import mechanize
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By... | StarcoderdataPython |
1692835 | from sigauth import permissions
from django.conf import settings
class SignatureCheckPermission(permissions.SignatureCheckPermissionBase):
secret = settings.SIGNATURE_SECRET
| StarcoderdataPython |
1628008 | from kivy.app import App
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import ListProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
Builder.load_file("widget... | StarcoderdataPython |
3230567 | <filename>program.py
"""This sample script demonstrates how to invoke the Data View REST API"""
import json
import copy
import datetime
import random
import traceback
from adh_sample_library_preview import (DataView, Field, FieldSource, ADHClient, Query,
SdsStream, SdsType, SdsT... | StarcoderdataPython |
1759779 | <filename>tools/reveal_savefile.py
from endless_sky.datafile import DataFile
f = DataFile("data/map.txt")
for i in f.root.filter_first("system"):
print("visited", "\"" + i.tokens[1] + "\"" )
for i in f.root.filter_first("planets"):
print("visited planet", "\"" + i.tokens[1] + "\"" ) | StarcoderdataPython |
1659194 | import metroui, sys, codeop
class PseudoFile:
def __init__(self, readline=None, write=None):
self.readline=readline
self.write=write
def writelines(self, lines):
for line in lines:
self.write(line)
def flush(self):
pass
def isatty(self):
return Tru... | StarcoderdataPython |
3359689 | <filename>oco2peak/_nbdev.py<gh_stars>0
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Datasets": "datasets.ipynb",
"gaussian": "find_peak.ipynb",
"build_sounding_scatter": "map.ipynb",
"build_sounding_map": "map.ipynb"}
modul... | StarcoderdataPython |
4827323 | <reponame>questionlp/wwdtm
# -*- coding: utf-8 -*-
# vim: set noai syntax=python ts=4 sw=4:
#
# Copyright (c) 2018-2021 <NAME>
# wwdtm is released under the terms of the Apache License 2.0
"""Wait Wait Don't Tell Me! Stats Scorekeeper Appearance Retrieval
Functions
"""
from functools import lru_cache
from typing import... | StarcoderdataPython |
1604753 | #!/usr/bin/env python3
import netifaces
for i in netifaces.interfaces():
print('\n**************Details of Interface - ' + i + ' *********************')
print(netifaces.ifaddresses(i)[netifaces.AF_LINK])
| StarcoderdataPython |
3220766 | <reponame>DhananjayAshok/PyStata
import os
import pandas as pd
from statapy.utils import column_corrector
class DataSet(object):
"""
Class to hold a pandas dataset under the data field.
"""
def __init__(self, name, filename="", url="", data=None):
"""
:param name: Name of the DataSet... | StarcoderdataPython |
1712390 | import importlib
import os
class SubcommandRegistry(object):
def __init__(self, setup=True):
self._setup()
def _setup(self):
self.subcommands_dir = os.path.dirname(__file__)
self._subcommands = {
subcommand: ...
for subcommand in self._get_subcommand_names()
... | StarcoderdataPython |
1702267 | """A class for microscope objects.
Author: <NAME>, ANL, 20.Feb.2015.
"""
import numpy as np
import scipy.constants as physcon
import scipy.ndimage as ndimage
class Microscope(object):
'''Class for Microscope objects.
A class that describes a microscope for image simulation and reconstruction
purposes... | StarcoderdataPython |
1682475 | import torch
import torch.nn as nn
class TensorSplitter:
@staticmethod
def predecessor_successor_split(tensor: torch.Tensor) -> torch.Tensor:
'''
Splits a tensor into the second dimension predecessors and successors
:param tensor: (dim1, dim2, ...) tensor
:return: (dim1, 0:dim... | StarcoderdataPython |
133511 | <reponame>Manny27nyc/oci-python-sdk
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache... | StarcoderdataPython |
3388221 | <reponame>NewGuonx/DST_algorithm
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
| StarcoderdataPython |
1760419 | <reponame>didiqu/IS_simulator<filename>launcher.py
""" Main script """
import os
import time
import shutil
import random
import argparse
import threading
from pylxd import Client
from colorama import Style, Fore
import netifaces as ni
from visualize import generate_topology
from logic_actio... | StarcoderdataPython |
1789901 | <reponame>OurHomeTrainer/OurHT_Backend
# Generated by Django 3.2.8 on 2021-11-11 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20211111_2020'),
]
operations = [
migrations.AddField(
model_name='use... | StarcoderdataPython |
3235140 | import numpy as np
import pandas as pd
import random
from collections import deque
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM, BatchNormalization
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks im... | StarcoderdataPython |
199459 | # encoding: utf-8
import sys
JYTHON = sys.platform.startswith("java")
import doctest
from test import test_support
import xml.parsers.expat as expat
from xml.etree.ElementTree import *
def jython(function):
if JYTHON:
return function
else:
return None
class sortdict(dict):
def __repr__(... | StarcoderdataPython |
3354193 | <reponame>kdeltared/tcex<filename>tests/batch/test_indicator_interface_1.py
"""Test the TcEx Batch Module."""
# third-party
import pytest
# pylint: disable=no-self-use
class TestIndicator1:
"""Test the TcEx Batch Module."""
def setup_class(self):
"""Configure setup before all tests."""
@pytest.m... | StarcoderdataPython |
183781 | <reponame>StargazerZhu/ray_dist_ml
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def proxgrad_l1l2(var, grad, lr, l1, l2):
# Try to perform proximal gradient step:
# x_{t+1} = prox_{lr * h}(var - lr * grad)
# where h(x) = l... | StarcoderdataPython |
3213869 | # Importing some modules and setting up a few properties
import sys
import os
from matplotlib import pyplot as plt
import numpy as np
import csv
from collections import Counter
sys.path.append(os.getcwd())
os.environ["DJANGO_SETTINGS_MODULE"] = "as8_db.settings"
import django
django.setup()
from core import backup
... | StarcoderdataPython |
26395 | import mne
import numpy as np
import pandas as pd
from mne.beamformer import make_dics, apply_dics_csd
from config import dics_settings, fname, args
from megset.config import fname as megset_fname
from megset.config import freq_range
subject = args.subject
print(f'Running analsis for subject {subject}')
mne.set_log_... | StarcoderdataPython |
1646167 | #! /usr/bin/env python
'''
To make the generation of imaging (including moving target)
simulated integrations easier, combine the 3 relevant stages
of the simulator (seed image generator, dark prep,
obervation generator) into a single script.
HISTORY:
13 November 2017 - created, <NAME>
13 July 2018 - updated for name... | StarcoderdataPython |
3334201 | import pygame
from pygame.locals import *
import sys
import time
from random import randrange
import random
SCREEN_SIZE = (1280, 720)
global HORIZ_MOV_INCR
HORIZ_MOV_INCR = 5
global FPS
global clock
global time_spent
WHITE = ((255,255,255))
BLACK = ((0,0,0))
BLUE = pygame.Color('dodgerblue4')
glo... | StarcoderdataPython |
1738396 | <filename>mmf/datasets/mmf_dataset_builder.py
import collections
import os
import typing
import warnings
import mmf.utils.download as download
from mmf.datasets.base_dataset_builder import BaseDatasetBuilder
from mmf.datasets.concat_dataset import MMFConcatDataset
from mmf.utils.configuration import get_global_config,... | StarcoderdataPython |
101892 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .reader import CorpusReader
from .reader_lxml import load
| StarcoderdataPython |
129192 | class ListTransformer():
def __init__(self, _list):
self._list = _list
@property
def tuple(self):
return tuple(self._list)
| StarcoderdataPython |
3261576 | def profile(name, age, language):
print(name, age, language)
profile(name="이지혁",language="Python", age=24) | StarcoderdataPython |
4822538 | from keanu.vartypes import tensor_arg_types
from .base import Vertex
from .generated import ConstantBoolean, ConstantDouble, ConstantInteger
from keanu.infer_type import infer_type_and_execute
from typing import Optional
def Const(t: tensor_arg_types, label: Optional[str] = None) -> Vertex:
vertex = infer_type_an... | StarcoderdataPython |
50693 | #!/usr/bin/env python3
import argparse
import json
import logging
import socket
import socketserver
import time
from collections import deque
from queue import Queue
from threading import Thread
import Ice
logger = logging.getLogger(__name__)
def retrieve_server_state():
try:
import mice3 as mice
... | StarcoderdataPython |
24858 | <filename>octoprint_marlin_flasher/validation/validators/arduino.py<gh_stars>1-10
from flask_babel import gettext
from marshmallow import ValidationError
import intelhex
import zipfile
def is_correct_file_type(filename):
try:
with zipfile.ZipFile(filename, "r") as _:
pass
except zipfile.BadZipfile:
try:
i... | StarcoderdataPython |
166377 | <reponame>Ibrahim2595/virtual_learning_softrobotics
import cv2
import mediapipe as mp
import numpy as np
import json
import time
import socket
import sys
# color in BGR
text_color = (255, 255, 255)
arrow_color = (0, 0, 255)
arrow_thickness = 6 #px
arrow_length = 200
cmd_text_position = [50,50]
last_cmd_expire_time = {... | StarcoderdataPython |
4818740 | <filename>socialcrawl/clients/cache.py<gh_stars>10-100
from datetime import datetime, timedelta
from django.utils import timezone
from socialcrawl.settings import CACHE_MAX_AGE
from socialcrawl.networks.models import Profile
class CachedClient(object):
def __init__(self):
super(CachedClient, self).__in... | StarcoderdataPython |
1630287 | #
#
#
##
"""
Test module.
ju
"""
__all__ = ['Cls1', 'func4']
class Cls1(object):
def __init__(self, a, b): pass
def func1(self, q, b):
pass
def func2(self, q):
"""Cls1.func2 docstring
\"\"\"
"""
pass
class Cls2(
Cls1,
dict
... | StarcoderdataPython |
1730553 | <gh_stars>1-10
#!/usr/bin/env python
# These are the key vertices of "The Cuttle"
VERTICES = [
# T
[
(15, 1),
(15, 51)
],
[
( 4, 51),
(30, 51)
],
# h
[
(35, 54),
(35, 2)
],
[
(35, 23),
(40, 32),
(49, 33),
... | StarcoderdataPython |
1739575 | def decompressRLElist(nums):
index = 0
result = []
while index < len(nums):
result += [nums[index+1]] * nums[index]
index +=2
return result
nums = [1,2,3,4]
print(decompressRLElist(nums))
nums = [1,1,2,3]
print(decompressRLElist(nums))
#... | StarcoderdataPython |
3272676 | # -*- coding: utf-8 -*-
"""Untitled0.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1_sI39MBHGRnt20inesIty9_uiUVUdJ4X
"""
# Commented out IPython magic to ensure Python compatibility.
import os
if 'TPU_NAME' in os.environ:
import requests
if... | StarcoderdataPython |
174293 | import os
import tensorflow as tf
from tensorflow.python.tools import freeze_graph
def save_model(folder_name, t=0):
save_path = folder_name + '/model-' + str(t) + '.cptk'
os.makedirs(os.path.dirname(save_path), exist_ok=True)
saver = tf.train.Saver()
result = saver.save(tf.keras.backend.get_session(... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.