text stringlengths 38 1.54M |
|---|
#coding=utf-8
#import PyExecJS
#version 1.1
import execjs
import sys
import os
if sys.platform=='linux':
import readline
def get_jscode(inp):
if os.path.exists(inp):
with open(inp,'r',encoding='utf-8') as f:
data=f.read()
return data
return inp
if len(sys.argv)==2:
data=get... |
import sys
import h5py
from pathlib import Path
import os.path
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets#, QColorDialog
import numpy as np
import matplotlib.pyplot as plt
import pickle
#import time
from lmfit.models import GaussianModel
import customplotting.mscope as cpm
sys.path.append... |
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, please take our poll.") |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Definition',
fields=[
('id', models.AutoField(v... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 11:38:27 2017
@author: D M Dolaputra
"""
import socket
import threading
import json
import time
from queue import Queue
N = 6
queue = Queue()
N_job = [1,2,3,4,5,6]
all_addresses = []
all_connections = []
node = 'node1'
parameter = {
'voltage':[5]
}
... |
from math import ceil
t = int(input())
for _ in range(t):
n, k = [int(i) for i in input().split()]
a = []
for i in range(n):
s, e = [int(i) for i in input().split()]
a.append((s,e))
a.sort(key = lambda x: x[0])
curr_end = 0
ans = 0
for i in range(n):
s,e = a[i][0], a... |
import RPi.GPIO as GPIO
import time
#IMPORTING LIBRARIES
GPIO.setmode(GPIO.BOARD)
# Use physical pin numbering
pin=11
GPIO.setup(pin, GPIO.OUT,initial=GPIO.LOW)
# Set pin 11 to be an output pin and set initial value to low (off)
while True:
GPIO.output(pin,GPIO.HIGH) #Turn On
time.sleep(1)... |
import os
import requests
from flask import Flask, session, render_template, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from datetime import datetime
# from flask.ext.heroku import Heroku
os.getcwd()
# res = requests.get("htt... |
'''
DER1547 methods defined for the DNP3 devices
'''
import os
from . import der1547
import svpdnp3.device_der_dnp3 as dnp3_agent
import subprocess
import socket
import subprocess
dnp3_info = {
'name': os.path.splitext(os.path.basename(__file__))[0],
'mode': 'DNP3'
}
def der1547_info():
return dnp3_info... |
"""
Copyright 2013 Rackspace
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 writing, software
dist... |
str=input("Enter a Word or a String-")
print(str[0:len(str)])
str1=str[::-1]
print(str1)
if(str[0:len(str)]==str[::-1]):
print("pal")
else:
print("not pal") |
"""
Some utilities for matrix
"""
import numpy as np
from scipy.sparse import csr_matrix
def init_sparse_vector(data):
"""
Intial sparse matrix from list of tuple(col_index, value)
Example:
data = [(0, 3), (1, 2), (5, 7), (20, 1)]
return: <1x21 sparse matrix of type '<class 'numpy.int64'>'... |
from .cauchy import Cauchy
from .exponential import Exponential
from .flat import Flat
from .inverse_gamma import InverseGamma
from .inverse_wishart import InverseWishart
from .laplace import Laplace
from .normal import Normal
from .poisson import Poisson
from .skewt import Skewt
from .t import t
from .truncated_normal... |
from dao.dao import get_dao
class Group(object):
def __init__(self, d=None):
self.id = None
self.name = ''
self.code = ''
self.description = ''
if d:
self.__from_dict(d)
def __from_dict(self, d):
if 'id' in d:
self.id = d['id']
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: liyinwei
@E-mail: coridc@foxmail.com
@Time: 2017/8/1 19:40
@Description: export xuexi.xxxx.com qa
"""
import json
"""
input.json @see browser F12, a json format string from:
https://xuexi.xxxx.com/app/module/report?mod_id=19911&tkh_id=326518&isMobile=false
"... |
import tkinter as tk
window=tk.Tk()
window.title('Hello world')
window.geometry('608x608')
window.bgcolor=('black')
label=tk.Label(window,text='this is a label')
label.pack(side='top',expand=True)
label=tk.Label(window,text='this is a label2')
label.pack(expand=True)
frame=tk.Frame(window)
frame.pack(side='top',pad... |
# config.py
class Config(object):
"""
@brief Class for configuration.
"""
# Put any configurations here that are common across all environments
class DeveleopmentConfig(Config):
"""
@brief Class for develeopment configuration.
"""
DEBUG = True
SQLALCHEMY_ECHO = True
class ProductionConfig(Config... |
from django.contrib import admin
from .models import Topic, TopicCategory, Comments, NodeLink
# Register your models here.
class TopicAdmin(admin.ModelAdmin):
# 要列出的字段
list_display = ('id', 'category', 'title', 'author', 'click_num', 'add_time')
# 可以搜索的字段
search_fields = ('title', )
... |
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
from conf import configuration as config
import logging
log = logging.getLogger(__name__)
from amazonproduct import API
amz_api = API(access_key_id=config.AMZ_ACCESS_KEY, secret_access_key=config.AMZ_SECRET_KEY, associate_tag=co... |
# Generated by Django 2.2 on 2021-05-01 06:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_... |
"""Code to wrap some NCCL API calls."""
import numpy
try:
import cupy
from cupy.cuda import nccl
from cupy.cuda import Device # noqa: F401
from cupy.cuda.nccl import get_version
from cupy.cuda.nccl import get_build_version
from cupy.cuda.nccl import NcclCommunicator
from cupy.cuda.nccl imp... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from main.models import SpeedModel, CustomUser
from main.forms import CustomUserChangeForm, CustomUserCreationForm
class CustomUserAdmin(UserAdmin):
fieldsets = (
(_('... |
distance = 25
rocks = [2, 14, 11, 21, 17]
n = 2
# distance = 16
# rocks = [4, 8, 11]
# n = 2
def solution(distance, rocks, n):
answer = 0
rocks.sort()
l = 1
r = distance
while l <= r:
mid = (l+r)//2 # 돌 간의 거리를 이 값 밑으로 맞춤
# print(mid)
s = 0
cnt = 0
m = float(... |
from random import randint, random
from matplotlib import pyplot as plot
from math import pi
print("--- Task A")
def loop_phrase(n):
for _ in range(n):
print("I need to comment my scripts. Comments are marked too!")
def sum_x2(n):
sum = 0
for x in range(n):
sum += (x+1) ** 2
return... |
from modules.printutils import *
big_banner("""
Exercise 82: MRO Genetics
""")
class Mother:
# dominant traits
def __init__(self):
self.eye_color = "brown"
self.hair_color = "dark brown"
self.hair_type = "curly"
class Father:
# recessive traits
def __init__(self):
... |
# -*- coding: utf-8 -*-
from flask import Blueprint
welcome = Blueprint('welcome', __name__)
import views
|
# -*- coding: utf-8 -*-
"""
The registry consists of a series of roots from each of which descends
a tree of keys and values. Each key has an anonymous (default) value
and optionally a set of named values, each of which has a particular
type (string, number etc.).
For convenience in accessing registry keys and values,... |
from django import template
register = template.Library()
@register.filter(name="myfilter", is_safe=True, needs_autoescape=True)
def myfilter(value, autoescape=True):
sentence = value.split(" - ")
return sentence[1] |
import os
import sys
import time
import json
from sys import platform
# Syntax
from ninja_syntax import Writer
# Builder
class build:
# Init
def __init__(self, tmp, out):
# Current dir
self.currentDir = os.getcwd()
# Linux compatibility
if platform == "linux" or platform == "linux2":
self.johnnyDir = ... |
from Tensorflow.models.research.object_detection.utils import visualization_utils as vis_util
from typing import Tuple, Dict
import numpy as np
from PIL import Image
class Process:
def __init__(self, config: Dict):
self.config = config
def add_detections_on_image(self, detections: Tuple, image: np.nd... |
from flask import Flask, render_template, request
import nltk
import matplotlib.pylab as plt
import numpy as np
from nltk.corpus import sentiwordnet as swn
import re
from nltk.corpus import stopwords
from nltk import pos_tag
from nltk.stem import PorterStemmer
app = Flask(__name__)
@app.route('/')
def student():
r... |
import argparse
import onnx
import mxnet as mx
import numpy as np
from mxnet.contrib import onnx as onnx_mxnet
import mxnet.contrib.onnx.mx2onnx.export_onnx as mx_op
from mxnet.contrib.onnx.mx2onnx._op_translations import get_inputs
@mx_op.MXNetGraph.register("BatchNorm")
def convert_batchnorm(node, **kwargs):
""... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:... |
from __future__ import division
from random import randint, choice
import random, decimal
from numpy import mean
import numpy as np
import pandas as pd
import argparse
parser = argparse.ArgumentParser(description='Breeder acquires new aptamers...')
parser.add_argument("--p", "--path_initial_aptamers"
... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 applic... |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print 'copying from %s to %s' % (from_file, to_file)
file_open=open(from_file)
data=file_open.read()
print 'the input file is %d bytes long' % len(data)
print 'does the output file exists? %r' % exists(to_file) # true or false
raw_i... |
#!/usr/bin/env python
#
# Patches and hooks for the binary translation of GAME.EXE.
# Micah Dowty <micah@navi.cx>
#
import sbt86
import bt_common
b = sbt86.DOSBinary('GAME.EXE')
bt_common.patch(b)
bt_common.patchChips(b)
bt_common.findSelfModifyingCode(b)
b.decl("#include <stdio.h>")
b.patchAndHook(b.findCode('2c01... |
import tornado.web
import tornado
import tornado.ioloop
import pyaes
import time
import uuid
import pymysql
import json
from remove_tags import *
import hashlib
from auth import *
from cross_origin import *
from db import *
@jwtauth
class blacklist(BaseHandler):
def post(self):
ruleType = remove_tag(self.... |
import csv
import numpy as np
import io
from ReaderPlus import ReaderPlus
from RoughSet import RoughSet
def incAll(p):
return list(map((lambda l: [i + 1 for i in l]), p))
with io.open("test2.csv", "r", encoding='utf_8_sig') as fp:
reader = csv.reader(fp, delimiter=';', quotechar='"', lineterminator='\n')
... |
# Copyright 2018 The Forseti Security 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 ap... |
import numpy as np
import matplotlib.pyplot as plt
import os
#############################################
## Define functions
#############################################
def Consumer(p1, p2, I, alpha, theta): # calculate consumer's optimal choices
power = 1-theta # for convenience
denom = alpha*(p1**power)+(1-alp... |
import logging
from tests.unit.chroma_core.lib.storage_plugin.resource_manager.test_resource_manager import ResourceManagerTestCase
class TestAlerts(ResourceManagerTestCase):
def setUp(self):
super(TestAlerts, self).setUp("alert_plugin")
def _update_alerts(self, resource_manager, scannable_pk, resou... |
# I'm gonna train you up, honey!
from pyAudioAnalysis import audioTrainTest as aT
class_dirs = [
# "./wernicke_server_training/burp/",
"./wernicke_server_training/dog/",
"./wernicke_server_training/lover/",
# "./wernicke_server_training/lyriq/",
"./wernicke_server_training/other/",
"./wernick... |
# Quality Investing
import yfinance as yf
import datetime
def invest(investmentAmount):
print("-------------------------- Quality Investing --------------------------")
# Quality Investment Stocks Traits
# Good Management - Ability to see opportunities and capitalize on them
# Strong Balance Sheet -... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
import os
from pocketsphinx.pocketsphinx import Decoder as _Decoder
# from sphinxbase.sphinxbase import *
class SphinxDecoder(object):
def __init__(self, kws_threshold = 1e-40):
# configuration.
base_dir = os.path.dirname(__file__)
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 13:35:09 2018
@author: njoos
"""
import math
import random
import threading
import time
floors = 10
numberOfRequests = 100
oddsOfKeypress = 20 #1/value
# 20 -> 5% chance, 4 -> 25% chance
requests = []
order = []
for x in range(numberOfRequests)... |
# TWITTER
"""
SOLVED -- LEETCODE#581
Given a list of numbers, find the smallest window to sort such that
the whole list will be sorted. If the list is already sorted return (0, 0).
You can assume there will be no duplicate numbers.
Example:
Input: [2, 4, 7, 5, 6, 8, 9]
Output: (2, 4)
E... |
import boto3
from boto3.dynamodb.conditions import Key
dynamodb_resource = boto3.resource('dynamodb')
#Python Code for Lambda function to DELETE OBJECTS IF A PRIMARY KEY IS SPECIFIED
def lambda_handler(event, context):
# TODO implement
try:
TABLENAME = event['queryParams']['table_name']
table =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import Club.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Club',
fields=[... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('news/', views.news, name="news"),
path('team/', views.team, name="team"),
path('course/', views.course, name="course"),
path('video/<int:pk>/<int:pks>/', views.video, name="video"),
]
|
# -*- coding: utf-8 -*-
"""
Testing of mpstat command.
"""
__author__ = 'Julia Patacz'
__copyright__ = 'Copyright (C) 2018, Nokia'
_email_ = 'julia.patacz@nokia.com'
from moler.cmd.unix.mpstat import Mpstat
def test_mpstat_returns_proper_command_string(buffer_connection):
mpstat_cmd = Mpstat(buffer_connection, ... |
# conjunto = {1, 2, 3, 4, 4, 2} # conjuntos são formados por chaves
# print(type(conjunto)) # tipo set
# print((conjunto)) # conjuntos não permitem duplicidade, por isto conjunto será {1, 2, 3, 4}
#
# conjunto.add(5) # acrescenta elemento ao conjunto na última posição
# conjunto.discard(2) # remove ... |
ans = 0
def check(v):
s = str(v)
flag = False
for i in range(5):
if s[i] > s[i+1]:
return False
if s[i] == s[i+1]:
flag = True
return flag
for i in range(372304, 847061):
if check(i):
ans+=1
print(ans)
|
# Y-network implementation using the Functional API for MNIST digit classification
# Use either CPU or GPU for computations in Keras
import tensorflow as tf
from keras import backend as K
GPU = False # boolean to use GPU
CPU = True # boolean to use CPU
num_cores = 4
if GPU:
num_GPU... |
#!/usr/bin/env python
# Output formatters (for printing info and data files)
#
# Copyright (C) 2014 Peter Wu <peter@lekensteyn.nl>
import math
from defs import info, data
# Python 2.7 compatibility
if b'' == '':
import functools, itertools
iterbytes = functools.partial(itertools.imap, ord)
else:
iterbytes... |
from scipy.spatial.distance import pdist, squareform
import numpy as np
import scipy as sp
from sklearn import datasets
def random_unlabel(true_labels,unlabel_prob=0.1,hard=False,seed=None,multiclass=False):
'''
randomly unlabel nodes based on unlabel probability
'''
np.random.seed(seed)
labels = t... |
#
# @lc app=leetcode id=1458 lang=python3
#
# [1458] Max Dot Product of Two Subsequences
#
# @lc code=start
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
@functools.lru_cache(None)
def dfs(i, j):
if i < 0 or j < 0:
return float('-in... |
# Copyright (C) 2014 Rémi Bèges
# For conditions of distribution and use, see copyright notice in the LICENSE file
# Test of the protocol algorithm with dummy frames
from API.Protocol import Protocol
from API.SerialPort import SerialPort
class SerialMgr():
def __init__(self):
# Create serial... |
import random
from pico2d import *
class Heart:
image = None;
def __init__(self):
self.randx = random.randint(1, 6)
if self.randx == 1:
self.x = 50
elif self.randx == 2:
self.x = 150
elif self.randx == 3:
self.x = 250
elif self.randx... |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
The MIT License (MIT)
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 res... |
#!/usr/local/bin/python3
#
# See https://theweeklychallenge.org/blog/perl-weekly-challenge-154
#
#
# Run as: python ch-2.py
#
print ("2, 3, 5, 7, 37, 151, 3329, 23833, 13091204281, 3093215881333057")
|
import numpy as np
import GeometryFunctions as gf
import MiscFunctions as mf
import GeneralLattice as gl
import LatticeDefinitions as ld
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import itertools as it
def PutAtomPositionsIntoList(inEdgeVectors: np.array, inLatticeBases: np.array, fltLatt... |
import openpyxl
wb = openpyxl.Workbook()
sheet1 = wb.active
cnt = 0
Tnum = 10000
for j in range(10):
for i in range(10):
path = 'C:/Users/Yeonkey/Desktop/DBLAB/유전알고리즘/Tinkerd_MST inputfile/Terminal_Result/EX'+str(j+1)+'/P110_'+str(Tnum)+'_50_'+str(i)+'_result.txt'
f = open(path, "r")
lines ... |
from django.shortcuts import render, redirect, get_object_or_404
from App_Shop.models import Product
from App_Order.models import Cart, Order
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.
def add_to_cart(request, pk):
items = get_object_o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List
def convert_to_absolute(number: float) -> float:
return number if number > 0 else -number
def use_prefixes() -> List[str]:
prefixes, suffixe = 'JKLMNOPQ', 'ack'
output = []
for letter in prefixes:
output.append(letter + ... |
rooms_num = int(input())
rooms = []
free_chairs = 0
for room in range(rooms_num):
rooms.append(input().split(' '))
for index, room in enumerate(rooms):
chairs = len(room[0])
taken = int(room[1])
free = chairs - taken
if free > 0:
free_chairs += free
elif free < 0:
print(f'{abs(f... |
import sys
import string
import numpy as np
import matplotlib as mpl
from matplotlib.font_manager import FontProperties
#import arrayUtil as au
import MFBinaryClass as mfb
reload(mfb)
def set_sizexaxis(a,fmt,sz):
success = 0
x = a.get_xticks()
# print x
xc = np.chararray(len(x), itemsize=16)
for i in range(0,le... |
class Solution:
def plusOne(self, digits):
s = ""
for i in digits:
s += str(i)
s = str(int(s)+1)
p = []
for i in list(s):
p.append(int(i))
return p
sol = Solution()
digits = [9,9]
print(sol.plusOne(digits)) ... |
from tkinter import *
root = Tk()
root.title("Tk Canvas")
cw = 400 # canvas width
ch = 400 # canvas height
canvas = Canvas(root, width = cw, height = ch, background = "white")
canvas.grid(row = 0, column = 0)
root.mainloop()
|
import os
import sys
path = 'C:\\Users\\JRA\\myProjects\\myProjects\\A'
dirs = os.listdir(path)
for file in dirs:
if file.lower().endswith('.txt'):
abPath = os.path.join(path,file)
timeStamp = os.path.getmtime(path)
print(abPath)
print(timeStamp)
#print(file)
#prin... |
from bs4 import BeautifulSoup
import urllib2
import html5lib
import time
#url = 'http://www.cnbc.com/pre-markets/'
url = 'http://www.bloomberg.com/markets/stocks/futures'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html5lib')
target = soup.find("tr", {"class": "data-table__row"}) #gets DJIA instead of S&... |
import csv
from sklearn.cluster import KMeans
import numpy as np
from sklearn import linear_model
from collections import defaultdict
import datetime
from sklearn.metrics import mean_squared_error
from math import sqrt
from random import randint
from sklearn.preprocessing import StandardScaler
from scipy.stats import t... |
# coding=utf-8
# Python爬虫——爬取豆瓣top250完整代码
# https://www.cnblogs.com/zq-zq/p/13974807.html
# 目录操作
import os
# 正则表达式
import re
# 访问SSL页面
import ssl
# 模拟阻塞
import time
# 获取URL得到html文件
import urllib.request as req
# Excel表格操作
import xlwt
# 解析网页
from bs4 import BeautifulSoup as bf
ssl._create_default_https_context = ssl... |
from ajenti.api import *
from ajenti.api.http import *
from ajenti.plugins import *
info = PluginInfo(
title='Core',
icon='link',
dependencies=[
],
)
def init():
import main
import api
import passwd
import controls_binding
import controls_containers
import controls_simple
... |
# Oh soldier Prettify my Folder
# path, dictionary file, format
# def soldier("C://", "harry.txt", "jpg")
import os
def soldier(path, file, format):
os.chdir(path)
i = 1
files = os.listdir(path)
with open(file) as f:
filelist = f.read().split("\n")
for file in files:
if file not... |
from subprocess import check_output
import time
def subjob(sub_command):
sub_command = sub_command.split()
subout = check_output(sub_command)
jobid = int(subout.split()[1][1:-1])
return jobid
def is_running(jobid):
bjobs_command = 'bjobs'.split()
bjobs_out = check_output(bjobs_command).split('... |
import os
from facebook_messenger_api import MessengerBot
import logging
def _validate_credentials(config):
if config is None:
msg = 'Corrupt credentials config'
raise Exception(msg)
if 'access_token' not in config:
msg = 'No page access token defined in test credentials config'
... |
#!/usr/bin/python
import sys
sys.path.append('/opt/contrail/lib/python')
import instance_service
import getopt
import logging
import socket
import subprocess
import re
from contrail_lib import rpc_client_instance, uuid_from_string
# global state
glb_interfaces = {}
# add-br <bridge>
def add_bridge(args):
cmd=... |
from bs4 import BeautifulSoup
from selenium.common.exceptions import TimeoutException
import requests
import re
from selenium import webdriver
import time
__author__ = 'Administrator'
defalut_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.30... |
import random
number_placement = [1, 2, 3, 4, 5, 6, 7, 8, 9]
player_1 = ""
computer = ""
choice = 0
board = ""
player_choice = []
i = False
# This is to decide which symbol the player is getting, is it X or O
while player_1 == "" or player_1 != "X" or player_1 != "O":
player_1 = input("What would ... |
#---------------------------------------------------------------------------------
# (c) 2013-2014 David Rajaratnam
#---------------------------------------------------------------------------------
#--------------------------------------------------------------------------
# Useful small utility functions and classes... |
from tkinter import Tk, Label, StringVar, END
from typing import Callable
from client.gui.error_message import VALIDATION_MESSAGES, AUTH_MESSAGES
from client.gui.menu.menu import menu_frame, menu_title
from client.gui.menu.player_component import PlayerComponent
from client.gui.view import View, ViewName
from client.c... |
import cs50
# Prompt user for change owed
dollars = 0
while dollars <= 0:
dollars = cs50.get_float("dollars = ")
# Convert dollars to cents to avoid floating-point imprecision
cents = int(round(dollars*100))
coins = 0
coins += cents // 25
# Amount of changed owed now equals remainder after dividing by 25... |
import sqlite3
from Forms._datasources import *
from Manager._User import User
from conf import load_in
import random
from flask import session, render_template, redirect
from Manager._FileController import FileController
import os
from ScraperTools.BuildModel import MakeModel, TestModel
import pickle
settings = load_... |
#coding:utf8
#generate all feature , all item will be train and create a model
import utils
import traceback
import datetime
import pdb
import time
start = time.time()
store_code = 5
period = 14
period_rst = [4, 5, 6, 7, 8]
# period_rst = [0, 3, 4, 7, 8, 9, 10]
try:
conn = utils.persist.con... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime
import os
import time
from nose.tools import *
from . import setup_each, teardown_each
from farnsworth.models import ChallengeSet, IDSRule, Round, Team
class TestIDSRule:
def s... |
# coding: utf-8
__author__ = "sunxr"
__version__ = "V1.0"
class ContactType:
"""联系类型元素定位"""
# 联系类型新增
ADDCONTACTTYPEINPUT = ("xpath", ".//*[@id='app']/div/div/div/div[2]/div[2]/div[1]/div/div[1]/input") # 新增联系类型文本框
ADDCONTACTTYPEBTN = ("xpath", ".//*[@id='app']/div/div/div/div[2]/div[2]/div") # 联系类... |
import ssl
import os
import urllib
from pymongo import MongoClient
username = '*********'
password = '*************'
mongoURI = f'mongodb+srv://{urllib.parse.quote(username)}:{urllib.parse.quote(password)}@ngapp-qfeen.mongodb.net/neargroup?retryWrites=true'
myclient = MongoClient(mongoURI, ssl_cert_reqs=ssl.CERT_NONE)... |
# To be compatible with Linux and other distros
#!/usr/bin/env python
# Import the shodan library
# and import the sys library
import shodan
import sys
def usage():
print("[!]Usage: ", sys.argv[0] + " <file_name> <shodan_api_key> <parameters> \n")
sys.exit()
# Now start the crutial part of ... |
#!/usr/bin/env python
# coding: utf-8
# # This project is to test my basic understanding of recommending systems. My goal is to tell you what movies are most similar to your movie choice.
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inl... |
import socket
import pickle
import time
import sys
# Advanced Features:
"""
1. Improved visuals for the program, including validation for server-client interaction.
Server closes when client force shuts down.
2. Ability to view other day's menu.
3. Ability to send the full transaction receipt after the u... |
from .test_db_base import DBTestsBase
from .context import bookstore # needed by pytest & therefore travis
from bookstore.db.dbops.inventory import add_inv, list_inv, del_inv
# Ref: https://gist.github.com/twolfson/13f5f5784f67fd49b245
# refactoring
class DBTests(DBTestsBase):
def setUp(self):
self.db ... |
#IMPORTS
import pygame
import sys
sys.path.append(".")
from Node import Node
import math
import time
pygame.init()
pygame.font.init()
# VARIABLES
height = 600
width = 800
screen = pygame.display.set_mode((width, height+100))
icon = pygame.image.load("cursor.png")
startSelected = False
endSelected = False
grid = []
ga... |
# import requests
#
# # #get
# # req = requests.get("https://financialmodelingprep.com/api/v3/financials/income-statement/AAPL,FB,GOOG")
# # print(req.status_code)
#
# #post --endpoint , and data along with it
# url = "https://jsonplaceholder.typicode.com/posts"
# data = {
# "title": 'foo',
# "body": 'bar',
# ... |
from nltk.tokenize import sent_tokenize, word_tokenize
# a word tokenizer separates sentences by words
# a sentence tokenizer separates paragraphs by sentences
# Corpora - body of text, ie: medical journals, presidential speeches, English language
# Lexicon - words and their means
example_text = 'Hello there, how are... |
from dev.setups_paper_gwp import *
from pathlib import Path
if __name__ == "__main__":
path_base = Path("/Users/akim/PycharmProjects/gsa_framework/dev/write_files/")
# 1. Models
num_params = 10000
# iter_corr = 4 * num_params
# gsa_corr = setup_corr(num_params, iter_corr, setup_morris4_model, pa... |
""" A collection of functions that transform OpenAPI spec to data structures convenient for codegen.
"""
import re
from pathlib import Path
from functools import reduce
from typing import NamedTuple, Mapping, Sequence, Generator, Optional, Callable, Any, Tuple, Union
from typeit.utils import normalize_name
import open... |
for i in range(7):
for j in range(4):
if j==2 or (i+j)==1 or (i==6 and j>0):
print("#",end="")
else:
print(end=" ")
print() |
from . import gp_emission_map
from .gp_illumination_map import *
from . import gp_map
from . import toy_model
from . import util
__version__ = "0.1.1"
|
#Enter a number: 4
#Enter a number: 5
#Enter a number: bad data
#Invalid input
#Enter a number: 7
#Enter a number: done
#16 2 5.3333333
#Write another program that prompts for a list of numbers as above and at the
#end prints out both the maximum and the miniumum of the numbers instead of a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.