text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python3
#******************************************************************************
#
#"Distribution A: Approved for public release; distribution unlimited. OPSEC #4046"
#
#PROJECT: DDR
#
# PACKAGE :
# ORIGINAL AUTHOR :
# MODIFIED DATE :
# MODIFIED BY :
# REVISION :
#
# Copyrigh... |
import math
from unittest import TestCase, main
import numpy as np
from ... import IntegerProgram, LinearProgram
class TestRelax(TestCase):
def test_relax(self) -> None:
A = np.array([[1, 2, 3, 4], [3, 5, 7, 9]])
b = np.array([-9, 7])
c = np.array([1, 7, 1, 5])
z = 25
ip... |
import json, uuid
import pandas as pd
from abc import ABC, abstractmethod
import datetime
import pytz
class MainDatabase: #Class that represents main database of users, strips, sections, and active patterns
def __init__(self):
self.users_database = pd.DataFrame(columns=["User ID", "User Object"]) #DataFr... |
from flask import Flask, render_template, json, request, jsonify
from myModules import StockPrice as sc
reload(sc)
app = Flask(__name__)
class MyIterator:
def __init__(self, data):
self.data = data
self.length = len(data)
self.index = 0
def __iter__(self):
return self
... |
# -*- coding: utf-8 -*-
from PIL import Image,ImageDraw,ImageFont
import requests
import json
from datetime import datetime, timedelta
import os
import lxml.html as LH
from wechatpy import WeChatClient
def get_quote_json(date):
url = 'http://www.ecmagnet.com/magnet/materialquoteexact/?quote_date=%s' % date.strftime... |
def Max(inum):
x = [0 for x in range(10)]
string = str(num)
for i in range(len(string)):
x[int(string[i])] = x[int(string[i])] + 1
ans = 0
val= 1
for i in range(10):
while x[i] > 0:
ans= ans+ (i * val)
x[i] = x[i] - 1
val = val* 10
return a... |
# Copyright The OpenTelemetry Authors
#
# 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 ... |
from django.contrib import admin
from django.urls import include, path
import riddles.urls
from base.views import index
urlpatterns = [
path('', index, name='index'),
path('admin/', admin.site.urls),
path('riddles/', include(riddles.urls)),
]
|
import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'treelite/python'))
import treelite
model = treelite.Model.load('/tmp/bst-model.bin', 'xgboost')
model.compile(dirpath='./model', compiler='ast_java')
|
#
#3D Ising model on simple cubic lattice
#
#
import pyalps
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pyalps.plot
#%matplotlib inline
import numpy as np
#prepare the input parameters
parms = []
for l in [2,4,6,8,10,12]:
for t in np.linspace(0.01,6.0,60):
parms.append(
... |
import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r... |
# coding: utf-8
import yaml
from os import listdir
from os.path import isfile, join
import sys
from collections import Counter, OrderedDict
reload(sys)
sys.setdefaultencoding('utf8')
mypath = '.'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f)) and f.endswith('.yml')]
d = {}
l = {}
# print len(onl... |
import numpy as np
import pandas as pd
from _plot_func import *
from _helper_func import *
def print_categories(df, cols):
'''
:param df: Pandas DataFrame
:param cols: Categorical columns
:return: prints all the categories of the categorical columns given
'''
print("\n##########--levels of ca... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.hello, name='hello'),
url(r'^posts/$', views.view_posts, name='view posts'),
url(r'^add/$', views.add_post, name='add posts'),
url(r'^fake/$', views.fake_add, name='fake add'),
url(r'^ajax/likepost/$', views.like_... |
from django import forms
from .models import Character_sheet, Equipment
class Character_sheet_form(forms.ModelForm):
class Meta:
model = Character_sheet
fields = [
"name",
"gender",
"race",
"class_x"
]
class Equipment_f... |
import os
import re
import torch
import torchvision.transforms as transforms
from models import TransformerNet
from utils import load_image, save_image, get_device
from test_config import *
if __name__ == "__main__":
device = get_device()
content_image = load_image(test_image)
content_transform = transf... |
import os
import asyncio # noqa: F401
import discord # noqa: F401
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
class Announcer:
"""Configureable Announcements."""
__author__ = "mikeshardmind"
__version__ = "1.0"
def __init__(self, bot):
... |
import unittest
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def __str__(self):
return "[" + str(self.start) + "," + str(self.end) + "]"
class Solution:
... |
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fin.")
print("Yay! printing")
print("It'so boring with learing python!")
|
from .sitebase import SiteBase
from .scraper import Scraper
from database import orm
class Okky(SiteBase):
def __init__(self):
self.url = 'https://okky.kr/articles/tech'
def update(self):
scraper = Scraper('','','','')
soup = scraper.get_page(self.url)
articles = []
fo... |
#!/usr/bin/python
import sys,subprocess
text=sys.stdin.read().rstrip()
try:
p = subprocess.Popen(['xclip', '-i', '-selection', 'clipboard'], stdin=subprocess.PIPE)
p.stdin.write(text)
p.stdin.close()
retcode = p.wait()
except:
pass
|
"""GOEA and report generation w/bonferroni multiple test corrections from statsmodels.
python test_goea_rpt_bonferroni.py
python test_goea_rpt_bonferroni.py [LOG FILENAME]
"""
__copyright__ = "Copyright (C) 2016, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import sys... |
from scrapy import cmdline
cmdline.execute("scray crawl tianyancha".split())
|
#-------------------------------------------------------------------------------
# Name: gatherLux
# Purpose: reads in data from a directory containing multiple csv files
# of GPS log paths, which are transormed into a point cloud with an
# assigned simulated lux
# Final dataset in shp and gdb has a li... |
import argparse
import csv
import logging
import networkx as nx
import src.community_detection.girvan_newman as girvan_newman
import src.community_detection.k_means as k_means
import src.community_detection.label_propagation as label_propagation
import time
from networkx.algorithms.community.centrality import girvan_ne... |
import tushare as ts
import matplotlib.pyplot as plt
from datetime import datetime
import pandas as pd
df = ts.get_tick_data('600848',date='2014-01-09')
df =df.set_index('time')
df =df.sort_index()
df['price'].plot() |
# all endpoints related to caterer's view
from db_connector import *
from flask_app import *
from common import *
#Signup
@app.route('/api/v1/caterer/signup', methods = [ 'POST' ] )
def signup_caterer():
if request.method == 'POST':
cat_name = request.json.get('cat_name')
username = request.js... |
def naver_excel_make():
data = pd.read_csv(RESULT_PATH+'contents10000_20000.txt', sep='\t', error_bad_lines=False)
data.columns = ['title','date','company','link','contents']
#print(data)
#xlsx_outputFileName = '%s-%s-%s %s½Ã %sºÐ %sÃÊ result.xlsx' % (now.year, now.month, now.day, now.hour, now.minute, ... |
# relative ranks
def solution(nums):
result = [-1 for i in range(len(nums))]
count = 1
while count <= len(nums):
maximum = max(nums)
temp_index = nums.index(maximum)
result[temp_index] = str(count)
count += 1
nums[temp_index] = -1
if '1' in result:
result... |
import numpy as np
from method2d import *
import figure2d as F
from ClossNum import CheckClossNum, CheckClossNum2
def CheckIB(child, fig, max_p, min_p, l):
# 円
if fig==0:
x, y, r = child
w, h = l/2, l/2
# 正三角形
elif fig==1:
x, y, r, _= child
w, h = l/2, l/2
# 長方形
... |
from graphene import Connection, ConnectionField, String
from graphene.types import ObjectType
from .data_source_handlers import get_data_source_data, get_data_sources
class DataSource(ObjectType):
info = String()
name = String(required=True)
class DataSourceConnection(Connection):
class Meta:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 高阶函数
# 变量可以指向函数
print(abs(-10))
print(abs)
# abs(-10)是函数调用,而abs是函数本身
f = abs(-10)
print(f)
f = abs
print(f)
# 变量可以指向函数
# 变量f现在已经指向了abs函数本身。直接调用abs()函数和调用变量f()完全相同
f = abs
print(f(-10))
# 函数名也是变量
# abs = 10
# print(abs(-10))
# 由于abs函数实际上是定义在import builtins模块中的,所以要让修改a... |
import ast
import astor
import logging
# ---------------- Add `import TensorFI as ti`, 'import numpy as np' -----------------
# FIXME: Developer may import numpy as xxx, and this will cause exception
def addImport(fPath):
i = 0;
parse_src = ast.parse(open(fPath).read())
for node in ast.walk(parse_src):
... |
import glob
import re
import json
import html
from io import BytesIO
import os
import xml.etree.ElementTree as ET
from zipfile import ZipFile, ZIP_DEFLATED
from decimal import Decimal
from datetime import datetime
BUILTIN_FORMATS = {
0: 'General',
1: '0',
2: '0.00',
3: '#,##0',
4: '#,##0.00',
5... |
# !/usr/bin/python
"""
-----------------------------------------------
Operator Controls the Assets and Scene Version Control
Written By: Colton Fetters
Version: 1.4
First release: 12/2017
-----------------------------------------------
DEVELOPER NOTES: Uses Ovid's influence to get data from config
V... |
import random,operator,math,pickle,Tkinter,os,gc
from copy import deepcopy
master=Tkinter.Tk()
canvas=Tkinter.Canvas(master,width=300,height=300,bg='black')
canvas.pack()
def setDirectory() :
if(os.path.isdir("GP Data") is False): os.mkdir("GP Data")
os.chdir("GP Data")
run_no=len(os.listdir(os.... |
from django.shortcuts import render
from product.models import Category, Product
def add_product(request):
if request.method == 'POST':
product_category = Category.objects.filter(pk=request.POST['select_category']).first()
print(request.POST['select_category'])
print(product_category)
... |
#recursion
#factorial(n) = 1*2*3*...*n
#factorial(1) = 1
#factorial(n) = n*factorial(n-1) = n
def factorail (n):
if n == 1:
return 1
else:
return n * factorail(n-1)
print("Enter Your number: ")
n = int(input())
print("Recursive Value is: ",factorail(n))
|
"""
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nu
ms2 的元素。
示例 1:
输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]
示例 2:
输入:nums1 = [1], m = 1, nums2 = [], n = 0
输出:[1]
提示:
nums1.length == m + ... |
from .auth import require
from .common import CommonController
import cherrypy
import simplejson
class Table(CommonController):
_cp_config = {
'tools.sessions.on': True,
'tools.auth.on': True
}
@cherrypy.expose
@require()
def list(self):
table=self.model.get_list()
data=dict(module_tem... |
#!/usr/bin/python
#
# Automatically adjusts times in the crontab for turning on/off the IR lights
#
# Requires:
# - python-crontab package via pip
# - /etc/motion/ir_control script
# - Weather Underground API key (for sunrise/sunset times)
#
import httplib
import json
from crontab import CronTab
import sys
# grab th... |
# This solution is O(n^2) and needs a lot of work to fix.
# All Pythagorean triples are of the form (a, (a^2-p^2)/2p, (a^2+p^2)/2p)
import math, time
#baseLengths = set()
possibles = set()
duplicates = set()
L = 10000
# This is the point where b <= a
sqrt2_1 = math.sqrt(2)-1
start = time.clock()
for a in range(2, L//3... |
def solution(arr, start, end):
if not arr or (start>end):
return False
i = start
root = arr[end]
while arr[i] < root:
i += 1
j = i
for k in range(j, end+1):
if arr[k] < root:
return False
left = True
if start < i:
left = solution(arr, start, i... |
from unittest import TestCase
from scrapy.http import HtmlResponse, Request
from slybot.spidermanager import SlybotSpiderManager
from .utils import open_spider_page_and_results, PATH
class SpiderTest(TestCase):
smanager = SlybotSpiderManager("%s/data/SampleProject" % PATH)
def test_spider_with_selectors(sel... |
from django.apps import AppConfig
class GazCounterConfig(AppConfig):
name = 'gaz_counter'
|
from django.conf.urls import url, include
from . import views
from django.conf.urls import url, include
from django.contrib import admin
from webapp.views import twitter_login, twitter_logout,twitter_authenticated,login1,twitter_signup,loginauth
admin.autodiscover()
urlpatterns = [
url(r'^$', views.index, name='ind... |
#
# Copyright (C) 2016 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
# pylint: disable=missing-docstring
from __future__ import absolute_import
import unittest
import sys
class TestImportErrors(unittest.TestCase):
def test_10_ac_compat(self):
fun = "NullHandler"
sys.modules["logging"] = Non... |
# ex34: Accessing elements of lists
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print animals
#print "The animal at 1: %s" % animals[1] # python
#print "The 3rd animal: %s" % animals[2] # peacock
#print "The 1st animal: %s" % animals[0] # bear
#print "The animal at 3: %s" % animals[3] #... |
#!/usr/bin/env python3
#
# Determine if this tool can run a test based on a test spec.
#
import datetime
import sys
import pscheduler
json = pscheduler.json_load(exit_on_error=True, max_schema=2);
try:
if json['type'] != 'simplestream':
pscheduler.succeed_json({
"can-run": False,
... |
# Generated by Django 2.1.15 on 2020-02-19 09:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField... |
from spddo.todo import model
from sqlalchemy.sql.expression import and_
from spddo.todo.actions.views import todo_view
def filter_todos(context: 'micro_context',
term: str='', offset: int=0, limit: int=10) -> list:
'''
filters the todos by term on description
returns: [{
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'linecut.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import Qt... |
from colorsys import rgb_to_hls
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from math import sqrt
import json
#TODO: rename file
#TODO: look at turning this into a module instead of a class
#TODO: figure out gamma correction to get relative luminance for colormap y-axis
#TODO: [POTENTIALL... |
"""CLI of MoSAIC.
MIT License
Copyright (c) 2021-2022, Daniel Nagel
All rights reserved.
"""
import click
import numpy as np
import pandas as pd
import trogon
from matplotlib import pyplot as plt
import mosaic
from mosaic.utils import save_clusters, savetxt
# setup matplotlibs rcParam
PRECISION = ['half', 'single'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy, time, sys, json, urllib, random, bitly_api
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
dpla_data... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
# Ввести свой ответ на пример.
число=input("4*100-69= ")
print("Ваш ответ {0}.".format(число))
print("Правильный ответ=311")
|
import numpy as np
import matplotlib.pyplot as plt
'''
*** DESCRIPTION ***
The following class generates a complete neural network, without biases.
To initialize the network, we need to give the network's dimensions in an array (let L be this array and N be the number of layers) :
- for each i, nat... |
import functools
from discord.ext import commands
from .context import Context
from .constants import ADMIN_ROLE_ID, TECHADMIN_ROLE_ID
def is_owner():
async def predicate(ctx: Context) -> bool:
if ctx.author.id not in ctx.bot.owner_ids:
raise commands.NotOwner("Must be a bot owner to use thi... |
from django.conf.urls import include, url
from waiting_room import views
urlpatterns = [
url(r'^$', views.wait_home, name='wait_home'),
]
|
#!/usr/bin/env python3
from typing import List
import os
import psycopg2
from psycopg2.extras import execute_values
class Database:
def __init__(self):
self.__connection = psycopg2.connect(
host=os.environ['DB_HOST'],
database=os.environ['DB_NAME'],
user=os.environ['DB_... |
from nameparser import HumanName as OriginalHumanName
from nameparser.config import Constants
# Disable stripping emoji from names
# https://nameparser.readthedocs.io/en/latest/customize.html#don-t-remove-emojis
constants = Constants()
constants.regexes.emoji = False
class HumanName(OriginalHumanName):
def __in... |
from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.kaistart.com/project/more.html'
try:
browser.get(url)
wait = ui.WebDriverWait(browser, 20)
wait.until(lambda dr: dr.find_element_by_class_name('project-detail').is_displayed())
# 一直滚动
js1 = 'return document.body.scro... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.rc('lines', linewidth=0.8)
from codingbounds import *
def gen_figure_1(resolution=100):
# Here we use results on the list decodability of multi-level
# concatenated codes to ob... |
# A list is another datatype in Python. It has the following structure:
# NAME_OF_LIST = ["item 0", "item 1", "item 2", "item 3", "item 4"]
# items on the LIST can be called with the following code:
# NAME_OF_LIST[3]
# the "3" in the structure above is called the "index".
# This will return ... |
count = 1
#Code block 1
while count < 11:
print(count)
count = count + 1
print("Counting compelte")
|
def collatz(n):
dictCollatz, keyMaxTraject = {}, 1
for i in range(n):
chisloK, pathLength = i + 1, 0
while chisloK:
if not chisloK in dictCollatz and chisloK != 1:
if not chisloK % 2:
chisloK //= 2
else:
chisloK... |
import pymysql.cursors
from memory_profiler import profile
@profile
def db_performance():
db = pymysql.connect(host="127.0.0.1", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="eas503db") ... |
from linear_classifier import *
|
# Draw a 5−pointed star
import turtle
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
|
from core.base import Base
import re
import json
import time
try:
from .base import *
except:
from base import *
class BaiDu(SpiderBase, Base):
name = 'baidu_photo'
def __init__(self, logger=None, *args):
super(BaiDu, self).__init__(logger, *args)
def query_list_page(self, key, page_to_... |
n = int(input())
for i in range(0, n):
for j in range((n-1), i, -1):
print(end=" ")
for j in range(0, i+1):
if(j==0):
print(end="*")
else:
print(end=" "+"*")
print() |
from share.exceptions import ShareException
class SchemaLoadError(ShareException):
pass
class SchemaKeyError(ShareException):
pass
|
"""Binary Search.
O(logN) time """
class BinarySearch:
def __init__(self, nums):
self.nums = nums
self.phrase = ''
def binary_search(self, search, nums=None):
if nums is None:
nums = self.nums
mid = (len(nums)-1) // 2
if len(nums) == 1 and nums[0] == s... |
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID
from .base import Base
class Tournament(Base):
__tablename__ = "tournaments"
id = sa.Column(
UUID(),
nullable=False,
primary_key=True,
server_default=sa.text("uuid_generate_v4()"),
)
year = sa.Col... |
#!/usr/bin/env python
import os
import re
import sys
from codecs import open
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'inkah',
]
requires = []
with open('inkah/__init__.py', 'r') as fd:
version = re.search(r'^__v... |
#!/usr/bin/python2.7
'''A script for gathering BlueArc NFS shares mounted on servers. It takes one
mandatory parameter, the BlueArc site location (either LAXHQ or SEA), and one
optional paramater, how many threads to use. Results are returned in
txt format.
'''
import argparse
import MySQLdb
import paramiko
from Queue... |
# MIT license
#
# Copyright (C) 2015 by XESS Corp.
#
# 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, mer... |
from python_framework import Serializer
import ContactDto
class PoolerRequestDto :
def __init__(self,
originContactDto = None,
destinyContactDto = None
) :
self.originContactDto = convertToContactDto(originContactDto)
self.destinyContactDto = convertToContactDto(destinyContactDt... |
# plot the energies
# Created by Martin Gren 2014-10-25.
# imports
import matplotlib.pylab as plt
import numpy as np
import math
# input file
filename = 'block_value.dat'
# import data
data = np.loadtxt(filename)
# initial size of plot window
plt.figure(figsize=(8,6))
sum = 0
start_avg = int(len(data[:,1]) / 5); ... |
#weighted uniform string
from collections import defaultdict
def isRepeated(k , r , alph):
n = len(k)
#aabba 2 6 1
prev = ''
count = 1
for i in range(n):
if prev == k[i]:
count += 1
#r[s[i] * count] = alph[... |
__author__ = 'rajaprasanna'
import datetime
from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework import status
from rest_framework.response import Response
from .models import BaseTable
import overlapping.serializers as serializers
... |
import pytest_check as ck
import pytest
@pytest.mark.p0
@pytest.mark.app
@pytest.mark.skip
def test_login(login_page,driver):
login_page.Login('18010181267','123456')
ck.is_true(driver.find_elements_by_xpath('//*[@text="LQRWeChat"]'))
if __name__ == "__main__":
pytest.main(["-s", r"D:\TestTool\Python\Loca... |
print('We start at: ' , __name__)
if __name__ == '__main__':
print('we end up in:', __name__) |
class AppriseNotificationFailure(Exception):
# Apprise returns false if something goes wrong
# they do not have Exception objects, so we're creating a catch all here
pass
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Region'
db.create_table('regional_region', (
('id', self.gf('django.db.models.fi... |
from tempfile import NamedTemporaryFile
import requests
from bs4 import BeautifulSoup
from django.core.files import File
from ..models import Image
def scrape_text(url, status_object):
"""
Function used to retrieve text from an HTML content and remove all the tags.
:param url: website's url as a string,... |
from time import sleep
import rclpy
import logging
from roboy_cognition_msgs.srv import RecognizeSpeech
# TODO: Create new service type with audio input, or change to empty request flow
def main():
rclpy.init()
node = rclpy.create_node('odas_speech_recognition')
publisher = node.create_publisher(Recogn... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
import email.utils
def fun(s):
# return True if s is a valid email, else return False
# regex = ^([a-zA-Z0-9_\-]+)@([a-zA-Z0-9]+)\.([a-zA-Z]{3})$
# print(s)
return bool(re.search(r"^[a-zA-Z][\w\-\.]+\@[a-zA-Z]+\.[a-zA-Z]{1,... |
# -*- coding: utf-8 -*-
for value in range(0,100):
print(str(value),"回目の処理")
|
# coding: utf-8
import csv
import os
import unicodecsv
from sets import Set
# remove comma from the tables
def cleanData(data):
idKeys=Set() #list of wiki page IDs
headline=data[0]
for row in data:
if (row[0] in idKeys) or (len(row)!=len(headline)): #delete double values and defected rows
... |
# -*- test-case-name: effect.test_twisted -*-
"""
Twisted integration for the Effect library.
This is largely concerned with bridging the gap between Effects and Deferreds,
and also implementing Twisted-specific performers for standard Intents.
The most important functions here are :func:`perform`,
:func:`make_twist... |
# -*- coding: utf-8 -*-
import pytest
from bravado_core.exception import MatchingResponseNotFound
from bravado_core.operation import Operation
from bravado_core.response import IncomingResponse
from mock import Mock
from mock import patch
from bravado.exception import HTTPError
from bravado.http_future import unmarsha... |
class Item:
def __init__(s, value=None):
s.value = value
s.nextValue = None
class LList:
def __init__(s):
s.head = None
def __repr__(s):
cur = s.head
sk = '[ '
while cur is not None:
sk += f'{cur.value},'
cur = cur.nextV... |
#from app import createUser as testnewuser
import unittest, sqlite3, os, time, sys
#from selenium import webdriver
# Global Scope
userdb = None
logindbfile = "../login.db"
def open_db(name):
conn = sqlite3.connect(name)
cur = conn.cursor()
return conn , cur
# returns the size of table
def getTableSize(d... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class TransformerBlock(layers.Layer):
def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
super().__init__()
self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
self.ff... |
from ejemplos.fechaR import Fecha
fecha = Fecha(10, 11, 2019)
|
import zmq
ctx = zmq.Context.instance()
server = ctx.socket(zmq.PUB)
server.bind('inproc://foo')
clients = [ctx.socket(zmq.SUB) for i in range(10)]
for client in clients:
client.connect('inproc://foo')
client.setsockopt_string(zmq.SUBSCRIBE, '')
server.send_string('FOO')
for client in clients:
print(clien... |
from selenium.webdriver.common.by import By
from Paragraphs.Paragraph import Paragraph
from magic_box.find_elements import find_element
from selenium.webdriver.support.ui import Select
import pytest, time
class ContentAsideParagraph(Paragraph):
def __init__(self, driver):
super().__init__(driver)
... |
access_mode_template = [
"switchport mode access", "switchport access vlan",
"switchport nonegotiate", "spanning-tree portfast",
"spanning-tree bpduguard enable"
]
port_security_template = [
"switchport port-security maximum 2",
"switchport port-security violation restrict",
"switchport port-se... |
# O programa recebe a entrada de tipos de investimento e devolve o valor corrigido
# após um mês de investimento.
print('Escolha o tipo de investimento: '
'\n1 - Poupança'
'\n2 - Fundos de Renda Fixa')
tipo = int(input())
print('Insira o valor investido: ')
valor = float(input())
poupança = valor * 0.03
rendaFixa =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.