text stringlengths 38 1.54M |
|---|
from keras.applications.vgg16 import VGG16
m = VGG16()
with open("vgg16.json", "w") as f:
f.write(m.to_json())
m.save_weights("vgg16.h5")
|
#
# -------------------------------------------------------------------------
# Copyright (c) 2018 Intel Corporation Intellectual Property
#
# 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... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def merge_sort(self,list):
# 1. return if at the bottom
# -- In this case, we are at the bottom when the list siz... |
#!/usr/bin/env python
print("Loading...")\
from gpiozero import DigitalOutputDevice
from time import sleep
pin = DigitalOutputDevice(21)
print("Turning fan on for 20 seconds, turn potentiometer to test.")
pin.on()
sleep(20)
print("Turning fan off")
pin.off()
print("Exiting")
pin.close()
exit()
|
import numpy as np
import scipy.io
from scipy.optimize import least_squares
import scipy.stats
cam_data = scipy.io.loadmat('cameraParameters.mat')
f = cam_data['focal']
pixelSize = cam_data['pixelSize']
pp = cam_data['pp']
K = np.array([[f[0][0]/pixelSize[0][0], 0, pp[0][0]], [ 0 ,f[0][0]/pixelSize[0][0], pp[0][1]], ... |
import requests
import pandas as pd
from bs4 import BeautifulSoup
import json
from boto.s3.connection import S3Connection
from boto.s3.key import Key
tournament = 'RBC Heritage'
tournament_link = 'rbc-heritage'
year = 2015
# create connection to bucket
c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLt... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# -- Function Print and Export Object
# ----------------------------------------------------------------------------
# -- (c) David Muñoz Bernal
# ----------------------------------------------------------------------... |
# Copyright (c) 2019 Cloudify Platform Ltd. 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 ap... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from deeplearning.helpers import L_layer_model, L_model_forward, normalize_input
DATA_DIR = './data/'
EXPORT_DIR = './exports/'
PLOT = True
def main():
# analyze_data()
X_train, X_test, Y_train, cache_test = basic_p... |
import tweepy
import os
import json
from decimal import *
from json.decoder import JSONDecodeError
import TravelDealDB as tddb
import TwitterHelper
from Airports import *
def add_defaults(body):
default = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
... |
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(raw_input()) # read a line with a single integer
for c in xrange(1, t + 1):
p = raw_input()
n = 0
while '-' in p:
for i in range(len... |
# -*- coding: utf-8 -*-
from selenium import webdriver
from bs4 import BeautifulSoup
import time
searchWords = ['hallo','how to kill','my teacher is','what is switzerland']
driver = webdriver.Firefox()
driver.get("https://www.google.ch")
for word in searchWords:
print "searching for: " + word
driver.find_element_... |
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, format_string
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
parking = spark.read.format('csv').options(header='true',inferschem... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# ***** BEGIN LICENSE BLOCK *****
# This file is part of EV3WebController.
# Copyright (c) 2014-2015 Cédric Bonhomme.
# All rights reserved.
#
#
#
# ***** END LICENSE BLOCK *****
import os
from flask import Flask
from ev3.ev3dev import Motor
#from ev3.lego import LargeM... |
from django.contrib import admin
from apps.forbidden_words.models import ForbiddenWord
class ForbiddenWordAdmin(admin.ModelAdmin):
list_display = ('id', 'word')
admin.site.register(ForbiddenWord, ForbiddenWordAdmin)
|
from roman import *
file = open('roman.txt', 'r')
content = file.read()
file.close()
s = 0
for u in content.split('\n') :
s+= len(u) - len(roman(dec(u)))
print(s) |
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from setuptools import find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
name = 'fhnw.office2plone'
long_description = (
read('README.rst')
+ '\n' +
read('CHANGES.rst')
+ '\n' +
... |
from time import sleep
import time
import datetime
from firebase import firebase
import urllib2, urllib, httplib
import json
import os
import Adafruit_DHT
import RPi.GPIO as GPIO
#URL firebase
URL_Firebase ='https://'
#Cria objeto firebase
firebase = firebase.FirebaseApplication(URL_Firebase, None)
#grava no data... |
# Formations AI for Mount & Blade by Motomataru
# rel. 01/03/11
# This function attaches AI_triggers only to mission "lead_charge"
# For other missions, add to end of triggers list like so: " ] + AI_triggers "
# Make sure to comment out competing AI triggers in the mission templates modified
# For example, for... |
"""
connection.py
"""
import re
import socket
import select
class Connection(object):
buffer = None
line_buffer = None
socket = None
def __init__(self, address):
self.line_buffer = ""
self.buffer = "<b>Attempting to connect to '%s' ...</b>\n" % address
self.socket = so... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-11-19 12:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_auto_20161112_1610'),
]
operations = [
... |
DEFAULT_VIEW_NAME = "Quali"
SNMP_CONF_PATH = "/etc/snmp/snmpd.conf"
IFACE_CONF_PATH = "/etc/network/interfaces"
SNMP_SERVICE_NAME = "snmpd"
|
#!/usr/bin/env python
import roslib; roslib.load_manifest('fmExtractors')
import rospy
from fmMsgs.msg import *
from math import *
class matrix:
# implements basic operations of a matrix class
def __init__(self, value):
self.value = value
self.dimx = len(value)
self.dimy = len(value[0])
if value == [[... |
# -*- coding: utf-8 -*-
import datetime
import pytest
from django.core.exceptions import ValidationError
from apps.merchandise.goods.factories import GoodFactory, ShopFactory
from apps.merchandise.goods.models import Good
pytestmark = pytest.mark.django_db
class TestGoods:
def test_date_validation(self):
... |
#
# @lc app=leetcode.cn id=200 lang=python3
#
# [200] 岛屿数量
#
# @lc code=start
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
row, col = len(grid), len(grid[0])
count = 0
def dfs(i,j):
grid[i][j]= '0'
fo... |
'''
项目名称:
创建时间:
'''
__Author__ = "Shliang"
__Email__ = "shliang0603@gmail.com"
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from PIL import Image
import os
import sys
#IMAGES_PATH = './JPEGImages' # 图片集地址
IMAGES_PATH = sys.argv[1] # 图片集地址
IMAGES_FORMAT = ['.jpg', '.JPG'] # 图片格式
IMAGE_SIZE = 200 # 每张小图片的大小
IMAG... |
# file: a_simple_sub.py
from mqtt import MQTTClient
import pycom
import sys
import time
import ufun
wifi_ssid = "AndroidAP"
wifi_passwd = "stalin1986"
broker_addr = "192.168.43.113"
#MYDEVID = "iot_10"
dev_id = 'test'
def settimeout(duration):
pass
def on_message(topic, msg):
print("Recei... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
names = ['Bob','Jessica','Mary','John','Mel']
grades = [76,95,77,78,99]
bsdegress = [1,1,0,0,1]
msdegrees = [2,1,0,0,0]
phddegrees = [0,1,0,0,0]
GradeList = zip(names,grades,bsdegress,msdegrees,phddegrees)
df = pd.DataFrame(data = GradeList, column... |
##this program allow to input some arguments to the function
def another_Introduction(name, city):
print("hello my name is", name)
print("I live in ", city)
another_Introduction("Maria", "Cork")
another_Introduction("Almir", "Paris")
def num_time(string, times):
for i in range(times):
print(stri... |
from helpers.sql_queries import SqlQueries
from helpers.create_tables import CreateTables
from helpers.check_queries import CheckQueries
__all__ = [
'SqlQueries',
'CreateTables',
'CheckQueries'
] |
'''
The data is standart response.
Postgresql database is being used.
Data from the database is taken as 500000 row.
The dataset size is 500000 rows.
All data is captured, processed and sent at one time. Blocks each other.
At the end of the transaction, the connection is disconnected.
'''
from aiopg.sa import create_e... |
import pandas as pd
dataset_2017 = pd.read_csv('datasets/datatran2017.csv', sep= ';', encoding='ISO-8859-1', header=0).dropna().drop_duplicates()
dataset_2018 = pd.read_csv('datasets/datatran2018.csv', sep= ';', encoding='ISO-8859-1', header=0).dropna().drop_duplicates()
dataset_2019 = pd.read_csv('datasets/datatran20... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 23:01:47 2021
@author: yinxiaoru
"""
import os,sys
input_dir = os.path.abspath(sys.argv[1])
result_dir = os.path.abspath(sys.argv[2])
for dirname, _, filenames in os.walk(input_dir):
for file in filenames:
print(os.path.join(os.pat... |
from django.contrib import messages
from django.core.mail import send_mail
from django.shortcuts import render
from django.http import HttpResponse
from ecom.models import User, Item, Basket, BasketItem
from django.core import serializers
appname = 'ecom'
def loggedin(f):
def test(request):
if 'username'... |
from Phone import app, api
from Phone.Control import global_controller
from Phone_Config_Boundary.Config_Sample_Boundary \
import Config_Sample_Boundary
from Phone_Config_Boundary.Config_Logger_Boundary \
import Config_Logger_Boundary
#
# Get the version of the API
#
version = global_controller.get_value('versi... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Album(models.Model):
id_album = models.FloatField(primary_key=True)
nombre = models.CharField(max_length=50, blank=True, null=True)
fecha = models.CharField(max_length=50, blank=True, null=True)
clas... |
#coding:utf-8
import csv
import hashlib
import json
import random
import re
import string
import time
from random import Random
from googletrans import Translator
from ali1688.helper import str_replace_new
import os
import sys
from random import Random
from hashlib import md5
root_path = os.path.abspath('.')
d... |
import bisect
import functools
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
unfolded = functools.reduce(list.__add__, matrix, [])
pos = bisect.bisect_left(unfolded, targe... |
# Uses python3
# Problem Description
# Task. The goal in this problem is to find the minimum number of coins needed to change the input value
# (an integer) into coins with denominations 1, 5, and 10.
# Input Format. The input consists of a single integer m.
# Constraints. 1 ≤ m ≤ 10**3 .
# Output Format. Output th... |
"""
Defines a Turing machine implementation.
"""
import automata.dfa as dfa
import automata.packs as pk
import automata.state as st
class TuringMachine(dfa.DFA):
"""
A Turing machine implementation.
It is inherited from DFA because it shares the same interface
but adds directly on it. DPDA is not suita... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "l... |
# -*- coding: utf-8 -*-
import time
import socket
import re
import xml.etree.ElementTree as ET
from actions import exec_cmd
import json
import os
def readjson(jfile):
f = open(jfile, 'r')
jsondata = json.load(f)
return jsondata
def setenv(jsondata):
# 各グループ毎にパラメーターの変数格納
groupdict = jsondata["OsE... |
# deseasonlize and normalize the summertime MDA8O3 from 2014 to 2021 in BTH, YRD and PRD regions
import numpy as np
from netCDF4 import Dataset
def moving_avg(data):
data_avg = np.zeros((92))
for m in range(0,len(data)-21):
data_avg[m] = data[m+21]-np.nanmean(data[m:m+21])
return data_avg
de... |
#Connor Oh & Benjamin Avrahami -- TEAM Socks
#SoftDev2 -- pd9
#K11 -- Ay Mon Go Git It From Yer Flask
#2020-03-19
from flask import Flask, render_template, request, session, redirect, url_for
from utl import movies
import os
import pymongo, json
from bson.json_util import loads
client = pymongo.MongoClient('localhost'... |
"""
Aggregation functions that can be used as arguments to the Field.apply method
"""
#from numba import jit
import numpy as np
def mask(values, above=None, below=None):
"""Mask values not between above and below, in other words
mask values below above and above below, its confusing but makes sense!
"""
if above... |
from Individual import *
from Problem import *
from copy import deepcopy
from Operators import *
class DifferentialEvolution:
def __init__(self, problem, NP, operator, max_iteration=1000, F=0.9, CR=0.2):
self.NP = NP
self.F = F
self.CR = CR
self.problem = problem
... |
import sys
INF = sys.maxsize
def dijkstra(start, goal, n, graph):
distance = [INF] * n
distance[start] = 0
visit = [False] * n
while True:
k = -1
m = INF
for i in range(n):
if m > distance[i] and not visit[i]:
m = distance[i]
k = i
... |
from neo4j import GraphDatabase
uri = "neo4j://localhost:7687"
user = "neo4j"
password = "password"
def pupulate():
driver = GraphDatabase.driver(uri, auth=(user, password ))
|
# Generated by Django 3.1.5 on 2021-01-08 13:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nobat', '0004_auto_20210108_1703'),
]
operations = [
migrations.AlterField(
model_name='nobat',
name='amount',
... |
# -*- coding:utf-8 -*-
"""
@Time:2018/5/15 20:09
@Author:yuhongchao
"""
import turtle
import random
import numpy as np
from math import *
class Dot:
def __repr__(self):
return "Dot(" + repr(self.xcoord) + ", " + repr(self.ycoord) + ", " + repr(self.color) + ")"
def __init__(self, xcoord, ycoord, colo... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 13:20:38 2021
@author: reetb
"""
import os
os.chdir('C:/Users/reetb/Desktop/LouvainInfMax/InitialExpts/Plots')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import statistics
import numpy as np
th_imm_10 = [13547, 13550, 13666, 13605, 13726]... |
#https://www.hackerrank.com/challenges/pangrams
# Enter your code here. Read input from STDIN. Print output to STDOUT
string=raw_input()
def isPangram(str):
result=True
for i in range(97,123):
if not (chr(i) in str or chr(i-32) in str):
result=False
break
return result
prin... |
from django.shortcuts import render, redirect
from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template
import datetime
from . import forms, models
# Create your views here.
def index(request):
form_class = forms.ContactForm
is_contact_sent... |
"""hackerrank_Sam_And_Substrings
https://www.hackerrank.com/challenges/sam-and-substrings
"""
def solve(n):
MOD = 10 ** 9 + 7
acc = 0
for i, char in enumerate(n):
state = int(n[0]) if i == 0 else (int(char) * (i + 1)) % MOD + (state * 10 % MOD) % MOD
acc = (acc + state) % MOD
print ... |
import webkit, gtk
import os
window = gtk.Window()
browser = webkit.WebView()
window.add(browser)
window.set_default_size(370,170)
window.show()
browser.set_size_request(360,170)
browser.show()
browser.load_uri("file:///home/pi/smartmirror/apps/horoscope/url.html")
window.connect("delete-event",gtk.main_quit)
window.s... |
# -*- coding: UTF-8 -*.
'''
Update your function so that when the user calls the function with wrong type
as a parameter it says "One or both of your parameters are wrong type!"
(Don't remove the ZeroDivision exception!)
'''
yks = raw_input("Annappa yks: ")
kaks = raw_input("Annappa toenen: ")
def division(x, y):
... |
## Exercise 1
## Write a function using recursion to calculate the greatest common divisor of two numbers
## Helpful link:
## https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
def gcd(x, y):
## get remainder
r = x%y
## base case, no remainder
## then that "... |
import os
from random import shuffle, choice
from collections import namedtuple
class Juego:
def __init__(self, turnos):
self.mazo = []
self.cartas_j1 = []
self.cartas_j2 = []
self.read_file()
self.repartir_cartas()
self.comenzar_juego(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 12:35:12 2018
@author: claypooldj
"""
####Load packages
import csv
import os
import random
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import math
import pandas as pd
import seaborn as sns
"""
##-... |
from django.shortcuts import render
from django.views.generic import (View, TemplateView, DetailView, ListView, CreateView, DeleteView, UpdateView)
from . import models
from django.urls import reverse_lazy
class SchoolListView(ListView):
context_object_name = 'schools'
model = models.School
class SchoolDetai... |
def encrypt(st,key):
en=""
for i in st:
if(i.isupper()):
st=ord(i)+(key%26)
if(st>ord('Z')):
st=st-26
if(i.islower()):
st=ord(i)+(key%26)
if(st>ord('z')):
st=st-26
file2.write(chr(st))
file1=open(... |
'''
$ python download_and_convert_data.py \
--dataset_name=imagedata \
--dataset_dir=.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from datasets import download_and_convert_imagedata
FLAGS = tf.compat.v1.app.flags.... |
# pylint: disable=missing-module-docstring
import os # pylint: disable=unused-import
import sys # pylint: disable=unused-import
def func(name): # pylint: disable=missing-function-docstring,unused-argument
try:
exec("1 + 1") # pylint: disable=exec-used
val = eval("2 + 2") # pylint: disable=eval... |
import turtle
#initializing the Drawing Objects
tee = turtle.Turtle()
outline = turtle.Turtle()
eyes = turtle.Turtle()
nose = turtle.Turtle()
eye_ball = turtle.Turtle()
#Adjusting the attributes
eye_ball.speed(0)
outline.speed(0)
eyes.speed(0)
eye_ball.pensize(8)
#Design for the outline
outline.color("black","yellow... |
import global land.land
import test_util
def _test_yaml1:
LandYaml *y = land_yaml_new("test1.yaml")
land_yaml_add_scalar(y, "a b c")
land_yaml_save(y)
land_yaml_destroy(y)
LandYaml *y2 = land_yaml_load("test1.yaml")
assert_string(land_yaml_get_scalar(y2.root), "a b c")
def _test_yaml2:
La... |
import cv2
import time
from predict_image import *
def show_webcam(mirror=False):
json_file = open('nn_struct.json', 'r')
model = json_file.read()
json_file.close()
model = model_from_json(model)
model.load_weights('best_weights_256.hdf5')
cam = cv2.VideoCapture(0)
while True:
ret_v... |
import tensorflow as tf
class BiLSTMSelfAttention(object):
def __init__(self, params):
self.params = params
def __call__(self, inputs, targets=None):
sequence_length = inputs['sequence_length']
input_embeddings = inputs['input_embeddings']
with tf.variable_sco... |
#元组就是不可改变的列表 元组使用()表示,元素和元素之间使用逗号隔开,数据类型没有限制,可以叫只读列表
#清朝的皇帝(努尔哈赤 皇太极 顺治 康熙 雍正 乾隆)
huang = ("努尔哈赤", "皇太极", "顺治", "康熙", "雍正", "乾隆","嘉庆","道光","光绪","咸丰")
# huang[1] = "朱元璋" #报错 tuple不支持元组的修改
print(huang)
#print((8+3)*7) #小括号不仅表示元组还可以表示优先级
tu = (1)
print(type(tu)) #只有1个元素会先表示优先级表示整型,所以加逗号
tu = (1,)
print(type(tu))
t... |
# Copyright (c) 2018 CEA
# Author: Yann Leprince <yann.leprince@cea.fr>
#
# This software is made available under the MIT licence, see LICENCE.txt.
import numpy as np
from neuroglancer_scripts.transform import (
nifti_to_neuroglancer_transform,
matrix_as_compact_urlsafe_json,
)
def test_matrix_as_compact_ur... |
import time
import csv
import requests
from selenium import webdriver
import lxml
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.f... |
##### APP ENDPOINTS #####
from flask import Blueprint, Flask, jsonify, redirect, render_template, request, send_file
from flask_assets import Environment
from flask_cors import CORS, cross_origin
from base64 import b64encode
from boto3.dynamodb.conditions import Key, Attr
from decimal import Decimal
from operator impo... |
'''
Created on Dec 21, 2019
@author: Florin
'''
from resources.variables import DIVIDE_FACTOR
class NumberGenerator():
def __init__(self, start_value, multiply_factor):
self.current_value = start_value
self._multiply_factor = multiply_factor
def __next__(self):
self.current_value = ... |
"""This example composes several key steps into a pipeline that can estimate
the Essential matrix between a pair of images, given an estimate of the
intrinsics of the camera (that took those images.) The estimated essential
matrix is used to triangulate a set of seed points (to create a sparse 3D
point cloud,) and to d... |
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
from tkinter import filedialog
from tkinter import *
import matplotlib.pyplot as plt
from skimage import data, util
from skimage.draw import ellipse
from skimage.measure import label, regionprops
from skimage.transform import rotate
impo... |
# Import modules
import os
# Read input
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
inputFile = open(os.path.join(__location__, 'input.txt'), 'r')
input = inputFile.read().split("\n\n")
# PART 1: Count the number of yes answers for each and sum up
answers = input.copy()
for ... |
import numpy as np
import os
import mdv
import re
from bert_serving.client import BertClient
from termcolor import colored
from imgcat import imgcat
# config like this:
mdv.term_columns = 60
topk = 5
prefix_q = '##### **Q:** '
stop_prefix = '<h2 align="center">:zap: Benchmark</h2>'
start = False
questions = []
answer... |
# Copyright (c) 2018 Andrew R. Kozlik
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, di... |
# from rest_framework import serializers
# from api.models import Board
#
# class BoardSerializer(serializers.Serializer):
# id = serializers.IntegerField(read_only=True)
# title = serializers.CharField(required=False, allow_blank=True, max_length=100)
# type = serializers.CharField(max_length=20, default='... |
import pandas
## reading using read_csv in pandas
df=pandas.read_csv('hrdata.txt')
print(df)
print(type(df['Salary'][0]))
print(type(df['Hire Date'][0]))
df1=pandas.read_csv('hrdata.txt',index_col='Name') ## use the Name field as the index
print(df1)
df2=pandas.read_csv('hrdata.txt',index_col='Name',parse_dates=['... |
from tkinter import *
import messagebox
import tkinter
top = tkinter.Tk()
def p_h():
print("Hello")
mb = Menubutton(top, text = "condiments", )
mb.grid()
mb.menu = Menu(mb, tearoff = 0)
mb["menu"] = mb.menu
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton(label = "mayo", variable = mayoVar, comman... |
# Rename Tool Window Procedure
def RenamerTool(name):
string renameWind = "RenamerScript"
for sels, i in enumerate(sels):
newName = "%s_%i" %(name, i)
cmds.rename(sels, newName)
# ---- Above is the actual function, and Below
class RenamerUI():
def__init__(self):
self... |
import pickle
from string import punctuation
import nltk
import numpy as np
import pandas as pd
import torch
import torch.utils.data as tdata
from gensim.models import Doc2Vec
from nltk.corpus import stopwords
from sklearn import preprocessing
from tqdm import tqdm
def load_torch_data(dataset: tdata.Dataset, ratio: ... |
from django.conf.urls import patterns, url
from questions.rest_views import QuestionCatalogueList, QuestionCatalogueDetail, QuestionCatalogueSeevcam, \
QuestionDetails, QuestionListSeevcam, QuestionList
from dashboard.views import DashboardView as EmptyView
rest_patterns = patterns('',
ur... |
import re
#Question1
def get_middle_chars(given_str):
size = len(given_str)
sep = (size - 3)//2
given_str = given_str[sep:size-sep]
return given_str
#Question2
def append_in_the_middle(s1, s2):
middle = len(s1) // 2
print("{}{}{}".format(s1[:middle], s2, s1[middle:]))
#Question3
def string... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Functional tests for :module:`flocker.node._docker`.
"""
from __future__ import absolute_import
import time
from functools import partial
from docker.errors import APIError
from docker import Client
# Docker-py uses 1.16 API by default, which isn't su... |
def convertSeconds (y):
day = y/86400
remainder = y%86400
uren = remainder / 3600
remainder = remainder % 3600
minuten = remainder / 60
seconden = remainder % 60
return '{0}:{1}:{2}:{3}'.format(int(day), int(uren), int(minuten), int(seconden) )
seconden = int(input('Geef het ... |
import pygame
from constants import *
class Runner:
def __init__(self, row, col, color, name):
self.row = row
self.col = col
self.name = name
self.color = color
self.x = 0
self.y = 0
self.calc_pos()
def move(self, row, col):
self.... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "hello!"
@app.route('/nba')
def show_nba_stuff():
return "Placeholder for nba text Placeholder for nba text Placeholder for nba text Placeholder for nba text"
@app.route('/soccer')
def show_soccer_stuff(... |
from nose.tools import assert_true
import requests
def test_request_response():
resp = requests.get('http://jsonplaceholder.typicode.com/todos')
assert_true(resp.ok)
|
# Generated by Django 2.1 on 2018-09-03 23:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0005_auto_20180903_1724'),
]
operations = [
migrations.AlterField(
model_name='events',
name='address',
... |
class Monostate(object):
__internal_state = {'A':5,'B':6}
def __init__(self):
self.__dict__ = self.__internal_state
class Monostatev2(object):
_internal_state = {}
def __new__(cls, *args, **kwargs):
obj = super(Monostatev2, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls._... |
"""
Created By : <Auto generated code>
Created On :
Reviewed By :
Reviewed On :
Version :
"""
import json
from django.http import HttpRequest
from examsystemapp.api.base_controller import BaseController
from examsystemapp.models.student import StudentModel
from examsystemapp.services.student_service import StudentServi... |
#!/usr/bin/env python3
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.datasets import mnist
from keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = np.reshape(x_train, [-1, 784])
x_test = np.reshape(x_test, [-1, 784])... |
"""
Making diagrams easily.
Need to have graphviz (pip install graphviz), but also need the backend of this python binder:
Mac: brew install graphviz
Linux: sudo apt-get install graphviz
Windows: google it
"""
import re
from typing import Optional
import json
from collections import defaultdict
from functools import ... |
"""
Spike train synchrony plots
---------------------------
.. autosummary::
:toctree: toctree/spike_train_synchrony
plot_spike_contrast
"""
# Copyright 2017-2023 by the Viziphant team, see `doc/authors.rst`.
# License: Modified BSD, see LICENSE.txt for details.
import matplotlib.pyplot as plt
import numpy ... |
name = []
print(len(name))
name.append("William")
if len(name) == 0:
print("The list is empty")
else:
print("The list contains sth")
name.append("John")
name.append("Amanda")
print(len(name))
print(name[2])
for i in range(len(name)):
print(name[i])
for i in range(len(name)):
print(str(i + 1) + ". "... |
from locast import get_model
from locast.api import *
def get_comments(request, object, comment_id=None):
comment_model = get_model('comment')
if comment_id:
comment = check_comment(object, comment_id)
return APIResponseOK(content=api_serialize(comment))
comments = comment_model.objects.... |
#What is the first term in the Fibonacci sequence to contain 1000 digits?
from math import ceil,log10,sqrt
def main(digits = 1000): return ceil((digits-1+log10(sqrt(5)))/log10((1+sqrt(5))/2))
print main()
|
import numpy as np
import pandas as pd
rad_feat = pd.read_csv('/media/bmi/Windows/MICCAI CHALLENGE 2020/BraTs 2020/validation_radiomic_features_full.csv')
rad_feat = rad_feat.sort_values(by = ['Brats20ID'])
surv_data = pd.read_csv('/media/bmi/Windows/MICCAI CHALLENGE 2020/BraTs 2020/survival_evaluation.csv')
# pri... |
"""
188.
Hard
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
Exa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.