id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
6490755
<gh_stars>1-10 #!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys import rclpy from gazebo_msgs.srv import SpawnEntity from ament_index_python.packages import get_package_prefix from ament_index_python.packages import get_package_share_directory import xacro def main(args=None): rclpy.init(args=args)...
StarcoderdataPython
129678
<gh_stars>1-10 # Copyright Amazon.com Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license"...
StarcoderdataPython
1825691
"""Collection of algebraic objects extending :mod:`~qnet.algebra.core`"""
StarcoderdataPython
6463432
<filename>array/computernumer.py def compute(instructions): stack = [0 for _ in range(9)] haveblock = False currentstage = 0 for ac in instructions: if ac == 'P': haveblock = True currentstage = 0 elif ac == 'M': if currentstage != 9: ...
StarcoderdataPython
11354509
<reponame>vromanuk/data-driven-web-app<gh_stars>0 from typing import List, Optional from application.pypi_org.nosql.packages import Package from application.pypi_org.nosql.releases import Release def get_latest_releases(limit=10) -> List[Release]: releases = Release.objects(). \ order_by("-created_date")...
StarcoderdataPython
6473220
# Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved. # # 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,...
StarcoderdataPython
6406301
import logging import sys import uuid from copy import deepcopy from joblib import hash as hashy import graphviz import ipywidgets as ipy import networkx as nx import pandas as pd from IPython.display import display from pipy.interactive import InteractiveDict from pipy.parameters import Iterable, PandasParam logge...
StarcoderdataPython
6652931
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-19 10:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fleet_management', '0013_auto_20180110_1349'), ] operations = [ migrations....
StarcoderdataPython
89172
<filename>mlp.py<gh_stars>0 import time # only required to run python3 examples/cvt_arm.py import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from torch.utils.data import Dataset import numpy as np import math device = torch.device('cuda'...
StarcoderdataPython
280285
<reponame>brennanmcfarland/gan-comparison from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer from tensorflow.keras.layers import Dense, Conv2D, Conv2DTranspose, UpSampling2D, BatchNormalization, Dropout, \ Activation, GaussianNoise, Reshape, Add, Flatten, LeakyReLU, Input from tenso...
StarcoderdataPython
3474421
<filename>lakeshore/model_155.py<gh_stars>1-10 """Implements functionality unique to the Lake Shore 155 Precision Source""" from time import sleep import itertools from .xip_instrument import XIPInstrument, RegisterBase, StatusByteRegister, StandardEventRegister class PrecisionSourceOperationRegister(RegisterBase):...
StarcoderdataPython
1902635
__author__ = 'bs' import cv2 import numpy as np from config.Const import * from tools import Utils from matplotlib.pyplot import figure def simpleTextureMap(): I1 = cv2.imread(ITU_LOGO) I2 = cv2.imread(ITU_MAP) #Print Help H,Points = Utils.getHomographyFromMouse(I1,I2,4) h, w,d = I2.shape o...
StarcoderdataPython
4872936
<filename>6_Builtin_Functions/_dir.py<gh_stars>0 """ dir """ import math __version__ = 1.0 # attribute def test(): pass print(dir()) # list thr names that the current module defines print() print(dir(math)) # list names from math module print() var = "teste" print(dir(var)) print() var =...
StarcoderdataPython
163122
<reponame>leferrad/rl-3 #!/usr/bin/env python # -*- coding: utf-8 -*- """""" __author__ = 'leferrad' import argparse import sys import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-src', '--source', dest='source', type=int, default=0, help...
StarcoderdataPython
4893044
# Copyright 2018 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
StarcoderdataPython
9712515
# coding: utf-8 # Goal: Rename multiple mp3 files with their properties to get them ready for iTunes """ Idea space: - Ask user to delete the Cover_Images folder on end """ import eyed3 as d3 import os, os.path, datetime, requests, re, string, PIL.Image, youtube_dl, json from bs4 import BeautifulSoup # path = "C:\\U...
StarcoderdataPython
3339398
""" Linear Regression example. Use 1 layer linear regression model to calculate add operation. ex) feature = [3, 5] then output should be 8 If cost graph doesn't converge, then change learning rate more smaller """ from Linear_Regression.model import * from matplotlib.pyplot import * feature = [[1, 3, 5], [1, 5, 4...
StarcoderdataPython
11383375
<reponame>Asurada2015/TFAPI_translation import tensorflow as tf """tf.einsum(equation, *inputs) 功能:通过equation进行矩阵乘法。 输入:equation:乘法算法定义。 # 矩阵乘 >>> einsum('ij,jk->ik', m0, m1) # output[i,k] = sum_j m0[i,j] * m1[j, k] # 点乘 >>> einsum('i,i->', u, v) # output = sum_i u[i]*v[i] # 向量乘 >>> einsum('i,j->ij', u, v) # output...
StarcoderdataPython
6515197
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from accounts import views as account_views urlpatterns = [ url(_(r'^register/$'), account_views.UserRegisterView.as_view(), name='register'), url(_(r'^login/$'), account_views.UserLoginView.as_view(), nam...
StarcoderdataPython
4976446
<reponame>IsaPeter/PythonProjects #!/usr/bin/env python3 import os, sys runpath = os.path.dirname(os.path.realpath(__file__)) approot = os.path.abspath(os.path.join(runpath, os.pardir)) sys.path.append(os.path.join(runpath,'..')) sys.path.append(approot) import lib.address_pool as ap from lib.tabCompleter import tabCom...
StarcoderdataPython
3447721
def isperfect(lst, l): perfect = True for i in range(l//2): if lst[i]!=lst[-(i+1)]: perfect = False break if perfect == True: print("PERFECT") else: print("NOT PERFECT") T = int(input()) for i in range(T): n = int(input()) arr = list(map(int, inpu...
StarcoderdataPython
9646255
import logging from typing import Callable import requests from attr import dataclass from returns.functions import tap from returns.pipeline import flow from returns.pointfree import alt, bind, rescue from returns.result import ResultE, safe from typing_extensions import final @final @dataclass(frozen=True, slots=T...
StarcoderdataPython
385079
<gh_stars>0 """ The dictionaries are blocks and they the present by '{}' , inside every block is represented by two elements, one key and one value, separated by ':' and with ',' separated every block Example: name = {key1:value1, key2:value2,.......} And inside the values you can have tuple, list, numbers, strings, al...
StarcoderdataPython
1823138
""" Copyright (c) 2021 BEAM CONNECTIVITY LIMITED Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. Download dashboards from a Grafana web instance. """ import json import logging from pathlib import Path from typing import Dic...
StarcoderdataPython
4909371
<filename>tests/unit/test_webhook.py #!/usr/bin/env python # -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """Tests for our webhooks: HTTP handl...
StarcoderdataPython
315954
# pylint: disable=missing-module-docstring # pylint: disable=missing-class-docstring # pylint: disable=missing-function-docstring from unittest import TestCase from src.game import Board from src.exceptions import ValidationError class BoardTest(TestCase): def test_start_cells(self): board = Board(2, 2, [T...
StarcoderdataPython
9735627
<reponame>supercatex/ML_Lesson # # Copyright (c) Microsoft Corporation and contributors. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for details. # def training(X, y, model, epochs=10, batch_size=128): history = model.fit( x=X, y=y, validatio...
StarcoderdataPython
6400398
<filename>plugins/module_utils/zpa_application_server.py from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible_collections.willguibr.zpacloud.plugins.module_utils.zpa_client import ( ZPAClientHelper, delete_none, ) class ApplicationServerService: def __init__...
StarcoderdataPython
11318099
import base64 import os import pickle import subprocess import sys from gym3.util import call_func def run_test_with_mpi(fn_path, kwargs=None, nproc=2, timeout=30): if kwargs is None: kwargs = {} serialized_fn = base64.b64encode(pickle.dumps((fn_path, kwargs))) subprocess.check_call( [ ...
StarcoderdataPython
5114077
from webdnn.backend.webgl.kernels import abs from webdnn.backend.webgl.kernels import average_pooling_2d from webdnn.backend.webgl.kernels import broadcast from webdnn.backend.webgl.kernels import clipped_relu from webdnn.backend.webgl.kernels import col2im from webdnn.backend.webgl.kernels import concat from webdnn.ba...
StarcoderdataPython
3360730
<gh_stars>0 import urllib.request for num in range(0, 500): url = 'http://localhost:11003/mana/getport' req = urllib.request.Request(url) data = urllib.request.urlopen(req).read() print(data, '-->' , num)
StarcoderdataPython
3322921
<filename>No_0925_Long Pressed Name/by_two-pointers_and_iteration.py ''' Description: Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True ...
StarcoderdataPython
1940259
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): replaces = [(b'emailApp', '0001_initial'), (b'emailApp', '0002_email_textcleaned'), (b'emailApp', '0003_email_removedcontent'), (b'emailApp', '0004_auto_20150329_0757')...
StarcoderdataPython
1838880
<reponame>alvarlagerlof/ball-pid import numpy as np import cv2 import imutils import copy class Process: def __init__(self): print("[init] Post process") def run(self, frame): #frame = self.resize(frame, 600) #frame = self.cropSquare(frame) return frame def resi...
StarcoderdataPython
1952078
import string print(string.punctuation) txt = """ Deserunt, minim! fugiat^$ adipisi*&*cing mollit et proident. Id qui magna ad proident proident elit esse elit amet nostrud irure sit. In anim magna culpa nostrud. Elit qui commodo mollit Lorem nostrud esse labore sunt est officia sint. Enim incididunt anim fugiat tempo...
StarcoderdataPython
9633864
<reponame>fgitmichael/SelfSupevisedSkillDiscovery import os import torch from diayn_original_tb.algo.algo_diayn_tb import DIAYNTorchOnlineRLAlgorithmTb from latent_with_splitseqs.main_all_in_one_horizon_step_collector import create_experiment from latent_with_splitseqs.post_epoch_funcs.algo_saving \ import config...
StarcoderdataPython
1769281
<gh_stars>1-10 from decouple import config, Csv from .base import * SECRET_KEY = '*xtipyb*z!q*! # wnca_q-2063m)+*80r2n=x)0i5sf=tafj21z' ALLOWED_HOSTS = [] DEBUG = True CAPTCHA_TEST_MODE = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { ...
StarcoderdataPython
5055192
<gh_stars>1-10 """Just a conftest.""" from typing import Any, Callable import httpbin as Httpbin import pytest from request_session import RequestSession @pytest.fixture(scope="function") def request_session(httpbin): # type: (Httpbin) -> Callable def inner(*args, **kwargs): # type: (*Any, **Any) ->...
StarcoderdataPython
1924274
from apscheduler.schedulers.background import BackgroundScheduler def init_tasks(app, engine): scheduler = BackgroundScheduler() scheduler.add_job( engine.start, "cron", day_of_week="mon-fri", hour=9, minute=30 ) scheduler.start()
StarcoderdataPython
1778496
class BaseItem: def __init_(self, name, item_id, page_url): self.name = name self.id = item_id self.page_url = page_url class ItemDrop: def __init__(self, enabled, level, max_level, leagues, areas, text): self.enabled = enabled self.level = level self.max_level ...
StarcoderdataPython
49081
__copyright__ = "Copyright 2016, http://radical.rutgers.edu" __license__ = "MIT" import radical.utils as ru from .base import LaunchMethod # ------------------------------------------------------------------------------ # class DPlace(LaunchMethod): # -------------------------------------------------------...
StarcoderdataPython
6614289
""" This module computes finite size supercell charge corrections for defects in anistropic systems using extended Freysoldt (or Kumagai) method developed by Kumagai and Oba. Kumagai method includes a) anisotropic PC energy b) potential alignment by atomic site averaging at Wigner Seitz cell edge If you us...
StarcoderdataPython
4814308
<filename>tests/mocks.py import datetime from random import randint from telegram.chat import Chat from telegram.message import Message from telegram.user import User class MockBot: last_message = {} def send_message(self, chat_id, text, **kwargs): self.last_message[chat_id] = text def sendMess...
StarcoderdataPython
207872
<reponame>ryanwersal/pyinfra<gh_stars>1-10 from __future__ import division import math import os import platform import sys from collections import deque from contextlib import contextmanager from threading import Event, Thread from time import sleep import pyinfra IS_WINDOWS = platform.system() == 'Windows' WAIT_...
StarcoderdataPython
5197397
# coding: utf-8 """ This file was created by Backlog APIGenerator """ from __future__ import unicode_literals, absolute_import from deprecated import deprecated from BacklogPy.base import BacklogBase class Statuses(BacklogBase): def __init__(self, space_id, api_key): super(Statuses, self).__init_...
StarcoderdataPython
9677270
<filename>mplop/__init__.py from .mplop import show from .mplop import figure __all__ = ["mplop"]
StarcoderdataPython
6695356
# this file is supposed to show the fibonacci sequence only with recursion. # for a more user friendly presentation of the fibonacci sequence there is 'src/fibonacci_sequence.py' # only functionality and error handling is to be expected from this file def fibonacci_recursion(n): if n < 2: return n if n...
StarcoderdataPython
5166591
#!/usr/bin/env python3 # 2019-5-5 class Spice: def __init__(self, name, price, quantity): self.__name = name self.__price = price self.__quantity = quantity def __str__(self): # return f'name={self.name}; price={self.price}; quantity={self.quantity};' return self.name ...
StarcoderdataPython
3220407
<gh_stars>0 from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World" @app.route("/") def create(): return "create" @app.route("/") def update(): return "update" @app.route("/") def remove(): return "remove" @app.route("/") def get(): return "get" if __nam...
StarcoderdataPython
3300968
from sklearn import model_selection from sklearn.tree import DecisionTreeClassifier from ml_factory.helper import Helper class DecisionTreeClassifierService: def __init__(self, url, columns, scoring): self._url = url self._columns = columns self._scoring = scoring def predict(self): ...
StarcoderdataPython
11272425
import requests from bs4 import BeautifulSoup import http.cookiejar as HC import json import html session = requests.session() session.cookies = HC.LWPCookieJar(filename='secret/cookies') try: session.cookies.load(ignore_discard=True) except: pass def detectInfo(nextpage=False): error_count = 0 page ...
StarcoderdataPython
1754516
import enum from numpy import e, nested_iters, printoptions from numpy.lib.npyio import load from sklearn.model_selection import cross_val_score from sklearn.datasets import load_iris from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import RandomForestClassifier import csv import matplotlib.pyplot ...
StarcoderdataPython
11250319
# -*- coding: utf-8 -*- # @Author: anh-tuan.vu # @Date: 2021-01-27 07:50:00 # @Last Modified by: anh-tuan.vu # @Last Modified time: 2021-01-27 20:03:29 import vtt2text if __name__ == '__main__': filepath = "files/transports_en_commun.vtt" # get clean content content = vtt2text.clean(filepath) pr...
StarcoderdataPython
11389294
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester l1tStage2CaloLayer2DEClientSummary = DQMEDHarvester("L1TStage2CaloLayer2DEClientSummary", monitorDir = cms.untracked.string('L1TEMU/L1TStage2CaloLayer2/L1TdeStage2CaloLayer2') )
StarcoderdataPython
11366544
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and...
StarcoderdataPython
12800552
from alpha_vantage.timeseries import TimeSeries from numpy.lib.index_tricks import _diag_indices_from from pandas.core.frame import DataFrame from sqlalchemy import create_engine from urllib.parse import quote from datetime import date import mysql.connector import pymysql import pandas as pd import pandas as pd impo...
StarcoderdataPython
1680867
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import tarfile import pandas as pd from libs.mppandas import mp_apply # ============================================================================= # CLASSES # ============================================================================= class Filter2Bands...
StarcoderdataPython
11297986
<filename>docs/ETC/Modes/S - Cone Scope/info.py<gh_stars>1-10 name = "S - Cone Scope" description = "Line oscilloscope with angle" knob1 = "X Position" knob2 = "Angle" knob3 = "Line Width" knob4 = "Color" released = "March 21 2017"
StarcoderdataPython
5045836
<gh_stars>1-10 # coding: utf-8 # import os import sys # def list_uniq(item_s): item_s_uniq = [] for item in item_s: if item not in item_s_uniq: item_s_uniq.append(item) return item_s_uniq # "exe" means executable, not just paths ending with ".exe" def find_exe_paths(prog): # 8f...
StarcoderdataPython
8155342
import torch import pydestruct.input class Dict: def __init__(self, words, unk=None, boundaries=False, pad=False, lower=False): self._boundaries = boundaries self._unk = unk self._lower = lower self._word_to_id = dict() self._id_to_word = list() if pad: ...
StarcoderdataPython
9657169
feat_settings = { "orient": 18, # 9 for rbf "pix_per_cell": 8, "cell_per_block": 2, "spatial_size": (16, 16), "n_bins": 68 }
StarcoderdataPython
194654
import numpy as np from .other import clip_boxes from .text_proposal_graph_builder import TextProposalGraphBuilder class TextProposalConnector: def __init__(self): self.graph_builder=TextProposalGraphBuilder() def group_text_proposals(self, text_proposals, scores, im_size): graph=self...
StarcoderdataPython
9642093
<reponame>ONSdigital/ras-frontstage<filename>frontstage/views/account/account_survey_share.py import json import logging from flask import flash, render_template, request from flask import session as flask_session from flask import url_for from structlog import wrap_logger from werkzeug.utils import redirect from fro...
StarcoderdataPython
128361
<reponame>PeterRydberg/rl_peg_solitaire from .Actor import Actor from .Critic import Critic from game.PegGame import PegGame import itertools import matplotlib.pyplot as plt class ReinforcementLearner: def __init__( self, episodes, game_settings, critic_settings, actor_set...
StarcoderdataPython
1968233
<gh_stars>0 # Experiment that generates several sets of networks of varying CH-divergence types # then trains an msbm of a single type in a "consensus" type of way. Then we report the # average rand_index and average entropy of the z variables, which are indicators of how well # the algorithm is learning the true mode...
StarcoderdataPython
3420651
<reponame>PavelTkachen/lost from datetime import datetime #from py3nvml.py3nvml import * import sys from lost.db import model, state, dtype import json import lost from lost.logic.pipeline import pipe_model import os import shutil from lost.logic.file_man import FileMan from lost.logic import anno_task as at_man from l...
StarcoderdataPython
11365232
''' Classes from the 'CVNLP' framework. ''' try: from rubicon.objc import ObjCClass except ValueError: def ObjCClass(name): return None def _Class(name): try: return ObjCClass(name) except NameError: return None CVNLPTextDecodingContext = _Class('CVNLPTextDecodingContext...
StarcoderdataPython
1704376
<filename>2019/Day 13/13.py from icc import ICC ID_EMPTY = 0 ID_WALL = 1 ID_BLOCK = 2 ID_PADDLE = 3 ID_BALL = 4 def gen_output(): out = [] while True: r = icc.run() if r is None: return out out.append(r) def play(): data = [] paddle_x, ball_x = 0, 0 inp = 0 ...
StarcoderdataPython
9732802
<filename>pulse/uix/vtk/vtkSymbols.py<gh_stars>10-100 import vtk import numpy as np from pulse.uix.vtk.actor.actorArrow import ActorArrow from pulse.uix.vtk.actor.actorSpring import ActorSpring class vtkSymbols: def __init__(self, project): self.project = project def getElasticLink(self, nodeA, nodeB)...
StarcoderdataPython
391297
<filename>subgroup_analysis/WhiteSubset/run_RandomForest.py import os import sys import numpy as np import argparse from easydict import EasyDict as edict from tqdm import trange from sklearn.model_selection import KFold from sklearn.ensemble import RandomForestClassifier as rfc YOUR_PATH = os.environ['YOUR_PATH'] sy...
StarcoderdataPython
8086093
<reponame>tirkarthi/python-cybox # Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import unittest from mixbox.vendor.six import u from cybox.objects.win_hook_object import WinHook from cybox.test.objects import ObjectTestCase from cybox.test.objects.win_handle_t...
StarcoderdataPython
9689778
<filename>src/cogs/server_management/management_core.py<gh_stars>1-10 from __future__ import annotations from typing import Optional from src.single_guild_bot import SingleGuildBot as Bot from src.custom_help_command import CommandWithDocs from discord import Member from discord.ext import commands, tasks from discor...
StarcoderdataPython
9622846
<filename>streamer/scripts/replay.py<gh_stars>10-100 """ Replay tweets from stdin (or a file) with a fixed delay, or by examining timestamps on original tweets and using a delay delta based on time between last and next tweet. How to do continuous play if coming from stdin? Or is that only possible if coming from a na...
StarcoderdataPython
273579
from django.conf.urls import url from evemansys.backend.views import CreateEventWizard from . import views urlpatterns = [ url(regex=r'^$', view=views.dashboard, name='Dashboard'), url(r'^create_event/$', CreateEventWizard.as_view(), name='create-event'), ]
StarcoderdataPython
9678921
# Project Imports from typing import Optional from pylidar_slam.common.geometry import projection_map_to_points, mask_not_null from pylidar_slam.common.pose import Pose from pylidar_slam.common.projection import Projector from pylidar_slam.common.utils import check_sizes, remove_nan, modify_nan_pmap from pylidar_slam....
StarcoderdataPython
9640173
from typing import List, Tuple, Dict import numpy as np from itertools import product from dwave.ComponentConverter import ComponentConverter from dwave.Sampler import Sampler from planner import Component class SimpleDWavePlanner: height: int width: int item_height: int item_width: int componen...
StarcoderdataPython
8030946
<gh_stars>10-100 from django.shortcuts import get_object_or_404, redirect, render from problems.models import Problem def problem_details(request, slug): problem = get_object_or_404(Problem, slug=slug) context = {"problem": problem} return render(request, "problems/details.html", context) def problem_r...
StarcoderdataPython
5023647
<reponame>whitneymichelle/class_enrollment_simulations """Tests for `simulation_probabilities` module.""" import pytest from class_enrollment_simulations.simulation_probabilities import get_cv_rate, get_eng_cv_rate, \ get_retention_rate, get_eng_two_cv_rate, get_transfer_cv_rate def test_get_cv_rate(): assert g...
StarcoderdataPython
12826702
<reponame>sridatta/mlrose<gh_stars>10-100 import numpy as np from mlrose_hiive import QueensOpt class QueensGenerator: @staticmethod def generate(seed, size=20): np.random.seed(seed) problem = QueensOpt(length=size) return problem
StarcoderdataPython
9620454
from pydantic.dataclasses import dataclass @dataclass class Document: name: str document_url: str download_url: str = None
StarcoderdataPython
31449
<filename>solver.py import cv2, os import numpy as np import sys from utils import movingAverage, plot, computeAverage import queue from sklearn import linear_model class Solver(): def __init__(self, config): self.vid = cv2.VideoCapture(config.vidpath) self.txtfile = config.txtfile self.vis = config.vis self....
StarcoderdataPython
4980175
<reponame>FLamparski/RailDelay import sys import json import logging import yaml import stomp import rethinkdb as r from time import sleep from os import path from toolz.dicttoolz import assoc import train_movements as tm conf_path = path.realpath(path.join(path.dirname(__file__), '..', 'conf.yml')) print('Using con...
StarcoderdataPython
172704
<gh_stars>1-10 import mock import unittest from . import testutils from ..layers import GitReindex from bin.commands import reindex class TestReindex(unittest.TestCase): layer = GitReindex @mock.patch('bin.commands.utils.directories.is_git_repository', return_value=True) @mock.patch('bin.commands.utils....
StarcoderdataPython
3475955
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-31 17:12 from __future__ import unicode_literals, print_function from django.conf import settings from django.db import migrations, models import django.db.models.deletion # # These 8 models use Member to map to a user and to make things easier for the # ...
StarcoderdataPython
1909406
<gh_stars>10-100 """ Module: 'pybricks.ev3devio' on LEGO EV3 v1.0.0 """ # MCU: sysname=ev3, nodename=ev3, release=('v1.0.0',), version=('0.0.0',), machine=ev3 # Stubber: 1.3.2 class Ev3devSensor: '' def _close_files(): pass _default_mode = None _ev3dev_driver_name = 'none' def _mode(): ...
StarcoderdataPython
1933510
<filename>display3d/display3d.py<gh_stars>1-10 import pickle import os import numpy as np import viewer3d from viewer3d import plot3d, inte_to_rgb, show_pillar_cuboid from msic import get_corners_3d from kitti import Object3d car_th = 0.5 ped_th = 0.5 data_dir = '/data/Machine_Learning/ImageSet/KITTI/object/trainin...
StarcoderdataPython
29887
#!/usr/bin/env python3 import logging import subprocess import re import boto.utils from jinja2 import Environment, FileSystemLoader from taupage import get_config logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) TPL_NAME = 'td-agent.conf.jinja2' TD_AGENT_TEMPLATE_PATH = '/etc/td-agent/t...
StarcoderdataPython
4803962
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\retail\retail_commands.py # Compiled at: 2018-03-06 02:00:39 # Size of source mod 2**32: 17737 bytes...
StarcoderdataPython
276058
from constants.processes import ptid_visualize_movement from defs import * from meta.process_base import Process from meta.registry_exports import Exports from providers.movement import passing_movement from utilities import visuals, world COLOR_WINE = "#6d213c" COLOR_RAW_UMBER = "#946846" COLOR_DARK_KHAKI = "#baab68"...
StarcoderdataPython
3388741
<filename>src/logger_setting/my_logger.py # Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved. import logging import os from src.setting.setting import my_logger_path LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d-%(funcName)s - %(message)s " log_parent_path = os.path.j...
StarcoderdataPython
6441107
<reponame>khanhnguyen21006/ViLT import math import torch import torch.nn as nn from torch.nn.modules.utils import _single class ConvTBC(nn.Module): """1D convolution over an input of shape [seq_len, batch_size, in_channels]. The implementation uses GEMM to perform the convolution. This implementation i...
StarcoderdataPython
3431136
from snovault import ( collection, calculated_property, load_schema, ) from .base import ( Item, ) from snovault.attachment import ItemWithAttachment @collection( name='images', unique_key='image:filename', properties={ 'title': 'Image', 'description': 'Listing of portal im...
StarcoderdataPython
1713776
<filename>Python Fundamentals/Text Processing/Exercise/Task09.py text = input() used_text = "" result = "" convert = "" symbols = "" index = 0 while index < len(text): convert = "" letter = text[index] if letter.isdigit(): if (index + 1) < len(text) and text[index + 1].isdigit(): conve...
StarcoderdataPython
11257554
from distutils.core import setup # see also http://docs.python.org/distutils/setupscript.html import os import sys #import subprocess import setup_conf DEBUG = False #DEBUG = True # checks # if sys.version_info < (2 , 6): sys.stderr.write("FATAL: sorry, Python versions" " below 2.6 are not...
StarcoderdataPython
6535507
# A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2021 NV Access Limited, <NAME> # This file is covered by the GNU General Public License. # See the file COPYING for more details. import enum class FillType(enum.IntEnum): NONE = 0 COLOR = 1 GRADIENT = 2 PICTURE = 3 PATTERN = 4 FillTy...
StarcoderdataPython
5037745
find("1265075160887.png") d = VDict() d["1265075226698.png"] = "OK" print d["1265075226698.png"][0]
StarcoderdataPython
9679714
""" GCN model for relation extraction. """ import copy import math """ GCN model for relation extraction. """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.tree import Tree, head_to_tree, tree_to_adj from utils import constant, to...
StarcoderdataPython
180163
<filename>{{cookiecutter.project_slug}}/{{cookiecutter.app_name}}/forms.py from django import forms # https://docs.djangoproject.com/en/1.10/topics/forms/ # https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/
StarcoderdataPython
3452474
from pathlib import Path ROJECT_ROOT_DIR = Path.cwd().joinpath("Results") CHECKPOINTS_DIR = ROJECT_ROOT_DIR.joinpath("Checkpoints") FIGURE_DIR = ROJECT_ROOT_DIR.joinpath("FigureFiles") DATA_DIR = Path.cwd().joinpath("DataFiles") TERRAIN_PATH = DATA_DIR.joinpath("SRTM_data_Norway_2.tif") CONFIGS_PATH = ROJECT_ROOT_DIR....
StarcoderdataPython
125938
import collections from .helpers import makeInverse, makeInverseVal class EdgeFeatures(object): pass class EdgeFeature(object): def __init__(self, api, metaData, data, doValues): self.api = api self.meta = metaData self.doValues = doValues if type(data) is tuple: ...
StarcoderdataPython