text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import webbrowser
url = "http://www.psicobyte.com"
webbrowser.open(url, new=2)
|
# Function: ScoreLetter
# Dependency:
# Input: a letter 'i'
# Output: an integer(score of letter)
# Description:
def ScoreLetter(letter):
magic_book = {
'a': 2, 'b': 5, 'c': 4, 'd': 4, 'e': 1, 'f': 6, \
'g': 5, 'h': 5, 'i': 1, 'j': 7, 'k': 6, 'l': 3, \
'm': 5, ... |
import cv2
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import numpy.ma as ma
import numpy as np
from image_utils import (EnhancedCompose, Merge, RandomCropNumpy, Split, to_tensor,
BilinearResize, CenterCropNumpy, RandomRotate, AddGaussianNoise,
... |
print("""
Short Tutorial on Sets
----------------------
Sets are mutable unorderd arrays of values. Sets are used for
comparisons, much like in boolean algebra. Importantly, sets
cannot contain duplicates! If duplicate values are passed into
a set creation, any duplicates are dropped.
""")
#Creating sets
pri... |
from data import Data_coldStart
import numpy as np
import logging
EPOCH = 30
LEARNRATE = 0.1
DECAY = 0.9
DIM = 10
FEATURE = 2
# logger = logging.getLogger()
# logger.setLevel(logging.NOTSET)
# formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
#
# l... |
from unittest import TestCase
from rest_framework.test import APIRequestFactory
from mimics.serializers import MimicSerializer
from windows.models import Window
class DeviceSerializerTestCase(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
def test_get_links(self):
# TODO: `Mim... |
#!/usr/bin/env python3
import argparse
import os
import os.path
from astroid.manager import AstroidManager
from astroid.utils import ASTWalker
from astroid.as_string import dump
from lib.check import check
import sys
class PrintAll:
def set_context(self, node, child_node):
pass
def visit_module(se... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.terraform.lint.tfsec.rules import rules as tfsec_rules
def rules():
return tfsec_rules()
|
import os
import pdb
import matplotlib as M
import matplotlib.pyplot as plt
import evac.utils as utils
fig,axes = plt.subplots(nrows=4,ncols=3)
CASES = collections.OrderedDict()
CASES[datetime.datetime(2016,3,31,0,0,0)] = [
datetime.datetime(2016,3,31,19,0,0),
datetim... |
import openpyxl as xl
from openpyxl.chart import Reference, BarChart
wb = xl.load_workbook("../files/excel/sample.xlsx")
sheet = wb["items"]
for row in range(2, sheet.max_row + 1):
priceCell = sheet.cell(row, 2)
descountCell = sheet.cell(row, 3)
totalCell = sheet.cell(row, 4)
totalCell.value = priceC... |
from utils import *
from .translators import *
from .scorers import *
from .keygenerators import *
from .solvers import * |
#!/usr/bin/python
import copy
class Polynomial:
# coeffs is a list of the coefficients where index represents the degree
def __init__(self, coeffs):
self.coeffs = coeffs
def __deepcopy__(self, memo={}):
return Polynomial(copy.deepcopy(self.coeffs))
def __getitem__(self, degree):
... |
import numpy as np
# 1ª questão, a.: Rede MLP para classificação
class MLPClassifier():
# Coloquei uma taxa de aprendizado (alpha) padrão de 0.1 e 100 épocas
def __init__(self, hidden_unit=None, epochs=100, alpha=0.1):
self.units = hidden_unit
self.epochs = epochs
self.alpha = alpha
... |
from database_connection import connect
conn = connect()
cursor = conn.cursor()
# print("database created successfully")
# cursor.execute('''CREATE TABLE IF NOT EXISTS Admin
# (id INT AUTO_INCREMENT PRIMARY KEY,
# name VARCHAR(30) NOT NULL,
# email VARCHAR(20) N... |
import numpy as np
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import (
Flask,
render_template,
jsonify)
#################################################
# Reflect Database
##... |
from translate import Translator
print('HEEEELLOOOOOOOO')
translator = Translator(to_lang='fr')
translation = translator.translate('This is a boy: Ibrahim Olawale')
print(translation)
print(Translator)
with open('scared.txt', mode='r') as my_story:
story = my_story.read()
print(story)
translated_... |
import os
import shutil
import sys
#directory = 'C:\\dev\\projects\\halo\halo-cli\\tests\\gen4\\BIAN_APIs_Release9.0'
#dest = 'C:\\dev\\projects\\halo\halo-cli\\tests\\gen4\\BIAN9'
directory = sys.argv[1]
dest = sys.argv[2]
do_copy = False
#[print(x[0]) for x in os.walk(directory)]
cnt = 1
for x in os.walk(directory)... |
"""
Implementation of Rescola-Wagner Model in Python3
"""
import numpy as np
import matplotlib.pyplot as plt
from utility import set_all_args
class pavlovian_conditioning(object):
def __init__(self, num_stimuli = 1, **kwargs):
self.num_stimuli = num_stimuli
self.learning_rate = 0.1 * np.ones(n... |
import socket
import sys
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = './uds_socket'
print >>sys.stdout, 'connecting to %s' % server_address
try:
sock.connect(server_address)
except socket.error, msg... |
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import unittest
import cvxpy as cp
import numpy as np
import fisherVerifier
import fisherMarket
np.set_printoptions(formatter={'float': '... |
li = []
while 1:
try: li.append(float(input()))
except: break
print(max(li) - min(li)) |
import turtle
turtle.pendown()
counter = 0
while(not (counter == 6)):
turtle.forward(100)
turtle.right(60)
counter = counter + 1
|
import tensorflow as tf
import numpy as np
#import tensorflow.examples.tutorials.mnist.input_data as input_data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST data", one_hot=True) |
import falcon
import log
from sqlalchemy.orm.exc import NoResultFound
from controller.base import BaseResource
from util.hooks import authorization
from util.authorization import encrypt_token, hash_password, uuid
from model import User, Base
from util.error.errors import NotValidParameterError, UserNotExistsError, App... |
from distutils.core import setup, Extension
module1 = Extension('_iter',
sources=['_iter.c'])
# extra_compile_args=['/Zi'],
# extra_link_args=['/DEBUG'])
setup(name='_iter',
version='0.1',
description='Contains iteration stuffs',
ext_modules=[module1])
|
"""Message View tests."""
# run these tests like:
#
# FLASK_ENV=production python -m unittest test_user_views.py
import os
import pdb
from unittest import TestCase
from models import Follows, db, connect_db, Message, User
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
from app import app, CURR_USER_... |
"""Module containing test functions for Income Account/Statement zones."""
from re import finditer
import numpy as np
import pandas as pd
import re
def test_caps_income_account(value):
"""Search zone content for 'INCOME ACCOUNT' string."""
def caps_ratio(value):
"""Define ratio of capital characters.... |
from Statstools.Timeseries import Timeseries
import numpy
import matplotlib.pyplot
from mpl_toolkits.axes_grid1 import make_axes_locatable
class Discretized():
def __init__(self, name, mesh, data, dimX, dimY, dimZ):
self.name = name
self.mesh = mesh
self.data = data
self.dimX = dim... |
class Player_Token:
def __init__(self, owner, owner_symbol):
self.owner = owner
self.owner_symbol = owner_symbol
|
from threading import Thread
from time import sleep, ctime
loops = (4, 2)
def loop(nloop, nsec):
print("Start loop", nloop, "at:", ctime())
sleep(nsec)
print("Done loop", nloop, "at:", ctime())
if __name__ == '__main__':
print("Starting at:", ctime())
threads = [Thread(target=loop, args=(nloop... |
MAIN_MENU = "Main menu"
ENTER_ENGLISH_WORD = "Please, enter your english word"
ENTER_RUSSIAN_WORD = "Please, enter russian translation"
ENTER_MORE_RUSSIAN_WORD = "You entered russian translation.\nEnter another translation or push buttons" |
from django.template.response import TemplateResponse
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from myapp.models import *
from django.http import HttpResponseRedirect
from myapp.forms import *
from django.co... |
# -*- coding: utf-8 -*-
class Solution:
def countArrangement(self, N):
return [1, 2, 3, 8, 10, 36, 41, 132, 250, 700, 750, 4010, 4237, 10680, 24679][
N - 1
]
if __name__ == "__main__":
solution = Solution()
assert 2 == solution.countArrangement(2)
|
from ftplib import FTP
class Uploader:
def connect(self, hostname, username, password):
raise NotImplementedError()
def disconnect(self):
raise NotImplementedError()
def upload(self, data, uploaded_name, destination=None):
raise NotImplementedError()
class FtpUploader(Uploader)... |
from xml.sax import make_parser
from xml.sax.handler import ContentHandler, feature_namespaces
from xml.dom.minidom import parse
import xml.dom.minidom
import xml.etree.cElementTree as cet
from html.parser import HTMLParser
class MovieHandler(ContentHandler):
def __init__(self):
super(MovieHandler, self).... |
import cv2
import numpy.ma as ma
import cv2.aruco as aruco
import numpy as np
import pickle
from numpy import linalg as LA
from numpy.linalg import inv
import math
import copy
import rospy
from sensor_msgs.msg import CameraInfo
from realsense2_camera.msg import Extrinsics
class projection:
def __init__(self, camId... |
# 15-112, Summer 1, Homework 1.4
######################################
# Full name: joyce moon
# Andrew ID: seojinm
# Section: B
######################################
######### IMPORTANT NOTE #############
# You are not allowed to use lists, or recursion.
# And you are not allowed to use any string methods or impor... |
#! /usr/bin/python
# Author: Ruoteng Li
# Date: 6th Aug 2016
import numpy as np
import png
import matplotlib.pyplot as plt
import matplotlib.colors as cl
import flowlib as fl
def flow_read(flow_file):
"""
Read kitti flow from .png file
:param flow_file:
:return:
"""
flow_object = png.Reader(f... |
# COMP90024 Assignment 2
# Team: 48
# City: Melbourne
# Members: Wenqi Sun(928630), Yunlu Wen(869338), Fei Zhou(972547)
# Pei-Yun Sun(667816), Yiming Zhang(889262)
import json
import argparse
from db import TweetStore
import requests
# json files
JSON_PATH = "json_files/"
FILE_DICT = {
"db_auth": "db_auth.json",... |
import unittest
from game_object import compare_points, wall_width
class TestComparePoints(unittest.TestCase):
def setUp(self):
self.f_wall = [[200, 200]]
self.res = None
# walls
def test_walls_negative(self):
# max point x
s_wall = [304, 200]
self.res = compare_po... |
#!/usr/bin/env python
# coding: utf-8
# ## Numpy 배열의 변경
# - append, insert, delete
# - concatenate, vstack, hstack
# - hsplit, vsplit
# In[19]:
import numpy as np
# In[2]:
a = np.arange(1, 10).reshape(3, 3)
b = np.arange(10, 19).reshape(3, 3)
# In[3]:
print(a)
# In[4]:
print(b)
# ## append()
# - 2개의 배... |
# -*- coding:utf-8 -*-
from flask import Blueprint, render_template, session
from flask_login import current_user
from app.forum.models import Topic
from app.message.models import Message
from app.game.models import Game_News
from app.util.helper import get_online_user_nums, highest_online_number
index = Blueprint("ind... |
api = input ("Please type your API key:")
mac = input ("Please share your macaddress:")
import requests
r = requests.get('https://api.macaddress.io/v1?apiKey='+str(api)+'&output=vendor&search='+str(mac)+'')
print (r.text)
|
# Generated by Django 3.2.5 on 2021-07-26 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0003_visit'),
]
operations = [
migrations.AddField(
model_name='patient',
name='phone',
fi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import SecureWitness.models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name... |
# -*- coding: utf-8 -*-
import inject, uuid
from model.config import Config
from model.users.users import Users
from model.systems.assistance.devices import Devices
from model.systems.assistance.templates import Templates
from model.systems.assistance.logs import Logs
class Firmware:
config = inject.attr(Config... |
'''
633. Sum of Square Numbers
Given a non-negative integer c, your task is to decide whether there're two
integers a and b such that pow(a, 2) + pow(b, 2) = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
'''
class Solution(object):
def mySqrt(self, x):
... |
#!/usr/bin/python3
from vector import Vector
vector1 = Vector([1,2,3])
vector2 = Vector([1,2,3])
vector3 = Vector([3,4,5]);
print( vector1,vector2 ,)
print( vector1 == vector2 )
print( vector1 == vector3 )
print ( vector1.plus(vector2))
print (value, sep, end, file, flush)
|
import unittest
# function spelling mistake is from CodeWars
from katas.beta.binary_pyramid_101 import binary_piramid
class BinaryPyramidTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(binary_piramid(1, 4), '1111010')
def test_equals_2(self):
self.assertEqual(binary_pira... |
import unicodecsv
enrollments = []
f = open('enrollments.csv', 'rb')
reader = unicodecsv.DictReader(f)
i = 0
for row in reader:
enrollments.append(row)
print enrollments[i]
i = i+1
f.close()
|
# import requests
# sessiion = requests.Session()
# params = {'username':'zhaolf','password':'password'}
# r = requests.post('http://pythonscraping.com/pages/cookies/welcome.php',params=params)
# print(r.text)
# print('cokkies is set to :')
# print(r.cookies.get_dict())
# print('Going to profile page..')
#
# s = sessii... |
""" Interactive Smoke Plume
Hot smoke is emitted from a circular region at the bottom.
The simulation computes the resulting air flow in a closed box.
The grid resolution of the smoke density and velocity field can be changed during the simulation.
The actual resolution values are the squares of the slider values.
Pe... |
import time
from snap7 import util
from snap7 import client
from LoadTags import loadTags
from LoadDBs import loadDBs
from restart import restart_program
import GravaDados
import logging
# initialize the log settings
logging.basicConfig(format='%(asctime)s - %(levelname)s:%(message)s', datefmt='%d/%m/%Y %H:%M:%S',fil... |
def Sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
z = []
x = Sieve(104730)
for i in range(2, 104730):
if x[i]:
z.append(i)
t = int(input... |
import json
import os
def getcount(filepath):
count = 0
#判断给定的路径是否是.py文件
if filepath.endswith('.py'):
#打开文件
f = open(filepath,'r',encoding='utf-8')
#先读取一行
content = f.readline()
#当读取的代码行不是空的时候进入while循环
while content != '':
#判断代码行不是换行符\n时进入,代码行数加1... |
from pyparsing import Or, And, Forward, Literal, ZeroOrMore, Group
from asn1PERser.classes.parse_actions import parse_ModuleDefinition
from .assignment_def import TypeAssignment, ValueAssignment
from .common_def import DefinedValue
from .lexical_items import COMMA, LEFT_CURLY_BRACKET, RIGHT_CURLY_BRACKET, \
assignm... |
import numpy as np
import sys
from keras.models import Model
import keras.layers as layers
# keras implement
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):
channel_axis = -1
filters = int(filters * alpha)
x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)), name='conv1_pad')(in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from models.reg import Registry
from storage.schema.deserialize import SchemaDeserializer
from storage.impl.merge_serializer import MergeSerializer
if __name__ == '__main__':
deserializer = SchemaDeserializer('./schema')
serializer = MergeSerializer('./schema/imp... |
# -*- coding: utf-8 -*-
# Import libraries
import os
import sys
import string
import copy
import datetime
import time
import requests
import numpy as np
import pandas as pd
from random import randint
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class Scr... |
import logging
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from gwhiz.lib.base import BaseController, render
log = logging.getLogger(__name__)
class EmacsclientController(BaseController):
def index(self,id):
import os
i... |
#!/usr/bin/env python
# encoding: utf-8
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
"""
def reverseWords(s):
return ' '.join(s.strip().split()[::-1])
|
class LinkedListNode:
def __init__(self,value=0,parent=None,leftnode=None,rightnode=None):
self.value=value
self.parent=parent
self.left=leftnode
self.right=rightnode
self.visited=False
def PreorderWalk(self, node):
if (node is not None):
pr... |
import clify
from dps import cfg
from dps.env.advanced import yolo_rl
from dps.datasets import EmnistObjectDetectionDataset
distributions = dict(
area_weight=list([1.5, 2.0, 2.5, 3.0]),
nonzero_weight=list([150, 200, 250, 300]),
)
config = yolo_rl.good_sequential_config.copy(
render_step=100000,
eva... |
class Trip:
def __init__(self, id, start_x, start_y, finish_x, finish_y, earliest, latest):
self.id = id
self.start_x = int(start_x)
self.start_y = int(start_y)
self.finish_x = int(finish_x)
self.finish_y = int(finish_y)
self.earliest = int(earliest)
self.late... |
# -*- coding: utf-8 -*-
"""
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array
is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be... |
__author__ = 'AlecGriffin'
from Verse import Verse
from Bible import Bible
from Chapter import Chapter
from Book import Book
def getParsedContent():
bookName = ""
bible = Bible()
book = Book("Genesis")
chapter = Chapter(1)
file = open("bible.txt")
bookname = ""
for line in file:
sp... |
import unittest
from katas.kyu_7.where_is_vasya import where_is_he
class WhereIsHeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(where_is_he(3, 1, 1), 2)
def test_equals_2(self):
self.assertEqual(where_is_he(5, 2, 3), 3)
def test_equals_3(self):
self.assert... |
#The "zip" built-in function takes a few lists (two in this example),
# and creates tuples by picking up elements from each list.
# The first tuple contains elements from the first positions in the lists, and so on.
d1=["a","b","c","d","e"]
d2=["f","g","h","i","j"]
d3=zip(d1,d2)
for x in d3:
print(x[0] + "" + x[... |
from logging import Logger, getLogger
from flask import Flask
def get_logger(app: Flask, name: str) -> Logger:
"""Utitlity method to get a specific logger that is a child logger of the app.logger."""
logger_name = f"{app.import_name}.{name}"
return getLogger(logger_name)
|
import logging
from flask import Response, make_response, jsonify, request
from flask_login import login_required
from waitlist.base import db
from waitlist.permissions import perm_manager
from waitlist.storage.database import Account, Character
from waitlist.utility.eve_id_utils import get_character_by_id,\
get_... |
class State(object):
# MARK: Constructor for a state object.
def __init__(self, state, parent, child):
# An integer.
self.state = state
# A state object.
self.parent = parent
# A set of state objects.
self.child = child
# An integer.
self.heuris... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 31 14:33:06 2017
@author: eardo
"""
import numpy as np
import os
import matplotlib.pyplot as plt
os.chdir('C:\Users\eardo\Desktop\pyoutput')
degree_sign= u'\N{DEGREE SIGN}'
freqT=np.genfromtxt("freqT.csv", delimiter=",")
T=freqT[:,0]
freq=freqT[:,1]
fig=pl... |
class A:
def __init__(self,no=0):
print("I am Const of A")
self.no = no
def display(self):
print(" I am display of A Class")
print(self.no)
class B(A):
def __init__(self,name="dummy"):
print("I am Const of B")
self.name = name
def show(self):
... |
name = "Sheila Brito"
age = 15
gpa = 4.0
print name
print age
print gpa
print 'My name is', name, 'I am', age, 'years old. My gpa is', gpa
print 'in ten years i will be', age+10
ageinhumanyears = 3
ageindogyears = ageinhumanyears * 7
print 'My dog is', ageindogyears, 'years old in dog years'
print 'but my dog is', a... |
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import *
import User.CustomAuth
from django.contrib.auth import login as authLogin
# Create your views here.
def login(request):
next = request.POST.get('next', request.GET.get('next', ''))
if not request.method == '... |
import requests
def main():
response = requests.get("https://api.exchangeratesapi.io/latest")
if response.status_code != 200:
print("Status Code: ", response.status_code)
raise Exception("There was an error!")
data = response.json()
print("JSON data: ", data)
if __name__ == "__... |
import random
import traceback
import requests
import logging
log = logging.getLogger('log')
def get_proxies():
# 代理服务器,支持http和https
return ['192.168.62.10:12000'] #
def req(session, url, proxies=None, debug=0, method='get', timeout=3, retry_times=2, proxy=False,**kwargs):
request_method = {'get': ... |
#Speed Tape Gauge
#
#
# -- Currently Missing
#
# -- Mach text
# -- Fine location and positioning
# -- Connection with GlassServer
import pyglet
from pyglet.gl import *
from gauge import gauge_parent
import common
import variable
import math, time
import text
class Vspeed_c(object):
#Hold all data on VS... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import getopt, datetime, os, subprocess, sys
#os.chdir('../')
def main(argv):
try:
opts, args = getopt.getopt(argv, "m:", ["message="])
except getopt.GetoptError:
sys.exit(2)
for opt, arg in opts:
if opt in ("-m", "--message"):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0001_initial'),
('core', '0001_initial'),
]
operations = [
migrations.CreateMode... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
valles = 0
altitude_nova = 0
altitude_velha = 0
for c in s :
if(altitude_velha >= 0 and altitude_nova < 0):
valles += 1
altitude... |
'''
Created on 27. feb. 2017
@author: tsy
License: CC-BY
'''
from random import randint
import numpy as np
if __name__ == '__main__':
pass
def roll(dice):
res = 0
for n in range(dice):
res =+ randint(1,6)
return res
def charge(M=None,distance = None,swiftStride=False):
assert M is... |
# import asyncio
# async def coro():
# i = 0
# while True:
# await asyncio.sleep(1)
# print(i)
# i += 1
# async def complete():
# print('complete')
# async def main():
# task = asyncio.create_task(coro())
# while True:
# await asyncio.sleep(5)
# print(task)... |
from _typeshed import Incomplete
def node_link_data(
G,
attrs: Incomplete | None = None,
*,
source: str = "source",
target: str = "target",
name: str = "id",
key: str = "key",
link: str = "links",
): ...
def node_link_graph(
data,
directed: bool = False,
multigraph: bool = T... |
from django.shortcuts import render,redirect
from .forms import git_userform
from django.http import HttpResponse
import requests
import json
from django.views.generic.base import TemplateView
def reposearch(request):
if request.method=='GET':
form=git_userform()
return render(request,'view.html',{'form':form})
... |
from matplotlib.animation import FuncAnimation
import json
import math
from math import acos
from time import time
from ahrs.common.constants import M_PI, RAD2DEG
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import frccontrol as fct
import control as ct
from frccontrol import kalmd
altArr = N... |
from substitutionkeygenerator import *
from .. import utils
import random
class PermutationKeyGenerator(SubstitutionKeyGenerator):
def __init__(self, sequence=utils.alphabet, rand_func=lambda x: x ** 5, **kwargs):
"""Similar to SubstitutionTranslator, but returns just lists"""
SubstitutionKeyGenerator.__init__(se... |
from nameparser import HumanName
from nameparser.config import CONSTANTS
name = HumanName("Ralf Mühlenhöver, Geschäftsführer")
print(name.title)
print(name.first)
print(name.middle)
print(name.last)
|
# Generated by Django 2.1.3 on 2018-11-28 11:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('MyClass', '0002_adress_email_group_phone'),
]
operations = [
migrations.RenameField(
model_name='phone',
old_name='person',
... |
from tornado.web import RequestHandler
import jsonpickle
from db.database import TraceDatabase
from trace import Trace
# POST USAGE:
# curl -v http://localhost:8888/ -X POST --data-binary '{"traceseq": 1, "customerseq": 100, "title": "post-test", "mainclass":"monitoring-manager", "subclass":"orchestrator-m" }' -H "C... |
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.maximize_window()
browser.get('http://113.108.207.92:7070/TNB/login.action')
userName = browser.find_element_by_id(... |
# template for "Guess the number" mini-project
#run the program in codeskulptor
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import math
import random
# helper function to start and restart the game
def new_game():
print "New game. Rang... |
import time
import logging
import RPi.GPIO as GPIO
# #############################################################################
# Class: PIR
# Detects whether there has been movement around the clock, and turns the
# matrix off if there has not been any
# ############################################################... |
timer = 0
def on_button_pressed_a():
global timer
timer = randint(5, 15)
basic.show_icon(IconNames.CHESSBOARD)
while timer > 0:
timer += -1
basic.pause(1000)
basic.show_icon(IconNames.SKULL)
pass
input.on_button_pressed(Button.A, on_button_pressed_a) |
import tensorflow as tf
import numpy as np
'''
f_org = open('filepath', 'r')
f_new = open('filepath', 'w')
while True:
line = f_org.readline()
if not line: break
line = line.replace('x', '1').replace('positive', '1').replace('b', '0.5').replace('o', '-1').replace('negative', '0')
f_new.write(line)
p... |
from django.urls import path, include
from django.views.generic import ListView, DetailView
from telecomNews.models import Articles
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', ListView.as_view(queryset=Articles.objects.all().order_by("-date")[:20],
templ... |
from django.test import TestCase
from mainapp.models import Url
from mainapp.forms import ShorteningForm
# python manage.py test --pattern="tests_forms.py"
class FormTestCase(TestCase):
@classmethod
def setUpTestData(cls):
obj = Url.objects.create(target_url="https://www.evernote.com/")
obj.sa... |
import boto3
region = 'us-west-2'
def account_alias():
iam_client = boto3.client('iam')
response = iam_client.list_account_aliases()["AccountAliases"][0]
return(response)
def main():
alias = account_alias()
print(alias)
if __name__ == '__main__':
main()
|
import unittest
from katas.beta.string_repeat import repeat_str
class StringRepeatTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(repeat_str(4, 'a'), 'aaaa')
def test_equal_2(self):
self.assertEqual(repeat_str(3, 'hello '), 'hello hello hello ')
def test_equal_3(se... |
"""
Application-specific configuration for Azzaip.
"""
from django.apps import AppConfig
class AzzaipConfig(AppConfig):
"""
Azzaip application metadata.
"""
name = 'azzaip'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.