id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3324298 | from django.conf import settings
blocks_apps = getattr(settings, "BLOCKS_APPS", None)
if blocks_apps:
for block_name in blocks_apps:
if block_name not in settings.INSTALLED_APPS:
settings.INSTALLED_APPS += (block_name, )
| StarcoderdataPython |
8165063 | <reponame>omitroom13/demisto-py
#!/usr/bin/env python2.7
# example
# An example to retrieve all availabile integrations and commands for each
# Works on Demisto 2.5 onwards
#
# Author: <NAME>
# Version: 1.0
#
import argparse
import csv
import demisto
def p(what):
if verbose:
print(what)
def... | StarcoderdataPython |
1728466 | <gh_stars>1-10
import torch
import torch.nn as nn
from .util import MonthlyMultiplexer, WeeklyMultiplexer
class BiasCorrectionModel(nn.Module):
def __init__(self):
super().__init__()
self.bias = nn.parameter.Parameter(torch.normal(torch.zeros(2, 121, 240)))
def forward(self, model_parameter)... | StarcoderdataPython |
6647967 | <reponame>lavon321/Kunlun-M
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/11 16:56
# @Author : LoRexxar
# @File : functions.py
# @Contact : <EMAIL>
function_dict = {'Object': 1,
'Function': 1,
'Array': 1,
'Number': 1,
'parseFlo... | StarcoderdataPython |
1918644 | buck1 = [int(x) for x in input().split()]
buck2 = [int(x) for x in input().split()]
milk1 = 1000
milk2 = 1000
outs = {}
def moveFrom(fromMilk, toMilk, fromBuck, toBuck, iters):
if iters == 4:
outs[fromMilk] = True
return
for i in range(len(fromBuck)):
rem = fromBuck.pop(i)
... | StarcoderdataPython |
9791080 | <reponame>adaptivelab/twitter-text-py
# encoding=utf-8
import re
from twitter_text.regex import REGEXEN
from twitter_text.unicode import force_unicode
class Autolink(object):
WWW_REGEX = re.compile(r'www\.', re.IGNORECASE)
DEFAULT_URL_CLASS = 'tweet-url'
DEFAULT_LIST_CLASS = 'list-slug'
DEFAU... | StarcoderdataPython |
3426821 | import rapidsms
class App (rapidsms.app.App):
def start (self):
"""Configure your app in the start phase."""
pass
def parse (self, message):
"""Parse and annotate messages in the parse phase."""
pass
def handle (self, message):
"""Add your main application logic in... | StarcoderdataPython |
8149806 | <gh_stars>1-10
#coding:utf-8
#Author:huchengsong
if __name__ == '__main__':
print("Python:helloWorld!!") | StarcoderdataPython |
1643412 | <filename>examples/update_ciphers/update_ciphers.py<gh_stars>1-10
#!/usr/bin/env python
""" Recreate Terraform code based on the AWS SSL policies """
import os
import jinja2
import boto3
def clean_attribute_name(attribute_name):
""" Return the sanitised attribute name to use as parameter name """
new_name =... | StarcoderdataPython |
11306995 | <gh_stars>1-10
# 250. Count Univalue Subtrees
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# Depth First Search
def countUnivalSubtrees(self, root:... | StarcoderdataPython |
4948217 | <filename>igibson/examples/example_selector.py<gh_stars>0
import importlib
import os
import pkgutil
import signal
import string
from multiprocessing import Process
import igibson.examples as examples
from igibson.utils.utils import let_user_pick
TIMEOUT = 3
def interrupted(signum, frame):
raise ValueError("Time... | StarcoderdataPython |
6631704 | <filename>tools/build_r8lib.py<gh_stars>0
#!/usr/bin/env python
# Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
'''
Build r8lib.jar using src/main/keep.txt a... | StarcoderdataPython |
3266978 | from .datajoint_core_lib import dj_core
from enum import Enum
class DataJointType():
Unknown = dj_core.DataJointType_Unknown
TinyInt = dj_core.DataJointType_TinyInt
TinyIntUnsigned = dj_core.DataJointType_TinyIntUnsigned
SmallInt = dj_core.DataJointType_SmallInt
SmallIntUnsigned = dj_core.DataJoin... | StarcoderdataPython |
1850608 | from justgood import imjustgood
media = imjustgood("YOUR_APIKEY_HERE")
city = "surabaya" # example city name
data = media.cuaca(city)
# Get attributes
result = "{}".format(data["result"]["location"])
result += "\nCuaca : {}".format(data["result"]["description"])
result += "\nSuhu : {}".format(data["result"]["temperat... | StarcoderdataPython |
8130054 | <reponame>ccj5351/DAFStereoNets<gh_stars>10-100
# !/usr/bin/env python3
# -*-coding:utf-8-*-
# @file: __init__.py
# @brief:
# @author: <NAME>, <EMAIL>, <EMAIL>
# @version: 0.0.1
# @creation date: 10-03-2019
# @last modified: Sun 10 Mar 2019 02:34:04 PM EDT
# see https://stackoverflow.com/questions/4383571/importing-fi... | StarcoderdataPython |
1992189 | <filename>experiments/__init__.py
# versioneer
from ._version import get_versions
__version__ = get_versions()["version"]
__commit__ = get_versions()["full-revisionid"]
__dirty__ = get_versions()["dirty"]
del get_versions
__url__ = 'https://github.com/humm/experiments'
# intra-imports
from .expcfg import desc
from .... | StarcoderdataPython |
3559513 | <reponame>ferdn4ndo/infotrem
from .generic_test_case import GenericTestCase
from .generic_create_test_case import GenericCreateTestCases
from .generic_destroy_test_case import GenericDestroyTestCase
from .generic_list_test_case import GenericListTestCase
from .generic_partial_update_test_case import GenericPartialUpdat... | StarcoderdataPython |
4917654 | <gh_stars>0
import math
import numpy as np
import IPython
from tsa.science import numpy_ext as npx
def nball(n):
# returns the volume of the unit ball in n-dimensional space
# going off the formula on Wikipedia
return (math.pi ** (n / 2.0)) / math.gamma((n / 2.0) + 1)
def curse_of_dimensionality(analys... | StarcoderdataPython |
1751928 | """
Test for Plackett-Burman Design Generator Module
"""
import numpy as np
import pytest
from tagupy.design.generator import PlackettBurman
@pytest.fixture
def correct_input():
return [1, 2, 5, 10, 40, 80, 97]
def test_init_invalid_input():
arg = ["moge", None, np.ones((2, 3)), 3.4, 0, -22]
for el in... | StarcoderdataPython |
3315487 | """
Project Euler Problem 100: https://projecteuler.net/problem=100
If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement,... | StarcoderdataPython |
11340602 | import sys
import json
import re
def json_to_nx_struct(data):
#data = json.loads(graph)
nodes = [] #all nodes
edges = [] #all edges
first_set_nodes = [] #red nodes
second_set_nodes =[] #yellow nodes
first_set_edges = [] #red edges
second_set_edges = [] #yellow edges
directed_edges = []... | StarcoderdataPython |
11355576 | <reponame>justicerae7/sweech-cli
#!/usr/bin/env python
from __future__ import print_function
import argparse
import codecs
import json
import os.path
import ssl
import sys
import types
if sys.version > '3':
from urllib.parse import quote
from urllib.request import build_opener, urlopen, urlparse, AbstractDig... | StarcoderdataPython |
141888 | <gh_stars>0
# Copyright 2011 <NAME>
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is di... | StarcoderdataPython |
5053959 | import m2
import m3
import re
while (True):
print("First name:")
fname = input().strip()
print("Last name:")
lname = input().strip()
if(not re.findall('^[A-Za-zæøåÆØÅ\s-]+$',lname) or not re.findall('^[A-Za-zæøåÆØÅ\s-]+$',fname)):
print("Invalid input")
else:
name = m2.capitali... | StarcoderdataPython |
5161536 | <filename>autonomous_task/gps_class.py
#!/usr/bin/env python
from sensor_msgs.msg import NavSatFix
import rospy
from std_msgs.msg import String
from std_msgs.msg import Int32
from sensor_msgs.msg import Joy
import math
import sys
forward = [0.0, 0.0, 0.8, 0.0, 0.0, 0.0, 0.0, 0.0]
left = [-0.8, 0.0, 0.8, 0.0, 0.0, 0.0,... | StarcoderdataPython |
9649105 | import threading
from serial import Serial
import time
import Queue
name = "esp8266.py"
__all__ = ["ESP8266"]
class ESP8266Serial(Serial):
def __init__(self, *args, **kwargs):
super(ESP8266Serial, self).__init__(*args, **kwargs)
self.hw_reset()
self._identifier_msg_lock = threading.Lock()... | StarcoderdataPython |
9751898 | S = list(input())
# Pass a tuple to the key field
S.sort(key=lambda c: ( (c.isdigit() and int(c) % 2 == 0), (c.isdigit() and int(c) % 2 == 1), c.isupper(), c.islower(), c ) )
print(*S, sep='') | StarcoderdataPython |
4812394 | <gh_stars>0
import os
import re
import json
import shutil
import pandas
import wikipedia
from wikipedia import PageError, RedirectError, HTTPTimeoutError, DisambiguationError
from numpy import nan
from pycountry import countries
from pygeocoder import Geocoder, GeocoderError
from admix.utils import wiki... | StarcoderdataPython |
1761752 | from functools import reduce
lines = [line.strip() for line in open('input.txt', 'r')]
groups = []
currentGroup = []
for line in lines:
if line == "":
groups.append(currentGroup)
currentGroup = []
else:
currentGroup.append(list(line))
if len(currentGroup) != 0:
groups.append(curre... | StarcoderdataPython |
5111633 | # encoding: UTF-8
from .rmEngine import RmEngine
from .uiRmWidget import RmEngineManager
appName = 'RiskManager'
appDisplayName = '风险管理'
appEngine = RmEngine
appWidget = RmEngineManager
appIco = 'rm.ico' | StarcoderdataPython |
8023981 | <filename>src/api/funders/db_services.py
from flask import current_app
from src.shared.entity import Session
from .entities import Funder, FunderSchema
from ..fundings.entities import Funding
from src.shared.manage_error import CodeError, ManageErrorUtils, TError
class FunderDBService:
@staticmethod
def get_a... | StarcoderdataPython |
8063713 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | StarcoderdataPython |
3235020 | <reponame>jhdarcy/needful
from json import dumps
from secrets import token_hex
from typing import Union, Optional, Type
from bokeh.plotting.figure import Figure as _Figure
from bokeh.themes.theme import Theme
from bokeh.embed import json_item
from bokeh.embed.util import FromCurdoc
from .grid_object import GridObject... | StarcoderdataPython |
4800584 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | StarcoderdataPython |
9773476 | <reponame>RaoefTaki/MNTDP-forked
import copy
import torch
import torch.nn as nn
from src.models.change_layer_llmodel import FrozenSequential
from src.models.utils import is_dummy_block, _get_used_nodes
from supernets.networks.StochasticSuperNetwork import StochasticSuperNetwork
class SPNN(StochasticSuperNetwork):
... | StarcoderdataPython |
6402161 | <filename>landing/admin.py
from django.contrib import admin
from mezzanine.pages.admin import PageAdmin
from landing.models import SiteInformation,AboutUs,Visualization,Data,Data_template,Visualization_template
# Register your models here.
admin.site.register(SiteInformation)
class SiteInformationAdmin(admin.Model... | StarcoderdataPython |
9798227 | import FreeCAD, Part, Mesh
DOC = FreeCAD.activeDocument()
DOC_NAME = "assembly_complete_electrolyser"
def clear_doc():
# Clear the active document deleting all the objects
for obj in DOC.Objects:
DOC.removeObject(obj.Name)
def setview():
# Rearrange View
FreeCAD.Gui.SendMsgToActiveView("Vi... | StarcoderdataPython |
3338350 | import cv2
from PIL import ImageGrab
import numpy as np
res = ImageGrab.grab()
width, height = res.size
format_vid = cv2.VideoWriter_fourcc("m", "p", "4", "v")
store_vid = cv2.VideoWriter("output.mp4", format_vid, 30, (width, height))
while True:
img = ImageGrab.grab(bbox=(0, 0, width, height))
c... | StarcoderdataPython |
9708412 | """Main entry point."""
from . import cli
if __name__ == "__main__":
cli()
| StarcoderdataPython |
46218 | #System libraries
import tkinter as tk
import sys
sys.path.insert(1, '../common')
import socket
from cli import *
#User libraries
# from motorcommands import *
key_to_direction = {
38: "left",
25: "forward",
40: "right",
39: "back",
65: "stop",
}
numbers = {
19 : 0,
10 : 1,
... | StarcoderdataPython |
9663913 | <gh_stars>0
file = './text.txt'
openFile = open(file)
dictionary = dict()
for line in openFile :
words = line.split()
for word in words :
dictionary[word] = dictionary.get(word,0) + 1
temp = list()
for k,v in dictionary.items() :
newt = (v,k)
temp.append(newt)
temp =sorted(temp, reverse=Tr... | StarcoderdataPython |
3391212 | <reponame>arcticlimer/minimalpaste
from typing import Optional
import sqlite3
import secrets
from utils.logger import logger
class Database:
"""
Main database class, uses the `endpoints` set to efficiently
manage the current existing urls.
Database usage:
The database is loaded only a single ti... | StarcoderdataPython |
156859 | <filename>backend/portal/management/commands/load_target_populations.py
import requests
from django.core.management.base import BaseCommand
from django.utils import timezone
from portal.models import TargetPopulation
class Command(BaseCommand):
def handle(self, *args, **kwargs):
# loads majors, years, sc... | StarcoderdataPython |
1746452 | <reponame>learninto/sentry
from __future__ import absolute_import
import six
from sentry.testutils import APITestCase, SnubaTestCase
from django.core.urlresolvers import reverse
from sentry.discover.models import DiscoverSavedQuery, DiscoverSavedQueryProject
class DiscoverSavedQueryDetailTest(APITestCase, SnubaTest... | StarcoderdataPython |
3458755 | print ('-'*30)
print ('ANÁLISE DE EMPRESTIMO')
print ('-'*30)
casa = float(input('Qual o valor da casa? R$ '))
sal = float(input('Qual o valor do seu salário por mês? R$ '))
tempo = int(input(('Em quantos anos você deseja pagar a casa? ')))
parcela = casa/(tempo*12)
print(f'Para pagar uma casa no valor R$ {casa:.2f}... | StarcoderdataPython |
1876324 | <gh_stars>1-10
# Logic for moves generated by using factors generated by simulation
import lib.move as move
import lib.state as state
def playStratCompTurn(state, factors_list):
posStates = [state]
move.genAllPossMoves(posStates)
best = evalStratMove(factors_list, posStates)
if (best == None):
print "cr... | StarcoderdataPython |
4860113 | import AoCReader as Reader
import unittest
import day07.Day07Solver as Solver
class TestDay07(unittest.TestCase):
# def test_part_01_example(self):
# self.assertEqual(Solver.solve_part_01("pbga (66)\nxhth (57)\nebii (61)\nhavc (66)\nktlj (57)\nfwft (72) -> "
# ... | StarcoderdataPython |
3368613 | class AutoNoEmbed:
"""
Logs join and leave messages.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
async def on_member_join(self, member):
await self.bot.add_roles(member, self.bot.noembed_role)
def setup(bot):
bo... | StarcoderdataPython |
4868743 | <filename>VTHunter/api/responses.py
'''
Created on September 15, 2016
@author: compsecmonkey
Helper methods for generating API response code and logging the responses.
Usage:
Utilize the below methods for all return statements in API endpoints
given the appropriate response.
Utilize the rfc7231 document... | StarcoderdataPython |
9631941 | from netapp.netapp_object import NetAppObject
class VserverPeerInfo(NetAppObject):
"""
Contains information about the Vserver peer relationship(s).
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
... | StarcoderdataPython |
9707933 | <reponame>elsholz/four_in_a_row_online<gh_stars>0
def flatten(*argv):
res = None
for t in argv:
if res is None:
res = t
else:
for i in range(len(t)):
res = res[:i] + (res[i]+t[i], ) + res[1+i:]
return res | StarcoderdataPython |
3310238 | <reponame>SeoulTechPSE/MultistepNNs<filename>Systematic.py
"""
@author: <NAME>
"""
from Multistep_NN import Multistep_NN
import numpy as np
from scipy.integrate import odeint
def main_loop(scheme, M, skip, noise, num_layers, num_neurons):
# function that returns dx/dt
def f(x,t): # x is 2 x 1
... | StarcoderdataPython |
3435943 | weight=1
a=_State(0)
def run():
_print('exec task')
if a.val <= 5:
_task_suspend()
def leave():
_print('leaving', a.val)
a.inc()
sleep(1)
if a.val <= 4:
_task_suspend()
| StarcoderdataPython |
3562793 | import time
from datetime import datetime
from typing import Callable, Union
from aiolimiter import AsyncLimiter
from ..errors import ValidationException
from ..util.mappings import Mappings
# TODO: Maybe do something like this for `setattr()` too?
def auto_repr(obj: object):
"""A lazy '__repr__()' substitute.... | StarcoderdataPython |
358157 | from redbot.core import commands, checks, Config
from redbot.core.utils.chat_formatting import box, humanize_list, pagify
import asyncio
import datetime
import dateutil
import dateutil.parser
import discord
import logging
import re
import random
from collections import OrderedDict
#from redbot.core.utils.chat_formatti... | StarcoderdataPython |
11383115 | # encoding=UTF-8
from __future__ import unicode_literals
class APIError(Exception):
def __init__(self, response, description):
super(APIError, self).__init__(response.status_code, description)
self.response = response
self.description = description
@property
def status_code(self)... | StarcoderdataPython |
1609646 | <filename>models/contentunderstanding/textcnn_pretrain/reader.py<gh_stars>1-10
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a... | StarcoderdataPython |
9627813 | <reponame>arkarhtethan/django-library-management-system<gh_stars>1-10
from django.contrib import admin
from .models import Issue
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin):
list_display = ['pk','member','book']
| StarcoderdataPython |
6656730 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | StarcoderdataPython |
123581 | <reponame>zacernst/nanostream<gh_stars>1-10
import os
import logging
import time
import tempfile
import pytest
import metalpipe.metalpipe_recorder as metalpipe_recorder
import metalpipe.node as node
os.environ["PYTHONPATH"] = "."
CONSTANTS_IN_LOOP = 5
@pytest.fixture(scope="function")
def constant_emitter():
... | StarcoderdataPython |
6484114 | <filename>setup.py<gh_stars>1-10
import os.path
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext as _build_ext
import warnings
# numpy path is needed
try:
import numpy
numpy_includes = [numpy.get_include()]
HAVE_NUMPY = True
except ImportError:
#... | StarcoderdataPython |
6404355 | import face_detection.video_receiver as video_receiver
import face_detection.face_detector as face_detector
import configuration.general_settings as settings
from model.vgg_adapted_model import FaceAnalyserModel
def main():
# Initialize model
model = FaceAnalyserModel(settings.model_weights_path)
# Init... | StarcoderdataPython |
5146139 | from datetime import datetime, timedelta
import time
import json
import numpy as np
import pandas as pd
from sklearn import linear_model
# returns unix timestamp of `origin`datetime + `hour` padding
def timestamp(origin, hour):
return int(time.mktime((origin + timedelta(hours=hour)).timetuple()))
def predict_for_... | StarcoderdataPython |
11387705 | import abc
import os
from xwavecal.database import query_db_for_nearest
import logging
class Stage(object):
def __init__(self, runtime_context):
self.runtime_context = runtime_context
self.logger = logging.getLogger(self.__class__.__name__)
@abc.abstractmethod
def do_stage(self, image):... | StarcoderdataPython |
4822719 | import typing
from tqdm import (
tqdm,
)
from . import(
ScrapeAnime,
Anime,
)
class ScrapeAnimes():
def __call__(
self,
ids: typing.List[int],
) -> typing.Iterator[Anime]:
fn = ScrapeAnime()
for i in tqdm(ids):
yield fn(i) | StarcoderdataPython |
3493775 | from kafka import KafkaConsumer
import argparse
import atexit
import logging
import redis
# - default kafka topic to write to
topic_name = 'stock-analyzer'
# - default kafka broker location
kafka_broker = '127.0.0.1:9092'
logger_format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=logger_format)
logger... | StarcoderdataPython |
3534223 | from django.urls import path
from . import views
app_name = 'service'
urlpatterns = [
path('', views.ServiceAgentViewSet.as_view(), name='service_agent',),
]
| StarcoderdataPython |
3291337 | from OFS.Image import Image
from zope.app.form.browser.widget import DisplayWidget
from zope.app.form.browser.textwidgets import FileWidget
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
class ImageWidget(FileWidget):
"""
The standard FileWidget returns a string instead of an IFile in... | StarcoderdataPython |
1784578 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test CLI."""
from __future__ import absolute_import, print_function
import os
... | StarcoderdataPython |
8131421 | import sqlite3
conn = sqlite3.connect('Chinook_Sqlite.sqlite')
cursor = conn.cursor()
query1 = '''
SELECT
CustomerId,
SUM(Total)
FROM
Invoice
GROUP BY
CustomerId
LIMIT 5
'''
result1 = cursor.execute(query1).fetchall()
print('Q1----------------')
print(result1)
query2 = '''
SELECT
*
FROM
Customer
WHERE (Country... | StarcoderdataPython |
5055120 |
from .base import Base
from .list import List
from .matrix import Matrix
from .tree import *
| StarcoderdataPython |
5120290 | <filename>pages/predictions.py
# YC list page
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
# Imports from this app... | StarcoderdataPython |
12808487 | class Animation:
def animate(self, speed, init):
positions = []
positions.append(init)
next_pos = ""
for character in init:
next_pos += "."
i = 0
for thing in range(0, 45):
last = positions[i]
next_pos = ""
for character in init:
next_pos += "."
j = 0
while(j < len(last)):
... | StarcoderdataPython |
1824577 | <reponame>squid314/terraform-workshop
#!/usr/bin/python3
import sys, pyodbc, socket, yaml, socketserver, http.server
from itertools import count
from textwrap import dedent
hostname = socket.gethostname()
CREATE_TABLE = """
IF NOT EXISTS
(SELECT *
FROM sys.tables t
WHERE t.name = 'hit_counter')
CREATE T... | StarcoderdataPython |
4829620 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# <NAME>. aïvázis
# orthologue
# (c) 1998-2020 all rights reserved
#
"""
Verify that the default values get registered correctly
"""
def test():
# get the descriptor package
from pyre import descriptors
# get the base metaclass
from pyre.patterns.Attr... | StarcoderdataPython |
9719340 | import os
from fugue import NativeExecutionEngine, QPDPandasEngine, SqliteEngine
from fugue.execution.execution_engine import _get_file_threshold
from fugue_test.builtin_suite import BuiltInTests
from fugue_test.execution_suite import ExecutionEngineTests
class NativeExecutionEngineSqliteTests(ExecutionEngineTests.T... | StarcoderdataPython |
8013277 | from .json_formatters import * # noqa
| StarcoderdataPython |
3564956 | <reponame>nanobrew/nanobrew-core
from ..domain_event import DomainEvent
class SensorValueChanged(DomainEvent):
def __init__(self, sensor_id, value, unit):
self._sensor_id = sensor_id
self._value = value
self._unit = unit
def get_name(self):
return 'sensor_value_changed'
d... | StarcoderdataPython |
8159138 | <filename>experiments/bar_charts.py<gh_stars>1-10
"""Read the overall summary file and create bar charts grouped by
observations given to the agent.
"""
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
# noinspection PyUnresolvedReferences,PyPacka... | StarcoderdataPython |
9799357 | <gh_stars>10-100
"""The functions having to do with planes and quadrangles projected thereupon"""
import numpy as np
def plane_from_coord(coord_arr):
"""
Return plane coefficients which best includes the coordinates
This is done via a singular value decomposition of the coordinates. Read
the following... | StarcoderdataPython |
4971516 | <reponame>eric11eca/inference-information-probing<filename>jiant/ext/allennlp.py
from typing import Optional
import torch
import torch.nn as nn
# noinspection PyTypeChecker
# noinspection PyUnusedLocal
class SelfAttentiveSpanExtractor(nn.Module):
"""
Computes span representations by generating an unnormalize... | StarcoderdataPython |
11233851 | <gh_stars>1-10
#import torch
def triu_to_full(cm0):
num_res = int(torch.ceil(torch.tensor([((len(cm0) * 2) ** 0.5)])).item())
iu1 = torch.triu_indices(num_res, num_res, 1)
cm_full = torch.zeros((num_res, num_res), dtype=cm0.dtype, device=cm0.device)
cm_full[iu1[0,:],iu1[1,:]] = cm0
cm_full[iu1[1,:... | StarcoderdataPython |
3423554 | <reponame>LourensVeen/QCG-PilotJob<gh_stars>0
from typing import Tuple, Any, Dict
from qcg.pilotjob.executor_api.templates.qcgpj_template import QCGPJTemplate
class BasicTemplate(QCGPJTemplate):
@staticmethod
def template() -> Tuple[str, Dict[str, Any]]:
template = """
{
'name': '... | StarcoderdataPython |
11204133 | # Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa
print('Welcome to the Fonterrada Bank :)')
#Pergunte o valor da casa, o salário do comprador
valor = int(input('Valor da casa: '))
salario = int(input('Digite seu salário: '))
#e em quantos anos ele vai pagar.
tempoEmAnos = int(input('... | StarcoderdataPython |
4853800 | # -*- coding: utf-8 -*-
# Copyright: (c) 2021, <NAME> (@Andersson007) <<EMAIL>>
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible_collections.community.postgresql.plugins.modules.postgresql_set import pretty_to_bytes
@pytest.mark.parametrize('input_,... | StarcoderdataPython |
9782807 | <filename>lib/py/test/thrift_json.py
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version... | StarcoderdataPython |
6471826 | <reponame>raychangCode/Python-projects<filename>Photoshop I/blur.py
"""
File: blur.py
-------------------------------
This file shows the original image first,
smiley-face.png, and then compare to its
blurred img. The blur algorithm uses the
average RGB values of a pixel's nearest neighbors
"""
from simpleimage import... | StarcoderdataPython |
224707 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
if '../../../embeddings' not in sys.path:
sys.path.append('../../../embeddings')
from seq2tensor import s2t
import keras
from keras.models import Sequential, Model
from keras.layers import De... | StarcoderdataPython |
11216052 | <gh_stars>1-10
GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#C2B3A9"
WINNER_BG = "#FFCC00"
LOSER_BG = "#A39489"
SCORE_LABEL_FONT = "Verdana", 20
SCORE_FONT = "Helvetica", 32, "bold"
GAME_OVER_FONT = "Helvetica", 48, "bold"
GAME_OVER_FONT_COLOR = "#FFFFFF"
# Cell number based fonts
CELL_NUMBER_FONTS = {
2: ("Helve... | StarcoderdataPython |
1982335 | #printando dicionário inteiro
dicionario = {'chave1':'valor1','chave2':'valor2','chave3':3}
print(dicionario) | StarcoderdataPython |
1670641 | <filename>exercicios/ex004.py
#Dissecando uma variavel
nome = input(('Qual é seu nome?'))
print('Olá {} Esse script de python vai dizer algumas caracteristicas do valor que voce dizer. [False] Significa Não e [true] Siginifica Sim.\nSe voce é um progamador ou poliglota voce sabe que não significa, Mas aqui siginifica ... | StarcoderdataPython |
8163349 | <reponame>binnev/what-can-be-computed
# SISO program loopIfContainsGAGA.py
# If the input contains the string 'GAGA', this program enters an
# infinite loop. Otherwise it returns 'halted'. This function is used
# for certain tests that involve infinite loops.
import utils
from utils import rf
def loopIfContainsGAGA(... | StarcoderdataPython |
5004688 | <filename>charts/RecommendedParameters/RecommendedParameters.py
import json
import requests
def getNames(teamCode):
url = 'https://rows.tech/api/people?teamCode=' + str(teamCode)
return list(map(lambda person: person["name"], json.loads(requests.get(url).text)))
def getBoats():
return ['1v', '2v', '3v', '... | StarcoderdataPython |
1962867 | <filename>2018/day_4/part_1.py
"""
Solution for Day 4 Part 1
"""
from datetime import datetime
from collections import defaultdict, Counter
data_file_path = "data.txt"
# Open file, read data and clean
with open(data_file_path, "r") as df:
lines = df.readlines()
markings = []
for line in lines:
date, event = lin... | StarcoderdataPython |
4933164 | from pathlib import Path
import pytest
from kiwi_scp._constants import COMPOSE_FILE_NAME
from kiwi_scp.config import KiwiConfig
from kiwi_scp.project import Project
class TestDefault:
cfg = KiwiConfig()
def test_example(self):
p = Project(
directory=Path("example/hello_world"),
... | StarcoderdataPython |
1668165 | <gh_stars>0
'''
Created on 30 Dec 2016
@author: chrisdoherty
'''
from datetime import datetime
class UnoccupiedState():
# Interval to check for between detections (Seconds)
max_detection_interval_ = 10
# Number of back to back detections with "interval" or less between
# them before we tr... | StarcoderdataPython |
1797161 | <gh_stars>0
from stacks_queues.stacks_queues import Node, Queue
from graph import Graph
def graph_breadth_first(vertex):
nodes = []
breadth = Queue()
visited = set()
breadth.enqueue(vertex)
visited.add(vertex)
while not breadth.is_empty():
front = breadth.dequeue()
nodes.appen... | StarcoderdataPython |
8045634 | <filename>functions/slack/main_test.py
# Copyright 2018, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | StarcoderdataPython |
11366447 | import sys
from collections import defaultdict
from pprint import pprint
from typing import Dict, List
from dataclasses import dataclass
from pprint import pprint
import numpy as np
import torch
from tqdm import tqdm
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from a2t.base import Class... | StarcoderdataPython |
5007246 | <reponame>pkocandr/dependency-analysis
#!/usr/bin/env python3
import sys
import argparse
import inspect
import os
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
class CLITool(object):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.