text stringlengths 38 1.54M |
|---|
from django.db import models
class Notice(models.Model):
title = models.CharField(verbose_name='제목', max_length=255, null=False, blank=False)
content = models.TextField(verbose_name='내용', null=False, blank=False)
author = models.ForeignKey('accounts.User', db_column='user_pk', related_name='author', verbos... |
import random
def m(a,b):
i,j = 0,0
c = []
while i+j < len(a) + len(b):
if i == len(a):
c += [b[j]]
j += 1
elif j == len(b):
c += [a[i]]
i += 1
elif a[i] <= b[j]:
c += [a[i]]
i += 1
else:
c... |
import sqlite3
import os
class DB:
conn_aspects = None
conn_reviews = None
conn_merged = None
conn_sentence = None
conn_aspects_one_word = None
conn_reviews_one_word = None
conn_sentences_one_word = None
conn_pmi_review = None
conn_pmi_sentence = None
conn_pmi_ideal_review = No... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
#
import pymssql
from scrapy import log
import datetime
from decimal import Decimal
import decimal
class sqlserver(object):
... |
import sys,os
import socket
import threading
import elevate
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
server.bind((local_host,local_port))
except:
print ("[!!] Erreur d'ecoute sur %s:%d" %... |
__author__ = 'Alex'
from ._mixin import FilterMultipleObjectMixin, UserFilterMultipleObjectMixin
from ._task import TaskListCreateView, TaskListActiveView, TaskListArchivedView, TaskDetailCompleteView
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
... |
import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from SA import SimulatedAnnealingBase
def swap(individual):
n1, n2 = np.random.randint(0, individual.shape[0] - 1, 2)
if n1 >= n2:
n1, n2 = n2, n1 + 1
individual[n1], indiv... |
# pantherine.py
# Author: Quentin Goss
# My personal collection of python methods that I frequently use
import operator # sortclasses, sortdicts
import pickle # load, save
import os # lsdir
import itertools # lncount
import glob # mrf
import xml.etree.ElementTree as ET # readXML
from bisect import bise... |
import pytest
import numpy as np
from gradgpad.foundations.metrics.hter import hter
scores = np.array([0.0, 0.2, 0.2, 0.5, 0.6])
labels = np.array([1, 2, 2, 0, 0])
expected_hter = 0.66
th_eer_dev = 0.25
@pytest.mark.unit
def test_should_throw_an_exception_when_input_is_not_np_array():
pytest.raises(TypeError, l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Generate a report for a list of project on XNAT
@author: Benjamin Yvernault, Electrical Engineering, Vanderbilt University
'''
from datetime import datetime
import logging
import os
from dax import XnatUtils
from dax.errors import XnatToolsError, XnatToolsUserError... |
import click
import logging
import multiprocessing
import signal
import sys
import yaml
import replicategithub
def set_up_logging(level=logging.WARNING, library_level=logging.WARNING):
logging.captureWarnings(True)
handler = logging.StreamHandler(stream=sys.stdout)
try:
import colorlog
ha... |
"""
Author: Nathan Lim
EDITING LOG:
May 3 - write incoming data from arduino to text file for matlab interpretation, improved GUI aesthetics, display label for heart rate
May 4 - use Method of Backward Difference (first order) to find the heart rates, can display MOBD data,
"""
from Tkinter import *
#import tkMes... |
import boto3
import os
from dotenv import load_dotenv
load_dotenv()
def set_resource():
s3 = boto3.resource('s3', aws_access_key_id=os.environ.get('access_key'),
aws_secret_access_key=os.environ.get('secret_key'),
region_name=os.environ.get('region'))
return s3
def get_s3_buckets(... |
class SpaceAge:
# Planet Years in seconds
EARTH_YEAR = 31557600.0
MERCURY_YEAR_RATIO = 0.2408467
VENUS_YEAR_RATIO = 0.61519726
MARS_YEAR_RATIO = 1.8808158
JUPITER_YEAR_RATIO = 11.862615
SATURN_YEAR_RATIO = 29.447498
URANUS_YEAR_RATIO = 84.016846
NEPTUNE_YEAR_RATIO = 164.79132
d... |
import os
from sqlalchemy import create_engine, Column, Text, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def new_db(path):
engine = create_engine(path)
Base.metadata.create_all(engine)
Base.... |
import numpy as np
import cv2
img = cv2.imread('../images/typewriter.jpg')
#print(img.shape)
with open('../model/synset_words.txt', 'r') as syn_f:
all_rows = syn_f.read().strip().split("\n")
classes = [r[r.find(' ')+1:] for r in all_rows]
net = cv2.dnn.readNetFromCaffe('../model/bvlc_googlenet.prototxt... |
#!/usr/bin/env python
import codecs
import optparse
import os
import sys
import hashlib
import os.path
import uuid
# simplejson is included with Python 2.6 and above
# with the name json
if float(sys.version[:3]) >= 2.6:
import json
else:
# python 2.4 or 2.5 can also import simplejson
# as working alternat... |
import os
from math import floor
import numpy as np
import dpm
import umne
import umne.util
#=============================================================================
class remapmatrix:
"""
Remap dissimilarity matrices into new matrices
"""
#----------------------------------------------------... |
"""
Tests for the beta poisson module
"""
import unittest
import numpy as np
import sys
import os
sys.path.append(os.path.abspath(f"{os.getcwd()}/."))
from tbk import bp
class TestBetaPoisson(unittest.TestCase):
def test_beta_poisson_equal(self):
"""
Test whether beta poisson 4 is equal to beta... |
'''
给定任意一个整数,打印出该整数的十进制、八进制、十六进制(大写)、二进制形式的字符串。
'''
int_num = int(input('input the integer'))
# 转二进制
print('二进制形式为 : {}'.format(bin(int_num)))
# 转八进制
print('八进制形式为 : {}'.format(oct(int_num)))
# 转十进制
print('十进制形式为 : {}'.format(int(int_num)))
# 转十六进制
print('十六进制形式为 : {}'.format(hex(int_num).upper())) |
import time
def ensure_execution(func):
def inner(*args, **kwargs):
while 1:
try:
func(*args, **kwargs)
break
except:
time.sleep(0.01)
return inner |
from collections import defaultdict
import math
from tqdm import tqdm
from util import load_json_file,norm
import numpy as np
def get_tfidf_weight(passages):
doc_frequency=defaultdict(int)
for list in passages:
for i in list:
doc_frequency[i]+=1
# calculate tf value
tf={}
f... |
list1 = ['qkl', 'zgq', 'pcb', 'nice']
print(list1)
print(list1[0])
print(list1[-1])
list1[0] = 'first'
list1.append('new');
list1.insert(0, 'insertFirst');
list1.insert(1, 'insertSecond');
print(list1)
lastItem = list1.pop()
print(lastItem)
print(list1)
#pop可指定index删除
index2Item = list1.pop(2)
print(index2Item)
print(... |
# Generated by Django 3.1.4 on 2021-03-03 23:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20210303_2346'),
('school', '0009_auto_20210303_2329'),
]
operations = [
migrati... |
import datetime
import json
import itertools
import math
import requests
import bz2
import re
import string
import pandas as pd
import nltk
import numpy
from nltk.corpus import stopwords
from elasticsearch import Elasticsearch, helpers
# ---------------------------------------------------------------------------------... |
from utils.listNode import ListNode
class Solution:
def rotate(self, head, k):
if not head:
return None
count, node = 1, head
while node.next:
node = node.next
count += 1
# link the end and the start of the list
node.next... |
"""
Exercício Python 27: Faça um programa que leia o nome completo de uma pessoa,
mostrando em seguida o primeiro e o último nome separadamente.
"""
n = str(input('Informe seu nome completo: ')).strip()
nome = n.split()
print(nome)
print(n)
print(f'Seu primeiro nome é: \033[1;34m{nome[0]}\033[m \nSeu último nome é: \0... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-10-10 11:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0014_auto_20181009_1247'),
('deployment_mana... |
# Kyle Jorgensen, CS 271, HW 1, 10/23/14
# This code is built upon https://gist.github.com/tai2/3684493
def marzullo_algorithm(ranges):
'''
Clock synchronization algorithm based on:
http://en.wikipedia.org/wiki/Marzullo%27s_algorithm
'''
table = []
for l,r in ranges:
table.append((l,-1))
tabl... |
#! /usr/bin/env python
import os
import time
import pickle
import pandas as pd
import numpy as np
import tensorflow as tf
from keras.models import load_model
import cv2
import scipy.ndimage as ndimage
import seaborn as sns
import matplotlib.pyplot as plt
from skimage.draw import circle
from skimage.feature import pea... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Diffuse emission spectra.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from astropy.units import Quantity
__all__ = ['diffuse_gamma_ray_flux']
def _power_law(E, N, k):
E = Quantity(E, 'TeV')
E0 = Quan... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from notes.models import Note
user_model = get_user_model()
class NoteSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Note
fields = (
... |
from telethon.errors.rpcerrorlist import PeerFloodError
import sys
import random
import utils
import config
import asyncio
import time
input_file = sys.argv[1]
users = utils.load_user(input_file)
print(len(users))
accounts = config.TELEGRAM_ACCOUNTS[:1]
clients = utils.login(accounts)
# client = clients[0]
async def... |
import math
import types
import torch
import torch.optim
class FairseqOptimizer(object):
def __init__(self, args, params):
super().__init__()
self.args = args
self.params = list(params)
@property
def optimizer(self):
"""Return a torch.optim.optimizer.Optimizer instance.""... |
print("File main.")
#vian
print("Virus Corona Heboh")
print("wish you were here")
print("ExR")
print("Faisal was here")
print("coba ubah nanang")
print("wish you were here")
print("ExR")
print("Faisal was here")
print("adit")
print("wish you were here")
print("ExR")
<<<<<<< HEAD
print("Harris was here")
=======
#ali... |
from random import randint, random
class Individ:
def __init__(self, intel=0, attract=0, age=0, MAX_AGE=100):
self.intel = intel
self.attract = attract
self.age = age
self.MAX_AGE = MAX_AGE
# Mutation
def mutate(self, probability=20):
if randint(0, 99) < probabilit... |
# PART I
# Create a Python class called MathDojo that has the methods add and subtract. Have these 2 functions take at least 1 parameter.
#
class MathDojo(object):
def __init__(self):
print ("The answer is: ")
self.summed = 0
def add(self, *numbers):
for x in numbers:
self.... |
# Copyright (c) 2019 kamyu. All rights reserved.
#
# Google Code Jam 2019 World Finals - Problem C. Won't sum? Must now
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000051708/000000000016c77e
#
# Time: O(2^(D/2) * D), D is the number of digits of S
# Space: O(D)
#
from itertools import imap
def t... |
n = int(input())
a = list (map (int, input().strip().split()))
x = 0
for i in range(n):
x^=a[i]
for i in range(n):
print(a[i]^x,end=" ")
|
import numpy as np
import scipy.stats as st
from statistics import mean, median
import os
import sys
if sys.argv[1] in ["seq","kseq","chain","kchain"]:
NAME = sys.argv[1]+"test"
else:
NAME="kseqtest"
#NAME="seqtest"
files = set()
for fn in os.listdir("."):#["chaintest-8388608.csv"]:#["chaintest-results.csv","seq... |
import telebot
TOKEN = "412526464:AAGPBU6liOdo8CsMmWJssFR08KPPZpJZaWg"
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=["Привет"])
def answer(message):
bot.send_massage(message.chat.id, "Валейкум")
@bot.message_handler(func=lambda message:True)
def say_smth(message):
if message.text == "Здр... |
import json
import praw
import boto3
import base64
from botocore.exceptions import ClientError
def get_secret():
secret_name = "API_KEY"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
... |
import sys
from quantum_espresso_tools.superconductivity.plots import plot_tc_vs_smearing
plot_tc_vs_smearing(sys.argv)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 5 09:08:33 2014
@author: Lanfear
"""
import urllib2
import getopt
import BeautifulSoup
import collections
import json
import csv
import re
base_url = 'http://www.jinni.com/movies/'
file_url = '/Users/Lanfear/Desktop/Research/CLuuData/CLuuScriptsGeneData/Holdoutgenes.tx... |
# %%spark
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import functions as sf
from pyspark.sql.types import *
from pyspark import SQLContext
from datetime import date,datetime,timedelta
from pytz import timezone
from pyspark.sql.functions import *
from pyspark.sql.window import... |
import argparse
import os
import random
import subprocess
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
from functools import partial
from glob import glob
from multiprocessing.pool import Pool
from os import cpu_count
import cv2
cv2.ocl.setUseOpenCL(... |
from mord import LogisticAT
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import RidgeClassifier
from xgboost import XGBClassifier
import numpy as np
def get_estimator(settings):
"""Returns an estmator as specified in the setting... |
from dao.parking_spot_pay_information import ParkingSpotPayInformation
from dao.parking_spot_information import ParkingSpotInformation
from dao.resident_information import ResidentInformation
from dao.pr import PR
from typing import *
from global_var import db
def get_parking_spot_pay_all_from_pid(pid: int):
park... |
import logging
import pytest
from remote_command_executor import RemoteCommandExecutionError, RemoteCommandExecutor
# timeout in seconds
OPENFOAM_INSTALLATION_TIMEOUT = 300
OPENFOAM_JOB_TIMEOUT = 5400 # Takes long time because during the first time, it's not only execute the job but also
# builds and installs many t... |
# coding: utf-8
# from config.views.config_pub import *
# from config.forms import *
import time
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required, permission_required
import json
from django.http import HttpResponse
fro... |
# This script contains useful functions
import sys
import os
import socket
import subprocess
from . import logger
install_data_dir = [
os.path.join(os.environ['HOME'], '.pdusim'),
os.path.join(sys.prefix, 'pdusim'),
os.path.join(sys.prefix, 'share', 'pdusim'),
os.path.join(os.path.split(__file__)[0], '... |
import json, ast
from optparse import OptionParser
from datetime import datetime
from elasticsearch import Elasticsearch
def get_options():
parser=OptionParser()
parser.add_option('-s', '--es-host', dest='es_host', help='ES host name')
parser.add_option('-o', dest='es_output', help='ES Output file name')... |
from torch.utils.data.dataset import Dataset
import numpy as np
from PIL import Image
from torchvision import transforms
transforms = transforms.Compose([
transforms.Resize((60, 60)),
transforms.ToTensor(),
transforms.Normalize([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])
])
def load_one_image(image_path, transform... |
from ebonite.core.objects.requirements import InstallableRequirement, Requirements, resolve_requirements
def test_resolve_requirements_arg():
requirements = Requirements([InstallableRequirement('dumb', '0.4.1'), InstallableRequirement('art', '4.0')])
actual_reqs = resolve_requirements(requirements)
assert... |
dic={}
for i in list(map(int,input().split())):
dic[i]=1+dic.get(i,0)
for i in sorted(dic ,key=lambda k: (dic[k],arr.index(k))):
for j in range(dic[i]):
print(i,end=" ")
|
#Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
#We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
class Solution(object):
def checkPossibility(self, nums):
... |
def compare(number1, number2):
if number1 == number2:
return 'They are equal'
elif number1 > number2:
return '{} is greater than {}'.format(number1, number2)
elif number1 < number2:
return '{} is greater than {}'.format(number2, number1)
print('You imported compare_two_numbers.py')
|
#! /usr/bin/env python
import nmrglue as ng
# read in the Bruker data
dic,data = ng.bruker.read("bruker_2d")
# Set the spectral parameters
u = ng.bruker.guess_udic(dic, data)
# Direct Dimsion #Indirect Dimension
u[1]['size'] = 768 ; u[0]['size'] = 600
u[1]['complex'] = T... |
from api import *
class Pheromone_A(Chemical) :
diffusion = 1.
decay = 0.01
class Pheromone_B(Chemical) :
diffusion = 1.
decay = 0.01
class Material(Chemical) :
decay = 0.001
class Start(Agent) :
clock = 1
pos = 10,50
reaction = lambda agent, conc : (1.0, 0.0, 0.0)
class Finish(Agent) :
clock = 1
pos ... |
x = input("Digite o valor correspondente ao lado de um quadrado:")
x = int(x)
Perímetro = x+x+x+x
Área = x*x
print("perímetro:",Perímetro,"- área:",Área)
|
# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(50, 100))
|
class Foo:
a = 10
def test(self):
a = 54
return a
def metaclass(self):
return "metaclass!"
def __dict__(self):
return "__dict__!"
print(Foo.a)
f = Foo()
print(f.test())
print(f.test())
print(f.metaclass())
print(f.__dict__())
|
#!/usr/bin/env python3
import numpy
import cv2
import sys
cap = cv2.VideoCapture(sys.argv[1])
OVERLAY_HUE = 0 # red
prev = None
hsv = None
while cap.isOpened():
ret, rawFrame = cap.read()
if ret:
frame = cv2.cvtColor(rawFrame, cv2.COLOR_BGR2GRAY)
if hsv is None:
hsv = numpy.zeros_like(rawFrame)
hsv[...,... |
import click
from fandogh_cli.fandogh_client.namespace_client import details_namespace
from .presenter import present
from .base_commands import FandoghCommand
from .utils import format_text, TextStyle
@click.group("namespace")
def namespace():
"""Namespace management commands"""
@click.command("status", cls=Fa... |
import numpy as np
config = {
# 'function': lambda x: -1 / ((x[0] - 1)**2 + (x[1] - 1.5)**2 + 1) # функция для оптимизации,
# * np.cos(2 * (x[0] - 1)**2 + 2 * (x[1] - 1.5)**2), # x - массив переменных (их две)
'function': lambda x: (
-1 / ((x[0] - 1)**2 + (x[1] - 1.5)**2 + 1)
* np... |
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
'''
while True:
print("Enter the word you want to speak it out by computer")
s = input()
speaker.Speak(s)
'''
def speak(string):
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak(string)
|
#!/usr/bin/python3
from os.path import isfile, isdir
from os import mkdir, makedirs, listdir, remove
import errno
import time
from zkstate import ZKState
import json
import threading
import subprocess
import multiprocessing
import requests
from db import DataBase
from abr_hls_dash import GetABRCommand
import shutil
a... |
from torch.utils.data.sampler import SubsetRandomSampler
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np
import matplotlib.pyplot as plt
class MNIST_CNN_Encoder(nn.Module):
def __init__(self):
super().__i... |
import requests
from bs4 import BeautifulSoup as bs
def is_holiday():
url = 'https://economictimes.indiatimes.com/markets/stocks/stock-market-holiday-calendar'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
... |
import sys
sys.path.append('/home/lujin/script')
from job.mr_service_order import MROrderTrade
mr_job = MROrderTrade(args=['-r', 'local', 'data/ods_service_order.mini.txt'])
COLUMES = ['predict_origin_amount',
'predict_amount',
'total_amount',
'compute_amount',
'pay_amount',
# status... |
from ._ComputeControl import *
from ._MPC_ACC import *
from ._MPC_CC import *
from ._MPC_LK import *
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 18:51:03 2019
@author: gille
"""
file = pd.read_excel(io='D:/Analyses/Fig E.1/Figure/35_Raster.xlsx')
data0 = file[['B']]
data1 = file[['C']]
|
import numpy as np
import pandas as pd
import datetime
from pymongo import MongoClient
def get_data_glucose(date1, date2):
#creamos los datos de glucosa para un dia y los hacemos dataframe
data = []
for _ in range(1,367):
s = pd.DataFrame(np.random.poisson(140, 24))
data.append(s)
... |
from multiprocessing import Queue,Process
# 队列,进程
import time,random
# 列表是数据源;在队列中读取数据源,将列表中的值添加到队列,然后从队列中读取该值
list1 = ["java","Python","JavaScript"]
def write(queue):
for value in list1:
print(f'正在向队列中添加数据-->{value}')
# 异步添加
queue.put_nowait(value)
time.sleep(random.random())
def... |
import pprint
from gdascore.gdaAttack import gdaAttack
from gdascore.gdaScore import gdaScores
from gdascore.gdaTools import setupGdaAttackParameters
def showResult(x,result,uidCol=None):
print(f"Received result length {len(result)}")
if uidCol is not None:
uids = []
for thing in result:
... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_table(conn, create_table_sql):
""" create... |
#! /usr/bin/env python
import pygame, sys, re, random, copy
from pygame.locals import *
class Square:
def __init__ (self, img, coords,
left = None, right = None, up = None, down = None,
robot = None, symbol = None):
self.img = img
self.coords = coords
se... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Webhook automated Dota 2 match parsing service for Discord
"""
from json import load as jload, dump as jdump
from time import sleep
from pathlib import Path
from Bot import WebHookBot
from requests import get, post
class Dotabot(WebHookBot):
DELAY_GAP = 30
O... |
#importing necessary libraries for math calculations and image generation
import math
from PIL import Image
#defines a function to generate a mandelbrot image
def mandelbrot(size, accuracy):
#initializes a new blank RGB image with a resolution of size x size
mandelbrot = Image.new("RGB", (size, size))
#creates a o... |
from itunes_to_universal_scrobbler import parse
import nose.tools as tools
def test_parse():
args = {
"<playlist>": """Porcelain 3:13 Hundredth RARE B-Sides - Single Rock 0
Bound 3:13 Hail the Sun Secret Wars - EP Rock 0
Guillotinas 3:15 Viva Belgrado Guillotinas - Single Electronic 0
(Telebrothy) ... |
from eppy.doc import EppDoc
class EppInfoLaunch(EppDoc):
_path = ('launch: info', )
def __init__(self, phase: str, applicationid: str):
dct = {
'launch:info': {
'@includeMark': 'true',
'phase': phase,
'applicationID': applicationid
... |
# Project: CS426 Spring 2018, Team #23: SkyWarden Senior Project, Aerial Drone Notification System (ADNS)
# Team: Rony Calderon, Bryan Kline, Jia Li, Robert Watkins
# Subsystem: Ground Base Unit
# File name: ROSNodeManager.py
# Description: ROSNodeManager class implementation (Headless ANDS)
# ROSNodeManager ... |
'''
Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e
quantas partidas ele jogou. Depois vai ler a quatidade de gols feitos em cada partida. No final, tudo isso será
guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
'''
nome ... |
#!/usr/bin/python
print "Number of words length"
list1 = input("Enter any words of list separated by commas :")
print list1
newlist = [len(str(element)) for element in list1]
print newlist
print list1[2]
|
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from apps.account.custom_openapi import (
AuthRetrieveAPIView, AuthUpdateAPIView, auth_param,
)
from apps.account.models imp... |
# 函数名规范
# SayHello
# def 8isay(name):
# print("你好:" + name)
# 1. 以大写或者小写字母或者下划线开始
# 2. 包含大小或小写字母,下划线,数字
#
def _isay(name):
print("你好:" + name) |
import pprint
import time
import argparse
from interface import input_terms, input_N_topN, input_choose_algo
from algorithms import NaiveAlgorithm, FaginsThreshold_Algorithm, FaginsThreshold_WithEpsilon_Algorithm, FaginAlgorithmW
from indexing import InvertedFileBuilder
from htmlwriter import HtmlWriter
from processin... |
import time
import curses
from maximize_console import maximize_console
def some(n, character):
stdscr = curses.initscr()
for x in range(25):
for y in range(35):
if not x:
stdscr.addstr(y, 0, str(y))
if x == y:
stdscr.addstr(y, x+n, character)
... |
from rest_framework import filters
from .models import Project
class ProjectPermissionFilter(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(Project.objects.permitted_query(request.user)).distinct()
|
#!/usr/bin/env python
import os
import string
import re
import struct
os.getcwd()
os.listdir('.')
f = open('c005r9951.eu', 'rb')
hdrKey = f.readline()
hdrStr = f.readline()
q1, q2, q3, loc, cell, dateStr, q4, q5, q6 = hdrStr.split()
print q1, q2, q3, loc, cell, dateStr, q4, q5
names_str = f.readline()
delimiters = ... |
from django.shortcuts import render
import requests
import json
import os
from fpdf import FPDF
from json import dumps
from zipfile import ZipFile
from urllib.request import urlopen
from json import load
from django.http import HttpResponse
from hops.models import OngoingJobs
from django.http import JsonResponse
from d... |
import urllib
import logging
import json
import heapq
from datetime import datetime
from datetime import time as ti
from spyne import Application, srpc, ServiceBase, Integer, String
from spyne import Iterable
from spyne.protocol.http import HttpRpc
from spyne.protocol.json import JsonDocument
from spyne.server.wsgi imp... |
import zmq
context =zmq.Context()
#From user to server
frontend = context.socket(zmq.SUB)
frontend.connect("tcp://nhkim91.ddns.net:2224")
#From server to user
frontreq = context.socket(zmq.REQ)
frontreq.connect("tcp://nhkim91.ddns.net:2225")
frontreq.send_string("t_STYROR_0xFF")
# frontend.setsockopt_string(zmq.SUB... |
from django.contrib import admin
from apps.tema.models import Tema
# Register your models here.
admin.site.register(Tema) |
# 列表的所有元素均变为两倍(函数)
def double(n):
return 2 * n
x = [1, 2, 3, 4]
y = map(double, x)
print(list(y))
|
'''
Métodos ---> (Funções)
-> Representam os comportamentos do objeto. Ou seja, as ações que este objeto pode realizar
no sistema
Divide-se métodos em 2 grupos:
- Métodos de Instância
- Métodos de Classe
# O método __init__ é um método especial chamado de 'construtor'. Sua função é construir o
objeto a parti... |
import numpy as np
def dft(x):
N = x.shape[0]
n = np.arange(N)
k = n.reshape((N, 1))
M = np.exp(-2j * np.pi * k * n / N)
return np.dot(M, x)
def fft(x):
n = x.shape[0]
if n <= 32:
return dft(x)
else:
x0 = fft(x[::2])
x1 = fft(x[1::2])
factor = np.exp(-2j... |
import re
import itertools
import textwrap
import functools
try:
from importlib.resources import files # type: ignore
except ImportError: # pragma: nocover
from pkg_resources.extern.importlib_resources import files # type: ignore
from pkg_resources.extern.jaraco.functools import compose, method_cache
from ... |
from Crypto.Cipher import AES
from itertools import *
import os,sys
import random
l=["MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=",
"MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=",
"MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==",
"MDAwMDAzQ29va2luZyBNQydzIGxp... |
name = '"Nightmare-fuel"'
location = 'Furi'
note = 'XBee rain gauge. Firmware rain0.1, hardware v0.2.'
#latitude = 21.3237992
#longitude = -157.8311465
conf = [
{
'dbtag':'ts',
'description':'Sample time',
'interval':60*60,
},
{
'dbtag':'mm',
'unit':'mm/hr',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.