text stringlengths 38 1.54M |
|---|
from axiomathbf import ParametricLine
import sympy
from math import isclose
def test_compare():
l1 = ParametricLine(point=[2, 1, 4], vector=[3, -2, 5])
l2 = ParametricLine(point=[3, -2, -1], vector=[-6, 4, -10])
l3 = ParametricLine(point=[1, 0, 2], vector=[0, 1, -1])
l4 = ParametricLine(point=[2, 4, ... |
# Python program to volume of a shape
from math import *
shapes = dict()
shapes['cone'] = ''
shapes['cube'] = ''
shapes['cylinder'] = ''
shapes['rectangular prism'] = ''
shapes['pyramid'] = ''
shapes['sphere'] = ''
while True:
try:
shape = input(
"Insert the name of a 3D figure to find its sur... |
"""
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Constra... |
import jwt
from flask import jsonify, Blueprint, request, render_template
import json
from utils.dbutils import get_db_session
import utils.utils as utils
import bcrypt
from db.user import User
import random
import smtplib
import httplib2
import os
import base64
import uuid
login_routes = Blueprint('login_routes',... |
#!/usr/bin/env python3
import requests
import argparse
# CREATE TABLE test_suites
# (
# sha String,
# pr UInt16,
# suite String,
# errors UInt16,
# failures UInt16,
# hostname String,
# skipped UInt16,
# duration Double,
# timestamp DateTime
# ) ENGINE = MergeTree ORDER BY tuple(timestamp, suite);
QUERY_SUITES="INSER... |
def impares():
n = 13
h = ''
while n <= 32:
if n%2 != 0:
h += ' %i' % n
n += 1
print (h)
impares()
|
import socket
import time
import os
import sys
from tqdm.auto import tqdm
host = input("Enter Address to Connect\n")
try:
port = int(1234)
except ValueError:
print("Error. Exiting. Please enter a valid port number.")
sys.exit()
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Receive... |
def cube(x):
return x * x * x
def square(x):
return x * x
def cube_root(x):
def improve_guess( y):
return (x/square(y) + 2 * y) / 3
def good_enough(guess):
v = abs(cube(guess) - x)
return v < 0.001
def cube_iter(guess):
if good_enough(guess):
print("-... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.patches as mpatches
datasets =[
"./datasheet/ring.csv",
"./datasheet/circularladdar.csv",
"./datasheet/hypercube.csv",
"./datasheet/complete.csv"
]
demo = {
"ring":{
"label":"ring",
"color":... |
import random
from tkinter import *
import tkinter as tk
import csv
def file_to_list(path):
'''
Turns a .txt file with a word list into a Python list
'''
list = []
with open(path, mode='r', encoding='utf-8') as file_reader:
for row in file_reader:
list.append(row.rstrip('\n'))... |
import importlib, os, logging, sys, ast, asyncio
MODULES_NAME="modules"
class Module():
"""There is no help for this module"""
def __init__(self):
self.name = "Unknown"
self.config = {}
def config_complete(self):
pass
# Will always be called after config loaded.
async def ... |
#Python获取pid和进程名字
# 1,安装psutil
#
# pip
# install
# psutil
#
# 如果pip不识别,就进入下载的python目录下面执行:。。。Python36\Scripts
#
# 2,获取信息代码
#o
import psutil;
import os;
import signal;
for proc in psutil.process_iter():
print("pid-%d,name:%s" % (proc.pid, proc.name()))
if proc.name() == "chrome.exe" or proc.name() == "chromedr... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 00:00:00 2018
@author: elcid
"""
""" Setup logging and environment """
# simulate that sarcasmdetection is installed as a python package
import context
#%%-----------------------------------------------------------------------------
import logging
from sarcasmdetecti... |
from django.apps import AppConfig
class ClienteFacadeConfig(AppConfig):
name = 'cliente_facade'
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 6 18:51:27 2011
@author: -
"""
import os
import re
import subprocess
n_runs = 50
project_dir = '/home/cheesinglee/workspace/cuda-PHDSLAM'
measurements_regex = r'(measurements_filename\s*=\s*).+'
controls_regex = r'(controls_filename\s*=\s*).+'
for n in xrange(n_runs):... |
from typing import Type, List, Optional
from probability.calculations.calculation_types.probability_calculation import \
ProbabilityCalculation
from probability.calculations.calculation_context import CalculationContext
from probability.calculations.mixins import OperatorMixin, \
ProbabilityCalculationMixin
fr... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 10:55:52 2019
@author: mckaydjensen
"""
import sys
sys.path.append(r'R:\JoePriceResearch\Python\Anaconda3\Lib\site-packages')
import pandas as pd
import numpy as np
import recordlinkage
import re
from sklearn.ensemble import RandomForestClassifier
from joblib import... |
import sys
import json
import argparse
from .parse import parse
from .gen_futil import emit
from .interp import interp, InterpError
def main():
parser = argparse.ArgumentParser(
"Interpret a MrXL program, or compile it to Calyx."
)
parser.add_argument(
"--i",
"--interpret",
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 10:47:31 2019
@author: 44775
"""
""" Aspiration Search """
import chess
import chess.syzygy
import chess.polyglot
import random
from ChessCore import BoardEval
def calcMinimaxMoveTT(board,depth,isMaximizingPlayer,alpha,beta):
if (depth == 0) ... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import traceback
import os
import re
import json
import hashlib
import mimetypes
import httplib2
import httplib
from .models import Lesson
from .models import Module
from .models import Question
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 5 17:43:35 2023
@author: Dartoon
"""
import numpy as np
import astropy.io.fits as pyfits
import matplotlib.pyplot as plt
import glob
import sys
import pickle
from galight.data_process import DataProcess
from galight.tools.astro_tools import read_... |
env = Environment(CCFLAGS = ['-DMY_VALUE'])
env.Append(CCFLAGS = ['-DLAST'])
env.Program('foo.c') |
from flask_caching.backends import SimpleCache
cache = SimpleCache(threshold=100, default_timeout=300)
|
#!/usr/bin/env python
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from qt.main import MainWindow
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow(app)
w.show()
app.exec_()
print 'after exec'
app.quit()
sys.exit()
|
'''
Created on 16 dec. 2016
@author: Camelia
'''
class PersonException(Exception):
pass
class PersonValidator(object):
@staticmethod
def validate(person):
err = ""
if len(str(person.entity_id)) == 0:
err += "Person must have an ID!"
if len(str(person.nam... |
def game(input, turns=2021):
memory = {}
for index, i in enumerate(input[:-1]):
memory[i] = index
last_spoken = input[-1]
for i in range(len(input), turns):
if memory.get(last_spoken, None) is None:
to_spoke = 0
else:
to_spoke = i-1-memory[last_spoken]
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 30 18:38:54 2021
@author: Goegg
"""
from spacy.lemmatizer import Lemmatizer, ADJ, NOUN, VERB
import pickle
import spacy
import re
dic = pickle.load( open( r"C:\Users\Goegg\OneDrive\Desktop\Durchgänge\PI.pickle", "rb" ) )
nlp = spacy.load("de_core_news_lg")
regex = "(ftp:... |
#!/opt/conda/bin/python
import argparse
import os
import sys
from typing import Dict
import urllib3
import yaml
from jinja2 import Environment, FileSystemLoader, select_autoescape
from kubernetes import client, config
urllib3.disable_warnings()
KERNEL_POD_TEMPLATE_PATH = "/kernel-pod.yaml.j2"
def generate_kernel_p... |
def solution(m, n, puddles):
answer = 0
ways = [[0]*(m+1) for _ in range (n+1)]
for t in range (len(puddles)):
ways[puddles[t][1]][puddles[t][0]] = 'x'
for y in range (1, n+1):
if ways[y][1] == 'x':
continue
ways[y][1] = 1
for x in range (1, m+1):
... |
import io
import struct
from datetime import datetime
from typing import Any, Callable, Optional
from .const import *
from .inverter import Sensor, SensorKind
class Voltage(Sensor):
"""Sensor representing voltage [V] value encoded in 2 bytes"""
def __init__(self, id_: str, offset: int, name: str, kind: Opti... |
import os
import bz2
import logging
import sys
from gensim.corpora.dictionary import Dictionary
from gensim.corpora import MmCorpus
from gensim.similarities import MatrixSimilarity
from gensim.corpora.wikicorpus import filter_wiki, extract_pages
from gensim.models import TfidfModel
# Add current dir to Python path
... |
s1 = 'https://ladsweb.modaps.eosdis.nasa.gov/archive/orders/501435569/'
files = ['VNP46A1.A2019001.h10v10.001.2019077152637.h5',
'VNP46A1.A2019001.h10v11.001.2019077152501.h5',
'VNP46A1.A2019001.h10v12.001.2019077154226.h5',
'VNP46A1.A2019001.h11v10.001.2019077153127.h5',
'VNP46A1.A2019001.h11v11.001.2019077152320.h5'... |
import torch
import ee
import time
import os
import json
ee.Initialize()
if __name__ == "__main__":
# Specify cloud storage bucket to save data too
BUCKET = 'ee-rsqa'
TF_DIR = ""
# Make a dictionary that maps Earth Engine outputs and inputs to
# AI Platform inputs and outputs, resp... |
# -*- coding: utf-8 -*-
"""
Export schema as SDL.
"""
import itertools
from typing import Any, Sequence, Union
from .._string_utils import wrapped_lines
from .._utils import flatten
from ..lang import print_ast
from ..schema import (
SPECIFIED_DIRECTIVES,
SPECIFIED_SCALAR_TYPES,
Argument,
Directive,
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
# This module is part of the package GTW.OMP.SRM.
#
# This module is licensed under the... |
import pandas as pd
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import train_test_split
from kobra.tr_utils import time_now_str
import numpy as np
import sklearn.preprocessing as prep
from sklearn import metrics
sample_file = '/kaggle/re... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from common.utils import logger
from test import test
class complex(test):
__list = {}
@property
def list(self):
return self.__list
def __new__(cls, **parameters):
logger.debug("New complex test")
inst = test.__new__(cls, **pa... |
import numpy as np
import random
from copy import deepcopy
def softmax(x):
return np.exp(x - np.max(x)) / np.exp(x - np.max(x)).sum()
def ReLU(x):
return max(x, 0)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def generateWeights(layerData, inputQuantity):
layerDepthLimit = len(layerData)
augmente... |
import sqlite3
import os
cur_dir = os.path.dirname(os.path.realpath(__file__))
DATABASE = cur_dir+'/tanyas_job.db'
def connect_db():
conn = sqlite3.connect(DATABASE)
return conn
def close_db():
conn = connect_db()
conn.close()
def create_email(email):
conn = connect_db()
c = conn.cursor()
c.execute("INSERT... |
currentlyFoundNums = []
for a in range(2, 101):
for b in range(2, 101):
if a**b not in currentlyFoundNums:
currentlyFoundNums.append(a**b)
print(len(currentlyFoundNums))
|
#!/usr/bin/python
import sys
from collections import Counter
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="verbose", action="store_true")
parser.add_argument("-s", "--short", help="short answer", action="store_true")
parser.add_argument("-g", "--group", help="group le... |
class Nqueen():
def __init__(self, N):
self.N = N
self.boards = [[[0] * self.N for _ in range(self.N)] for _ in range(self.N)]
self.temp = [[0] * self.N for _ in range(self.N)]
self.count = 0
self.verify()
def verify(self, boardIndex = 1):
if boardIndex == self.... |
# Geek lost the password of his super locker. He remembers the number of digits N as well as the sum S of all the digits of his password. He know that his password is the largest number of N digits that can be made with given sum S. As he is busy doing his homework, help him retrieving his password.
#
# Example 1:
#... |
import configparser
import os.path
import os
import click
import re
from .cli import run
run(prog_name='ghia')
|
import os
import sys
import re
import time
import paramiko
from scp import SCPClient
class SSH(object):
# 初始化参数
def __init__(self, host, port, username, passwd):
self.__host = host
self.__port = port
self.__username = username
self.__passwd = passwd
self.__stdin = ''
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup python package."""
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
requirements = [
"numpy>=1.16.1",
"pandas>=1.1.4",
"scikit_learn>=0.22.2.post1",
"scipy>=1.2.0",
"tqdm>=4.... |
# -*- coding: utf-8 -*-
class StartsWithEqual(object):
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.startswith(other)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return self.name
def __str__(... |
#!/usr/bin/python3
import Lab
class Plateau:
def __init__(self) -> None:
self.var_lab = Lab.Labyrinth((21,21),0,0) |
import rospy
import actionlib
from actionlib_msgs.msg import *
from squirrel_manipulation_msgs.msg import DropAction, DropGoal, DropResult, PutDownAction, PutDownGoal, PutDownResult, PtpAction, PtpGoal
from kclhand_control.msg import ActuateHandAction, ActuateHandGoal
from visualization_msgs.msg import Marker
class Me... |
#!/usr/local/bin/python3
import sys, json
from util import HTTP
import chatserv
#chatserv.io.transports['xhr-polling']: sys.modules[__name__]]
def connect(sock):
while True:
response = HTTP.get(
'http://' + sock.server + ':' + sock.port + '/socket.io/1/xhr-polling/' + sock.session + '/',
{
'name': chats... |
from sqlalchemy import Column, Integer, String, Date, TIMESTAMP
import datetime
from utils.dbutils import get_base
import uuid
Base = get_base()
class EventType(Base):
__tablename__ = 'event_type'
id = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
def __init... |
"""Class for performing a full ACSD analysis."""
import itertools
import os
import numpy as np
from mala.datahandling.data_converter import descriptor_input_types, \
target_input_types
from mala.descriptors.descriptor import Descriptor
from mala.targets.target import Target
from mala.network.hyperparameter import... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name='company'
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^(?P<c_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<a_id>[0-9]+)/app_detail/$', ... |
import numpy
m,n=map(int,input().split())
a=[]
b=[]
for i in range(m):
a.append(list(map(int,input().split())))
for j in range(m):
b.append(list(map(int,input().split())))
a=numpy.array(a)
b=numpy.array(b)
print(numpy.add(a,b))
print(numpy.subtract(a,b))
print(numpy.multiply(a,b))
print(a//b)
print(numpy... |
import multiprocessing
import numpy as np
import os
import sys
from sklearn.decomposition import MiniBatchDictionaryLearning
if len(sys.argv) != 4:
sys.stderr.write('usage: %s data_dir cosim_size dict_size\n' % sys.argv[0])
sys.exit(1)
data_dir = sys.argv[1]
cosim_size = int(sys.argv[2])
dict_size = int(sys... |
# Get Dataset
from scipy.io import loadmat
import pdb
import numpy as np
from DisplayCorrespondence import DisplayCorrespondence
from LinearPnP import LinearPnP
from triangulation import LinearTriangulation
from epipolar_correlations import EstimateFundamentalMatrix, EssentialMatrixFromFundamentalMatrix
data = loadma... |
#napisi program koji za ucitani broj ispisuje zbroj njegovih znamenki
a=int(input())
s=0
a=abs(a)
for i in str(a):
s+=int(i)
print (s)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/6 21:07
# @Author : Hongjian Kang
# @File : train.py
import os
import tensorflow as tf
from ResNet_registration_3D.model.ResNet import ResNetRegressor
from ResNet_registration_3D.trainNet.config_folder_guard import config_folder_guard
from ResNet_r... |
from typing import List
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
from . import ids
import pandas as pd
def render(app: Dash, data:pd.DataFrame) -> html.Div:
all_nations = ["South Korea", "China", "Canada"]
@app.callback(
Output(ids.NATION_DROPDOWN, "value"),
... |
import socket
import twisted
from twisted.internet import reactor
from twisted.python import log
from coapthon.client.coap_protocol import CoAP, HelperClient
from coapthon.proxy.forward_coap_protocol import ProxyCoAP
__author__ = 'giacomo'
class CoAPForwardProxy(ProxyCoAP):
def __init__(self, host, port, client)... |
'''
__created__= '31 Oct 2019'
__developer__ = 'disooqi@gmail.com'
'''
import numpy as np
import pandas as pd
from scipy.io import arff
from sklearn.preprocessing import OneHotEncoder, LabelEncoder, OrdinalEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklea... |
import boto3
import csv
#Enter your own aws keys
s3 = boto3.resource('s3', aws_access_key_id = '', aws_secret_access_key='')
dyndb = boto3.resource('dynamodb',aws_access_key_id = '', aws_secret_access_key='', region_name='us-west-2')
try:
s3.create_bucket(Bucket='datacont-kevitsui', CreateBucketConfiguration={'... |
from django.db import transaction
from rest_condition import And, Or
from rest_framework import viewsets
from rest_framework.response import Response
from applications.models import Repository
from common import permissions
from common.utils import git
from projects.mixins import ProjectViewSetMixin
from .models impor... |
"""RIOT pkg generator module."""
import os
import click
from .common import load_and_check_params, check_overwrite, render_source
PKG_PARAMS = {
"name": {"args": ["Package name"], "kwargs": {}},
"displayed_name": {
"args": ["Package displayed name (for doxygen documentation)"],
"kwargs": {},... |
# -*- coding: utf-8 -*-
import re
pattern = re.compile('(http|ftp)(?!(ru)\w+)', re.DOTALL)
# result = pattern.findall(raw_input())
# result = pattern.match('httpuururrururruruurururrrrrurrurrurruruuruuu')
result = pattern.findall('ftphttprururu')
# result = pattern.findall('httpuururrururruruurururrrrrurrurrurruruuru... |
from src.all_imports import *
import src.steps.utilities as utils
class BasePage():
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(self.driver, 20)
self.logger = utils.create_logger()
def click_element_by_xpath(self, xpath):
try:
element... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'create_project.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# 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 QtCor... |
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
import os
from OCC.Core.gp import gp_Pnt
from OCC.Core.IFSelect import IFSelect_RetError
from OCC.Core.Interface import Interface_Static_SetCVal
from OCC.Core.STEPConstruct import stepconstruct_FindEntity
from OCC.Core.STEPControl import STEPCon... |
from models.device import Device
from models.location import Location
from app_config import db
def addLocationPoint(item):
device_id = item['device_id']
recorded_at = item['recorded_at']
data = item['data']
geometry = data['geometry']
location_type = geometry['type']
longitude = geometry[... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
import django
django.setup()
from rango.models import Category, Page
def update():
category_list = Category.objects.all()
page_list = Page.objects.all()
n = 1
m = 2
for category in category_list:... |
__author__ = 'QiYE'
import numpy
import scipy.io
import theano
from src.utils import constants, xyz_result_path
dataset_path_prefix=constants.Data_Path
setname='msrc'
dataset ='test'
if setname =='icvl':
hol_path = xyz_result_path.icvl_hol_path
hol_derot_path = xyz_result_path.icvl_hol_derot_path
hier... |
import gym
import time
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
# from tensorboardX import SummaryWriter
import ipdb
from utils import *
from functions import *
def getTrajectoryLoss... |
from django.db import models
# Create your models here.
class Trainer(models.Model):
first_name=models.CharField(max_length=20,null=True)
last_name=models.CharField(max_length=16,null=True)
email=models.EmailField(max_length=30,null=True)
phone_number=models.CharField(max_length=15,null=True)
prof... |
from rest_framework import serializers
class CreditCardSerializer(serializers.Serializer):
cc_num = serializers.IntegerField()
cvv = serializers.CharField()
exp_date = serializers.CharField(max_length=128)
trans_id = serializers.IntegerField()
|
from flickrapi import FlickrAPI
import urllib.request
import requests
from pprint import pprint
from dotenv import load_dotenv
import os, time, sys
load_dotenv()
key = os.environ.get('FRICKR_KEY')
secret = os.environ.get('FRICKR_SECRET')
wait_time = 1
animal_name = sys.argv[1]
save_dir = "../images/" + animal_name
... |
'''
爬取链家租房信息
'''
import requests
from bs4 import BeautifulSoup
import pandas as pd
def text():
ips = ["115.219.108.246:8010", "117.88.5.135:3000", "114.223.208.165:8118"]
Lists = []
for page in range(2,100):
url = "https://sz.lianjia.com/zufang/pg%s/#contentList" % page
headers = {'User-... |
import pandas as pd
from os.path import join, dirname, realpath, exists
from os import listdir, makedirs
import re
import config
StartDate = config.StartDate
EndDate = config.EndDate
SpeciesCode = config.SpeciesCode
folder = join(dirname(dirname(realpath(__file__))), f"{StartDate}_{EndDate}")
batch_files = [file for... |
import math
from utils.opbox import *
class Anchors:
"""
This class generate anchors.
"""
def __init__(self, stride, ratios, scales):
self.stride = stride
self.ratios = ratios
self.scales = scales
self.anchor_num = len(self.scales) * len(self.ratios)
self.anch... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# This tries a couple function-fitting routines to find the best-fit
# Layden coefficients if the input data is synthetic data with no errors
# Created 2020 Jan. 25 by E.S.
# #### In the following, we plot fits in KH space and write out data including the BIC to sele... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013, 2014 Intel Corporation.
# Copyright 2013, 2014 Isaku Yamahata <isaku.yamahata at intel com>
# <isaku.yamahata at gmail com>
# All Rights Reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); ... |
#-*-coding: utf-8 -*-
"""
This job conducts search in Whoosh index.
Created on Sep 2013
@author: zul110
"""
from mrjob.job import MRJob
from mrjob.protocol import PickleProtocol
from match_engine.functions.index_processor import IndexProcessor
from match_engine.datamodel.tv_rec import TvRec
from match_engine.datam... |
#!/usr/bin/env python
# coding=utf-8
import re
#file=open('./weihai1.html','r')
file2=open('./wwwList.txt','a+')
for time in range(1,6):
time_str="%d" %time
name=time_str + '.htm'
file=open(name,'r',encoding='utf-8')
for line in file:
if "tobacco" in line:
file2.write(line)
... |
x = int(input("Give me any number between 1 and 10 "))
if 1 <= x <= 10:
print("good job")
else:
print("You did not follow the range")
#opposite codition:
if x < 1 or x > 10:
print("You did not follow the range")
else:
print("Good job!")
|
import tkinter as tk
class ChangeUsername(tk.Frame):
def __init__(self,master):
mainchangeusername_frame = tk.Frame(master.editprofile.maineditprofile_frame,bg = "white")
mainchangeusername_frame.place(relheight = 1,relwidth = 1)
back_button = tk.Button(mainchangeusername_frame,bg = "black",fg = "white",tex... |
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class ArticleSpider(CrawlSpider):
name = 'articles'
allowed_domains = ['wikipedia.org']
start_urls = ['https://en.wikipedia.org/wiki/'
'Benevolent_dictator_for_life']
rules = [Rule(LinkExtract... |
#!/usr/bin/env python
from manimlib.imports import *
from wifi_creature.wifi_creature import *
# To watch one of these scenes, run the following:
# python -m manim example_scenes.py SquareToCircle -pl
#
# Use the flat -l for a faster rendering at a lower
# quality.
# Use -s to skip to the end and just save the fina... |
# coding: utf-8
"""sGDML force field"""
__all__ = ['GDMLPredict']
# MIT License
#
# Copyright (c) 2019-2020 Jan Hermann, Stefan Chmiela
# modified by Alexander Humeniuk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... |
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... |
#
# Copyright (c) 2019 Juniper Networks, Inc. All rights reserved.
#
from builtins import object
try:
# python2.7
from collections import OrderedDict
except Exception:
# python2.6
from ordereddict import OrderedDict
from builtins import str
import copy
import itertools
import sys
from time import time ... |
# Generated by Django 3.2.5 on 2021-09-12 21:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('characters', '0012_alter_limitingbeliefs_beliefs'),
]
operations = [
migrations.RenameModel(
ol... |
import logging
from sqlalchemy.sql.expression import false, true
from sqlalchemy.sql.functions import func
from models import Sensor, Zone
from constants import ARM_AWAY, ARM_STAY, LOG_MONITOR
logger = logging.getLogger(LOG_MONITOR)
def get_arm_delay(session, arm_type):
if arm_type == ARM_AWAY:
return... |
import pandas as pd
import numpy
import gensim
Len = 256
train_df = pd.read_csv('../input/train.csv', sep='\t')
datas = train_df.loc[:, ['summary', 'reviewText']]
f = open('../data/train.txt', 'w')
for i in range(datas.shape[0]):
print(datas.loc[i].summary, datas.loc[i].reviewText, file = f)
f.close()
tr... |
from scapy.all import *
import arp_spoofing
arp_check = arp_spoofing.ARP_Spoofing()
def Server():
Run_Scan_Insert()
def Detection(p):
if (ARP in p) and (p[ARP].op == 2):
arp_check.check(p)
def Run_Scan_Insert():
print "Starting to sniff network fraffic..."
while True:
packet = sniff(count = 1, prn = De... |
9-25-17
M and A
Redefining terms
Security -> lien on assets of borrower
Seniority / subordination -> seniority built into debt. Structural handles subsidiaries vs parents
M & A Valuation
3 ways of valuing a company
Comparible companies
Overly simplistic
Relies on valuations at just one point in ti... |
'''
Created on 17 Dec 2017
@author: Daniel
'''
import random
import matplotlib.pyplot as plt
import pandas as pd
import math
import numpy as np
def create_city_frame():
#Generate Set of Cities
num_cities=5+int(math.floor(10.0*random.random()))
print("Number of Cities: " + str(num_c... |
import scrapy
from scrapy.loader import ItemLoader
from ..items import BabbremendeItem
from itemloaders.processors import TakeFirst
class BabbremendeSpider(scrapy.Spider):
name = 'babbremende'
start_urls = ['https://www.bab-bremen.de/bab/erfolgsgeschichten.html']
def parse(self, response):
post_links = respon... |
#coding=utf8
from collections import namedtuple
import mxnet as mx
import numpy as np
import six.moves.cPickle as cPickle # pylint: disable=no-name-in-module,import-error
import time
from aisdk.framework.base_forward import BaseForwardServer
from aisdk.common.mxnet_base import net
from aisdk.common.logger import log... |
''''
Input : arr= [10, 20, 20, 10, 10, 20, 5, 20]
Output : 10 3
20 4
5 1
Input : arr = [10, 20, 20]
Output : 10 1
20 2
'''
arr= [10, 20, 20, 10, 10, 20, 5, 20]
mydict = {
}
for elem in arr:
if elem not in mydict:
mydict[elem] = 1
else:
mydict[elem] = mydict[ele... |
# coding=UTF-8
'''
条件、循环和其他语句
'''
print("--------------print语句-------------------")
# print要打印多个变量,直接用逗号隔开即可,打印结果以空格隔开
# Python3.0中不再支持print 1,2,3的写法,不再是语句,变成函数
print(1, 2, 3)
# 不采用格式化字符串的方法打印
name = 'Tom'
hello = '中午好'
print(name + ',', hello + '!')
print("--------------import语句-------------------")
... |
import csv
FILENAME = r'etc-passwd.txt'
"""
root:x:0:0:root:/root:/bin/bash
watney:x:1000:1000:Mark Watney:/home/watney:/bin/bash
jimenez:x:1001:1001:José Jiménez:/home/jimenez:/bin/bash
ivanovic:x:1002:1002:Иван Иванович:/home/ivanovic:/bin/bash
"""
with open(FILENAME, encoding='utf-8') as file:
fieldnames = ['u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.