index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,400 | 8db3a0e8a4d36176e9d8593226b6a883d688d03e | import requests
from multiprocessing import Pool
import math
import logging
import os
import pickle
import clip
PROCESS_NUM = 20
RETRY_TIME = 5
MAGIC_CLIENT_ID = "jzkbprff40iqj646a697cyrvl0zt2m6"
def init_directory_structure():
if not os.path.exists('data'):
os.mkdir('data')
if not os.path.exists('da... |
10,401 | bedd53d964519e5424447a9af0449abf31ab5eee | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
mi... |
10,402 | 4c294684d97014057fe4953779e166e64ea8a98b | from mutagen.mp3 import MP3
from mutagen import MutagenError
import os
from stat import *
path = input("path to directory with mp3: ")
path = os.path.abspath(path)
def iterate_in_folder(path):
ln = 0
num = 0
for item in os.listdir(path):
if S_ISDIR(os.stat(os.path.join(path,item))[ST_MODE]):
... |
10,403 | 16e315113a61fdab87ee67f4ffca38101e9d09d6 | # Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... |
10,404 | 30126431bc014950669f552b430c6626c6e32c9a | from django import template
from ..models import Post
from ..forms import SearchForm
from django.db.models import Count
register = template.Library()
@register.simple_tag
def total_posts():
return Post.published.count()
# Tag to display the latest posts (default nimber of posts 5)
@register.inclusion_tag('bl... |
10,405 | b88b46b5789d08bdad07f7ee14d570f02cecaa37 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pip install console-menu
from consolemenu import *
from consolemenu.items import *
from converter import *
def cm_hexadecimal2decimal():
Screen().println(str(hexadecimal2decimal(Screen().input('Enter a hexadecimal without Ox : ').input_string)))
Screen().input... |
10,406 | 139d129ce1220cf0b78416b12f813e15f313139d | '''
Created on 19 apr 2017
@author: Conny
'''
from FunctionalLayer.PDS import PDS
class LIGHT(PDS):
def __init__(self,dev_id="+",dev_type="LightSensor",dev_location="+",shadow=True,starter=None,remote=True):
super(LIGHT, self).__init__(dev_id,dev_type,dev_location,shadow,starter,remote) |
10,407 | f20c1057d85210fed30923dbf467e6f8f442b79b | import os
from setuptools import setup, find_packages
from setuptools.command.install import install
class CustomInstall(install):
def run(self):
install.run(self)
for filepath in self.get_outputs():
if os.path.expanduser('~/.lw') in filepath:
os.chmod(os.path.dirname... |
10,408 | 48ab70febf4c0ab898ae58a96e6a95cb4566c21b | #!/bin/python3
# copyright Lauri K. Friberg 2021
"""System module."""
import sys
def is_even(number):
"""Find out if number is even."""
return (number%2)==0
def is_odd(number):
"""Find out if number is odd."""
return (number%2)==1
print ("©2021 Lauri K. Friberg. Weird algorithm. Look at https://cses.fi/... |
10,409 | 349f47e053cc529018782e6b05b975ba8c0431ff | numList = list(map(int, input().split()))
first = True
for i in numList:
if i % 2 != 0:
if first:
first = False
minOdd = i
else:
if i < minOdd:
minOdd = i
print(minOdd)
|
10,410 | 65833e4e9f17b32fd00f27bc62d38ff06a16b5e7 | import os
import re
import sys
import numpy
import netCDF4
import rasterio
from glob import glob
from datetime import datetime
from collections import namedtuple
from osgeo import osr
TileInfo = namedtuple('TileInfo', ['filename', 'datetime'])
def parse_filename(filename):
fields = re.match(
(
... |
10,411 | 0da06cefb231e9f2d4a910310966eb6cac752136 | # 修改串列中的元素
motorcycle = ["honda", "yamaha", "suzuki"]
print(motorcycle)
motorcycle[0] = 'ducati'
print(motorcycle)
# 在串列尾端新增元素
motorcycle.append('honda')
print(motorcycle)
# 在空串列中新增元素
motorcycle = []
motorcycle.append('honda')
motorcycle.append('yamaha')
motorcycle.append('suzuki')
print(motorcycle)
# 在串列中插入元素
m... |
10,412 | b187884e63b485c5cb62abdc787adef4bb73b20b | import numpy as np
class Clue:
def __init__(self, x_pos, y_pos, num, _direction, _length):
self.x_position = x_pos
self.y_position = y_pos
self.number = num
self.direction = _direction
self.length = _length
self.clue = ""
self.answer = np.ndarray(self.le... |
10,413 | 65a7b71fc54fe0f6a06b13053517929daa5054fc | import cv2 as cv
image_path = "C:/Users/xwen2/Desktop/109.JPG"
image = cv.imread(image_path)
image_size = image.shape
print(image_size) |
10,414 | f615ef8645204075d4157c1eb1ba471a550ba165 | def divisors(num):
sum = 1;
for i in range(2,int(num/2)+1):
if(num%i==0):
sum = sum +i;
return sum;
def is_abundant(num):
if(divisors(num)>num):
return True;
return False;
def do_loop(list,abundants,num,MAX):
res_list = list;
for i in range(num+1):
if(ab... |
10,415 | dfcc47eb3b83816855612bd0ee99c0171d47ef8d | import pdfquery
import xml.etree.ElementTree as et
from django.conf import settings
import os
import pandas as pd
from .models import Image
import json
from wand.image import Image as wi
import cv2
from .face_api import face_detect, face_verify
def processPdf(filename):
pdfPath = settings.UPLOAD_DIR + '/' + filena... |
10,416 | 5d6fc5369a6c9514e8d386d37e0c02281a46da7f | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 21:59:06 2016
@author: Eirik
"""
import numpy as np
import matplotlib.pyplot as plt
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
e = 1.6e-19
m_p = 1.672621637e-27 #Reference Pearson
r_D = 50.0E-03# radius
D = 90.0E-06 #valleygap
c = 3.0E... |
10,417 | 832caa8c3e815782b98143a08c3f8226f8db8536 | dicionario = {"um": 1, "dois": 2, "tres": 3, "quatro": 4, "cinco": 5, "seis": 6,
"sete": 7, "oito": 8, "nove": 9, "dez": 10, "onze": 11,
"doze": 12, "treze": 13, "catorze": 14, "quatorze": 14,
"quinze": 15, "dezesseis": 16, "dezessete": 17, "dezoito": 18,
"dezen... |
10,418 | c737a456cc6c0c35418221bc39b84721fafe20df | from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import detail_route, list_route
from django.contrib.auth.models import User
from rest_framework import serializers
from jose import jwt
from rest_framework.views import APIVi... |
10,419 | b6d7654052b94d3282fb19872e575b7c104ceb7f | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
10,420 | 225d65394029d91972a9c65d82180a8c48b6657e | from Factories.FirebaseFactory.FirebaseClient import FirebaseClient
class WalletFirebaseRepository(FirebaseClient):
def __init__(self):
super().__init__()
self.collection = "wallets"
|
10,421 | 90371d77c7c43381281c301fdac05bd3412a7eac | from tkinter import *
root = Tk()
def f():
root.geometry("20x20")
print("A")
root.after(50, f)
root.mainloop() |
10,422 | e4c7195fc2eb653bcb52843761209b0141e6b259 | import os, unittest, argparse, json, client
import xml.etree.ElementTree as ET
class TestPerson(unittest.TestCase):
test_data = ('first_name,surname,age,nationality,favourite_color,interest\n'
'John,Keynes,29,British,red,cricket\n'
'Sarah,Robinson,54,,blue,badminton\n')
def test_json_file(s... |
10,423 | 0091a099e73fd55adfc7899bbdb86d7ae6171854 | import cv2
rect_width = 10
rect_height = 5
def get_vertical_lines_2(image, line_count):
row = image.shape[0]
col = image.shape[1]
vertical_lines = []
for i in range(col):
count = 0
for j in range(row):
px = image[j, i]
if px == 255:
count += 1
... |
10,424 | a2a0c4db2cce39bc3426f3bd6d39957dcb8df655 | from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User, Group
from rest_framework.viewsets import ReadOnlyModelViewSet
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_clas... |
10,425 | b27879a5677a2108f02ea41fecededc280c04162 | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# the angles of rotations
theta1 = 3*2*pi/31
theta2 = 7*2*pi/31
theta3 = 11*2*pi/31
# we read streams of length from 1 to 30
for i in range(1,31):
# quantum circuit with three qubit... |
10,426 | f032da298207c0e38945f673148cd92dc6d50c5e | from numpy import *
def predict_ratings(US, SV, m, u, v, tt, num_test):
pr = [0]*num_test
for j in range(num_test):
user_id = tt[j, 0]
movie_id = tt[j, 1]
r = u[user_id]
c = v[movie_id]
pr[j] = float("{0:.4f}".format(dot(US[r, :], SV[:, c]) + m[0, c]))
re... |
10,427 | fbb94abedcccc82c76cbbd6fc1c98414cd1f7050 | # Python
from __future__ import annotations
# Internal
from server import server
|
10,428 | 8efd15dc91886dc5418852bad00e4455298e3044 | ''' split.py
Split Data into train (80%) and validate (20%)
Run from root of project as
python scripts/split.py
'''
import os
import glob
import shutil
def mkdir(dirname):
if not os.path.isdir(dirname):
os.mkdir(dirname)
VALIDATE_DIR = "data/validate"
mkdir(VALIDATE_DIR)
TRAIN_DIR = "data/train"
mkdir(T... |
10,429 | 5baae0826b0f6f57ce43b17ec73dd30e15dbc46a | #!/usr/bin/python2
from stadium import ui
import pytest
import mock
class TestListDialogController:
def test_cancel_calls_callback(self):
# Cancel should call cancel_func
a = []
def cancel_func():
a.append('cancelled')
def select_func():
a.append('s... |
10,430 | 8fb696d63c786d144c157d5678b55b80f171d98d | #!/usr/bin/python2
import pygame.joystick
class Joystick:
def __init__(self):
print "Creating Joystick"
self.errors = []
self.init()
self.set_buttons(0, 1, 2, 3,8)
def init(self):
print "Initialising joysticks"
if(pygame.joystick.get_init()):
print "Joystick module active - restarting"
pygame... |
10,431 | 19000b8c3d8e3f5bebaa32c98cf694332d2a0f12 | import os
import sys
# 부모디렉토리 참조를 위한 설정추가
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from user import User
user = User('test123','홍길동')
# 초기패스워드 조회
print(user.get_passowrd())
# get full name
if user.get_full_name() == '홍길동':
print('pass => get full name : ', user.get_full_na... |
10,432 | 38b701c0715ecd70c326c13f97505879c8a2c2c6 | # Generated by Django 2.0.10 on 2019-04-30 11:24
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Alertas',
fields=[
... |
10,433 | 5e7273c8f9f5ba54c3f9469612df271c40918a2c | import glob
import os
import numpy as np
from chainer import dataset
from chainer.dataset import download
from chainercv.datasets.cityscapes.cityscapes_utils import cityscapes_labels
from chainercv.utils import read_image
class CityscapesSemanticSegmentationDataset(dataset.DatasetMixin):
"""Semantic segmentati... |
10,434 | b5d218b2cd0f1222144e02367aa6cd4700044eea | """Module containing base class for lookup database tables.
LookupDBObject defines the base class for lookup tables and defines
relevant methods. LookupDBObject inherits from DBObjectUnsharded and
extends the functionality for getting, creating, updating and deleting
the lookup relationship.
"""
from vtdb import db_o... |
10,435 | 8b4887e22726f0cf571ebea0174fcef42681a3ce | '''
Abril 17
Autor: Vitoya
'''
theBoard = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
boardKeys = []
for key in theBoard:
boardKeys.append(key)
def printBoard(board):
print(board['7']+'|'+board['8']+'|'+board['9'])
print('------')
... |
10,436 | 35be3e3d4596a80cf26a3c1e47da41d85a9efc86 | import requests
import json
import csv
from os.path import dirname
def sendMessage(jsonId):
baseURLDir = dirname(__file__)
json_open = open(baseURLDir + '/tmp/json/' + jsonId + '.json', 'r')
json_load = json.load(json_open)
with open(baseURLDir + '/data/webhookURL.csv') as f:
reader = csv.... |
10,437 | e1b547b86f286e57f948dc3f7ec5b068ab63b75e | from flask import Flask
from flask import render_template, request, url_for, jsonify
import pickle
import numpy as np
import pandas
app = Flask(__name__,template_folder="templates")
model = pickle.load(open("rf_model.pkl","rb"))
label = pickle.load(open("label_encoder.pkl","rb"))
columns = ["age","workclass","fnlgwt... |
10,438 | 9049371a4c88edf184c6f83ad164bb4e1f50c0d4 | from pyBuilder import *
class MyGUIBuilder(BuildCMakeTarget):
def __init__(self):
self.initPaths()
def extract(self):
res = self.unzip('files/mygui-*.zip')
# unpack dependencies, needed for freetype
res |= self.unzip('files/OgreDependencies_MSVC_*.zip', self.path+'/mygui-*')
return res
def configur... |
10,439 | 0b847c67efc34cd2e4673f611bf337dd62fabe1f | # coding: utf-8
# @Time : 2020/7/10 11:00
# @Author : Liu rucai
# @Software : PyCharm
import random
import pandas as pd
import numpy as np
import os
import datetime
import sys
isGO = True
list = []
def sum_list(bool_list, n, now_sum):
global isGO
global list
if isGO == False:
return list
... |
10,440 | adf7ab792f7539dfe6ff90ed2d5d18b6ddd7398c |
def wrap_around(string, offset):
offset = offset % len(string)
return string[offset:] + string[:offset]
|
10,441 | cfe897ed9651a3bc8eae8c0c739d353e0106f461 | """import smtplib
import email.utils
#from smtplib import SMTP
massge = "this is just letter from python"
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
except:
print ("Something went wrong...")
mail.starttls()
mail.login('boooooo.2018@gmail.com','adgjmpw12345')
mail.sen... |
10,442 | 6bece2b738cab259221b05dd4df1ad247f2d6d83 | #!/usr/bin/env python
__author__ = "Alberto Riva, ICBR Bioinformatics Core"
__contact__ = "ariva@ufl.edu"
__copyright__ = "(c) 2019, University of Florida Foundation"
__license__ = "MIT"
__date__ = "Mar 19 2019"
__version__ = "1.0"
import sys
import gzip
import os.path
import subprocess as sp
# Global
... |
10,443 | e3aa7c9485f02828bd969a5dc9bdd72b8e47f050 | # This is the weather module.
import keys
from urllib.request import urlopen
from twilio.rest import Client
import json
def is_valid(number, digits):
if len(number) != digits or not number.isdigit():
return False
def get_degree(zip_code):
if not is_valid(zip_code, 5):
return False
url = ... |
10,444 | fb3c3cdab3e7e304e685afa3d226ace324d59bc5 | # Generated by Django 2.1.5 on 2019-01-09 00:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_db_logger', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='statuslog',
options={'order... |
10,445 | 3bb5e10459e633a57993be7fb33377c48bdf769b | from flask import Flask, render_template
from game_of_life import GameOfLife
app = Flask(__name__)
game_of_life = None
@app.route('/')
def index():
GameOfLife(20, 20)
return render_template('index.html')
@app.route('/live')
def live():
life = GameOfLife()
if life.counter > 0:
life.form... |
10,446 | 8072c709f042a0be7a05b727bd0f32fae852eb78 | from gensim.models import Word2Vec
import gensim.downloader as api
corpus = api.load('text8')
model = Word2Vec(corpus)
model.wv.save("text8vectors.wordvectors")
|
10,447 | 205ac6e49769dabdd0ab09cd58606005f040e43e | # to read in an integer and double it
# python script.py
user_input = int(input('Type in an integer ')) # converts user input to int
double = user_input * 2 # multiply user input by 2
# print('User input = {}'.format(double))
print('You entered {}: Result doubled = {}'.format(user_input, double))
|
10,448 | 9810e045fefda259ba17ba3db90a162bfd92d553 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from to... |
10,449 | 2de35309d010027f3fdcedc5f0b42493a6ce6809 | import os
import logging
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import defaultdict
from time import time
class DataLoader:
"""
Utility class for loading various types of data from CSV files
"""
def __init__(self, id_prefix='', header_file=Non... |
10,450 | 18bbe7d9961aeac2db08d8115f575cabd756b559 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,... |
10,451 | dd70fe2c48b9f094ecea75f1426ac453fba7e3cf | # Generated by Django 3.1.2 on 2020-10-09 08:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0002_product_product_id'),
]
operations = [
migrations.AlterField(
model_name='product',
name='detail',
... |
10,452 | 77e53110f7585128f08dfe2ba76176035530af57 | # -*-coding:utf8-*-
################################################################################
#
#
#
################################################################################
"""
模块用法说明: 登录的引导页
Authors: turinblueice
Date: 2016/7/26
"""
from base import base_frame_view
from util import log
from gui_widg... |
10,453 | fd98dc891bdee68eb0d26638d91493da43a2d6f5 | #!/usr/bin/python
# Version 0.05
#
# Copyright (C) 2007 Adam Wolk "Mulander" <netprobe@gmail.com>
# Slightly updated by Mikael Berthe
#
# To use this script, set the "events_command" option to the path of
# the script (see the mcabberrc.example file for an example)
#
# This script is provided under the terms of the G... |
10,454 | f54bc661b9400206bafe571051f4fe4721e27cf2 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import ngraph.op_graph.hetr_grpc.hetr_pb2 as ngraph_dot_op__graph_dot_hetr__grpc_dot_hetr__pb2
class HetrStub(object):
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Build... |
10,455 | aa497969a588e15beb447df88a90b8ab1e6e7af4 | listdata = list(range(5))
ret1 = reversed(listdata)
print('원본 리스트 ', end='');print(listdata);
print('역순 리스트 ', end='');print(list(ret1))
ret2 = listdata[::-1]
print('슬라이싱 이용 ', end='');print(ret2)
|
10,456 | 35f07233857de4103826fe132654c3814cf65d02 | from Qt import * |
10,457 | 6b3934c1a1e7db09a524005485ced8b1a218dc0d | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OpenNebula Driver for Linstor
Copyright 2019 LINBIT USA 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/LICEN... |
10,458 | 7413ffdb53524a72e59fae9138e1b143a9a2e046 | import os
import curses
import random
class CaroBoard(object):
"""A class handle everything realted to the caro board"""
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[' ' for x in range(self.width)] for y in range(self.height)]
self._turnCount = 0
def ConfigBoar... |
10,459 | 6ef8f6ab961db2cd66cdf90f7cd254bce23e9434 | """
pyeventhub - a CLI that sends messages to an Azure Event Hub.
"""
import asyncio
import random
import time
import json
from itertools import count
from datetime import datetime, timedelta
from argparse import ArgumentParser
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData... |
10,460 | 65b4f90ee9b19c1a6406ab99f370a01aa9a8b79c | from itertools import product
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
P = primes(1000000)
def num (n, ba... |
10,461 | 3bcf4f4a4cfcb83fc088f60c119bd4f6c0320d48 |
# -*- coding: utf-8 -*-
import rivescript
import interaction
import re
import diccs
import pickle
import os
def give_card(text,card_options):
buttons=[]
for option in card_options:
buttons.append({
"type":"postback",
"title":option,
"payload":"DEVELOPER_DEFINED_PAYLO... |
10,462 | ea552e4771c4fec4b9992a96bf0996b2f76b46cc | """
Entradas
compra-->int-->c
salidas
Descuento-->flot-->d
"""
c=float(input("digite compra"))
#caja negra
d=(c*0.15)
total=(c-d)
#Salidas
print("el total a pagar es de :"+str(total))
|
10,463 | 6237ba43195b7b69706e5d46b0627423177c12e3 | from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Localite)
admin.site.register(User)
admin.site.register(Groupe)
admin.site.register(Membre)
admin.site.register(Alerte)
admin.site.register(SuiviAlerteGroupe)
admin.site.register(SuiviAlertePerso)
admin.site.registe... |
10,464 | 2e039c917d6c8267ad71fd88085122aa7759cd79 | import os
import requests
import re
def main():
print('start download test')
with requests.get('http://tedisfree.github.io/abcdef', stream=True) as r:
if r.status_code!=200:
print('failed to download file (code=%d)' % r.status_code)
if 'Content-Disposition' not in r.headers:
... |
10,465 | f5f21e75a61dab08f6efb88b0e6d47b39617378d | import logging
from urllib.request import urlopen, Request, HTTPError, URLError
import json
logger = logging.getLogger()
class CustomResourceResponse:
def __init__(self, event):
self.event = event
self.response = {
"StackId": event["StackId"],
"RequestId": event["RequestId"... |
10,466 | 5a3e8d74198a054ca3a259ec5826bdb7b40f8672 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTableWidgetItem
import Estate
import login
... |
10,467 | 4ca92509dcea2fb058f1278be4269f85939db5b3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on
@author: a.mikkonen@iki.fi
"""
import time
import scipy as sp
from matplotlib import pyplot as plt
def power_law_profile(nn):
n = 7
yperR = sp.linspace(0,1, 1000)
u_rat = (yperR)**(1/n)
# plt.plot(yperR, u_rat, 'k:', label=r"$\frac{\over... |
10,468 | f510b19b9cd2b13fb7cf6033c3180622c2e410da | # q2b.py
# Name:
# Section:
# TODO: fill sv_recursive
# m is a matrix represented by a 2D list of integers. e.g. m = [[3, 0, 2, 18],[-1, 1, 3, 4],[-2, -3, 18, 7]]
# This function returns the Special Value of the matrix passed in.
def sv_recursive(m):
# your code here
return 0 # change
|
10,469 | a5f5cf0a0965e5bafc578a0c4bf0dad9d4714e00 | #
# * The Plan class for the <i>groupby</i> operator.
# * @author Edward Sciore
#
from simpledb.materialize.GroupByScan import GroupByScan
from simpledb.materialize.SortPlan import SortPlan
from simpledb.plan.Plan import Plan
from simpledb.record.Schema import Schema
class GroupByPlan(Plan):
#
# * Crea... |
10,470 | 6618c741754d4dcc209e95a3a9e56814ac9243c4 | #!/usr/local/bin/python3
from lib import *
if __name__ == '__main__':
input = [str.split("\t") for str in open('./input.txt', 'r').read().strip().split("\n")]
print("solution: {}".format(Solver().solve(input)))
|
10,471 | c372dc232f0a7e10145d1b15e6457373ce2f9abb | from dataChest import *
import matplotlib.pyplot as plt
# import os
file_path = 'GapEngineer\\Nb_GND_Dev01\\Leiden_2020Feb\\LIU\\Q1\\03-16-20\\QP_Tunneling_PSD\\HDF5Data'
file_name = 'cvd2133wum_QP_Tunneling_PSD.hdf5'
# ftag = file_name.split('_')[0]
print(file_path.split('\\'))
dc = dataChest(file_path.split('\\'))
... |
10,472 | b51705afbfedb1f8b33fa0457c98262670a151a2 | pattern = {'N':(1,5,2,3,0,4),'S':(4,0,2,3,5,1),'E':(3,1,0,5,4,2),'W':(2,1,5,0,4,3)}
dice_num = input().split()
for x in input():
dice_num = [dice_num[i] for i in pattern[x]]
print(dice_num[0])
|
10,473 | 446ce06b97ac1183d73546eb376cb79a71ac9176 | from flask import Flask, abort, make_response, jsonify, render_template
from util.utils import Member,getSchedules
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.config['JSON_SORT_KEYS'] = False
@app.route('/', methods=['GET'])
def index():
api_list = ['/members', '/member/20','/schedules']
r... |
10,474 | a29022140fd7603594c802b27b442c676ab167b7 | __author__ = 'sunary'
from time import sleep
from multiprocessing import Process
class StreamEachId():
'''
Each stream listen each id
'''
def __init__(self):
self.list_process = []
def run(self):
list_ids = [i for i in range(10)]
for id in list_ids:
self.lis... |
10,475 | 02026c1c6f3de9d2b0ce9dcd0c438dfaf8ef8a56 | #Read in the data
import pandas as pd
import numpy as np
dete_survey = pd.read_csv('D:\\dataquest\\projects\\dete_survey.csv')
#Quick exploration of the data
pd.options.display.max_columns = 150 # to avoid truncated output
dete_survey.head()
#Read in the data
tafe_survey = pd.read_csv("D:\\dataquest\\proje... |
10,476 | de39e4dd694431a279c829b01de68084773403c1 | from invoke import task, run
@task(aliases=["sh"])
def shell(ctx):
"""
Runs django's interactive shell
:return:
"""
run("./manage.py shell_plus", pty=True)
@task(aliases=["mg"])
def migrate(ctx):
"""
Runs the migrations
:return:
"""
run("./manage.py migrate", pty=True)
@tas... |
10,477 | 6174ea75dd183ccef94441f055397f0e3e9dca8d | import sys
import json
import numpy as np
# import tensorflow as tf
from scipy import sparse
from sklearn.metrics import f1_score
from sklearn import svm
import random
def print_request(r):
"""Print a request in a human readable format to stdout"""
def fmt_token(t):
return t['shape'] + t['after']
... |
10,478 | b90d6c878b312820f3b4da10d47ec93a7fd27057 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 18 20:03:29 2014
3. Faça um programa que crie dois vetores com 10 elementos aleatórios entre 1 e 100. Gere um
terceiro vetor de 20 elementos, cujos valores deverão ser compostos pelos elementos
intercalados dos dois outros vetores. Imprima os três vetores.
@author: portela... |
10,479 | a94dc128ab45088bd205ce6cd334eb1a05898a18 | import cv2
import numpy as np
from tensorflow.keras.utils import Sequence
import pydicom
from rle2mask import rle2mask
class DataGenerator(Sequence):
'Generates data for Keras'
def __init__(self,
all_filenames,
batch_size,
input_dim,
n_channe... |
10,480 | 98d2a9b7f4b143fc875e7d14267b02aee7930c12 | from .declaration_parser import DeclarationParser
class ModelParser:
def __init__(self, model):
self.model = model
def parse_model(self):
dp = DeclarationParser(self.model)
for decl in self.model.declarations:
dp.parse_declaration(decl, type(decl).__name__)
return ... |
10,481 | 80026f6fa46b3c73aa80ae34745b90719af95e41 | import utilities as ut
import numpy as np
from skimage import data, io, color, transform, exposure
from pprint import pprint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def listToRows(x) :
X = np.array([x])
r = X.shape
return np.reshape(x, (r[1], -r[1]+1))
def addCol... |
10,482 | 1ab8a7c2bd7a5eab94986675ac8d6bb429618150 | def recite(start_verse, end_verse):
days = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth']
presents = ['a Partridge',
'two Turtle Doves',
'three French Hens',
'four Calling Birds',
... |
10,483 | 73fb3fc8f7bee256475e7e28db9e98d71565f9b2 | import json
import logging
import logging.config
import logging.handlers
from .agent import Agent
from .log import Log
from .profile import Profile, Snmp
with open("/monitor/config/python_logging_configuration.json", 'r') as configuration_file:
config_dict = json.load(configuration_file)
logging.config.dictConfig... |
10,484 | 83a1153e25ecedf23d081afb3508764cf4101432 | # configuring PYTHONPATH (By default, this will add the src and lib directory for each of your dependencies to your PYTHONPATH)
import roslib; roslib.load_manifest('sap_pkg')
# import client library
import rospy
# import messages
import auction_msgs.msg
# import services
import auction_srvs.srv
import auction_commo... |
10,485 | 7dcf4c203debfd0eee120597d760a799daf074c6 | #%% load dataset
import numpy as np
import DL
# change the directory
Label_Train, Features_Train, Label_Test, Features_Test = DL.ReadFile("H:\\4th comp\\NN\\cifar-10-batches-py")
# features dimensions (m, c, h, w)
#%% training
batch_size = 128
num_epochs = 20
num_classes = 10
hidden_units = 100
input_dimensions =... |
10,486 | 2d080d53d3f88bcb1a4cfe8040fe015e950b8b54 | import socket, json, sqlite3, threading, time
from datetime import datetime
RegCount = 12
#bytesToSend = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
bytesToSend = (255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255)
#bytesToSend = (170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170)
#bytesToSend = (255, 255, ... |
10,487 | a7cec4b8152740086e40d37c303eccab4e485641 | # Generated by Django 3.1 on 2020-10-29 13:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0046_stream'),
]
operations = [
migrations.AlterField(
model_name='stream',
name='ss',
field=model... |
10,488 | 6c4db2f9f02bd3d1975509bd47efe0067da03735 | from functools import reduce
numTestCases = int(input())
def go():
global opt,p,s
numParties = int(input())
parties = []
for i in range(numParties):
si, pi = [int(x) for x in input().split(' ')]
pi = float(pi)/100
parties.append((pi,si))
p,s = zip(*parties) # arranged in descending... |
10,489 | 53c2b4434cd9b843bab99d1a48e36942f5d35a09 | #!/usr/bin/python3
# ------------------------------------------------
# Honas state rotation script. Run regularly to
# automatically archive Honas state information.
# ------------------------------------------------
import datetime
import glob
import os
import argparse
import shutil
import logging
import logging.han... |
10,490 | e60fb6412fecc8d0b4978799a6b6fd822d12c533 | #!/usr/bin/env python
__author__ = "Pedro Heleno Isolani"
__copyright__ = "Copyright 2019, QoS-aware WiFi Slicing"
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Pedro Heleno Isolani"
__email__ = "pedro.isolani@uantwerpen.be"
__status__ = "Prototype"
" Python script for making graphs from CSV output"
impor... |
10,491 | b6bc2cc268adeb29cf8d916661c13141d4b1f8e9 | """
Script to Query ArangoDB. See README.md.
Author: Volker Hoffman <volker.hoffmann@sintef.no>
Update: 06 June 2018
"""
from __future__ import print_function
import pyArango.connection
import json
import time
import argparse
def connect_to_database():
conn = pyArango.connection.Connection(arangoURL='http://192... |
10,492 | 95942c9e825639385c7d4b1f73ee615215053478 |
"""Services Module."""
import shell
def run_service_command(serviceName, command='status'):
"""Run Service Command."""
command = "sudo service %s %s" % (serviceName, command)
shell.run_shell_cmd(command)
def stop_service(serviceName):
"""Stop Service."""
run_service_command(serviceName, 'stop'... |
10,493 | 62273a72af52cea2659a7139fc702a49cd05d4d9 | #!/usr/bin/env python
import os
from setuptools import setup
with open('README.rst', encoding='utf-8') as readme_file:
readme = readme_file.read()
try:
# Might be missing if no pandoc installed
with open('CHANGELOG.rst', encoding='utf-8') as history_file:
history = history_file.read()
except IOEr... |
10,494 | b6774fa2338acc8cf754dc1cd1511743236c9b17 | #coding=utf8
import sys,os,os.path
reload(sys)
sys.setdefaultencoding('utf8')
from doclib import doclib
from numpy import *
import nmf
def getarticlewords():
dl=doclib('data/doclib/')
dl.load()
return dl.allwords,dl.articlewords,dl.articletitles
def makematrix(allw,articlew):
wordvec=[]
for w,c in... |
10,495 | 48d91936f900dadae69629e1b48d581c32f47534 | #!/usr/bin/env python3
""""
Model that uses standard machine learning method - linear regression
It can be used for whole molecules or their fragments, but it has to be consistent.
If we use fragments then the similarity is computed as average similarity of the descriptors.
input model_configuration should look li... |
10,496 | 10f0d1eee2cf39fc6e07662c6efc230020daa10b | from pymongo import MongoClient
from bson.raw_bson import RawBSONDocument
from bson.codec_options import CodecOptions
import requests
import json
client = MongoClient()
codec_options = CodecOptions(document_class=RawBSONDocument)
client = MongoClient('mongodb://localhost:27017')
db = client['jacaranda-db']
def pr... |
10,497 | 597bda36405f8e362256e108a5ad017fd8cd0ce8 |
from cgml.constants import SCHEMA_IDS as SID
from cgml.validators import validateSchema
def makeSchema(n_in=None,
n_out=None,
nLayers=1,
inputDropRate=2,
modelType=None,
costFunction=None,
activationFunction="tanh",
... |
10,498 | b3b25c18a4af5c6d83c0f935aba1b074519b15a3 | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate
from django.contrib.auth.views import logout
from django.contrib.auth.mixins import PermissionRequiredMixin
from .forms import StudentRegisterForm, TeacherRegisterForm, NewGroupForm, NewAssignmentForm
f... |
10,499 | f8512db4b717612e06515a617592384039aec9ad | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, chardet, codecs, math, pymongo, Queue, os, re
from foofind.utils import u, logging
from threading import Thread
from multiprocessing import Pool
class EntitiesFetcher(Thread):
def __init__(self, server, results):
super(EntitiesFetcher, self).__init... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.