text stringlengths 38 1.54M |
|---|
#!/usr/bin/python
""" Script for computing observables from a transport+hydro hybrid output """
import argparse
import os.path
import math
import array
from collections import defaultdict
from hic import flow
from hybrid_analysis.event_selection import centrality_filters as cf
from hybrid_analysis.file_reader import h... |
from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import StudySession, Participant
from login.serializers import TeacherSerializer, SubjectSerializer, UserSerializer, UserShortVersionSerializer, TeachingFacilitySerializ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import collections.abc
import datetime
import json
from typing import List, Dict, Any, Union, Optional
from azure.functions import _abc as azf_abc
from azure.functions import _queue as azf_queue
from . import meta
class Q... |
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
from button.button import Button
import threading
import time
class LedButton(Button):
def __init__(self, ... |
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .decorators import onlyStaff
from schedule.form import appointment
from .models import Schedule
from django.contrib.auth.decor... |
from tfidf import ExtractiveSummarizer_tfidf
from bayes import ExtractiveSummarizer_bayes
import random
import pickle
space = "---" * 72 + "--"
if __name__ == "__main__":
article, actual_summary = None, None
with open("dataset.pkl", "rb") as fp:
x, y = pickle.load(fp)
seed = random.randrange(len(x... |
from django.db import models
class UserManager(models.Manager):
def register_validator(self, post_data):
errors = {}
if len(post_data['first_name']) < 3:
errors['first_name'] = "First name must be 3 characters or more!"
if len(post_data['last_name']) < 3:
errors[... |
from git import Repo
repo = Repo('/home/pi/Examensarbete/scripts')
repo.index.add(['/running-configs'])
repo.index.commit('Auto-commit')
origin = repo.remote('Dmajstrolov/python-ciscoconfig.git')
origin.push()
|
"""
Given a binary tree, determine if it is height-balanced. For this problem,
a height-balanced binary tree is defined as: a binary tree in which the depth
of the two subtrees of every node never differ by more than 1.
"""
class Solution:
def isBalanced(self, root):
if not root:
return True
return... |
from depender.graph.structure import StructureGraph
def test_structure_layout(graph: StructureGraph) -> None:
graph.layout(base_distance_x=1, base_distance_y=1)
# Check X coordinates
assert graph.nodes["1"]["x"] == 0.0
assert graph.nodes["2"]["x"] == -1.5
assert graph.nodes["3"]["x"] == -0.5
a... |
#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
# von Iliyana Kamenova, Yeon Joo Oh, Iuliia Nigmatulina
# Big Data, FS19
# Ex04
import os
import string
import re
import csv
from collections import Counter
INPUT_DIR = "../data/"
NEG_PATH = "../data/lexicon/negative-words.txt"
POS_PATH = "../data/lexicon/positive-words... |
# Generated by Django 3.0.7 on 2020-09-07 14:21
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('hr', '0015_auto_20200907_1949'),
]
operations = [
migrations.AddField(
model_name='salaryemp',
... |
class A(object):
val = 1
def foo(self):
self.val +=3
def op(self):
A.val +=5
a = A()
b = A()
a.foo()
b.op()
c = A()
print(a.val)
print(b.val)
print(c.val)
|
###########################################################################################
# membershipcleanup - clean up membership worksheet for use by RA club membership registration system
#
# Date Author Reason
# ---- ------ ------
# 10/29/13 Lou Ki... |
from setuptools import setup
setup(
name='krds_openapi_client',
version='0.1.0',
packages=['krds_client'],
url='https://github.com/jixiangqd/krds_openapi_sdk',
license='Apache License 2.0',
author='KSC_DB',
author_email='KSC_DB@kingsoft.com',
description='Kingsoft Cloud Service OpenAPI ... |
#Automatically created by SCRAM
import os
__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/OSUDisplacedHiggs/Configuration/',1)[0])+'/cfipython/slc6_amd64_gcc530/OSUDisplacedHiggs/Configuration')
|
# Import dependecies
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time
# Set global variables to store the data from the funtions
# Deafult parser - it can be orriden at fucntion level
parser= 'html.parser'
# Default browser wait time to allow page load.
wait_time = 5
# Save n... |
def mainMenu():
print("1) Substraction[-]")
print("2) Addition[+]")
print("3) Multiplication[*]")
print("4) Division[\]")
a = int(input("Your choice: "))
if a==1:
print("Substraction")
b=float(input("Enter the minuend: "))
c=float(input("Enter the subtrahend: "))... |
nums = [100, 200, 300, 400, 500]
nums.remove(400)
nums.remove(500)
print(nums) # pop은 맨 마지막 요소 제거
|
# Generated by Django 3.2.4 on 2021-06-19 15:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CategoryProduct',
fields=[... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import datetime
from django.db import models
class Products(models.Model):
name = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
description = models.CharField(max_length=500, blank=True, null=True)
image1 = models.ImageField(upload_to='product_images', blank=True, null=True)
price = model... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def search(array, element):
"""
Binary search
Complexity
Memory
O(n) - since no additional data structure used
Time
Always Log(n) with base 2 - because after every comparison,
length of array divided by 2
:param array: sorte... |
#coding=utf-8
import torch
from torchvision import models
from collections import namedtuple
from SPP_Layer import SPPLayer
def VggBaseModel(model_type, model_origin_param, dropout, output_size):
if model_type == 'vgg13':
model = models.vgg13(pretrained=False)
elif model_type == 'vgg16':
... |
__author__ = 'gbhardwaj'
def isBalanced(symbolString):
'''
:param symbolString: "()()()" - balanced == True
:return:
'''
retList = []
isBalanced = True
index = 0
while index < len(symbolString) and isBalanced:
if symbolString[index] in ['(','{','[']:
retList.append(s... |
dic = {
"a": 100,
"b": 200,
"c": 300,
"d": 400,
"sum" : [10,20,30,40,50]
}
#print(dic)
#print(dic["a"])
#print(dic["d"])
#print(dic['sum'])
for key in dic.keys(): # keys라는 함수를 사용하면 dictionary 안의 모든 데이터를 읽어옴.
print(key, "=", dic[key])
del dic['sum']
print(dic)
if 'sum' in d... |
from mlsolver.formula import Atom, And
from mlsolver.kripke import KripkeStructure, World
from mlsolver.tableau import Node
def test_semantic_p_and_q():
worlds = [
World('1', {'p': True, 'q': True})
]
relations = {}
ks = KripkeStructure(worlds, relations)
mpl = And(Atom('p'), Atom('q'))
... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
INTERNAL_MODULES_BRANDS = {
'Scripts',
'Builtin',
'd2',
'testmodule',
}
def get_enabled_instances():
enabled_instances = []
readable_output = []
instances = demisto.getModules()
for instance_nam... |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgphotoalbum"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import OpenThreads
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgText
from osgpypp im... |
import matplotlib.pyplot as plt
Bitcoin = []
Timestamp=[]
Timestamp_labels=[]
months=["January","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"]
file = open('6to447_sorted.txt', 'r')
data = file.readlines()
for i in range(1,len(data)-1):
date_string=""
date=int(float(data[i].split(',')... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2015, Matthew Brennan Jones <matthew.brennan.jones@gmail.com>
# A module for identifying Sega Dreamcast games with Python 2 & 3
# It uses a MIT style license
# It is hosted at: https://github.com/workhorsy/identify_dreamcast_games
#
# Permission is hereby ... |
import numpy as np
import json
import matplotlib.pyplot as plt
import copy
import pandas as pd
from tqdm import tqdm
from os import listdir
PATH = "../Datasets/"
SECTIONS = 5
class RNN:
def __init__(self, k=1, m=100, seq_length=25, eta=0.1, sig=0.01):
self.m = m # Dimensionality of hidden state
... |
# Problem #80
# Given the root of a binary tree, return a deepest node. For example, in the following tree, return d.
#
# a
# / \
# b c
# /
# d
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):... |
def processObj(file):
vertices = []
faces = []
normals = []
textures = []
cont = 0
for line in file:
try:
lineArr = line.rstrip().split()
if lineArr[0] == 'v':
vertices.append(list(map(float, lineArr[1:])))
elif lineArr[0] == 'f':
... |
import mongoi
import numpy as np
import stats
import errors
import tensorflow_fold as td
PREFERRED_BATCH_SIZES = {
'snli': {
'train': 32,
'dev': 32,
'test': 32
},
'carstens': {
'all': 32
}
}
class Batcher:
"""Base class for a wrapper for a batch generator.
Th... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 10:13:17 2020
@author: 정한민
"""
import pymysql
import json
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
#====local_DB==========
db_host_ip = '127.0.0.1'
db_id = 'root'
db_password = '1234'
db_name = 'cloling_test'... |
import numpy as np
import numexpr as ne
from abc import ABC, abstractmethod
class Kernel():
def kernel(self, X, Y, gamma, var):
X_norm = -gamma * np.einsum('ij,ij->i', X, X)
Y_norm = -gamma * np.einsum('i,i->', Y, Y)
return ne.evaluate('v * exp(A + B + C)', {\
'A' :X_norm,\
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 liangliang <liangliang@Liangliangs-MacBook-Air.local>
#
# Distributed under terms of the MIT license.
class Solution(object):
def maximumSubsequenceCount(self, text, pattern):
"""
:type text: str
:type patt... |
import scrapy
from scrapy.http import Request
from crawler.crawler.utils import get_global_settings
from db import get_collection_article,find_one
from crawler_assist.tidy_req_data import TidyReqData
from crawler.crawler.items.crawl_article import CrawlArticleItem,CrawlArticleReadDataItem
from time import time
from ui ... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from tfsnippet import Distribution, Normal
import ipdb
class RecurrentDistribution(Distribution):
"""
A multi-variable distribution integrated with recurrent structure.
"""
@property
def dtype(self):
return self._dtype
@property
def... |
from Menu import menu
def start():
"""
__author__: Jan Arendt(7297944) and Niklas Ponzer(4467584)
__version__: 1.0.0
python_version: 3.7
python_moduls:
- pygame
- shapely
Copyright content:
Music and Sound:
- drive_sound.wav: "Sound effects obtained from https://... |
# Package
from User import (
UserForm,
ValidateForm,
LoginForm,
LostPassword,
ResetForm,
SetPassword,
MagicUserEdit,
)
from event import (
EventForm,
)
from contest import (
ContestForm,
)
from village import (
V... |
string = input('Enter string: ')
length = len(string);
first_space = (20 - length - 2)//2
last_space = 20 - length - 2 - first_space
print('*' * 20)
print('*' + (' '* first_space) + string + (' '* last_space) + '*')
print('*' * 20) |
#Example 8
#GLOBAL VARIABLES
#Variables that are created outside of a function (as in all of the examples above) are known as global variables.
#Global variables can be used by everyone, both inside of functions and outside.
x = "Prem"
def myfunc():
print("My Name is " + x)
myfunc()
#The global Keyword
#Normally, whe... |
# -*- coding: utf-8 -*-
"""
Library with simple funcions for learning and better understanding polarization concepts.
It contains:
A function for rotating optical elements such as polarizers and waveplates
defined by a Jones Matrix.
A function for plotting polarizarion ellipses of a given polarization state.
"""
... |
#
# @lc app=leetcode.cn id=138 lang=python3
#
# [138] 复制带随机指针的链表
#
# @lc code=start
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
... |
import socketio
import json
import time
import datetime
import board
import busio
from digitalio import DigitalInOut, Direction, Pull
from adafruit_pm25.i2c import PM25_I2C
import obdUtils
RESET_PIN = None
SENSOR_TYPE = 'AIR'
ERROR = 'ERR'
INFO = 'INFO'
RETRY_INTERVAL = 1 #Delay in seconds when retrying to connect... |
# Write a program to look for lines of the form:
""" Write a program to look for lines of the form:
New Revision: 39772
Extract the number from each of the lines using a regular expression
and the findall() method. Compute the average of the numbers and
print out the average as an integer. """
import re
f... |
from django.db import transaction
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from apps.user.permissions import is_organize... |
import random
from practice import Practice
lowerBound = 0
upperBound = 16
def trialDataGenerator():
while True:
x = random.randint(lowerBound, upperBound)
yield((x,), str(x * 16))
taskName = 'Multiples de 16'
instructions = 'Effectuez mentalement la multiplication par 16.\nPetit truc... |
from Pages.page import Page
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
class AuthPage(Page):
PATH = '/login'
LOGIN = '//input[... |
#OrConditional.py
import re
randStr= "1. Dog 2. Cat 3.Turtle"
regex= re.compile(r"\d\.\s(Dog|Cat)")
matches=re.findall(regex, randStr)
for i in matches:
print(i)
|
from flask import Blueprint, request, json
from flask_jwt_extended import jwt_required
from extension import mongo
from api.app.Users.HandlerDetectUserFace import detect as dt, detect_test
from api.app.Helper.JSONEncoder import JSONEncoder
detect = Blueprint('detect', __name__)
@detect.route('/facedetect', methods=['... |
from es_client.builder import Builder, ClientArgs, OtherArgs
from es_client.version import __version__
|
import wikipedia
import sys
wikipedia.set_lang("it")
elemento = sys.argv[1:]
page = wikipedia.page(elemento)
print(wikipedia.summary(elemento))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def validate(node=root, _min=float('-inf'), _max=float('inf')):
if node... |
'''
blueprint for this folder
'''
from flask import Blueprint
# create blueprint first
bp = Blueprint('frontend', __name__.split('.')[0], url_prefix='', static_folder='static/frontend', template_folder='templates/frontend')
# fsrc specific
from . import home
from . import membership_frontend
from . import racingteam... |
from sqlalchemy import Table, Column, Integer, ForeignKey
from .db import Base
articles_tags_table = Table(
"blog_articles_tags_association_table",
Base.metadata,
Column("article_id", Integer, ForeignKey("blog_articles.id"), primary_key=True),
Column("tag_id", Integer, ForeignKey("blog_tags.id"), prim... |
import cv2
import numpy as np
from scipy.signal import find_peaks
from scipy.ndimage import gaussian_filter1d
from text_detector import detect_text_box
def my_find_peaks(array, height_ratio, distance_between_peaks):
"""
Peak finding algorithm in which we can select the required height of the
returned peak... |
parar = 1
while parar == 1:
sexo = str(input('Digite seu sexo: '))
if sexo.lower() == 'm' or sexo.lower() == 'f':
parar = 0 |
# Week 03: Lab 2.3.4 Variables and State
# This program ouptputs a random number between 1 and 10
# Author: Ross Downey
import random
min = int(input ("Please enter the minimum range number:"))
max = int(input ("Please enter the maximum range number:"))
number = random.randint (min, max)
print ("This is a random num... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 11:23:12 2020
@author: billcoleman
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# visualisations
import matplotlib.pyplot as plt
import seaborn as sns
# Storage
import pickle
from sklearn.ext... |
from typing import List, Set, Dict
from enum import Enum
from pathlib import Path
import re
IMAGE_EXTENSIONS: Set[str] = {".png", ".jpg", ".bmp", ".gif"}
VIDEO_EXTENSIONS: Set[str] = {".mp4", ".mov"}
class FileType(Enum):
NONE = 1
IMAGE = 2
VIDEO = 3
class FileData:
def __init__(self, path: Path, ... |
import torch
import sys
import numpy as np
from contextualized_topic_models.models.ctm import CTM
from contextualized_topic_models.datasets.dataset import CTMDataset
from contextualized_topic_models.evaluation.measures import Matches, KLDivergence, CentroidDistance
from contextualized_topic_models.utils.data_preparatio... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 11:54:20 2019
@author: Sai Karthik Yadav
"""
import numpy as np
import preprocess
import tensorflow as tf
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
class Data:
def __init__(self, Category, Directory, label_dict,... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 11:57:51 2021
@author: m1390
"""
import numpy as np
import matplotlib.pyplot as plt
from utils import load_sparse_matrix
A = load_sparse_matrix('usps_norm_5NN.mat')
#%%
plt.spy(A[::10,::10],marker='.',markersize=6)
plt.xticks([], [])
plt.yticks([],[])
# plt.axis('off... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
author: Gangaprasad Koturwar
website: www.iitk.ac.in/~users/koturwar (internal site)
last edited: TMar 12, 2014
"""
import sys
import threading
import subprocess
import time
import urllib2
from PyQt4 import QtGui, QtCore
from PyQt4.Qt import *
hostname1 = None
passwd1 = ... |
import numpy as np
from spn.algorithms.Inference import add_node_likelihood, leaf_marginalized_likelihood
from spn.structure.leaves.parametric.Parametric import Gaussian, Categorical
from spn.structure.leaves.parametric.utils import get_scipy_obj_params
def compute_leaf_value(node, **kwargs):
if isinstance(node, ... |
from setuptools import setup, find_packages
setup(name = 'FRBID',
version = '1.0.0',
description = 'Fast Radio Burst Intelligent Distinguisher using Deep Learning',
author = 'Zafiirah Hosenie',
author_email = 'zafiirah.hosenie@gmail.com',
license = 'MIT',
url = 'https://github.com/Z... |
# writing files
# "w" is for write
with open("out.txt", "w") as f:
f.write("this is my file!")
# reading files
# "r" is for read
with open("out.txt", "r") as f:
print(f.read())
|
# coding: utf-8
"""
Knetik Platform API Documentation latest
This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
OpenAPI spec version: latest
Contact: support@knetik.com
Generated by: https://github.com/swagger-api/swagger-codeg... |
import requests # 导入网络请求模块
# 头部信息
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/72.0.3626.121 Safari/537.36'}
proxy = {'http': 'http://116.140.53.173:22016',
'https': 'https://116.140.5... |
# -*- coding: utf-8 -*-
import pickle
import docreader
import numpy
import mmh3
import math
import sys
from collections import Counter
from struct import *
import os
from os import lseek, read, write
import re, string, timeit
import time
from string import lower
import solution
import expr
all_words = []
class Node:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 19 08:11:59 2020
@author: dohyu
"""
from pkmnobject import get_data
import csv
namelist = []
with open('allfile.csv',newline='') as pokefile:
reader = csv.reader(pokefile)
for row in reader:
if row[0] != 'Name':
... |
def fibonacci (num):
if isinstance (num,int) and (num>0):
return fibonacci_aux(abs(num))
else:
return "Error"
def fibonacci_aux (num):
if num==0:
return 1
elif num == 1:
return 1
else:
print (( num-1) + (num-2))
return fibonacci_aux(num-1) + fibonacci_aux (num-2)
|
import game_framework
from pico2d import *
import game_world
PIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm
SPEED_KMPH = 10.0 # Km / Hour
SPEED_MPM = (SPEED_KMPH * 1000.0 / 60.0)
SPEED_MPS = (SPEED_MPM / 60.0)
SPEED_PPS = (SPEED_MPS * PIXEL_PER_METER)
class Eru_Illustration:
image = None
def __init__(self... |
# -*- coding: utf-8 -*-
obj = [ "python", "cpp", "c", "git" ]
def tot( *args ):
"""
Parameters
----------
*args : int variables
Returns
-------
sum of this variables .
"""
sm = 0
for arg in args:
sm += arg
return sm
def hello( s ):
"""
... |
import requests
from bs4 import BeautifulSoup
import pymysql
import exDate
from Pic import *
import urllib
from django.contrib import messages
from django.shortcuts import render
from dataApp import models
from catchdata import *
import datetime
# Create your views here.
def aa(req):
return render(re... |
def powerset(input, output, result=set()):
if len(input) == 0:
result.add(output)
return
powerset(input[1:], output + "", result)
powerset(input[1:], output + input[0], result)
return result
if __name__ == "__main__":
print(powerset("abcd", ""))
|
from __future__ import with_statement
from builderror import BuildError
import base64
import hashlib
import os
import re
htmlEscapeTable = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<"
}
""" Produce entities within text. """
def htmlEscape(text):
return "".join(htmlE... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'ac$', 'rozklad.views.predmet_autocomplite'), #обро... |
# coding=utf-8
from objects.models import *
from django.http import HttpResponse
from django.conf import settings
import os
import urllib
def serve_config(request, mac_addr, cfg_name):
mac_addr = urllib.unquote(mac_addr)
try:
machine = Machine.objects.get(mac=mac_addr.lower())
if cfg_name == ... |
class Solution:
def climbStairs(self, n: int) -> int:
if n < 3:
return n
second_last_step, last_step = 1, 2
# For a given postion you can reach it by
# 1 step + number of way you reached last step
# 2 step + number of way you reached second last step
# 1 ... |
import frontmatter
import pandas as pd
import copy
from datetime import datetime
stockable = pd.read_excel('_Appendix.C_Full.detail.stocktake.xlsx')
with open('dummy.md') as f_dummy:
dummy = frontmatter.load(f_dummy)
description_header = 'Purpose and description of dataset'
nhi_header = 'Have_(encrypted)_NHI'
phi_... |
from num2words import num2words
def numberLetterCount(num):
sum = 0
for l in num2words(num):
if l.isalpha():
sum += 1
return sum
sum = 0
for i in xrange(1, 1001, 1):
sum = sum + numberLetterCount(i)
print sum |
import numpy as np
import math
class DATA(object):
def __init__(self, n_question, seqlen, separate_char, name="data"):
self.separate_char = separate_char
self.n_question = n_question
self.seqlen = seqlen
def load_data(self, path):
f_data = open(path , 'r')
user_to_q_sequ... |
#!/usr/bin/env python
import sys
import pickle
import pandas as pd
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import Multinomial... |
def refs(year, genre):
import pandas as pd
import requests
from bs4 import BeautifulSoup
# import re
import json
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random
from numpy import NaN as nan
... |
#!/usr/bin/env python
import pkg_resources;
pkg_resources.require( "Cheetah" )
import sys
from Cheetah.Template import Template
import string
from subprocess import Popen, PIPE
import os.path
assert sys.version_info[:2] >= ( 2, 4 )
def run( cmd ):
return Popen( cmd, stdout=PIPE).communicate()[0]
templates = [... |
'''
Created on Jul 19, 2012
@author: autumn
'''
import sys
import argparse
import swiftconsole.ui.commands as commands
cmd_parser = argparse.ArgumentParser(description='Swift console')
cmd_parser.add_argument('command', choices = ['show-ring', 'push-config'])
if len(sys.argv) < 2:
cmd_parser.print_help()
sy... |
#!/usr/bin/python
from pychartdir import *
# Create an AngularMeter object of size 300 x 300 pixels with transparent background
m = AngularMeter(300, 300, Transparent)
# Set the default text and line colors to white (0xffffff)
m.setColor(TextColor, 0xffffff)
m.setColor(LineColor, 0xffffff)
# Center at (150, 150), sc... |
import torch
import torchvision
print(torch.cuda.is_available())
#a = torch.Tensor(5 ,3)
#a = a.cuda()
#print(a)
def f():
yield 1
yield 2
yield 3
yield 4
f1 = f()
print([next(f1) for i in range(4)])
def fibonacci():
a = [1, 1]
while True:
a.append(sum(a))
# add next element for ... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# There is also a User model, which is not explicitly written here because it is done automatically by django
# User:
# _id
# firstname
# lastname
# username
# password
# email
class Settings(mode... |
from typing import Union
import sys
import commons.errors as errors
"""
Change type String to Bool.
String型からBool型への変更.
"""
def str_to_bool(string: str) -> bool:
return str(string).lower() in ["true", "1", "yes"]
"""
Change type String to Int.
String型からInt型への変更.
"""
def str_to_int(string: str) -> Union[int, bool... |
class Module:
"""
Provides information, context and functionality of the current module.
"""
def __init__(self, symbol_resolver, function_table, mutation_table,
features, root_scope, service_typing):
self.symbol_resolver = symbol_resolver
self.function_table = function_... |
import datetime
import requests
class Forecast():
def __init__(self, data, response, headers):
self.response = response
self.http_headers = headers
self.json = data
def update(self):
r = requests.get(self.response.url)
self.json = r.json()
self.response = r
... |
import numpy as np
import cv2
camera = cv2.VideoCapture(0)
#frame = cv2.imread("./frame.png")
while True:
(grabbed, frame) = camera.read()
if not grabbed:
break
h, w = frame.shape[:2]
newWidth = int(w * 40 / 100)
newHeight = int(h * 40 / 100)
frame = cv2.resize(frame, (newWidt... |
from tkinter import *
tk = Tk()
canvas = Canvas(tk,width=800,height=400)
canvas.pack()
my_image= PhotoImage(file="ball.gif")
canvas.create_image(50,50,anchor=NW, image=my_image)
tk.mainloop() |
class Formatter():
def format(parser_output1, parser_output2, similarity_checker_output):
completed_output = parser_output1+parser_output2+similarity_checker_output
return completed_output |
"""
Tektronix RSA_API Multi-Unit Example
Date edited: 8/17
Windows 7 64-bit
RSA API version 3.11.0038
Python 3.6.1 64-bit (Anaconda 4.3.0)
NumPy 1.11.3, MatPlotLib 2.0.0
Download Anaconda: http://continuum.io/downloads
Anaconda includes NumPy and MatPlotLib
Download the RSA_API: http://www.tek.com/model/rsa306-software... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.