text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
"""
m802_DSCsched.py
A script to power up and configure an IC-M802 for a DSC sked. ENSURE YOUR RADIO IS IN DSC WATCH MODE AND THEN TURNED OFF BEFORE YOU RUN THIS SCRIPT.
Created by Mark Pitman of sv Tuuletar and Mike Reynolds of sv Zen Again (vk6hsr@gmail.com)
This script requires the following p... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
acct_name = models.CharField(max_length=24) # primary_key=True "id" field is default
first_name = models.CharField(max_length=24)
last_name = models.CharField(max_length=24)
def ... |
from data_multiview import Data, PadBatch
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torch.optim as optim
import numpy as np
from sklearn.metrics import confusion_matrix
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_s... |
# Generated by Django 2.2.1 on 2019-07-12 14:33
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.AUT... |
import uuid
from app.main import db, flask_bcrypt
class Alumni(db.Model):
__tablename__ = "alumni"
alumni_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
alumni_uuid = db.Column(db.String(50), unique=True)
odoo_contact_id = db.Column(db.String(50), unique=True, nullable=False)
em... |
from cookiecutter.main import cookiecutter
import os
import psutil
import pkg_resources
def process(args):
# Create project from the cookiecutter-pypackage/ template
extra_context = {
'publish_host': os.uname()[1],
'docker_host_cache_dir': os.path.join(os.getcwd(), 'cache',),
'docker_h... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from pwn import *
#context.log_level = 'debug'
def main():
elf = ELF('./magic')
# libc = ELF('')
proc = remote('bamboofox.cs.nctu.edu.tw', 10000)
# proc = elf.process()
#log.debug('You may attatch this process to gdb now.')
#raw_input()
pr... |
# -*- coding: utf-8 -*-
# @Author: Sean
# @Date: 2016-03-29 21:44:28
# @Last Modified by: Seanli310
# @Last Modified time: 2016-04-12 22:46:33
from spacy.en import English, LOCAL_DATA_DIR
import spacy.en
import os
import preprocessing
import sys
def dependency_labels_to_root(token):
'''Walk up the syntactic ... |
"""Websocket API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import errno
import fnmatch
import glob
import heapq
import io
import json
import logging
import os
import re
import sqlite3
imp... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(16,GPIO.OUT)
for x in xrange(2):
GPIO.output(16, GPIO.HIGH)
time.sleep(.15)
GPIO.output(16, GPIO.LOW)
time.sleep(.15)
GPIO.output(16, GPIO.HIGH)
|
import json
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView, DetailView, ListView
from whiskydatabase.models import *
def distillery_list():
distillery_list = Distillery.objects.filter(is_active=True).distinct()
return... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from .models import Coupon, Claim
from accounts.models import Person
class IndexView(generic... |
import os,sys,inspect
import random
import numpy as np
import copy
import tagger as tg
import tag_utils as tu
from nltk.parse import stanford
from nltk import tree
lo2count = 'count ( <field>:0 )'
lo2avg = 'avg ( <field>:0 )'
lo4max_1 = 'max ( <field>:0 )'
# lo4min_1 = 'min ( <field>:0 )'
lo4max = '<field>:0 where (... |
__author__ = "Sean D'Rosario"
"""
Submission for HW 10 for DS-GA-1007
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import Assignment10 as a10
class Assignment10mainclass:
if __name__ == '__main__':
a10.read_data()
a10.main()
|
#!flask/bin/python
from flask import Flask, jsonify
from flask import request
from flask import abort
from flask import make_response
import false_packer
import json
app = Flask(__name__)
@app.route('/packer_faker/api/v1.0/pack_asin', methods=['OPTIONS'])
def option_interceptor():
response = make_response()
r... |
# In this notebook we use symbolic calculation to find all critical points of a function and the eigenvalues associated. This way we can know the shape of the maxima / minima
import sympy as sy
import plotly.graph_objs as go
x,y = sy.symbols('x y')
sy.init_printing(use_unicode=True)
#%% Define Function
f = x**4+y**2-... |
import re
def phoneNumberValidator(number):
pattern = '^[6-9][0-9]{9}$|^[0][6-9][0-9]{9}$|^[+][9][1][6-9][0-9]{9}$'
if re.match(pattern, str(number)):
#print("valid number")
return True
else:
#print("Not valid number")
return False
def emailValidator(email):
patter... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 16:50:16 2019
@author: HP
"""
class Node:
def __init__(self,data):
self.key=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def push(self,data):
new_node=... |
import healpy as hp
import healsparse as hsp
import numpy as np
from scipy.spatial import cKDTree
import astropy.io.fits as pyfits
from astropy.coordinates import SkyCoord
from astropy.cosmology import FlatwCDM
cosmo = FlatwCDM(H0=70, Om0=0.3)
def footprint_check(mask_file, ra, dec):
masks=pyfits.open(mask_file)[1... |
"""
TECHX API GATEWAY
COMMUNICATION WITH WEBEX TEAMS
CREATED BY: FRBELLO AT CISCO DOT COM
DATE : JUL 2020
VERSION: 1.0
STATE: RC2
"""
__author__ = "Freddy Bello"
__author_email__ = "frbello@cisco.com"
__copyright__ = "Copyright (c) 2016-2020 Cisco and/or its affiliates."
__license__ = "MIT"
# ==== Libraries ====
import... |
from rest_framework import serializers
from ebooks.models import Ebook, Review
class ReviewSerializer(serializers.ModelSerializer):
review_author = serializers.StringRelatedField(read_only=True)
class Meta:
model = Review
exclude = ("ebook",)
# fields = "__all__"
class EbookSeriali... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/4/8 19:07
# @Author :'liuyu'
# @Version:V 0.1
# @File :
# @desc :
import pandas as pd
from pandas import read_parquet
def verify_product(path):
data = read_parquet(path)
print(data.count())
data.head()
def verify_user(path):
data = read_pa... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from skimage import io
pic = io.imread("./data/bird_small.png") / 255.
io.imshow(pic)
print(pic.shape)
data = pic.reshape(128 * 128, 3)
def k_means(data, k, epoch=100, n_init=10):
"""do multiple random init and pick the best one to return
... |
N = 6
L = 1
NUM_SWITCHES = 49
|
#!/usr/bin/python
from Tkinter import *
w = Tk()
text = Text(w)
scrollbar = Scale(w, from_=0, to=5)
# Code to add widgets
text.insert(INSERT, "git gud skrub")
text.pack()
scrollbar.pack()
w.mainloop() #Main Window
|
# -*- coding: utf-8 -*-
# Copyright (C) 2018 by
# David Amos <somacdivad@gmail.com>
# Randy Davila <davilar@uhd.edu>
# BSD license.
#
# Authors: David Amos <somacdivad@gmail.com>
# Randy Davila <davilar@uhd.edu>
"""Function for computing the triameter of a graph.
"""
from itertools import combin... |
# Given a square matrix mat, return the sum of the matrix diagonals.
#
# Only include the sum of all the elements on the primary diagonal
# and all the elements on the secondary diagonal
# that are not part of the primary diagonal.
class Solution:
def diagonalSum(self, mat):
from numpy import... |
def drawpoly(myturtle,sides,length):
angle=360/sides
dside=0
while sides!=dside:
myturtle.right(angle)
myturtle.forward(length)
dside+=1
from turtle import *
n=int(input("number of sides>>"))
s=int(input("length of sides>>"))
t=Turtle()
drawpoly(t,n,s)
|
#coding=utf-8
import json
import sys # 导入sys模块,用于引入thrift生成的文件
import xlrd
reload(sys)
sys.setdefaultencoding('utf8')
#print os.path.abspath('..\\searchClient')
sys.path.append("../searchClient")
#sys.path.append(r'''E:\AutoTestInterface\search-service''')
from lib.Client import Client
#from searchClient.li... |
from tastypie.resources import ModelResource
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
import models
class TestResource(ModelResource):
class Meta:
queryset = models.Test.objects.all()
authorization = Authorization()
authentication =... |
# import the necessary packages
import os
import logging
from configuration import Config as cfg
from card_util import get_game_area_as_2d_array, rgb_yx_array_to_grayscale, \
find_contours, diff_polygons, display_image_with_contours, timeit
import numpy as np
logger = logging.getLogger(__name__)
trace_logger = lo... |
def read_out(acrostic):
return "".join([x[0] for x in acrostic])
'''
An acrostic is a text in which the first letter of each line spells out a word.
It is also a quick and cheap way of writing a poem for somebody, as exemplified below:
Write a program that reads an acrostic to identify the "hidden" word. Specific... |
# Generated by Django 3.1.5 on 2021-01-22 13:10
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('processer', '0003_remove_video_firstframe'),
]
operations = [
migrations.AddField(
model_name='vide... |
#获取分数
score = int(input('请输入你的分数(0-100)'))
if score >= 90:
print('A')
elif score>=80 and score<90:
print('B')
elif score>=70 and score<80:
print('C')
elif score>=60 and score<70:
print('D')
elif score>=0 and score<60:
print('E')
else:
print('输入错误')
|
#!/usr/bin/env python
# Copyright (c) 2015 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure that the (custom) NoImportLibrary flag is handled correctly.
"""
import TestGyp
import os
import sys
if sys.platform == 'wi... |
import math
import stl
from stl import mesh
import numpy
import glob
def combine_stl(data_dir):
'''This function combines all the STL file in a directory and merges them together'''
#storing all the stl file in a directory
stl_dir = 'data_dir/*.stl'
#Creating an Empty mesh to concatenate all the stl fi... |
# class 1
# 7/11/16
# Write a function that takes an input and does something with it
# Variables, inputs, basic methods
# radius of a circle
input_value = input("Enter a radius:")
radius = float(input_value)
area = 3.14159 * radius * radius
print("The area of a circle with radius " + input_value + " is: " + str(ar... |
"""
Main file
We will run the whole program from here
"""
import torch
import hydra
from train import train
from dataset import VQADataset
from models.base_model import VQAModel
from torch.utils.data import DataLoader
from utils import main_utils, train_utils
from utils.train_logger import TrainLogger
from omegaconf i... |
import os
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Input, Activation, Dropout, Flatten, Dense
from keras import callbacks
from keras import optimizers
import numpy as np
from resnet import ResnetBuilder
batch_size = 300
num_c... |
import pandas as pd
def to_reise(data):
"""Format data for REISE.
:param pandas.DataFrame data: data frame as returned by
:func:`prereise.gather.winddata.rap.rap.retrieve_data`.
:return: (*pandas.DataFrame*) -- data frame formatted for REISE.
"""
ts = data["ts"].unique()
plant_id = da... |
from django.urls import path
from .views import certPost, certDetailView, certUpdate, toProxyView
app_name ='manager'
info_post = certPost.as_view({
'post': 'create',
})
detail = certDetailView.as_view({
'get': 'list',
})
info_update = certUpdate.as_view({
'post': 'partial_update',
})... |
"""Helper modules for spectrum SimSUSY-based spectrum generators."""
|
# -*- coding: utf-8 -*-
"""
pelesent
~~~~~~~~~~~~~~~~~~~
Sentiment analysis from pelenudos to pelenudos
:copyright: (c) 2017 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
from __future__ import absolute_import, unicode_literals
import logging
import theano
theano.config.floatX = 'float32' # XXX... |
import numpy as np
import os
import re
from random import shuffle
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits import mplot3d
import random
class Data:
def __init__(self,config):
self.config = config
self.train_batch_index = 0
... |
import sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','..','lib')))
import time, pytest
from clsCommon import Common
import clsTestService
from localSettings import *
import localSettings
from utilityTestFunc import *
import enums
class Test:
#====================... |
import socket
import thread
import cPickle as cp
from thread import *
PortOfServer = 7734
SocketOfServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
NameOfSocket=socket.gethostbyname(socket.gethostname())
SocketOfServer.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
SocketOfServer.bind((NameOfSocket, PortO... |
# Generated by Django 2.0.2 on 2019-10-17 13:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20191015_1340'),
]
operations = [
migrations.RenameField(
model_name='product',
old_name='votes_totla'... |
# sending emails with python
# -*- coding: utf-8 -*-
import win32com.client as win32
import psutil
import os
import subprocess
# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification(recipient: str, textbody: str):
outlook = win32.Dispa... |
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class CustomObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
# Add custom claims
... |
from .model import ClsModel |
import os
import sys
from multiprocessing import Process
from enum import Enum
try:
from enum import IntFlag
except:
pass
from z import getp, setp
import logging
import util
try:
class Modes(IntFlag):
none = 0
trim = 1
zoom = 2
average = 4
more = 8
change = 1... |
import optparse
from socket import *
from threading import *
screenLock=Semaphore(value=1)
def connScan(tgtHost,tgtPort):
try:
connSkt=socket(AF_INET,SOCK_STREAM)
connSkt.connect((tgtHost,tgtPort))
connSkt.send('Hi!')
result=connSkt.recv(100)
screenLock.acquire()
prin... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def top_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering
Args:
logits: logits distribution shape (vocabulary size)
... |
import pickle
import math
import time
import numpy as np
from plotly.offline import plot
import plotly.graph_objs as go
from compute import grid_analytical_logF_conditional, sum_F_smart
from definitions import large_log_sum_array
from conditions import cond_map
def main():
# compute_count_vs_n(65536, 64)
pl... |
from time import sleep
from dateutil import parser
import datetime
import database
import pytz
import json
refresh = True # for debug
frequency = 10 # in minutes
"""
Why is this file called witchdoctor?
This file is called witchdoctor because it magically
handles all of the backend data parsing.
Simply fire i... |
import nltk
from nltk.corpus import wordnet as wn
from bs4 import BeautifulSoup
import urllib3
import html5lib
from tqdm import tqdm
def findOrigins(word):
urllib3.disable_warnings()
http = urllib3.PoolManager()
url = "http://www.dictionary.com/browse/antique"
response = http.request('GET', url)
soup = BeautifulS... |
#!/usr/bin/env python3
#
# This example shows how to run a combined fluid-kinetic simulation with
# with both the hot-tail and runaway electron grids.
#
# Run as
#
# $ ./basic.py
# $ ../../build/iface/dreami dream_settings.h5
#
# ###################################################################
import numpy as n... |
"""
The rabbitpy.queue module contains two classes :py:class:`Queue` and
:py:class:`Consumer`. The :py:class:`Queue` class is an object that is used
create and work with queues on a RabbitMQ server. The :py:class:`Consumer`
contains a generator method, :py:meth:`next_message <Consumer.next_message>`
which returns messa... |
n=int(input("Enter a limit:"))
for i in range(1,n+1):
for j in range(0,i+1):
a=i*j
if a==0:
continue
else:
print(a,end=" ")
print("\n")
|
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE... |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# 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/licen... |
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from ..preprocessing import data_splitting as ds, labels
def calc_f1_and_acc_for_column(true, predicted):
f1 = f1_score(true, predicted)
acc = accuracy_score(true, predicted)
return f1, ... |
with open(r"C:\Users\admin\OneDrive\デスクトップ\python1\07\20k1026-06-dictionary.txt",encoding="utf8") as file:
dict = input("キーを入力してください:") # input
for line in file:
data = line.split(":") # ["input", " " ]
if data[0] == dict:
print(f"{data[1]}")
#
'------------------------... |
import socket
client = socket.socket()
ip = '192.168.0.155'
port = 22564
client.connect((ip, port))
while True:
date = input('cmd:').strip()
if not date:
continue
elif date == 'q':
break
else:
client.sendall(date.encode('utf-8'))
output = ''
cmd_ack_result = clie... |
# File: hw4_part3.py
# Author: Joel Okpara
# Date: 2/28/2016
# Section: 04
# E-mail: joelo1@umbc.edu
# Description: Figures out how much money user made for charity
# based on the amount of pledges and plunges
def main():
pledges = int(input("How many pledges did you get? "))
value = 0
fkThis... |
"""
You've finished eating at a restaurant, and received this bill:
Cost of meal: $44.50
Restaurant tax: 6.75%
Tip: 15%
"""
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total = meal + meal * tip
print("%.2f" % total)
|
class Add:
requires = ["input"]
provides = ["output"]
def __init__(self, val):
self.val = val
def process(self, data):
data["output"] = data["input"] + self.val
class Mult:
requires = ["input"]
provides = ["output"]
def __init__(self, val):
self.val = val
de... |
#!/usr/bin/env python
"""
@file runner1_try.py
@author yao
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2009-2017 DLR/TS, Germany
latest version
"""
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import optparse
import random
import Gl... |
FROM continuumio/anaconda3:4.8.3
COPY . /usr/app/
EXPOSE 8501
WORKDIR /usr/app/
RUN pip install -r requirements.txt
CMD streamlit run pratice.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
port = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=3.0)
def readlineCR(port):
rv = ""
while True:
ch = port.read()
rv += ch
if ch=='\r' or ch=='':
return rv
def keysPS():
salida = {"PS1_CUADRAD... |
# -*- coding: utf-8 -*-
_ROOM_INIT_DATA={
"hs_hero":[
{
"uid": None, "heroId": 1, "buff":{}, "crystal":1, "name":"PA", "heroClass":"warrior", "element":"air", "atk": 0, "hp": 30, "skillId": 0, "flavorText":"The time is now!"
},
{
"uid": None, "heroId": 2, "buff":{}, "crystal":1, "name":"SK... |
from router_solver import *
class Instruction(object):
def __init__(self, character_name, movement, times=None):
self.character_name = character_name
self.movement = movement
if type(times) == int:
self.times = int(times)
# Verifica que dos instructiones sean iguales
d... |
# -*- coding: utf-8 -*-
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http:/... |
def should_check_command(data):
return data.IsChatMessage() and is_from_streaming_platform(data)
def is_from_streaming_platform(data):
return data.IsFromTwitch() or data.IsFromYoutube()
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class... |
from .depth_model import DepthNet
from .depth_net_res_net import DepthNetResNet
from .pose_model import PoseNet, PoseNetResNet
from .scaled_unsupervised_depth_model import ScaledUnsupervisedDepthModel
from .depth_evaluation_model import DepthEvaluationModel
from .multi_unsupervised_depth_model import MultiUnsupervisedD... |
import django_filters
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.utils.timezone import now
from elections.models import Election
from organisations.models import OrganisationGeography
class ElectionFilter(django_filters.FilterSet):
def election_intersects_local_a... |
import re
s="adfkasdjklfjdslf???"
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
print(s)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 8/2/2017 5:03 PM
# @Author : Winnichen
# @File : LoginPage.py
from pages.BasePage import BasePage
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_condition... |
#!/usr/bin/python3
import socket
import struct
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
host = socket.gethostbyname('vortex.labs.overthewire.org')
port = 5842
s.connect( (host, port) )
in1 = s.recv(4)
in2 = s.recv(4)
in3 = s.recv(4)
in4 = s.recv(4)
int1 = struct.u... |
import numpy as np
import matplotlib.pyplot as plt
import layer
import activation
import loss
import metric
import data
'''
nn_basics
--basic_neuron.py
--logical_operations.py
import nn_basics.basic_neuron as bn
import nn_basics.logical_operations as lo
network = bn.Neuron()
network.add_x(1, 1)
network.ad... |
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
from pygame import mixer
import random
import sys
import select
import math
#Constants
SOUND_FOLDER= "./sounds/"
LANGUAGE = "en"
EXT = ".wav"
#More sounds here http://theportalwiki.com/wiki/Turret_voice_lines#Turret_fire
SOUNDS_DETECTED = ["i_see_you","here_you_ar... |
a = 100
b = 200
c = a + b
print (c)
|
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType
from pyasn1.type.namedval import NamedValues
from asn1PERser.classes.data.builtin import *
from asn1PERser.classes.types.type import AdditiveNamedTypes
from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E... |
from keras.utils import to_categorical
from keras.models import load_model
from sklearn.model_selection import StratifiedKFold
import numpy as np
import pandas as pd
import spectral
import cv2
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_fscore_support, accuracy_score, cohen_kappa_score,... |
import socket
ServerSock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ServerSock.bind(('localhost',7777))
(ClientMsg, (ClientIP, ClientPort)) = ServerSock.recvfrom(1000)
ServerSock.sendto('xiu', (ClientIP, ClientPort))
print 'Client Message', ClientMsg
ServerSock.close()
|
import asyncio
import primes
from concurrent.futures import ProcessPoolExecutor as Pool
pool = Pool(max_workers=8)
async def primes_server(address):
server = await asyncio.start_server(primes_handler, *address)
addr = server.sockets[0].getsockname()
print(f"start on {addr}")
await server.serve_foreve... |
# -*- coding: utf-8 -*-
'''
Management of artifactory repositories
======================================
:depends: - requests Python module
:configuration: See :py:mod:`salt.modules.artifactory` for setup instructions.
.. code-block:: yaml
local_artifactory_repo:
artifactory_repo.repo_present:
- n... |
"""
Created on Sun Nov 22 17:26:01 2015
Script will do sentiment analysis on restaurant reviews.
@author: Ricky
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import Logi... |
from django.shortcuts import render, redirect
import random
VALUES = [
"alpha",
"bravo",
"charlie",
"delta",
"echo",
"foxtrot",
"golf",
"hotel",
"india",
"juliet",
"kilo",
"lima",
"mike",
]
def shuffle_values():
for i in range( len( VALUES ) / 2 ):
j = r... |
# -*- encoding : utf-8 -*-
import pandas as pd
from utils import emailUtils
def emailFormat(content):
d = ""
print(content)
for i in range(len(content)):
d = d + """
<tr>
<td align="center"><a href="http://10.10.12.47/zentao/bug-view-"""+str(content[i]["id"])+""".html"> ""... |
def DoWorkInGenerator(num_work_items):
for i in xrange(num_work_items):
print 'G do some work here'
yield i
print 'G do more work here'
for i in DoWorkInGenerator(3):
print i
################################################################################
def DoWorkWithCallback(num_work_items, callba... |
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from newsletter.weather import get_weather_json
from NotiWeather import settings
NICE_OUT_SUBJECT = "It's nice out! Enjoy a discount on us!"
POOR_OUT_SUBJECT = "Not so nice out? That... |
#!/Users/john/anaconda/bin/python3
print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
print('Hey, this works.')
|
import sys
from .parsing_structure import parse_symbols
__all__ = [
'parse_all_symbols',
'parse_all_sections_symbols',
]
def parse_all_symbols(args):
if not args:
for x in parse_symbols(sys.stdin, 'stdin'):
yield x
else:
for filename in args:
with open(filename)... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.openapi.util_rules import pom_parser
from pants.backend.openapi.util_rules.pom_parser imp... |
#coding:utf-8
import requests
import json
import time
import random
import io
#下载第一页数据
def get_one_page(url):
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'
}
response = requests.get(url,headers=headers)
if respo... |
def numOfRotations(arr,l,r):
if(r-l==1):
return arr[0] if arr[l]<arr[r] else arr[r]
if(r-l>1):
mid = (l+r)//2
if(arr[mid]<arr[r]):
return numOfRotations(arr,l,mid)
else:
return numOfRotations(arr,mid,r)
return arr[0]
arr = [15,2,3,6,12]
arr2 = [15,16,... |
import requests
import json
def get(url, headers={}, queryparams={}):
result = requests.get(url, headers=headers, params=queryparams)
return result.json()
def post(url, headers={}, data=None):
result = requests.post(url, headers=headers, data=json.dumps(data))
return result |
from Base import *
from Object import *
'''
Esta funcao cria um objeto do tipo Arvore e o retorna
@PARAMETROS
id_tex_livre - primeiro id de textura nao utilizado - passado como lista de tamanho 1
vertices_list - lista de coordenadas de vertices
textures_coord_list - lista de coordenadas de textura
norm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.