id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6409273 | <gh_stars>10-100
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token not in {"+", "-", "*", "/"}:
stack.append(int(token))
else:
r, l = stack.pop(), stack.pop()
if token == "+":
... | StarcoderdataPython |
3492037 | import examples
from examples.meta import C, F
from mkapi.core.base import Docstring
from mkapi.core.docstring import parse_bases
from mkapi.core.inherit import inherit
from mkapi.core.node import get_node
def test_mro_docstring():
doc = Docstring()
parse_bases(doc, C)
assert len(doc["Bases"].items) == 2
... | StarcoderdataPython |
1834712 | <filename>clkhash/clk.py<gh_stars>10-100
"""
Generate CLK from data.
"""
import concurrent.futures
import csv
import logging
import time
from typing import (AnyStr, Callable, cast, Iterable, List, Optional,
Sequence, TextIO, Tuple, TypeVar, Union)
from bitarray import bitarray
from tqdm import tqdm... | StarcoderdataPython |
234326 | from .setup_structlog import setup_structlog
setup_structlog()
| StarcoderdataPython |
1925428 | <filename>core/middleware.py
from django.db.models import signals
from django.utils.functional import curry
class AuditMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRAC... | StarcoderdataPython |
1920135 | <gh_stars>0
from ..data_object.pyradiomics_response import NumpyArrayEncoder
from ..models.SitkImage import get_metadata_dictionary
import os
import SimpleITK as sitk
from django.http import HttpResponse, JsonResponse
from django.conf import settings
def handle(request, idImage=''):
method = request.method
... | StarcoderdataPython |
4917831 | from setuptools import setup, find_packages
def get_tag():
f = open('VERSION', 'r')
tag = f.read().strip()
f.close()
return tag
def get_description():
f = open('README', 'r')
desc = f.read()
f.close()
return desc
setup(name='hailc',
version=get_tag(),
description='Lightl... | StarcoderdataPython |
224793 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from eospac import EosMaterial
from eospac.eospac.libsesio import _write_sesbin
import numpy as np
from numpy.testing import assert_allclose
def is_equal(x,y):
assert x == y
| StarcoderdataPython |
9601800 | from .pen import Pen
class PenCollection:
def __init__(self, initialisation_collection):
self.pens = {}
i = 0
for p in initialisation_collection:
self.pens[i] = Pen(p["brand"], p["name"], rgb=p["rgb"])
i = i+1
def closest_pen_to_colour(self, colour... | StarcoderdataPython |
11306516 | <gh_stars>1-10
from math import floor
from pathlib import Path
from sys import argv
def main():
file_path = Path(argv[1])
with file_path.open() as file:
result = 0
while text := file.readline().strip():
number = floor(int(text) / 3) - 2
result += number
print(resu... | StarcoderdataPython |
8002632 | <reponame>htlcnn/ironpython-stubs
class TriangulatedShellComponent(object,IDisposable):
"""
This class represents a triangulated boundary component of a solid or a
triangulated connected component of a shell.
"""
def Clear(self):
"""
Clear(self: TriangulatedShellComponent)
Empties the content... | StarcoderdataPython |
8063591 | <reponame>Stevesie/stevesie-py
import pytest
@pytest.fixture
def app():
return {
"id": "e43a024d-9e16-41ea-8d16-b8b0e8d88464",
"name": "App",
"description": "Access your account programmatically.",
"website": "https://test.com/",
"slug": "test",
"createdAt": "2016-0... | StarcoderdataPython |
9796323 | <filename>tests/testelementindexing.py
"""
Test cases for both indexing and slicing of elements
"""
import numpy as np
from holoviews import Histogram, QuadMesh
from holoviews.element.comparison import ComparisonTestCase
class HistogramIndexingTest(ComparisonTestCase):
def setUp(self):
self.values = [i f... | StarcoderdataPython |
6471400 | <filename>skgstat/stmodels.py
from functools import wraps
import numpy as np
def stvariogram(func):
@wraps(func)
def wrapper(*args, **kwargs):
st = args[0]
if st.ndim == 2:
new_args = args[1:]
mapping = map(lambda lags: func(lags, *new_args, **kwargs), st)
... | StarcoderdataPython |
8114374 | <reponame>joonyoungleeduke/MatchMe
from django.db import models
from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField... | StarcoderdataPython |
9775591 | <filename>community_pulse/questions/tests/test_admin.py
from django.contrib import admin
from django.test import TestCase
from ..admin import QuestionAdmin
from ..models import Question
class QuestionAdminTest(TestCase):
def test_admin_should_be_registered(self):
assert isinstance(admin.site._registry[Qu... | StarcoderdataPython |
8064928 | from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView, \
... | StarcoderdataPython |
212839 | import sys, os
import time
import argparse
import numpy as np
from bilby.core.prior import Uniform as bilbyUniform
from bilby.core.prior import DeltaFunction as bilbyDeltaFunction
from bilby.core.prior import Gaussian as bilbyGaussian
from PyGRB.main.fitpulse import PulseFitter
from PyGRB.backend.... | StarcoderdataPython |
11215512 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# _________ _______ __
# / _/ ___// ____/ | / /
# / / \__ \/ __/ / |/ /
# _/ / ___/ / /___/ /| /
# /___//____/_____/_/ |_/
#
# Isentropic model - ETH Z... | StarcoderdataPython |
9658897 | <gh_stars>0
from __future__ import print_function, division, absolute_import
import os
import libsbml
from .MetabolicModel import MetabolicModel
from ..globals import MODEL_DIR
from . import importMATLAB
from . import importSBML2
from . import importSBML3
from .geneSymbols import resolve_genes, convert_species
from .... | StarcoderdataPython |
9650463 | """Testing for bicluster metrics module"""
import numpy as np
from sklearn.utils._testing import assert_almost_equal
from sklearn.metrics.cluster._bicluster import _jaccard
from sklearn.metrics import consensus_score
def test_jaccard():
a1 = np.array([True, True, False, False])
a2 = np.array([T... | StarcoderdataPython |
9671090 | <reponame>uk-gov-mirror/alphagov.digitalmarketplace-api<gh_stars>10-100
from datetime import datetime
from dmutils.formats import DATE_FORMAT
from flask import abort, request, current_app
from sqlalchemy.exc import IntegrityError, DataError
from dmapiclient.audit import AuditTypes
from dmutils.config import convert_... | StarcoderdataPython |
6704422 | <reponame>ev-ev/CS-Pound
import subprocess
import discord
from discord.ext import commands
from library import pound_countdown, mongodb_find
class AutoRemind:
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['ar'])
@commands.guild_only() # Command can only be run in guilds
... | StarcoderdataPython |
8088028 | <reponame>AnnaMelk/spatial-visual-networks
import numpy as np
import itertools as it
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colorbar as colorbar
from matplotlib.patches import Ellipse,Polygon,FancyArrowPatch
import networkx as nx
import os
import shutil
from shapely import geometr... | StarcoderdataPython |
256356 | <reponame>mtanner161/kingops
##File to Clean the Operating Statment via Wolfpak
import os
import pandas as pd
import numpy as np
import requests
osRaw = pd.read_csv(
r"C:\Users\MichaelTanner\Documents\code_doc\king\combocurve\ComboCurve\operatingstatementOctober.csv"
)
fp = open("./king/combocurve/ComboCurve/cle... | StarcoderdataPython |
6617043 | """Current version of package cdesf2"""
__version__ = "1.0.0" | StarcoderdataPython |
11245716 | import ledgerx
from examples.example_util import get_env_api_key
ledgerx.api_key = get_env_api_key()
# id=22202077 -> BTC Mini 2021-12-31 Call $25,000
contract_id = 22202077
contract = ledgerx.Contracts.retrieve(contract_id)
print(contract)
| StarcoderdataPython |
5010668 | <reponame>sharduldk14/greyatom-python-for-data-science<filename>Numpy-Census-Project/code.py
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
data=np.genfromtx... | StarcoderdataPython |
17090 | <reponame>rithvikp1998/ctci
'''
If the child is currently on the nth step,
then there are three possibilites as to how
it reached there:
1. Reached (n-3)th step and hopped 3 steps in one time
2. Reached (n-2)th step and hopped 2 steps in one time
3. Reached (n-1)th step and hopped 2 steps in one time
The total number... | StarcoderdataPython |
4879154 | from django.db import models
class SubscribeModel(models.Model):
email_id = models.CharField(max_length=255, blank=True)
regist_date = models.CharField(max_length=255, blank=True)
| StarcoderdataPython |
5074353 | """
See problem as defined in "Boosting systematic search by weighting constraints" by Boussemart, Hemery, Lecoutre and Sais, ECAI 2004
Examples of Execution:
python3 QueensKnights.py
python3 QueensKnights.py -data=[15,5]
"""
from pycsp3 import *
n, nKnights = data or (8, 5) # n is the order(board width), and s... | StarcoderdataPython |
8163964 | class SerializationException(Exception):
def __init__(self, error_message, path, result, backup_path=None):
self.path = path
self.backup_path = backup_path
self.result = result
super(SerializationException, self).__init__(error_message)
class DeserializationException(Excepti... | StarcoderdataPython |
1826716 | <gh_stars>0
"""
Desarrolle un algoritmo, que dado como dato una temperatura en grados Fahrenheit, determine el deporte que es apropiado practicar a esa temperatura, teniendo en cuenta la siguiente tabla:
"""
T=float(input("Digite la temperatura: "))
if(T>85):
print("Deporte que es apropiado practicar a esa temperatur... | StarcoderdataPython |
1986580 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from structural_patterns.decorator.frame import Frame
# ˄
class SideFrame(Frame):
# ˅
# ˄
def __init__(self, display, frame_char):
# Decoration character
self.__frame_char = frame_char
# ˅
super().__init__(display)
... | StarcoderdataPython |
5131494 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QApplication, QWidget)
class MainWidget(QWidget):
def __init__(self):
QWidget.__init__(parent=None, flags=0)
app = QApplication(sys.argv)
w = MainWidget()
app.exec()
| StarcoderdataPython |
4830080 | '''
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by <NAME>/<NAME>
'''
#testing variables
x = 25
print (x)
x = 30
print (x)
#end of the Program | StarcoderdataPython |
356222 | <filename>UNetRestoration/train.py
"""
Main training file
The goal is to correct the colors in underwater images.
The image pair contains color-distort image (which can be generate by CycleGan),and ground-truth image
Then, we use the u-net, which will attempt to correct the colors
"""
import tensorflow as tf
from sc... | StarcoderdataPython |
5064315 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Vim:fenc=utf-8
#
# Copyright © 2018 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""Ensure the example files are valid."""
from pathlib import Path
import pytest
from click.testing import CliRunner
from experi.run import main
@pytest.fixture
def ... | StarcoderdataPython |
3467453 | import json
from pathlib import Path
from typing import Dict, Set
from dtags.commons import normalize_tags
from dtags.exceptions import DtagsError
CONFIG_ROOT = ".dtags"
CONFIG_FILE = "config.json"
COMP_FILE = "completion" # used for tag name completion
DEST_FILE = "destination" # used for d command
ConfigType = D... | StarcoderdataPython |
8108459 | <reponame>metakirby5/jisho-to-anki<gh_stars>0
# -*- coding: utf-8 -*-
"""
Configuration values.
"""
import json
class Config:
def __init__(self, fp):
config = json.load(fp)
self.profile: str = config['profile']
self.note: str = config['note']
self.deck: str = config['deck']
... | StarcoderdataPython |
8109779 | # coding:utf-8
from django.db import models
from django.contrib.auth.models import User
from django.utils.html import escape
class Activity(models.Model):
FAVORITE = 'F'
LIKE = 'L'
UP_VOTE = 'U'
DOWN_VOTE = 'D'
ACTIVITY_TYPES = (
(FAVORITE, 'Favorite'),
(LIKE, 'Like'),
(UP_... | StarcoderdataPython |
5198397 | <filename>setup.py<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
from ml import __version__
setup(
name='ml',
version=__version__,
license='PRIVATE',
author='',
author_email='',
description='robin know everything',
url='<EMAIL>:Fydot... | StarcoderdataPython |
5123162 | from voronoi import Voronoi, Polygon
# Define a set of points
points = [
(2.5, 2.5),
(4, 7.5),
(7.5, 2.5),
(6, 7.5),
(4, 4),
(3, 3),
(6, 3),
]
# Define a bounding box
polygon = Polygon([
(2.5, 10),
(5, 10),
(10, 5),
(10, 2.5),
(5, 0),
(2.5, 0),
(0, 2.5),
(0,... | StarcoderdataPython |
5098960 | import sys
from PyQt4 import QtCore, QtGui
from ui.ui_chat import Ui_chatWindow
class ChatWindow(QtGui.QWidget, Ui_chatWindow):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
self.chat_view = self.chatHistoryTextEdit
self.convTab.clear()
self.convTa... | StarcoderdataPython |
4918838 | <reponame>simplerick/sqlopt
import numpy as np
from gym.spaces import Box, Dict, Discrete
from database_env.foop import DataBaseEnv_FOOP
from database_env.query_encoding import DataBaseEnv_QueryEncoding
class DataBaseEnv_FOOP_QueryEncoding(DataBaseEnv_FOOP, DataBaseEnv_QueryEncoding):
"""
Database environmen... | StarcoderdataPython |
3490074 | <reponame>NarrativeScience/sfn-workflow-client
"""Contains a client for interacting with a workflow"""
import boto3
from .config import AWS_ACCOUNT_ID, STEPFUNCTIONS_ENDPOINT_URL
from .execution import ExecutionCollection
class Workflow:
"""Client wrapper around boto3's Step Functions interface.
This class... | StarcoderdataPython |
3230212 | <filename>mods/LA/demo.py
#
from common import *
from mods.LA.raanes2015 import step, X0
from mods.Lorenz95.demo import amplitude_animation
##
simulator = make_recursive(step, prog="Simulating")
x0 = X0.sample(1).squeeze()
xx = simulator(x0, k=500, t=0, dt=1)
##
amplitude_animation(xx,periodic=True,skip=3)
##
| StarcoderdataPython |
6582773 | <gh_stars>10-100
#
# PySNMP MIB module IB-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IB-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:22:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, M... | StarcoderdataPython |
9710086 | <gh_stars>10-100
BASE_URL = "https://raw.communitydragon.org/"
def strip_k(string: str) -> str:
'''Strips char k if string start with k'''
if string is None: return string
return string[1:] if string[0] == "k" else string
def abs_url(link: str, version="latest") -> str:
'''Return the CDragon url f... | StarcoderdataPython |
9618156 | import pytest
import numpy as np
from needlestack.apis import indices_pb2
@pytest.mark.parametrize(
"X,k",
[
(np.array([[1, 1, 1]]), 1),
(np.array([[1, 1, 1]]), 5),
(np.array([[1, 1, 1]]), 1000000),
],
)
def test_query(shard_3d, X, k):
shard_3d.load()
results = shard_3d.qu... | StarcoderdataPython |
104188 | from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from profiles.models import FavoritesProducts, Address
from accounts.models import User
... | StarcoderdataPython |
132827 | import torch
import torch.nn as nn
from ltprg.model.seq import sort_seq_tensors, unsort_seq_tensors, SequenceModel
from torch.autograd import Variable
class ObservationModel(nn.Module):
def __init__(self):
super(ObservationModel, self).__init__()
def forward(self, observation):
"""... | StarcoderdataPython |
6496630 | <filename>k_means.py<gh_stars>0
import pandas as pd
from sklearn.cluster import MiniBatchKMeans
from sklearn.cluster import KMeans
if __name__ == '__main__':
df_candies = pd.read_csv('./data/raw/candy.csv')
x = df_candies.drop('competitorname', axis=1)
mini_kmeans = MiniBatchKMeans(n_clusters=4, batch_s... | StarcoderdataPython |
8163208 | import smtplib
file=open("password.txt","r")
target_gmail=input("ENTER THE TARGET EMAIL:")
def brut():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(target_gmail, line)
print("THE PASSWORD IS\n", line)
g=0
for line in file:
if g==1:
break
else:
... | StarcoderdataPython |
4910532 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 12:32:57 2019
@author: ghosh128
"""
import sys
sys.path.append("../")
import os
import numpy as np
import config
from scipy import io
from sklearn.metrics import mean_squared_error
from math import sqrt
#%%
print("LOAD DATA")
test_da... | StarcoderdataPython |
6588234 |
from .defaults import get_default_config
from .defaults import imagedata_kwargs, optimizer_kwargs, lr_scheduler_kwargs, engine_run_kwargs
from .defaults import get_defeault_exp_name | StarcoderdataPython |
105463 | <filename>src/containerapp/azext_containerapp/tests/latest/test_containerapp_commands.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for li... | StarcoderdataPython |
9632801 | #########################################################
# 2020-01-23 23:25:05
# AI
# ins: CPL A
#########################################################
from .. import testutil as u
from ..asmconst import *
p = u.create_test()
for value in range(0x100):
p += atl.move(SFR_A, atl.I(value))
p += "CPL A"
... | StarcoderdataPython |
8057901 | <gh_stars>0
#!/usr/bin/env python
# Copyright (C) <2018> Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
"""
Prepare development environment.
"""
import os
import shutil
import sys
import subprocess
HOME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
PATCH_PATH = os.path.join(HOME_PA... | StarcoderdataPython |
9681690 | <filename>_codes/_figurecodes/fig5_RainfallHistograms_CDFs.py
#/!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Figure 5 from Adams et al., "The competition between frequent and rare flood events:
impacts on erosion rates and landscape form"
Written by <NAME>
Updated April 14, 2020
"""
from landlab.io import read... | StarcoderdataPython |
11288806 | #!/usr/bin/python
'''
This script parses an input PDB file and returns weighted contact number (WCN)
values, calculated with respect to the alpha-carbon (wcn_ca) and the sidechain
geometric center (wcn_sc).
Author: <NAME>
'''
import os
import csv
import warnings
import argparse
import textwrap
from Bi... | StarcoderdataPython |
3428870 | <filename>ted/ted/run.py
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Intel Corporation
#
# 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 th... | StarcoderdataPython |
5176517 | <reponame>cblair/docset_from_html
#!/usr/bin/env python3
import os
import sys
import shutil
from get_plist_text import get_plist_text
import sqlite3
import re
import lxml
import json
from pyquery import PyQuery as pq
class docset_from_html:
def __init__(self, docset_name, html_src_dir, config_filename):
... | StarcoderdataPython |
11328567 | <reponame>dhasegan/xcpEngine
import os
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
def get_parser():
"""Defines the command line interface of the wrapper"""
parser = ArgumentParser(
description='xcpEngine: the extensible connectome pipeline',
formatter_class=R... | StarcoderdataPython |
6560583 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module uses selenium automation to visit a list of sites loaded
from configuration and either accept or reject cookies retrieving the
cookies created during the visit and creating statistics around them.
It also screenshots the site and some of its importan... | StarcoderdataPython |
4831766 | <filename>realsense/img2video.py
import cv2
import argparse
import os
import numpy as np
from tqdm import tqdm
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--img-root', type=str, default='rs/JPEGImages')
parser.add_argument('--fps', type=int, default=30)
parser.add... | StarcoderdataPython |
6614350 | # Django
from django.db import models
class ShiftType(models.Model):
"""Shift Types model.
List of Shift types, used by users and clients.
"""
name = models.CharField('shift type', max_length=100)
def __str__(self):
return self.name
| StarcoderdataPython |
9632708 | <reponame>eaudeweb/natura2000db<filename>naturasites/storage.py
import os.path
import json
import re
import logging
import urllib
import urllib2
import errno
from contextlib import contextmanager
from collections import namedtuple
import flask
import schema
log = logging.getLogger(__name__)
class StorageError(Except... | StarcoderdataPython |
1838578 | """
TODO
"""
from selenium.webdriver.common.by import By
from .base import BasePageLocators
# pylint: disable=too-few-public-methods
class AccountLocators(BasePageLocators):
"""
TODO
"""
ADDRESS_BOOK_LINK = (By.LINK_TEXT, "Address Book")
EDIT_ACCOUNT_LINK = (By.XPATH, "//div[@id='content']//a[.='E... | StarcoderdataPython |
9663651 | <reponame>bpiwowar/TexSoup
from TexSoup.reader import read_expr, read_tex
from TexSoup.data import *
from TexSoup.utils import *
from TexSoup.tokens import tokenize
from TexSoup.category import categorize
import itertools
def read(tex, skip_envs=(), tolerance=0):
"""Read and parse all LaTeX source.
:param Un... | StarcoderdataPython |
4892376 | import os
import sys
import glob
import re
import h5py
os.environ['KERAS_BACKEND'] = 'tensorflow'
import setGPU
from keras.callbacks import EarlyStopping, ModelCheckpoint
if __package__ is None:
sys.path.append(os.path.realpath("/data/shared/Software/CMS_Deep_Learning"))
from CMS_Deep_Learning.io import gen_f... | StarcoderdataPython |
4806863 | import qiskit
from qiskit import *
from qiskit.tools.visualization import plot_histogram
secretnumber = input("Enter Secret number")
circuit = QuantumCircuit(len(secretnumber)+1, len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii,yes... | StarcoderdataPython |
6653359 | #! /usr/bin/env python
class Colours(dict):
def __init__(self):
dict.__init__(dict(self))
self.yellow = '\033[93m'
self.green = '\033[92m'
self.red = '\033[91m'
self.reset = '\033[0m'
def to_yellow(self, message):
return self.yellow + message + self.reset
de... | StarcoderdataPython |
9685461 | from rules import sshd_secure
from insights.tests import InputData, archive_provider, context_wrap
from insights.core.plugins import make_response
from insights.specs import Specs
# The following imports are not necessary for integration tests
from insights.parsers.secure_shell import SshDConfig
OPENSSH_RPM = """
open... | StarcoderdataPython |
6573275 | <reponame>uktrade/directory-components
from unittest.mock import Mock, patch
import pytest
from directory_components import context_processors
def test_analytics(settings):
settings.GOOGLE_TAG_MANAGER_ID = '123'
settings.GOOGLE_TAG_MANAGER_ENV = '?thing=1'
settings.UTM_COOKIE_DOMAIN = '.thing.com'
... | StarcoderdataPython |
1884434 | <gh_stars>10-100
"""
Plot output json files
"""
import json
import logging
logger = logging.getLogger("matplotlib")
logger.setLevel(logging.INFO)
from matplotlib import pyplot as plt
def classification_poisoning(
json_filepath="outputs/latest.json", output_filepath=None, show=False
):
"""
Plot classifi... | StarcoderdataPython |
4802761 | # Search a 2D Matrix
class Solution:
def searchRow(self, matrix, target):
left, right = 0, len(matrix) - 1
while left < right:
mid = (left + right) // 2
mv = matrix[mid][0]
# print(f'left: {left}, mid: {mid}, right: {right}, mv: {mv}')
if target < mv... | StarcoderdataPython |
9745332 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.shell.sh import ShellModule as ShModule
class ShellModule(ShModule):
def build_module_command(self, env_string, shebang, cmd, arg_path=None, rm_tmp=None):
new_cmd = super(ShellModule, self).build_m... | StarcoderdataPython |
3294755 | # STD
import unittest
from unittest import mock as mock
# PROJECT
import bwg
from tests.fixtures import RELATION_MERGING_TASK
from tests.toolkit import MockOutput, MockInput
class RelationMergingTaskTestCase(unittest.TestCase):
"""
Test RelationMergingTask.
"""
@mock.patch('bwg.tasks.relation_merging... | StarcoderdataPython |
6537736 | <filename>repiko/module/ygoOurocg_ver4.py
#coding:utf-8
import sqlite3
import configparser
import json
from urllib import request
from urllib import parse
from bs4 import BeautifulSoup
from .ygo.card import Card,CardAttribute,CardRace,CardType,LinkMark
class ourocg():
def __init__(self):
#config = confi... | StarcoderdataPython |
8168124 | import FWCore.ParameterSet.Config as cms
process = cms.Process("SKIM")
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/data/Commissioning08/Cosmics/RECO/CRAFT_ALL_V9_225-v2/0000/FE32B1E4-C7FA-DD11-A2FD-001A92971ADC.root'),
... | StarcoderdataPython |
4872744 | <reponame>manojkumar-github/DataStructures-DynamicProgramming-in-Python-JAVA-Cplusplus
#!/usr/bin.env python
# Copyright (C) Pearson Assessments - 2020. All Rights Reserved.
# Proprietary - Use with Pearson Written Permission Only
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/foo',... | StarcoderdataPython |
1802246 | <reponame>chndear/nanaimo<gh_stars>10-100
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# This software is distributed under the terms of the MIT License.
#
import argparse
import os
import typing
from unittest.mock import MagicMock
import pytest
import material
import nanaimo
import na... | StarcoderdataPython |
1984271 | <reponame>jensv/relative_canonical_helicity_tools
import numpy as np
from invert_curl.invert_curl import devore_invert_curl
from laplace_solver.laplace_solver import laplace_3d_dct_fd
import vector_calculus.vector_calculus as vc
def determine_reference_fields(mesh, circulation,
return_s... | StarcoderdataPython |
3345947 | from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from issues.views import *
urlpatterns = patterns("issues.views",
(r"^delete-comment/(\d+)/$", "delete_comment", {}, "delete_comment... | StarcoderdataPython |
4800958 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from __future__ import print_function
# from __future__ import absolute_import
import os
import sys
if not os.path.abspath("../") in sys.path:
sys.path.append(os.path.abspath("../"))
try:
from unittest import mock
except ImportError:
import mock
... | StarcoderdataPython |
4943269 | <reponame>fBloc/bloc-client-python<filename>bloc_py_tryout/math_calcu_test.py<gh_stars>0
import unittest
from bloc_client import *
from bloc_py_tryout.math_calcu import MathCalcu
class TestMathCalcuNode(unittest.TestCase):
def setUp(self):
self.client = BlocClient.new_client("")
def test_add(self):... | StarcoderdataPython |
9773420 | from errors import CustomListSumException
from tests.customlist_tests.base.customlist_test_base import CustomListTestBase
class CustomListSumTests(CustomListTestBase):
def test_customListSum_whenEmptyList_shouldReturn0(self):
custom_list = self.setup_list()
result = custom_list.sum()
self... | StarcoderdataPython |
9749158 | <reponame>billyio/atcoder<gh_stars>1-10
# https://drken1215.hatenablog.com/entry/2020/10/11/211000
N = int(input())
if N == 1:
print(0)
exit()
dp = [0 for _ in range(N+1)]
dp[0], dp[1], dp[2] = 1, 0, 0
for i in range(2,N+1):
for j in range(0,i-2):
dp[i] += dp[j]
print(dp[-1] % (10**9+7)) | StarcoderdataPython |
301948 | <filename>src/ctc/db/schemas/contract_abis/contract_abis_statements.py
from __future__ import annotations
import json
import typing
import toolsql
from ctc import spec
from ... import schema_utils
async def async_upsert_contract_abi(
address: spec.Address,
abi: spec.ContractABI,
includes_proxy: bool,
... | StarcoderdataPython |
8116274 | # coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... | StarcoderdataPython |
1964190 | <reponame>design-automation/video-generator
import glob
import os
def get_paths_by_typ(fdr_path,typ):
paths = glob.glob(fdr_path + "\\*.%s" % (typ))
ret_paths = [path for path in paths if not os.path.basename(path).startswith("~$")]
# if (len(paths)==0):
# raise Exception ("No .%s file found in \\%... | StarcoderdataPython |
11260381 | import sys
import os
import os.path
import hashlib
import re
import errno
import itertools
import tempfile
import hashlib
import requests
from xml.etree import ElementTree
import xml.sax
from xml.sax.handler import ContentHandler
_this_dir = os.path.dirname(os.path.abspath(__file__))
prefs = { 'verb... | StarcoderdataPython |
11301757 | #!/usr/bin/env python
"""
Provides user job base class to be used to build user job scripts.
db = MythDB()
j = Job(2353)
Recorded((j.get('chanid'),j.get('starttime')))
"""
from MythTV import MythDB
from MythTV import Job
from MythTV import Recorded
from argparse import ArgumentParser
class UserJob(object):
"""
... | StarcoderdataPython |
11205082 | <reponame>labscript-suite-temp-2-archive/zachglassman-labscript--forked-from--labscript_suite-labscript
#####################################################################
# #
# /example.py #
# ... | StarcoderdataPython |
72954 | #!/usr/bin/env python
# -*- encode: utf-8 -*-
#Copyright 2015 RAPP
#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 applicabl... | StarcoderdataPython |
6435671 | # coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 co... | StarcoderdataPython |
8058007 | <reponame>alexchunet/raster-vision
# flake8: noqa
from rastervision2.pipeline.file_system.file_system import (
FileSystem, NotReadableError, NotWritableError)
from rastervision2.pipeline.file_system.local_file_system import LocalFileSystem
from rastervision2.pipeline.file_system.http_file_system import HttpFileSys... | StarcoderdataPython |
3531758 | """Dummy dataset to test runner"""
# pylint: disable=R0201,W0613
class DummyPrimaryConcern(object):
"""Dummy primary concern"""
def true(self):
"""Notify inside function"""
print "In true"
def before(*args, **kwargs):
"""Before advice"""
print "Before true"
def after(*args, **kwar... | StarcoderdataPython |
6586586 | <reponame>Asnebula/test_java_env<filename>src/py4j/examples/_3_4_MultiThread/single/PythonPlayer.py
class PythonPlayer(object):
def start(self, player):
return player.firstPing(self)
def firstPong(self, player):
return player.secondPing(self)
def secondPong(self, player):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.