index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
8,900 | d3d90b8ccd0ec449c84ac0316c429b33353f4518 | # Copyright (c) 2017, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import unittest
from distutils.version import StrictVersion
import numpy as np
from coremltools._deps ... |
8,901 | 7be62ce45f815c4f4cf32df696cc444f92ac6d5c | #Bingo Game
#Anthony Swift
#06/05/2019
'''
A simple bingo game. Player is presented with a randomly generated grid of numbers.
Player is asked to enter the number called out by the caller, each time a number is called out.
A chip ('X') is placed on the grid when the number entered (that has been called) match... |
8,902 | b0a354d82880c5169293d1229206470c1f69f24f | '''
ESTMD
Tool to isolate targets from video. You can generate appropriate videos
using module Target_animation.
__author__: Dragonfly Project 2016 - Imperial College London
({anc15, cps15, dk2015, gk513, lm1015,zl4215}@imperial.ac.uk)
CITE
'''
import os
from copy import deepcopy
import cv2
import nump... |
8,903 | 08a0ab888886184f7447465508b6494b502821ea | #!/usr/bin/env python
# coding: utf-8
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import tensorflow as tf
print(tf.__version__)
print(tf.keras.__version__)
print(tf.__path__)
import numpy as np
from tqdm import tqdm, tqdm_notebook
from utils import emphasis
import tensorflow.keras.backend as K
from tensorflow.... |
8,904 | 63a7225abc511b239a69f625b12c1458c75b4090 | import threading
import serial
import time
bno = serial.Serial('/dev/ttyUSB0', 115200, timeout=.5)
compass_heading = -1.0
def readBNO():
global compass_heading
try:
bno.write(b'g')
response = bno.readline().decode()
if response != '':
compass_heading = float(response.split(... |
8,905 | 477d1629c14609db22ddd9fc57cb644508f4f490 | #!/usr/bin/env python
from django.contrib import admin
from models import UserProfile, AuditTrail
class UserProfileAdmin(admin.ModelAdmin):
list_display = [i.name for i in UserProfile._meta.fields]
admin.site.register(UserProfile, UserProfileAdmin)
class AuditTrailUserAdmin(admin.ModelAdmin):
list_display ... |
8,906 | fa5468741e9884f6c8bcacaf9d560b5c93ee781a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from setup_env import *
#from mmlibrary import *
from astropy.coordinates import SkyCoord
import astropy.units as u
from mmlibrary import *
import numpy as np
import lal
from scipy.special import logsumexp
import cpnest, cpnest.model
# Oggetto per test: GW170817
#GW =... |
8,907 | 892c363c247177deb3297af84a93819a69e16801 | from EdgeState import EdgeState
from rest_framework import serializers
from dzTrafico.BusinessLayer.TrafficAnalysis.TrafficAnalyzer import TrafficAnalyzer, VirtualRampMetering
from dzTrafico.BusinessEntities.Location import LocationSerializer
from dzTrafico.BusinessLayer.SimulationCreation.NetworkManager import Network... |
8,908 | a81ee0a855c8a731bafe4967b776e3f93ef78c2a | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
#import matplotlib.cbook as cbook
import Image
from matplotlib import _png
from matplotlib.offsetbox import OffsetImage
import scipy.io
import pylab
#for question 1 (my data)
def resample(ms,srate):
return int(round(ms/1000*srate))
de... |
8,909 | 5750fd4b59f75ea63b4214ee66b23602ed4d314d | # Copyright 2021 Yegor Bitensky
# 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, ... |
8,910 | 338bf2406c233d857e1a688391161d58e1dab23c | from __future__ import annotations
from VersionControl.Branch import Branch
from Branches.Actions.Actions import Actions
from VersionControl.Git.Branches.Develop.Init import Init
class Develop(Branch):
def process(self):
if self.action is Actions.INIT:
self.start_message('Develop Init')
... |
8,911 | 067e0129b1a9084bbcee28d1973504299b89afdb | import json
import os
from django.conf import settings
from django.db import models
from jsonfield import JSONField
class Word(models.Model):
value = models.CharField(
max_length=50,
verbose_name='Слово'
)
spelling = models.CharField(
max_length=250,
verbose_name='Транскри... |
8,912 | 0ae5d20b78bf7c23418de55ffd4d81cd5284c6d5 | class Tienda:
def __init__(self, nombre_tienda, lista_productos = []):
self.nombre_tienda = nombre_tienda
self.lista_productos = lista_productos
def __str__(self):
return f"Nombre de la Tienda: {self.nombre_tienda}\nLista de Productos: {self.lista_productos}\n"
def anhadir_prod... |
8,913 | 031727fa42b87260abb671518b2baeff1c9524f9 | #C:\utils\Python\Python27\python.exe incompletosClean.py incompletos\inc.dat incompletos\out.dat
import sys
import os
import os.path
bfTmp = ''
lsOutTmp = []
InFileName = []
lsHTMLName = []
fileNameIn= sys.argv[1]
fileNameOu= sys.argv[2]
fo = open(fileNameIn)
InFileName += [x.replace('\n', '') for x ... |
8,914 | 74eea67b8640a03e616bebdadba49891017b921d | from collections import Counter, defaultdict
import pandas as pd
from glob import glob
import subsamplex
files = glob('outputs.txt/*.unique.txt.gz')
files.sort()
biome = pd.read_table('cold/biome.txt', squeeze=True, index_col=0)
duplicates = set(line.strip() for line in open('cold/duplicates.txt'))
counts = defaultdi... |
8,915 | ba7db49ca7956fdc055702ffccba769485fd0046 | import os
import location
import teamList
import pandas as pd
import csv
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
##adapted from code from this website:
## https://towardsdatascience.com/simple-little-tables-with-matplotlib-9780ef5d0bc4
year = "18-19"
team = "ARI"
seasonReportRaw =... |
8,916 | af2ef3c77cefe675f3d30c3234401f0f9bda3505 | work_hours = 8
work_days = 5
pay_periods = 2
total = work_hours * work_days * pay_periods
rate = 17
pay = total * rate
print(pay)
# variables
name = "josh"
age = 30
# float
weight = 160.5
# list
kill_streak = [3, 5, 1, 9] # [90.9] list can contain sub lists
# range
players = list(range(1,10))
odds =... |
8,917 | 75958b48a3372b56e072a0caa468171ab6b99eb6 | #!/usr/bin/env python3
from flask import Flask, request
from flask_restplus import Resource, Api, fields
from pymongo import MongoClient
from bson.objectid import ObjectId
import requests, datetime, re
#------------- CONFIG CONSTANTS -------------#
DEBUG = True
MAX_PAGE_LIMIT = 2
COLLECTION = 'indicators'
DB_CONFIG =... |
8,918 | 9bf4725c054578aa8da2a563f67fd5c72c2fe831 | #coding=utf8
uu=u'中国'
s = uu.encode('utf-8')
if s == '中国' :
print 11111
print u"一次性还本息".encode('utf-8')
|
8,919 | 1bdc1274cceba994524442c7a0065498a9c1d7bc | #Adds states to the list
states = {
'Oregon' : 'OR' ,
'Flordia': 'FL' ,
'California':'CA',
'New York':'NY',
'Michigan': 'MI',
}
#Adds cities to the list
cities = {
'CA':'San Fransisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
cities['NY'] = 'New York'
cities['OR'] = 'PortLa... |
8,920 | b6e28f29edd0c4659ab992b45861c4c31a57e7fd | import os
import pytest
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver import Firefox
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.comm... |
8,921 | 63093190ee20e10698bd99dcea94ccf5d076a006 | species(
label = 'C=C([CH]C)C(=C)[CH]C(24182)',
structure = SMILES('[CH2]C(=CC)C([CH2])=CC'),
E0 = (249.687,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([325,375,415,465,420,450,1700,1750,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3000,3033.33,... |
8,922 | 9ae92d6ee4b82f7ed335c47d53567b817140a51c | from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
db = SQLAlchemy()
def connect_db(app):
"""Connect to database."""
db.app = app
db.init_app(app)
"""Models for Blogly."""
class User(db.Model):
__tablename__= "users"
id = db.Column(db.Integer, primary_key=True, autoincre... |
8,923 | e7ac5c1010330aec81ce505fd7f52ccdeddb76de | import database
import nltk
def pop(i): # pupulate the words table
loc = i
sentencesTrial = []
File = open('words.txt')
lines = File.read()
sentences = nltk.sent_tokenize(lines)
locations = ["Castle","Beach","Beach","Ghost Town","Ghost Town","Haunted House","Jungle","Carnival", "Ghost Town", "Hi... |
8,924 | fcdb43e36a4610ca0201a27d82b1a583f1482878 | import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
POWER_PIN = 21
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25
PAUSE = 0.1
# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
ret... |
8,925 | 71e0137fc02b4f56bdf87cc15c275f5cca1588c4 | from enum import IntEnum
class DaqListType(IntEnum):
"""
This class describes a daq list type.
"""
DAQ = 0x01
STIM = 0x02
DAQ_STIM = 0x03 |
8,926 | 1c2a862f995869e3241dd835edb69399141bfb64 | import numpy as np
import tensorflow as tf
K_model = tf.keras.models.load_model('K_model.h5')
K_model.summary()
features, labels = [], []
# k_file = open('dataset_20200409.tab')
k_file = open('ts.tab')
for line in k_file.readlines():
line = line.rstrip()
contents = line.split("\t")
label = contents.pop()... |
8,927 | 892d6662e4276f96797c9654d15c96a608d0835a | import itertools
import unittest
from pylev3 import Levenshtein
TEST_DATA = [
('classic', "kitten", "sitting", 3),
('same', "kitten", "kitten", 0),
('empty', "", "", 0),
('a', "meilenstein", "levenshtein", 4),
('b', "levenshtein", "frankenstein", 6),
('c', "confide", "deceit", 6),
('d', "... |
8,928 | 1576693264a334153c2752ab6b3b4b65daa7c37c | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 17/02/17 at 11:48 PM
@author: neil
Program description here
Version 0.0.1
"""
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import sys
# detect python version
# if python 3 do this:
if (sys.version_info > (3, 0)):
import tkint... |
8,929 | 592d5074eeca74a5845d26ee2ca6aba8c3d0f989 | from os import listdir
from os.path import isfile, join
from datetime import date
mypath = '/Users/kachunfung/python/codewars/'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
py_removed = [i.replace('.py','') for i in onlyfiles]
file_counter_removed = py_removed.remove('file_counter')
day_removed... |
8,930 | 2d503c93160b6f44fba2495f0ae0cf9ba0eaf9d6 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindo... |
8,931 | 40637c7a5e45d0fe4184478a1be2e08e5040c93b | from colander_validators import (
email,
url)
def test_url():
assert url("ixmat.us") == True
assert url("http://bleh.net") == True
assert type(url("://ixmat.us")) == str
assert type(url("ixmat")) == str
def test_email():
assert email("barney@purpledino.com") == True
assert email("b... |
8,932 | d2787f17a46cf0db9aeea82f1b97ee8d630fd28a |
from xai.brain.wordbase.adjectives._corporal import _CORPORAL
#calss header
class _CORPORALS(_CORPORAL, ):
def __init__(self,):
_CORPORAL.__init__(self)
self.name = "CORPORALS"
self.specie = 'adjectives'
self.basic = "corporal"
self.jsondata = {}
|
8,933 | 322795bce189428823c45a26477555052c7d5022 | # Author: Andreas Francois Vermeulen
print("CrawlerSlaveYoke")
print("CSY-000000023.py")
|
8,934 | e2a38d38d2ab750cf775ed0fbdb56bc6fc7300c4 | from typing import *
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
map_: List[List[int]] = [[0 if (i > 0 and j > 0) else 1 for j in range(m)] for i in range(n)]
for row in range(1, n):
for col in range(1, m):
map_[row][col] = map_[row][col - 1] + map_[ro... |
8,935 | 4b647d37d390a4df42f29bbfc7e4bae4e77c5828 | import string
import random
file_one_time_pad = open("encryption_file.txt","r")
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21,25,20,15,16,14,10,26,24,9,8,13]
alphabets = ['a','b','c','d','e','f','g','h','i','j','... |
8,936 | 24368b6c607c0524f8b52b279a6dce0fde72294b | import typing
import time
import cv2
import os
from .ABC import ABC
from .Exceptions import *
from .Constants import *
class Video(ABC):
def __init__(self, filename: str, *, scale: float = 1, w_stretch: float = 2, gradient: typing.Union[int, str] = 0, verbose: int = False):
if not os.path.isfile(filename... |
8,937 | a6bd10723bd89dd08605f7a4abf17ccf9726b3f5 | # pyre-ignore-all-errors
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
from wallet.storage import db_session, engine, Base
from wallet.storage.models import User, Account
from wallet.types import RegistrationStatus
from diem_utils.types.currencies import FiatCurrency
def clear_db(... |
8,938 | c4720eb5a42267970d3a98517dce7857c0ba8450 | import datetime
import json
import logging
from grab import Grab
from actions import get_course_gold, get_chat_type, get_indexes, group_chat_id
# logging.basicConfig(
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# level=logging.DEBUG)
# logger = logging.getLogger(__name__)
results = None... |
8,939 | f6dd5acc75d1a85a996629e22e81cdef316c1dcd | """Test functions for util.mrbump_util"""
import pickle
import os
import sys
import unittest
from ample.constants import AMPLE_PKL, SHARE_DIR
from ample.util import mrbump_util
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thisd = os.path.abspath(os.path.dirname(__file__))
... |
8,940 | 3431e342c940b0d91f817c3e583728e55e305210 | # import the necessary packages
from .pigear import PiGear
from .camgear import CamGear
from .videogear import VideoGear
__all__ = ["PiGear", "CamGear", "VideoGear"] |
8,941 | adfdd988b7e208229f195308df8d63fd2799046f |
from math import exp
from math import e
import numpy as np
import decimal
import pandas as pd
pop = []
x = 0
for a in range(1,10001):
pop.append((1.2)*e**(-1.2*x))
x =+0.0001
for k in range(100,10100,100):
exec(f'S{k} =pop[1:k]')
################################################... |
8,942 | 031f668fbf75b54ec874a59f53c60ceca53779cf | from django.urls import path
from . import views
app_name = 'orders'
urlpatterns = [
path('checkout' , views.order_checkout_view , name='orders-checkout') ,
]
|
8,943 | 590baf17d9fdad9f52869fa354112d3aa5f7d5f0 | import requests
import json
import io
import sys
names = ['abc-news', 'abc-news-au', 'aftenposten','al-jazeera-english','ars-technica','associated-press','australian-financial-review','axios', 'bbc-news', 'bbc-sport','bleacher-report', 'bloomberg','breitbart-news','business-insider', 'business-insider-uk','buzzfeed','... |
8,944 | 74fae3636b1c1b0b79d0c6bec8698581b063eb9c | from . import by_trips
from . import by_slope
|
8,945 | f26c624e8ae9711eb835e223407256e60dfc6d6e | # Ejercicio 1
print('Pepito')
print('Cumpleaños: 22 de enero')
edad = 42
print('Tengo', edad, 'años')
cantante = 'Suzanne Vega'
comida = 'rúcula'
ciudad = 'Barcelona'
print('Me gusta la música de', cantante)
print('Me gusta cenar', comida)
print('Vivo en', ciudad) |
8,946 | 8fdc9a52b00686e10c97fa61e43ddbbccb64741b | """
OO 05-18-2020
Task
----------------------------------------------------------------------------------------------------------
Your company needs a function that meets the following requirements:
- For a given array of 'n' integers, the function returns the index of the element with the minimum value
... |
8,947 | cd07dd596f760e232db5c0fd8e27360d61bda635 | #!/usr/bin/python3
import i3ipc
if __name__ == "__main__":
i3 = i3ipc.Connection()
wp = [int(w["name"]) for w in i3.get_workspaces() if w["num"] != -1]
for k in range(1, 16):
if k not in wp:
i3.command("workspace {}".format(k))
break
|
8,948 | 94130b4962ecff2ea087ab34cf50a084254bf980 | """This module provides the definition of the exceptions that can be raised from the database module."""
class DatabaseError(Exception):
"""Raised when the requested database operation can not be completed."""
pass
class InvalidDictError(Exception):
"""Raised when the object can not be created from the pr... |
8,949 | 137f9310256f66ccd9fbe6626659c3c4daea0efc | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Event(models.Model):
name = models.CharField('Назва', max_length=200)
date = models.DateField('Дата')
address = models.CharField('Адреса', max_length=255, blank=True, null=True)... |
8,950 | e6d4d12d47391927364fdc9765c68690d42c5d8d | import pygame
import serial
import time
ser1 = serial.Serial('/dev/ttyACM0', 115200) #Right
ser1.write('?\n')
time.sleep(0.5)
if ser1.readline()[4] == 0:
ser2 = serial.Serial('/dev/ttyACM1', 115200) #Left, negative speeds go forward
else:
ser1 = serial.Serial('/dev/ttyACM1', 115200)
ser2 = serial.Serial('/... |
8,951 | 785dcaf7de68174d84af3459cde02927bc2e10cc | tabela = [[1,-45,-20,0,0,0,0],[0,20,5,1,0,0,9500],[0,0.04,0.12,0,1,0,40],[0,1,1,0,0,1,551]]
colunas = ["Z","A","B","S1","S2","S3","Solução"]
linhas = ["Z","S1","S2","S3"]
n_colunas=7
n_linhas=4
#Inicio do algoritmo
#Buscar o menor numero negativo na linha 0
menor_posicao=-1
menor_valor=0
for coluna in rang... |
8,952 | 39affe139eec4cf6877646188839d79ed575235c | from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.app import App
import webbrowser
a=0.0
b="?"
n=0.0
k=""
g=""
class ghetto(GridLayout):
def matCallback(self,a):
webbrowser.open_n... |
8,953 | f25db7d797f1f88bd0374d540adcb396e16740a0 | from django.contrib.auth import authenticate
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
import json
from userprofile.models import Profile
from .models import *
#发送私信
def sendmessage(request):
if request.method == "POST":
data = json.loads(request.body)
... |
8,954 | c2e0f2eda6ef44a52ee4e192b8eb71bde0a69bff | import json
import logging
logger = logging.getLogger(__name__)
from django.db.models import Q
from channels_api.bindings import ResourceBinding
from .models import LetterTransaction, UserLetter, TeamWord, Dictionary
from .serializers import LetterTransactionSerializer, UserLetterSerializer, TeamWordSerializer
cla... |
8,955 | 35a95c49c2dc09b528329433a157cf313cf59667 | import hashlib
def md5_hexdigest(data):
return hashlib.md5(data.encode('utf-8')).hexdigest()
def sha1_hexdigest(data):
return hashlib.sha1(data.encode('utf-8')).hexdigest()
def sha224_hexdigest(data):
return hashlib.sha224(data.encode('utf-8')).hexdigest()
def sha256_hexdigest(data):
return hashlib... |
8,956 | 7e3a5e1f19683b1716f3c988dcc1e65fee1cae13 | import sys
sys.stdin = open('magnet.txt', 'r')
from collections import deque
def check(t, d, c):
if t == 1:
if m1[2] != m2[-2] and not c:
check(t + 1, d * (-1), 1)
if d == 1:
m1.appendleft(m1.pop())
else:
m1.append(m1.popleft())
elif t == 4:
... |
8,957 | 53cbc3ca3a34a8aafa97d6964337cfabb1bebac5 | from sklearn.datasets import fetch_20newsgroups
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import make_pipeline... |
8,958 | 6b1970ee2b0d24504f4dea1f2ad22a165101bfbe | # -*- coding=utf-8 -*-
# ! /usr/bin/env python3
"""
抽奖活动-摇一摇活动
"""
import time
import allure
from libs.selenium_libs.common.base import Base
from libs.selenium_libs.page_object.page_activity import PageActivity
from libs.selenium_libs.page_object.page_personal_center import PagePersonalCenter
class LuckDrawActivity... |
8,959 | 3accf1c066547c4939c104c36247370b4a260635 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 10:18:35 2019
@author: zehra
"""
import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy.special import expit
X_train, y_train, X_val, y_val, X_test, y_test = pickle.load(open("data.pkl", "rb"))
id2word, word2id = pickle.load( open("dicts.pkl", "r... |
8,960 | 903d5913025d7d61ed50285785ec7f683047b49a | # -*- encoding: utf-8 -*-
#
# BigBrotherBot(B3) (www.bigbrotherbot.net)
# Copyright (C) 2011 Thomas "Courgette" LÉVEIL <courgette@bigbrotherbot.net>
#
# This program 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 Foundat... |
8,961 | 292cfecb701ecc179381d4453063aff532a0e877 | import cv2
img = cv2.imread('Chapter1/resources/jacuzi.jpg')
imgGrey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgCanny = cv2.Canny(img,240,250)
cv2.imshow("output",imgCanny)
cv2.waitKey(0) |
8,962 | 86ea1c46383b5a8790eb187163107f4100395ef3 | from typing import Set, Dict, Tuple
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top_secret'
# Определение константных величин
RULE: Dict[Tuple[str, str], str] = {('H', 'a'): 'S',
('H', 'b'): 'SE',
... |
8,963 | 14826b5b121ba2939519492c1e1d8700c32396d2 | from pyzabbix import ZabbixMetric, ZabbixSender, ZabbixAPI
from datetime import datetime
from re import findall
# current_time = datetime.now().strftime("%H:%M:%S %d.%m.%Y")
class ZabbixItem():
def __init__(self, user, password, ext_group, ext_template, zabbix_host):
self.user = user
self.passwor... |
8,964 | 237277e132c8223c6048be9b754516635ab720e2 | # -*- coding: utf-8 -*-
import requests
import json
import boto3
from lxml.html import parse
CardTitlePrefix = "Greeting"
def build_speechlet_response(title, output, reprompt_text, should_end_session):
"""
Build a speechlet JSON representation of the title, output text,
reprompt text & end of session
... |
8,965 | 035043460805b7fe92e078e05708d368130e3527 | # ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Test create publ... |
8,966 | 97a059d6d34b924a0512ebe6ff5ab1d5ccc072d5 | # Author: Loren Matilsky
# Date created: 03/02/2019
import matplotlib.pyplot as plt
import numpy as np
import sys, os
sys.path.append(os.environ['raco'])
sys.path.append(os.environ['rapl'])
sys.path.append(os.environ['rapl'] + '/timetrace')
from common import *
from cla_util import *
from plotcommon import *
from timey... |
8,967 | dfaea1687238d3d09fee072689cfdea392bc78f9 | #-*- coding: utf-8 -*-
import argparse
import pickle
def str2bool(v):
return v.lower() in ('true', '1')
arg_lists = []
parser = argparse.ArgumentParser()
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
# Network
net_arg = add_argument_group('Network')
n... |
8,968 | 3b77f7ea5137174e6723368502659390ea064c5a | import csv
with open('./csvs/users.csv', encoding='utf-8', newline='') as users_csv:
reader = csv.reader(users_csv)
d = {}
for row in reader:
userId, profileName = row
if profileName == 'A Customer':
continue
value = d.get(profileName)
if not value:
d... |
8,969 | 34c7e6b6bc687bc641b7e3b9c70fd0844af8e340 | """
CONVERT HOURS INTO SECONDS
Write a function that converts hours into seconds.
Examples:
- how_many_seconds(2) -> 7200
- how_many_seconds(10) -> 36000
- how_many_seconds(24) -> 86400
Notes:
- 60 seconds in a minute; 60 minutes in a hour.
- Don't forget to return your answer.
"""
"""
U.P.E... |
8,970 | 68493acce71060799da8c6cb03f2ddffce64aa92 | import requests, vars
def Cardid(name):
query = {"key":vars.Key, "token":vars.Token, "cards":"visible"}
execute = requests.request("GET", vars.BoardGetUrl, params=query).json()
for row in execute['cards']:
if row['name'] == name:
cardID = 1
break
else:
ca... |
8,971 | 6f5eda426daf5db84dc205f36ec31e9076acb8ee | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 13:04:32 2018
@author: andrew
"""
import os
import glob
import initialize
import psf
from astropy.io import fits
import filters
import numpy as np
import sys
import MR
from tqdm import tqdm
def sextractor_MR(location, MR_method='swarp', use_con... |
8,972 | 9b7601a5230bfd2370e73a71d141d6de68ade50f | # Generated by Django 2.2.1 on 2020-02-13 05:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app01', '0004_auto_20200213_1202'),
]
operations = [
migrations.DeleteModel(
name='Subject',
),
migrations.Renam... |
8,973 | 6c6a49dfced680fe034cbbc2fa28d57d2aa1273e | import discord
import requests
import math
from keys import GITHUB_DISCORD_TOKEN, GITHUB_FORTNITE_API_KEY
client = discord.Client()
# Constant
DISCORD_TOKEN = GITHUB_DISCORD_TOKEN
FORTNITE_API_KEY = GITHUB_FORTNITE_API_KEY
LIST = ['Verified']
VERIFIED = 4
# Return the current season squad K/D of the fortnite player... |
8,974 | e3aa38b5d01823ed27bca65331e9c7315238750a | import utils
from problems_2019 import intcode
def run(commands=None):
memory = utils.get_input()[0]
initial_inputs = intcode.commands_to_input(commands or [])
program = intcode.Program(memory, initial_inputs=initial_inputs, output_mode=intcode.OutputMode.BUFFER)
while True:
_, return_signal... |
8,975 | 14cc048f517efd3dad9960f35fff66a78f68fb45 | from django.test import TestCase
from ..models import FearConditioningData, FearConditioningModule
from ..registry import DataViewsetRegistry, ModuleRegistry
class ModuleRegistryTest(TestCase):
def test_register_module_create_view(self) -> None:
registry = ModuleRegistry()
registry.register(Fear... |
8,976 | bd81f4431699b1750c69b0bbc82f066332349fbd | from django.shortcuts import render
# Create your views here.
from django.shortcuts import render_to_response
from post.models import Post
#def ver_un_post(request, idpost):
# post = Post.objects.get(id=idpost)
#
# return render_to_response("post.html",{"post":post,},)
def home(request):
cursos = Cur... |
8,977 | 7ea81f83f556fcc55c9c9d44bcd63c583829fc08 | import re
n = input("電話番号を入力してください>>")
pattern = r'[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}'
if re.findall(pattern, n):
print(n, "は電話番号の形式です")
else:
print(n, "は電話番号の形式ではありません")
|
8,978 | 34536e3112c8791c8f8d48bb6ffd059c1af38e2f | from django.db.models import manager
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.utils import serializer_helpers
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from rest_fr... |
8,979 | d412e5768b23b8bbb8f72e2ae204650bbc1f0550 | class MinHeap:
__heap = [-0]
def __init__(self): pass
def insert(self, value):
self.__heap.append(value)
self.__sift_up()
def pop(self):
if len(self.__heap) == 1:
return None
minimum = self.__heap[1]
if len(self.__heap) == 2:
self.__h... |
8,980 | 9f7b1cfcc3c20910201fc67b5a641a5a89908bd1 | import numpy as np, pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.base import BaseEstimator, TransformerMixin
from datetime import timedelta
import sys
DEBUG = False
class DailyAggregator(BaseEstimator, TransformerMixin):
''' Aggregates time-series values to daily level. '''
def... |
8,981 | 4b85479af7d65d208fab08c10afbf66086877329 | import sys
n= int(sys.stdin.readline())
dp = {1:'SK', 2: 'CY', 3:'SK', 4:'SK', 5:'SK',6:'SK'}
def sol(k):
if k in dp:
return dp[k]
else:
for i in range(7, k+1):
if dp[i-3]=='SK' and dp[i-1]=='SK' and dp[i-4]=='SK':
dp[i] = 'CY'
else:
dp[... |
8,982 | f1c65fc4acafbda59aeea4f2dfca2cf5012dd389 | from pyecharts.charts.pie import Pie
from pyecharts.charts.map import Map
import static.name_map
from pymongo import MongoClient
# html代码头尾
html1 = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>疫情数据可视化</title><script src="/static/echarts/echarts.js"></script><script src="/static/china.js"></... |
8,983 | 6eac04bc10ef712ab4e2cde4730950ddcbe42585 | import queue
from enum import IntEnum
from time import sleep
import keyboard
# I know, I copy pasted this horrobly written class
# again...
# and again.. I should really write a proper intcode computer
class IntCodeComputer:
def __init__(self, code):
self.defaultCode = code
self.runningCode = self... |
8,984 | 0150e1db3ef2f6c07280f21971b43ac71fc4cada | """Handles loading and tokenising of datasets"""
import enum
import numpy as np
import os.path
import pickle
from tqdm import tqdm
import nltk
from nltk import WordPunctTokenizer
nltk.download('punkt')
from nltk.tokenize import word_tokenize
from lib.utils import DATASETS_BASE_PATH, SAVED_POS_BASE_PATH
from lib.pos im... |
8,985 | 18ae982c7fac7a31e0d257f500da0be0851388c2 | from secrets import randbelow
print(randbelow(100)) |
8,986 | ad53b100a1774f5429278379302b85f3a675adea | # Generated by Django 2.2 on 2019-05-13 06:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base_data_app', '0008_key_keyslider'),
]
operations = [
migrations.AddField(
model_name='key',
name='image',
... |
8,987 | 2cff5fdfc86793592dd97de90ba9c3a11870b356 | from odoo import api, tools, fields, models, _
import base64
from odoo import modules
class InheritUser(models.Model):
_inherit = 'pos.config'
related_pos_user = fields.One2many('pos.session.users', 'pos_config', string='Related User')
class InheritSession(models.Model):
_name = 'pos.session.users'
... |
8,988 | 9fdc7c1eb68a92451d41313861164a915b85fcee | from django.conf.urls import url
from .views.show import show_article, show_articles, export_db
urlpatterns = [
url(r'^$', show_articles, name='index'),
url(r'^article/$', show_article, name='article'),
url(r'^export/$', export_db, name='article'),
]
|
8,989 | 458124aa0d6f04268ad052f74d546b12d3f3f5f7 | import os, gc, random
from time import time
import pickle
import numpy as np
import pandas as pd
from sklearn.metrics import log_loss, f1_score, accuracy_score
from collections import Counter
from IPython.display import clear_output
import torch
from transformers import (
AutoTokenizer, RobertaTokenizerFast,
B... |
8,990 | 1a569b88c350124968212cb910bef7b09b166152 |
## This file is the celeryconfig for the Task Worker (scanworker).
from scanworker.commonconfig import *
import sys
sys.path.append('.')
BROKER_CONF = {
'uid' : '{{ mq_user }}',
'pass' : '{{ mq_password }}',
'host' : '{{ mq_host }}',
'port' : '5672',
'vhost' : '{{ mq_vhost }}',
}
BROKER_URL = 'amqp://... |
8,991 | 743d261052e4532c1304647501719ad897224b4e | #!/usr/bin/env python3
"""
Python class to access Netonix® WISP Switch WebAPI
** NEITHER THIS CODE NOR THE AUTHOR IS ASSOCIATED WITH NETONIX® IN ANY WAY.**
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software,... |
8,992 | e1da3255668999c3b77aa8c9332b197a9203478e | from marshmallow import ValidationError
from werkzeug.exceptions import HTTPException
from flask_jwt_extended.exceptions import JWTExtendedException
from memedata.util import mk_errors
from memedata import config
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return mk... |
8,993 | a1ca6c258298feda99b568f236611c1c496e3262 | C = {i:0 for i in range(9)}
N = int(input())
A = list(map(int,input().split()))
for i in range(N):
a = A[i]
if a<400:
C[0] += 1
elif a<800:
C[1] += 1
elif a<1200:
C[2] += 1
elif a<1600:
C[3] += 1
elif a<2000:
C[4] += 1
elif a<2400:
C[5] += 1
... |
8,994 | ba34bae7849ad97f939c1a7cb91461269cd58b64 | from numpy import array
import xspec as xs
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Grid
from spectralTools.step import Step
class xspecView(object):
def __init__(self):
#xs.Plot.device="/xs"
xs.Plot.xAxis='keV'
self.swift = []
self.nai=[]
s... |
8,995 | a22aa66bd65033750f23f47481ee84449fa80dbc | # Python 3.6. Written by Alex Clarke
# Breakup a large fits image into smaller ones, with overlap, and save to disk.
# Sourecfinding is run on each cutout, and catalogues are sifted to remove duplicates from the overlap.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import multiprocessing... |
8,996 | eb043c4c981b48763164e3d060fd52f5032be0ea | """ Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... |
8,997 | 58204b4b035aa06015def7529852e882ffdd369a | #!/usr/bin/env python
##############
#### Your name: Alexis Vincent
##############
import numpy as np
import re
from skimage.color import convert_colorspace
from sklearn.model_selection import GridSearchCV
from sklearn import svm, metrics
from skimage import io, feature, filters, exposu... |
8,998 | edfad88c837ddd3bf7cceeb2f0b1b7a5356c1cf7 | from sense_hat import SenseHat
import time
import random
#Set game_mode to True for single roll returning value
#False for demonstration purposes
class ElectronicDie:
def __init__(self, mode):
self.game_mode = mode
sense = SenseHat()
#Colours
O = (0,0,0)
B = (0, 0, 255)
#Settings
#... |
8,999 | 6a954197b13c9adf9f56b82bcea830aaf44e725f | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.