id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3377563 | <filename>data_processing/processing_core.py<gh_stars>0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@module : processing_core.py
@author : ayaya
@contact : <EMAIL>
@time : 2022/3/25 9:11 下午
"""
import copy
import json
import os
import random
import time
import concurrent.futures
from typing import List
impor... | StarcoderdataPython |
6452151 | import os
import spacy
import streamlit.components.v1 as components
_RELEASE = True
if not _RELEASE:
_component_func = components.declare_component(
"st_ner_annotate", url="http://localhost:5000",
)
else:
parent_dir = os.path.dirname(os.path.abspath(__file__))
build_dir = os.path.join(parent_d... | StarcoderdataPython |
9611260 | <filename>cogs/misc.py<gh_stars>0
from discord.ext import commands
import discord
import tools
class Misc(commands.Cog):
"""Random commands for the bot"""
def __init__(self, bot):
self.bot = bot
self.database = bot.database
@commands.command(name='invite', aliases=["getinvite", "botinvi... | StarcoderdataPython |
193741 | <reponame>vovawed/fastapi-cloudauth
import pytest
from fastapi_cloudauth.messages import (NO_PUBLICKEY, NOT_AUTHENTICATED,
NOT_VALIDATED_CLAIMS, NOT_VERIFIED,
SCOPE_NOT_MATCHED)
from tests.helpers import assert_get_response
from tests.test... | StarcoderdataPython |
6553000 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
def main():
user_file_name = input("Please enter file name: ")
try:
read_file = open(user_file_name, 'r')
except:
print(f'Error! I could not find/read "{user_file_name}"')
sys.exit()
nums = read_file.rea... | StarcoderdataPython |
216881 | <filename>src/xeda/xedaproject.py
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Dict, List, Optional, Union
import yaml
from .dataclass import XedaBaseModel
from .design import Design
from .utils import WorkingDirectory, toml_load
class XedaProject(XedaBaseMod... | StarcoderdataPython |
1908113 | class Solution:
def longestCommonPrefix(self, strs):
size = len(strs)
if size == 1:
return strs[0]
prefix = strs[0]
while(len(prefix) > 0):
flag = True
for i in range(1, size):
flag &= strs[i].startswith(prefix)
if flag:... | StarcoderdataPython |
3494338 | # Generated by Django 3.0.8 on 2020-07-17 21:06
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('manager', '0002_auto_20200717_2204'),
]
operations = [
migrations.AlterField(
model_name='hardware'... | StarcoderdataPython |
3599840 | <reponame>kigensky/awwards<filename>awwards/migrations/0003_auto_20210531_2202.py
# Generated by Django 3.1.7 on 2021-05-31 19:02
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('awwards', '0002_auto_20210531_2049'),
]
operation... | StarcoderdataPython |
285408 | import unittest
from sphinxcontrib.autohttp.bottle import get_routes
from bottle import Bottle, Route
def create_app():
app = Bottle()
@app.route("/bottle")
def bottle_bottle():
return 12
@app.post("/bottle/post/")
def bottle_bottle_post():
return 23
return app
def creat... | StarcoderdataPython |
5086367 | import numpy as np
import torch
from a2c_ppo_acktr import utils
from a2c_ppo_acktr.envs import make_vec_envs
def evaluate(actor_critic, ob_rms, env_name, seed, num_processes, eval_log_dir,
device):
eval_envs = make_vec_envs(env_name, seed + num_processes, num_processes,
... | StarcoderdataPython |
6403788 | <filename>server/services/user.py
from flask import Blueprint, jsonify, request, current_app
from datetime import datetime, timedelta
from server.utils.view_utils import wrapped_response, serialize_list
from server.models.key import Key
from server.models.user import User
from server.utils.core_utils import logger
from... | StarcoderdataPython |
4803707 | import random as r
import math as m
def aproximation_pi(n_points):
# Number of darts that land inside.
inside = 0
# Iterate for the number of darts.
i = 0
while i < n_points:
# Generate random x, y in [0, 1].
x2 = r.random()**2
y2 = r.random()**2
# Increment if inside unit circle.
if m.s... | StarcoderdataPython |
6448855 | # BB Keyboard Driver
#
# Released under The MIT License (MIT)
#
# Copyright (c) 2021 <NAME>
from arambadge import badge
KBD_ADDRESS = 0x42
CMD_BACKLIGHT_ON = 0x03
CMD_RESET = 1 << 7
RESP_RESET = 0xfe
RESP_EOF = 0xff
RESP_FLAG_KEYDOWN = 1 << 6
RESP_FLAG_KEYUP = 1 << 7
kbd_matrix = [
... | StarcoderdataPython |
1754920 | <filename>tests/test_dsm.py
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from mne_rsa import searchlight, dsm_array, compute_dsm, compute_dsm_cv
from mne_rsa.dsm import _ensure_condensed, _n_items_from_dsm
class TestDsm:
"""Test computing a DSM"""
def test_basic(s... | StarcoderdataPython |
3458378 | <reponame>sadimer/nfv_tosca_translator<filename>translator/translator.py
import os
import yaml
import logging
import sys
import translator.utils as utils
from toscaparser.tosca_template import ToscaTemplate
from translator.template import ToscaNormativeTemplate
VNF_DEF_PATH = '/definitions/VNF_types/'
NFV_DEF_PATH =... | StarcoderdataPython |
1682694 | <gh_stars>1-10
# coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from citeproc.py2compat import *
import unicodedata
from . import (parse_argument, eat_whitespace, parse_macro_name,
OPEN_SCOPE, CLOSE_SCOPE, START_MACRO)
__al... | StarcoderdataPython |
4805353 | <filename>bot_scheduler/actions.py<gh_stars>0
from typing import Callable
class Action:
"""Encapsulates the calling of a callback with an object."""
def __init__(self, actor: Callable):
"""Initialise the Action with a callback.
Args:
actor: Takes one argument and acts on it.
... | StarcoderdataPython |
5039642 | <gh_stars>1-10
from random import randint
from scribbler.document.document import Document
from scribbler.document.parser import parse_document
from scribbler.resources.resources_helper import list_resources
from scribbler.dataset import Dataset
from scribbler.document.document_handwriting_line import DocumentHandwrit... | StarcoderdataPython |
1990502 | <gh_stars>0
# from rdkit import Chem
# from rdkit.Chem import Draw, AllChem
# from rdkit.Chem.Draw import IPythonConsole #Needed to show molecules
# from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions #Only needed if modifying defaults
# for i in range(1,2):
# opts = DrawingOptions()
# opts.inc... | StarcoderdataPython |
172874 | <filename>tests/test_main_redirects.py
# -*- coding: utf-8 -*-
# vim: set noai syntax=python ts=4 sw=4:
#
# Copyright (c) 2018-2022 <NAME>
# stats.wwdt.me is released under the terms of the Apache License 2.0
"""Testing Main Redirects Module and Blueprint Views"""
import pytest
def test_favicon(client):
"""Testin... | StarcoderdataPython |
3312195 | <reponame>stckwok/cashInterop
#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Test emergent consensus scenarios
import time
import random
import p... | StarcoderdataPython |
68092 | #
# 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 agreed to in writing, software
# ... | StarcoderdataPython |
4986617 | import time
import binascii
import json
import requests
res = requests.get('https://biblia.sk/api/preklady')
with open('preklady.json', 'wb') as f:
f.write(res.content)
preklady = res.json()['data']
preklad = preklady[2] # roh
identifier = preklad['identifier']
books = preklad['books']
params = {
'timestamp':... | StarcoderdataPython |
1977177 | import collections
import sys
from abc import ABCMeta
from typing import *
import functools
import types
import operator
__all__ = ['TypedDict', 'Final', 'Literal']
GenericAlias = List[int]
class _Final:
"""Mixin to prohibit subclassing"""
__slots__ = ('__weakref__',)
def __init_... | StarcoderdataPython |
6404435 | <gh_stars>0
from authx.authenticate import authenticator
from authx.exception import (InvalidUsername, NotLoggedInError,
NotPermittedError, PermissionError)
class Authorizer:
def __init__(self, authenticator):
self.authenticator = authenticator
self.permissions = {}
... | StarcoderdataPython |
6550620 | #!/usr/bin/env python
##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# 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 Lice... | StarcoderdataPython |
5057104 | # -*- coding: utf-8 -*-
import numpy
import numpy.random
import time
import os
import magdynlab.instruments
import magdynlab.controllers
import magdynlab.data_types
import threading_decorators as ThD
import matplotlib.pyplot as plt
@ThD.gui_safe
def Plot_ColorMap(Data):
f = plt.figure('PNA-FMR', (5, 4))
exte... | StarcoderdataPython |
11323290 | <gh_stars>1-10
with open("../input/day8.txt", 'r') as inputFile:
data = inputFile.read()
data = data.split(" ")
class Node():
def __init__(self):
self.children = []
self.metadata = []
def parseChild(parent):
newNode = Node()
if parent is not None:
parent.children.append(newNode... | StarcoderdataPython |
5082834 | from .core.models import Squad, Group, Project, Build, Environment, Test, Metric, TestRun, SquadObjectException
from .utils import split_build_url, first, split_group_project_slug
squad = Squad()
def compare_builds(baseline_id, build_id):
return Project.compare_builds(baseline_id, build_id)
def retrieve_lates... | StarcoderdataPython |
6615505 | import psutil
import re
from pypresence import Presence
from time import time, sleep
from win32gui import GetForegroundWindow, GetWindowText
from win32process import GetWindowThreadProcessId
client = Presence(659889732939022366)
client.connect()
last_activity = ''
def get_current_process():
fw = Get... | StarcoderdataPython |
9661812 | <gh_stars>10-100
"""
Core logic
"""
from maya_mock.base.node import MockedNode
from maya_mock.base.port import MockedPort
from maya_mock.base.connection import MockedConnection
from maya_mock.base.session import MockedSession
from maya_mock.base.schema import MockedSessionSchema
| StarcoderdataPython |
1794252 | <reponame>Joan95/TFM
"""
<Name>
tuf/encoding/snapshot_asn1_coder.py
<Purpose>
This module contains conversion functions (get_asn_signed and get_json_signed)
for converting Snapshot metadata from TUF's standard Python dictionary
metadata format (usually serialized as JSON) to an ASN.1 format that conforms
to ... | StarcoderdataPython |
5197672 | <gh_stars>1-10
from django.conf.urls import url
from django.contrib.auth.views.login import login, logout_then_login
from usuarios.views import RegistrarUsuarioView
urlpatterns = [
url(r'^registrar/$', RegistrarUsuarioView.as_view(), name='registrar'),
url(r'^login/$', login,
{'template_name': 'logi... | StarcoderdataPython |
320328 | <gh_stars>0
import requests
import json
db = "data/"
def test_face_match():
url = 'http://0.0.0.0:5000/face_match'
# open file in binary mode
files = {'file1': open(db+'1.jpg', 'rb'),
'file2': open(db+'2.jpeg', 'rb')}
resp = requests.post(url, files=files)
print(json.dumps(resp.j... | StarcoderdataPython |
5072962 | <reponame>MatthewScholefield/autodo
from collections import namedtuple
import pandas
from os.path import join
from prettyparse import Usage
from autodo.scripts.base_script import BaseScript
from autodo.stage_three_predictor import StageThreePredictor
StageThreeRow = namedtuple('StageThreeRow', 'image_id box_id x y z... | StarcoderdataPython |
351374 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class GetVaultResult(object):
"""
A collection of values ... | StarcoderdataPython |
4928816 |
from abc import ABCMeta, abstractmethod
class Strategy(metaclass=ABCMeta):
@abstractmethod
def key_exists(self, key):
pass
@abstractmethod
def delete_key(self, key):
pass
@abstractmethod
def get_data(self, key):
pass
@abstractmethod
def update_data(self, ke... | StarcoderdataPython |
3436544 | <gh_stars>0
class Solution:
def knightDialer(self, N: int) -> int:
| StarcoderdataPython |
11261699 | <reponame>troyready/runway
"""Split lookup."""
# pylint: disable=arguments-differ,unused-argument
from runway.lookups.handlers.base import LookupHandler
TYPE_NAME = "split"
class SplitLookup(LookupHandler):
"""Split lookup."""
@classmethod
def handle(cls, value, context=None, provider=None, **kwargs):
... | StarcoderdataPython |
9670517 | import discord
from discord.ext.commands import Greedy
from redbot.core import commands, checks
from redbot.core.utils.chat_formatting import box
from redbot.core.utils.menus import menu, DEFAULT_CONTROLS
from .constants import ACTION_CONFIRMATION
from .rules.config.models import BlackOrWhiteList
from .utils import (
... | StarcoderdataPython |
8091916 | import numpy as np
import pandas as pd
import matplotlib.pylab as plt
from efficient_frontier import EfficientFrontier
class Stock(object):
# Object that contains information about a stock.
def __init__(self, data):
self.data = data
class Portfolio(object):
# Object that contains information ab... | StarcoderdataPython |
6668096 | <filename>07_list.py
def average_temps(temps):
sum_of_temps = 0
for temp in temps:
sum_of_temps += temp
return sum_of_temps / len(temps)
if __name__ == '__main__':
temps = [21,24,24,22,20,36,59]
average = average_temps(temps)
print('La temperatura promedio es: {}'.format(average)) | StarcoderdataPython |
11273770 | <reponame>jschavesr/LibCST
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import Dict, Mapping, Optional, Set, Union
import libcst as cst
from libcst.helpers.common import ... | StarcoderdataPython |
4926398 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Class Recommendation System.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1cErX1ARVB1TLtVZVXof1HIzsuGl3K8Rw
"""
import pandas as pd
from rake_nltk import Rake
import numpy as np
from sklearn.metrics.pair... | StarcoderdataPython |
1844311 | import os, time, sys
pipe_name = 'pipe_test'
def child():
pipeout = os.open(pipe_name, os.O_WRONLY)
counter = 0
while True:
time.sleep(1)
os.write(pipeout, 'Number %03d\n' % counter)
counter = (counter + 1 ) % 5
def parent():
pipein = open(pipe_name, 'r')
while True:
... | StarcoderdataPython |
2031 | <filename>build/scripts-3.6/fit_background_model.py<gh_stars>0
#!python
import numpy as np
from numpy import inf
from numpy import nan
from scipy.optimize import fmin
from scipy.stats import beta
from scipy.special import beta as B
from scipy.special import comb
import argparse
import sys
def parseArgs():
'''Funct... | StarcoderdataPython |
234772 | <reponame>ChaoticMarauder/Project_Rosalind
def dict_words(string):
dict_word={}
list_words=string.split()
for word in list_words:
if(dict_word.get(word)!=None):
dict_word[word]+=1
else:
dict_word[word]=1
return dict_word
def main()... | StarcoderdataPython |
231606 | <filename>src/minimax.py
from typing import Tuple, List
from sys import maxsize as MAX_INT
from board import Board, Direction
def maximize(state: Board, a: int, b: int, d: int) -> Tuple[Board, int]:
max_child, max_util = None, -1
if d == 0 or state.player_cannot_move_anymore():
return None, state.uti... | StarcoderdataPython |
3305304 | <gh_stars>1-10
"Test mansel module"
from collections import Counter
import os
from pathlib import Path
import sys
import tempfile
try:
from PySide2 import QtCore, QtWidgets
except ImportError:
try:
from PyQt5 import QtCore, QtWidgets
except ImportError:
raise ImportError("PySide2 or other Q... | StarcoderdataPython |
1927212 | #!/usr/bin/env python3
import os
FILE_DIR = os.path.dirname(os.path.relpath(__file__))
SNIPPETS_DIR = "snippets"
base_template = """
import os
from base import TestBase
class {cls}Test(TestBase):
snippet_dir = "{dir}"
"""
test_template = """
def test_{name}(self):
self.validate_snippet(self.get_sn... | StarcoderdataPython |
4906407 | <reponame>alviproject/alvi<filename>alvi/client/data_generators/random.py
import random
from alvi.client.data_generators.base import DataGenerator
class RandomDataGenerator(DataGenerator):
def _values(self):
qty = self.quantity()
return (random.randint(1, qty) for _ in range(qty)).__iter__() | StarcoderdataPython |
3380769 | <gh_stars>1-10
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2021 <NAME>.
#
# Invenio-Utilities-TUW is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Some utilities for InvenioRDM."""
from invenio_rdm_records.proxies import curren... | StarcoderdataPython |
11244521 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""AFN for 8-bit time series from the Rössler oscillator.
Since each point in the time series is an 8-bit integer (i.e., it's in
the range [-127, 127]), the reconstructed phase space is essentially a
grid with zero dimension. To actually measure the di... | StarcoderdataPython |
4808558 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 23:07:30 2020
@author: virati
DO_Phase portrait and dynamics work
"""
import sys
sys.path.append('/home/virati/Dropbox/projects/Research/MDD-DBS/Ephys/DBSpace/')
import DBSpace as dbo
from DBSpace import nestdict
import DBSpace.control.dyn_osc as... | StarcoderdataPython |
1751547 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas.geometry import length_vector_sqrd
from compas.utilities import Colormap
from compas_rhino.artists import MeshArtist
__all__ = ['CablenetArtist']
class CablenetArtist(MeshA... | StarcoderdataPython |
4958397 | <gh_stars>0
from django.apps import AppConfig
class AcheveMgtConfig(AppConfig):
name = 'acheve_mgt'
verbose_name = '成绩管理'
| StarcoderdataPython |
6610539 | <gh_stars>0
from urllib.request import urlopen
from bs4 import BeautifulSoup
import bs4
import datetime
from datetime import date
import calendar
import ssl
import re
import openpyxl
from algorithms import checkResult
import getpass
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CE... | StarcoderdataPython |
3378666 | # coding: utf-8
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_cl... | StarcoderdataPython |
11250253 | <gh_stars>1-10
import os
import sys
import argparse
from shutil import copyfile, copytree, rmtree
GODOT_PATH = os.environ["GODOT_PATH"]
def patch_script(godot_root, filename):
current_path = os.getcwd()
patch_path = os.path.join(current_path, filename)
os.chdir(godot_root)
os.system("git am %s"%patch_path)
os.ch... | StarcoderdataPython |
5125358 | import pandas as pd
import numpy as np
import igraph as ig
from scipy.spatial import distance_matrix
from scipy.spatial.distance import pdist, squareform
from sklearn.metrics.pairwise import cosine_distances, euclidean_distances
import scipy
from copy import deepcopy
import pprint
history_x = []
history_y = []
history... | StarcoderdataPython |
8045152 | from bs4 import BeautifulSoup
from bs4.dammit import EntitySubstitution
from bs4.element import Comment
from bs4.element import Doctype
from bs4.element import NavigableString
from bs4.element import ProcessingInstruction
from bs4.element import Tag
from zpretty.attributes import PrettyAttributes
from zpretty.text impo... | StarcoderdataPython |
192096 | #!/usr/bin/env python
from setuptools import setup
setup(version_format='{tag}.dev{commits}')
| StarcoderdataPython |
6627808 | <reponame>jasonwee/asus-rt-n14uhp-mrtg
import argparse
parser = argparse.ArgumentParser(description='Short sample app')
parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)
print(parser.parse_ar... | StarcoderdataPython |
1708468 | <filename>ntc_rosetta_conf/usr_datastore.py
from jetconf.data import JsonDatastore
class UserDatastore(JsonDatastore):
pass
| StarcoderdataPython |
6503473 | """
Modeling: Mass Total + Source Parametric
========================================
This script gives a profile of a `DynestyStatic` model-fit to an `Imaging` dataset where the lens model is initialized,
where:
- The lens galaxy's light is omitted (and is not present in the simulated data).
- The lens gal... | StarcoderdataPython |
3470939 | <reponame>XiaopeiZhang/CS450
# This program was written under Python 2.7. Please test with Python 2.7 if Python 3 does not work well.
# It will ask for 3 variables. If you just press enter, it will use default values 20 stack size, 5 discs per bucket and 3 folfers.
__author__ = 'Xiaopei'
from threading import Thread,... | StarcoderdataPython |
252754 | import gzip
from pathlib import Path
import pandas as pd
from src.data.paths import DataDirs
def read_compressed_file(file_path: Path) -> bytes:
"""Read in .tsv.gz file from disk"""
try:
with gzip.open(file_path, "rb") as f:
return f.read()
except FileNotFoundError:
raise Fil... | StarcoderdataPython |
12853757 | <filename>Python/index_finder.py
#!/usr/bin/env python3
# Author: <NAME>, Dec 2018
# Script for checking index clashes
# Input one or several nucleotide sequences and print any matches found in
# the index reference file. This version is only good for checking for
# full matches.
# It is pretty useful though to list ... | StarcoderdataPython |
11346167 | <filename>scripts/us_bjs/nps/import_data_test.py
# Copyright 2020 Google LLC
#
# 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 req... | StarcoderdataPython |
3581638 | #Functions implementing potential parameter space symmetries
#<NAME> (2019) NASA-GSFC
#
#These functions are of a standard form needed for specifying (potential)
#symmetries of the parameter state space, and can be exploited as
#specialized MCMC proposals.
#Implementing potential parameter space symmetries
#These clas... | StarcoderdataPython |
11260751 | <reponame>danuluma/dannstore
import os
import sys
import unittest
import json
# local imports
LOCALPATH = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, LOCALPATH + '/../../../')
from run import create_app
from app.api.v1.auth import create_admin, clear_users
from app.api.v1.products_view import clear_... | StarcoderdataPython |
12836733 | <filename>8_2.py
from numpy import zeros, sign
# Define bisection function
def bisection(f,a,b,n):
c = zeros(n)
for i in range(n):
c[i] = (a + b)/2.0
if sign(f(c[i])) == sign(f(a)):
a = c[i]
else:
b = c[i]
return c
# Define function
def f(x):
return -x*... | StarcoderdataPython |
3456326 | # Exercise 1: Create VLANs and Assign IP using SSH
from netmiko import ConnectHandler
from getpass import getpass
# user input
password = <PASSWORD>()
secret = getpass("Enter secret: ")
#Creat a dictionary for a perticular device
CoreSW = {
'device_type': 'cisco_ios',
'ip': '192.168.100.20',
'username': 'admin',
... | StarcoderdataPython |
1698759 | <reponame>hhh123123123/ESP32-Webserver<filename>py/Webclient.py
import socket
import gc
class HttpRequest:
RequestHeader_template = '''{0} {1} HTTP/1.1
host: {2}
Content-Type: application/json
cache-control: no-cache
content-length: {3}
'''
# url = 'https://www.example.com/info/sendair'
method = 'POST'
... | StarcoderdataPython |
6638319 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2015-09-17 11:41:18
# @Email: <EMAIL>
# @Last modified by: etrott
# @Last Modified time: 2015-09-17 11:41:37
| StarcoderdataPython |
149854 | <reponame>tzeikob/walle
#!/usr/bin/env python3
# An executable script resolving system data
import argparse
import signal
import json
import time
from common import globals
from util.logger import Router
from resolvers import static
from resolvers import uptime
from resolvers import monitor
from resolvers import netwo... | StarcoderdataPython |
3364163 | # from chatterbot import ChatBot
# from chatterbot.trainers import ListTrainer
# from chatterbot.ext.django_chatterbot import settings
# from chatterbot.trainers import ChatterBotCorpusTrainer
# chatterbot = ChatBot(**settings.CHATTERBOT)
# trainer = ChatterBotCorpusTrainer(chatterbot)
# trainer.train(
# "ch... | StarcoderdataPython |
1766587 | # Copyright (c) 2019 fortiss GmbH
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import unittest
import os
import matplotlib
from serialization.scenario_set_serializer import ScenarioSetSerializer
from modules.runtime.commons.parameters import ParameterServer
class Scenario... | StarcoderdataPython |
315759 | <reponame>kedz/cuttsum<filename>trec2015/cuttsum/l2s/_simple.py
import pyvw
from cuttsum.l2s._base import _SearchBase
import pandas as pd
class SelectBasicNextBias(_SearchBase):
def setup_cache(self):
return None
def basic_cols(self):
return [
"BASIC length", "BASIC char length", "BAS... | StarcoderdataPython |
12803828 | <gh_stars>1-10
#!/usr/bin/python
#
# Copyright (c) 2018 <NAME>, <<EMAIL>>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | StarcoderdataPython |
5052927 | <filename>blend.py<gh_stars>0
from glob import *
def blend_subtract(col1, col2):
if not var['grey']['var']:
r = max(min(255, (col1[0]-col2[0])), 0)
g = max(min(255, (col1[1]-col2[1])), 0)
b = max(min(255, (col1[2]-col2[2])), 0)
color = (r, g, b)
else:
c = max(min(255, ((... | StarcoderdataPython |
9778787 | <filename>opensfm/actions/detect_features.py
import logging
from timeit import default_timer as timer
from opensfm import features_processing, io
from opensfm.dataset_base import DataSetBase
logger = logging.getLogger(__name__)
def run_dataset(data: DataSetBase):
"""Compute features for all images."""
sta... | StarcoderdataPython |
1808943 | <filename>examples/controller.py
"""
This example:
1. Connects to current controller.
2. Creates a new model.
3. Deploys an application on the new model.
4. Disconnects from the model
5. Destroys the model
"""
import asyncio
import logging
from juju.controller import Controller
from juju import loop
async def main... | StarcoderdataPython |
287674 | <filename>utils/metric.py
import numpy as np
import math
from skimage.measure import compare_ssim
"""
img1, img2 should be in numpy format with type uint8.
"""
def psnr(img1, img2):
assert (img1.dtype == img2.dtype == np.uint8)
img1 = img1.astype(np.float64)
img2 = img2.astype(np.float64)
mse = np.me... | StarcoderdataPython |
1902814 | <gh_stars>0
import pytest
from collections import defaultdict
from breaking_changes import collector
# TODO: add a fixture to keep clean up the result every time
@pytest.fixture(autouse=True)
def reset_result():
collector.result = defaultdict(list)
def test_collector_decorator(reset_result):
@collector.co... | StarcoderdataPython |
8133073 | <reponame>Stanford-PERTS/triton
import sys
import os.path
# Tell python to look in some extra places for module files for easy importing.
subdirs = [
('app',), # /app, python server code
('lib',), # /lib, python libraries
('gae_server',),
# include subdirectories, e.g. dir1/dir2, like this:
#('d... | StarcoderdataPython |
4907492 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 20:43:18 2019
@author: blose
"""
#%%
import numpy as np
from tqdm import tqdm
import time
def read_data(filename):
lines = open(filename).read().split('\n')
data = []
for line in lines[:-1]:
data.append(line.split(', '))
... | StarcoderdataPython |
5101080 | # -*- coding: utf-8 -*-
import sys, getopt
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import re
import nltk
import regex
from nltk.corpus import stopwords
import json
import cPickle as pickle
from sklearn.feature_extraction.text import CountVectorizer
#from pprint import pprint
from math impor... | StarcoderdataPython |
3433245 | <filename>cogs/helper_files/crossword_cog_helper.py<gh_stars>0
import datetime
from firebase_config import ibaelia_db
from dateutil.parser import parse
import discord
def get_scores_by_id(user_id, guild, time, limit=7):
dates = get_past_num_days(time, limit)[::-1]
final_scores = {key:None for key in date... | StarcoderdataPython |
316192 | from argparse import ArgumentParser
from snapchat_bots import SnapchatBot, Snap
import random
class RandoBot(SnapchatBot):
def initialize(self):
self.connections = self.get_friends()
#If your bot ever gets blocked, uncomment these lines.
#Of course, make sure you have your old users backed up
#to the us... | StarcoderdataPython |
9716458 | import typing
import torch
from .base import *
from .prim import *
from .aten import *
from .quantized import *
OPERATOR_CONVERTER_DICT: typing.Dict[str, OperatorConverter] = {
"prim::Constant": PrimConstantConverter,
"prim::TupleConstruct": PrimTupleConstructConverter,
"prim::ListConstruct": PrimListCons... | StarcoderdataPython |
11248903 | # vestlus:settings
import os
CRISPY_TEMPLATE_PACK = 'bootstrap4'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': os.environ.get('ELASTICSEARCH_URL', 'http://127.0.0.1:9200/'),
'INDEX_NAME': 'haystack',
},
}
| StarcoderdataPython |
4804254 | <reponame>rafa-evangelista/PYTHON<gh_stars>0
preco=float(input('Qual o preço do produto a ser adquirido: R$ '))
print('O preço original do produto era de R$ {} mas na liquidação o seu novo preço é de R$ {}.'.format(preco, preco*0.95)) | StarcoderdataPython |
1678134 | from .env_wrapper import *
from .utils import *
from .ddpg import *
from .networks import *
__all__ = [ 'EnvWrapper', 'RLTrainingLogger',
'DDPGAgent', 'TrainDDPG']
| StarcoderdataPython |
3429307 | <filename>2017-09-15/github_bot/git_bot.py
#!/usr/bin/env python
import argparse
from decouple import config
from github import Github
# definimos configuracoes
github_username = config('github_username')
github_password = config('github_password')
github_api = Github(github_username, github_password)
escopo_do... | StarcoderdataPython |
3549183 | #!/usr/bin/python
# A daemon which serializes create-slice.sh and delete-slice.sh requests, to
# avoid multiple simultaneous requests to the Ansible scripts
from pymongo import MongoClient
import subprocess
import time
import sys
import os
import json
import datetime
#
# Connect to the db server on the mongo containe... | StarcoderdataPython |
4986237 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import shlex
import unittest
from dockermap.shortcuts import (str_arg, get_user_group, rm, chown, chmod, curl, wget, tar, untar, targz, untargz,
mkdir, mkdir_chown, addgroup, CmdArgMappings, assignuser, adduser, addgroupu... | StarcoderdataPython |
3497209 | _base_ = ['../actnn/resnet18_b64x4_imagenet.py']
actnn = False
| StarcoderdataPython |
4985950 |
__author__ = '<NAME>'
from setuptools import setup
requires = [
]
setup( name='sarch2',
version="1.1.0",
description='Simple archiving solution',
scripts=['bin/sarch2'],
packages=['sarch2'],
long_description=open('README.rst').read(),
url='https://github.com/susun... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.