text stringlengths 38 1.54M |
|---|
while True:
registro = []
caso = int(input())
if caso == 0:
break
while caso > 0:
caso -= 1
registro.append(input())
manipulacao = list(registro)
regPalMudada = []
for i in registro:
palMudada = 0
for j in manipulacao:
preLen = len(j... |
from collections import OrderedDict
import glob
import imp
import json
import os
import shutil
from houdiniResourceManager.core import node_manager
imp.reload(node_manager)
node_type_data = None
file_name_data = None
class JSON_Loading_Error(Exception):
pass
def init_file_name_data():
'''
Set's the global varia... |
#!/usr/bin/env python
import os
import sys
import tempfile
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
import evaluate
from torch.nn.parallel import DistributedDataParallel as DDP
from transformers import AutoTokenizer
from transfo... |
from flask import Flask
from prometheus_client import start_http_server,Summary,Counter,Gauge
app = Flask(__name__)
TOTAL_REQ = Counter('hello_worlds_total','Hello Worlds requested.')
LAST_TIME = Gauge('hello_world_last_time_seconds','The last time a Hello World was served.')
@app.route("/")
def hello():
LAST_TI... |
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
import os
import tables
from bisect import bisect_left
from sklearn.linear_model import Ridge
from sklearn.decomposition import PCA
from sklearn.neural_network import MLPRegressor
import cv2
from tqdm import tqdm
import Regress... |
"""
solver_strategy.py module
"""
from queue import Queue, LifoQueue
from abc import ABC, abstractmethod
class SearchStrategy(ABC):
"""
abstract search strategy class
"""
@abstractmethod
def __str__(self):
pass
@staticmethod
@abstractmethod
def get_strategy():
"""
... |
# Generated by Django 3.2.4 on 2021-06-22 15:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='lang',
)... |
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class DataImputer(BaseEstimator, TransformerMixin):
def __init__(self):
self.X = None
def fit(self, x, y=None):
return self
def transform(self, x, y=None):
try:
x.drop(['Unnamed: 9', 'visi... |
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import h5py
#File path
directory = 'D:\Data\Calibration'
measurement = 'Calibration_IQ_NOAMP-30dBm_40mV_2.csv'
path = directory + '\\' + measurement
I = np.genfromtxt(path)[1:5001,0]
Q = np.genfromtxt(path)[1:5001,1]
I_ref = np.gen... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Potsdam dataset."""
import os
from typing import Callable, Optional
import matplotlib.pyplot as plt
import numpy as np
import rasterio
import torch
from matplotlib.figure import Figure
from PIL import Image
from torch im... |
# -*- coding: utf-8 -*-
import re
class WeiboContenData:
def __init__(self,line=""):
re.split(r',(?=([^\"]*\"[^\"]*\")*[^\"]*$)',)
print len(list)
for ss in list:
print ss
if __name__ == '__main__':
weibo =WeiboContenData('3942456455792392,5516920356,5516920356,欢乐喜剧人,,我发... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch as tc
from torch import nn
import pandas as pd
from torchtext import data
import torchtext
import time
import argparse
from torch import autograd
from torch.autograd import Variable
from tkinter import _flatten
import numpy as np
import pandas as pd
from se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017, Data61
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# ABN 41 687 119 230.
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE... |
# Generated by Django 3.1.1 on 2020-10-09 23:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('checkout', '0003_auto_20201009_2053'),
]
operations = [
migrations.AddField(
model_name='user',
name='balance',
... |
# -*- coding: utf-8 -*-
# ***************************************************
# * File : house_always_win.py
# * Author : Zhefeng Wang
# * Email : wangzhefengr@163.com
# * Date : 2023-07-30
# * Version : 0.1.073019
# * Description : description
# * Link : link
# * Requirem... |
# server.py
import socket
from random import randint
import pickle
from bitarray import bitarray
import hashlib
# import Crypto
# from Crypto.PublicKey import RSA
# from Crypto import Random
# import ast
# create a socket object
import json
publkey = "001100010011000100110000001100110111"
serversocket = socket.socket(... |
from tealight.robot import (move,
turn,
look,
touch,
smell,
left_side,
right_side)
# Add your code here
def tri():
move()
a =str(touch())
l... |
from rest_framework import viewsets
from info.models import Posting, PointOfInterest
from info.forms import CommentForm
from info.serializers import PostingSerializer
from django.views.generic import View
from django.shortcuts import render
from django.core.urlresolvers import reverse
from base.views import cek_sessio... |
import base64
from bsn_sdk_py.client.config import Config
from bsn_sdk_py.trans.transaction_header import get_notrust_trans_data, created_peer_proposal_signedproposal
from bsn_sdk_py.common.myecdsa256 import ecdsa_sign, hash256_sign
from bsn_sdk_py.until.bsn_logger import log_debug,log_info
class NotTrustTransRequest... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import unittest
from tests.utils import run_test
# copy database
# check if in folder _build
class HwtBuildReport_directive_TC(unittest.TestCase):
def test_buildreport_simple(self):
run_test("test_buildreport_simple")
if __name__ == "__main__":
unitte... |
import wx
import controller
import wx.lib.masked as masked
from datetime import datetime
import wx.propgrid as wxpg
from model import Skeleton
class RecordDialog(wx.Dialog):
"""
dialog for edit and add record
"""
def __init__(self, session, row=None, title="Add", addRecord=True):
... |
from bs4 import BeautifulSoup
import requests
import urllib3
def get_homework_info(Username, Password):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
url = 'https://qytsystem.qytang.com/accounts/login/'
username = str(Username)
password = str(Password)
header = {
'U... |
#!/usr/bin/python
import httplib2
import os
import sys
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
import httplib2
import os
from apiclient... |
#!/usr/local/bin/python
import numpy as np
import datetime as dt
import argparse
import pdb
import matplotlib as mpl
mpl.use("Agg")
from mpl_toolkits.basemap import Basemap, cm
import matplotlib.pyplot as plt
############################# set parameters #############################
MAXY = 200
MAXC = 500
cellsize = 0... |
"""Replay analysis - playground
"""
import bambi.tools.matlab
import bambi.tools.activity_loading
import bambi.analysis.maximum_likelihood
import matplotlib.pyplot as plt
events_filename = r'D:\data_for_analyzing_real_time_event_detector\c40m3_day1\events.mat'
frame_log_filename = r'D:\data_for_analyzing_real_time_ev... |
cars = 100 #specify number of cars
space_in_a_car = 4.0 #specify average space in a car in floating no. style
drivers = 30 #specify number of drivers
passengers = 90 #specify number of passengers
cars_not_driven = cars - drivers # calculates number of cars no driven
cars_driven = drivers #cars that are driven
ca... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module, Sequential, Conv2d, ReLU,AdaptiveMaxPool2d, AdaptiveAvgPool2d, \
NLLLoss, BCELoss, CrossEntropyLoss, AvgPool2d, MaxPool2d, Parameter, Linear, Sigmoid, Softmax, Dropout, Embedding
from torch.nn import functional as F
from... |
# -*- coding: utf-8 -*-
"""
806. Number of Lines To Write String
Created on Fri May 11 09:25:42 2018
@author: FT
"""
class Solution:
def numberOfLines(self, widths, S):
"""
:type widths: List[int]
:type S: str
:rtype: List[int]
"""
SumWidths = 0
count = 0
... |
from django.urls import path
from paginator_app import views
urlpatterns = [
path('hello/', views.hello, name='hello'),
path('getdata/', views.getdata, name='getdata')
] |
#! /usr/bin/python3
import pdb
import time
import iota.harness.api as api
import iota.test.apulu.config.api as config_api
import apollo.config.agent.api as agent_api
import iota.test.utils.traffic as traffic_utils
import iota.test.apulu.utils.flow as flow_utils
import apollo.config.utils as utils
from iota.harness.inf... |
def vecteur_coord ():
x_a = int(input("Coordonnées x de A: "))
y_a = int(input("Coordonnées y de A: "))
x_b = int(input("Coordonnées x de B: "))
y_b = int(input("Coordonnées y de B: "))
coord_X = x_b - x_a
coord_Y = y_b - y_a
print("")
print("coordonnées du vecteur AB: ")
print(st... |
import facebook
import webapp2
import os
import jinja2
import urllib2
import models
import app_config
import json
import datetime
import logging
import quopri
import random
import math
import string
import base64
from google.appengine.ext import db
from webapp2_extras import sessions
from google.appengine.api import m... |
import numpy as np
import os
import glob
import argparse
def get_obs_pred(data, observed_frame_num, predicting_frame_num, pos=True):
obs = []
pred = []
count = 0
if len(data) >= observed_frame_num + predicting_frame_num:
seq = int((len(data) - (observed_frame_num + predicting_frame_num)) / obs... |
from utils_dir import my_utils
import cv2
import os
import time
import argparse
import numpy as np
import random
def calculate_rgb_mean(img_paths):
start_time = time.time()
num_err_files = 0
imgs = []
print("\nStart process {} images ...".format(len(img_paths)))
for i, img_path in en... |
from snovault.project.access_key import SnovaultProjectAccessKey
class FourfrontProjectAccessKey(SnovaultProjectAccessKey):
def access_key_has_expiration_date(self):
return False
|
import tensorflow as tf
from keras.layers import Dense, Flatten, Lambda, Activation, MaxPooling2D
from keras.layers.convolutional import Convolution2D
from keras.models import Sequential
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import numpy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Dec 07 14:27 2018
@author: phongdk
"""
"""
TODO:
1. get all unique users from various sources
2. Compute score base on its properties like gender, age, hardware, or so
"""
import os
import gc
import time
import numpy as np
import pandas as pd
import sys
... |
# Load libraries
import pandas as pd #Data analysis library
from pandas.tools.plotting import scatter_matrix #Graphics library
import matplotlib.pyplot as plt #Graphics library
from sklearn import model_selection #Machine learning models
from sklearn.metrics import classification_report #Build a text report showing the... |
# list는 []로 감싼다
# empty
empty_list = []
empty_list2 = list()
print(empty_list == empty_list2) # True
# lists. list 는 어떤 자료형도 포함 가능
odd = [1, 3, 7]
e = [1, 2, ['Life', 'is']]
# indexing, slicing 은 문자열을 다루는 것과 거의 동일함
print(e[2][1])
print(e[1:])
# 리스트 더하기
print([1,2,3] + ['a','b'])
# 리스트 곱셈
print([1,2,3] * 2)
# 리스트 ... |
""" file: utilities.py (bomber)
author: Jess Robertson
CSIRO Minerals Resources Flagship
date: June 2015
description: utility functions for bomber
"""
from __future__ import print_function, division
from .converters import grid_to_geotiff
import requests
import subprocess
def download(u... |
# coding: utf-8
# 참고문헌: http://learnpythonthehardway.org/python3/ex4.html
# 입력 후 add, commit / Enter source code, add, and commit
# 각 행 주석 입력 후 commit / Enter comment for each line and commit
# 각자 Study drills 시도 후 필요시 commit / Try Study Drills and commit if necessary
# print 'abc' -> print('abc')
# print 'abc', 123 ->... |
# Generated by Django 3.0.3 on 2020-04-06 20:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_auto_20200406_2222'),
]
operations = [
migrations.AddField(
model_name='profile',
name='subtitle',
... |
from sqlalchemy import Column, BigInteger, DateTime, LargeBinary, Integer, Float
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm import relationship
from db import Base, table_args
class ElecData(object):
_mapper = {}
base_class_name = "elec_data"
@classmethod
def model(cl... |
import pygame
from game import gamelogic
from game import SettingGame
from PIL import Image, ImageDraw, ImageOps
RED = (255, 0, 0)
COLOR_PADDLE = (255, 0, 0)
COLOR_BOARD_LINE = (0, 255, 0)
COLOR_BACKGROUND = (100, 0, 100)
COLOR_BALL = (222, 222, 222)
class Painter:
def __init__(self, SCREEN: pygame.display, ga... |
import os
PROJECT_PATH = os.getenv("PROJECT_PATH")
SERVER_HOST = os.getenv("SERVER_HOST")
CONFIG_PATH = os.path.join(PROJECT_PATH, "config")
DATA_PATH = os.path.join(PROJECT_PATH, "data")
ENVS_PATH = os.path.join(PROJECT_PATH, "envs")
LOGS_PATH = os.path.join(PROJECT_PATH, "logs")
config_file = os.path.join(CONFIG_P... |
from queue import PriorityQueue
import threading
import random
import time
class MTQ:
def __init__(self, q, lock):
self.q = q
self.lock = lock
def push(self, val):
self.lock.acquire()
self.q.put(val)
self.lock.release()
print("ADD", val)
def pop(self):
... |
from log_into_wiki import *
import mwparserfromhell
limit = -1
site = login('bot', 'fortnite-esports')
summary = 'Automatically create player pages for Power Rankings'
result = site.api('cargoquery',
tables = 'TournamentResults=TR,TournamentResults__RosterLinks=RL,_pageData=PD',
join_on = 'TR._ID=RL._rowI... |
#!/usr/bin/env python
import torch as th
def get_model(in_size, out_size, sizes=[64, 64]):
params = [th.nn.Linear(in_size, sizes[0])]
for i in range(1, len(sizes)):
params.append(th.nn.Sigmoid())
params.append(th.nn.Linear(sizes[i-1], sizes[i]))
params.append(th.nn.Linear(sizes[-1], out_si... |
import dog
sugar = dog.Dog('Sugar', 'Border Collie')
print(sugar.tricks)
sugar.teach('frisbee')
print(sugar.tricks)
sugar.knows('frisbee')
sugar.teach('fetch')
sugar.knows('fetch')
sugar.knows('arithmetic')
print(dog.Dog.species)
print(sugar.species) |
from core.decorators import instance
from core.registry import Registry
from tools.logger import Logger
from __init__ import get_attrs
import time
@instance()
class EventManager:
def __init__(self):
self.handlers = {}
self.logger = Logger("event_manager")
self.event_types = []
self... |
'''
Write a Python program to read an entire text file.
'''
fhand = open('text.txt', 'r')
print (fhand.read())
fhand.close() |
# -*- coding: utf-8 -*-
"""
File: shapes.py
Date:21/09/2016
Author: prashanthisudha kosgi
Course: CSE 7014
Instructor:Nguyen Thai
Description:A simple python program to introduce the turtle module.
"""
import turtle
#set up screen
turtle.setup(800,300) #window size
screen = turtle.Screen() # instantiate scree... |
"""chat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import requests
PORT = 10000
GOOGLE_SERVICE_URL_HEADER = 'goog_service_url'
HOST_HEADER = 'host'
class GoogleCertificateProxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
# The handler for all 'GET' request.
def do_GET(self):
request_headers... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-18 06:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20171118_0536'),
]
operations = [
migrations.CreateModel(... |
import pytchat
chat = pytchat.create(video_id="11 character live video ID")
wordlist = ("?", "what", "when", "where", "which", "who", "why", "how")
while chat.is_alive():
for c in chat.get().sync_items():
for i in wordlist:
if i in c.message:
print(f"QUESTION ASKED FROM - [{c.a... |
# MapSeq.py
# Eric Johannsen Apr 2011
#
#
# Given a PSSM for a pattern, will output a flat file that can be pasted into WebLogo to make a log
# Only works if each position in the matrix adds up to the same number (i.e., A + C + G + T = constant)
import sys
import string
import math
def order(profile):
ord ... |
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[3],[2],[1]])
Y = np.array([8,6,4])
alpha = 0.1
weights = np.ones((1, 2))
def add_bias(X):
return np.hstack((np.ones((X.shape[0],1)),X))
def batch_gradient_descent(X,Y,num_iter=1000):
X = add_bias(X)
weights = np.zeros(X.... |
# @Author: sachan
# @Date: 2019-03-09T22:29:01+05:30
# @Last modified by: sachan
# @Last modified time: 2019-03-10T00:17:45+05:30
import torch
import torch.nn.functional as F
class gap_model1(torch.nn.Module):
""" Bilinear model with softmax"""
def __init__(self, embedding_size):
super(gap_model... |
from getpass import getpass
correct_pin = "1234"
attempt_n = 1
total_attempts = 3
while attempt_n <= total_attempts:
supplied_pin = getpass("Enter your PIN: ")
if supplied_pin == correct_pin:
print('Pin accepted')
break
elif attempt_n < total_attempts:
print('Pin incorrect, this is ... |
line = input()
text = ""
new_letter = ""
for letter in line:
if not letter == new_letter:
text += letter
new_letter = letter
print(text) |
import subprocess
import os, logging
import datetime
def log_event(msg, level = "i"):
timestamp = "%s " % datetime.datetime.now()
if level.lower() == "w":
logging.warn(timestamp + msg)
elif level.lower() == "e":
logging.error(timestamp + msg)
else:
logging.info(timestamp + msg)... |
#!/usr/bin/env python3
'''
转换5分钟K线的原始数据
默认先查找当天数据库的所有股票,然后按每日便利每只股票
'''
import os, sys, datetime
PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
sys.path.append(PROJECT_ROOT)
from DataTransform.Transform5M import process_single_shot
if __name__ == "__main__":
if len(sys.argv) != 3:
... |
#!/usr/bin/python
#encoding=utf-8
'''
Created on 2016/12/23
@author:Ljx
'''
'''
提取种子站点的一级目录和二级目录页面上的中文,提取关键字Top50:
1.爬虫(bs4)
1.1连接数据库,读取种子站点
1.2通过正则匹配把首页上所有的http链接都爬下来
1.3筛选链接
筛选规则:保留本域名的链接,去除含数字的链接
2.提取关键字
2.1读取链接页面上的内容
2.2通过正则匹配选取中文
2.2导入LDA模型提取关键字Top50
2.3把关键字插入到数据库中
'''
#import bs4
#from bs4 import... |
# from skopt.space import Categorical, Integer, Real
from skopt.space import Integer
from src.hyper_opt.run import run_hyper_opt
from src.rf.forest import RandomForestRegressor
space = (
Integer(1, 100, name="n_estimators"),
# Categorical([None, 1, 10, 100, 1000], name="max_depth"),
# Categorical([None, 1... |
# -*- coding: utf-8 -*-
# # # #
# NER_BERT_CRF.py
# @author Zhibin.LU
# @created Fri Feb 15 2019 22:47:19 GMT-0500 (EST)
# @last-modified Sun Mar 31 2019 12:17:08 GMT-0400 (EDT)
# @website: https://louis-udm.github.io
# @description: Bert pytorch pretrainde model with or without CRF for NER
# The NER_BERT_CRF... |
import os
import time
print("MadLibs Final Project")
print("By Indigo Suh")
print()
answer = input("Ready to play? Type yes or no: ")
if answer == "yes" or answer == "Yes" or answer == "yes." or answer == "yes." or answer == "Yes!" or answer == "yes!" :
import random
madlib=random.randint(1, 2)
if madlib==1:
... |
import random
class Laboratory(object):
def __init__(self, shelf1, shelf2):
self.shelf1 = shelf1
self.shelf2 = shelf2
def can_react(self, substance1, substance2):
condition1 = (substance1 == "anti" + substance2)
condition2 = (substance2 == "anti" + substance1)
... |
def sum():
x = int(input())
for q in range(x):
s = input()
s = list(s)
lengden = len(s)
s.reverse()
for i in range(lengden):
if i % 2 == 1:
n = int(s[i])
n *= 2
if n > 9:
n = str... |
#!/usr/bin/env python
'''
This script will attempt to open your webbrowser,
perform OAuth 2.0 authentication and print your access token.
To install dependencies from PyPI:
$ pip install oauth2client
Then run this script:
$ python get_oauth2_token.py
This is a combination of snippets from:
https://developers.... |
#访问限制
#!/usr/bin/bash
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
... |
from src.map_module.worldmap import WorldMap
from src.creature_module.player import Player
class GameState:
def __init__(self, player: Player, wmap: WorldMap):
# player character data
self.player: Player = player
# creatures actively taking actions/moving
self.active_creatures =... |
a=dict()
b=dict()
word=input()
for x in word:
a[x]=a.get(x,0)+1
word2=input()
for x in word2:
b[x]=b.get(x,0)+1
for i in a.keys():
if i in b.keys():
if a[i]!=b[i]:
print("NO")
break
else:
print("NO")
break
else:
print("YES")
|
#!/usr/bin/env python
import rospy
from std_msgs.msg import Bool, Float64, Int32
from styx_msgs.msg import Lane, TrafficLightArray
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped, PoseStamped
# from tl_detector import TLDetector
import math
imp... |
'''
Created on 26 mei 2017
@author: Robin Knoet
'''
import configparser
import os
class unitConverter(object):
'''
classdocs
'''
__MODULECOMMAND = "convert"
__isPublicOnError = False
__isPublicOnHelp = False
__helpMessage = """
Convert message part command
... |
# Generated by Django 2.2.9 on 2020-01-24 17:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('homechallenge', '0008_auto_20200124_1132'),
]
operations = [
migrations.CreateModel(
name='Self... |
class Node:
def __init__(self, var, posCof, negCof):
self.var = var
self.posCof = posCof
self.negCof = negCof
class Formula:
def __init__(self, node, compBit):
self.node = node
self.compBit = compBit
class ROBDD:
# init
def __init__(self, varSeq):
self.v... |
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
nonebot.init(command_start=[""])
app = nonebot.get_asgi()
driver = nonebot.get_driver()
driver.register_adapter('cqhttp', CQHTTPBot)
nonebot.load_builtin_plugins()
nonebot.load_plugins('src/plugins')
nonebot.load_plugin("nonebot_plugin_apscheduler")... |
#-*- coding: UTF-8 -*-
import os
import json
import codecs
import logging
import ray
import subprocess
import master
import senteval
from collections import defaultdict
def prepare(params, samples):
vocab = defaultdict(lambda : 0)
for s in samples:
for word in s:
vocab[word] = 1
vocab... |
import numpy as np
from binomial_node import BinomialNode
def binomial_pricing(spot, strike, dividend_yield, volatility, time_mature, desired_length, interest_rate):
"""
Generates a binomial price tree for an American-Style call option
:param spot: current price of stock in question
:param stri... |
# This program creates an object of the pet class
# and asks the user to enter the name, type, and age of pet.
# The program retrieves the pet's name, type, and age and
# displays the data.
class Pet:
def __init__(self, name, animal_type, age):
# Gets the pets name
self.__name = name
... |
class Solution(object):
def fn(self,v):
#able to decode
if v=="":
return False
elif len(v)==1:
if int(v)==0:
return False
else:
return True
elif len(v)==2:
if v[0]=='0':
return False
elif 1<=int(v) and int(v)<=26:
return True
else:
return False
else:
... |
'''
User enters an arithmetic progression, with one item omitted, and the length of the input, the
program tells the omitted item
'''
import sys
import numpy as np
def solution1():
n = int(raw_input())
list= raw_input().split()
for i in range(0,n):
list[i] = int(list[i])
difference = list[len... |
import ROOT
import argparse
from ROOT import TLorentzVector, TH1D
import numpy as np
import Sample
from helpers_old import progress, makeDirIfNeeded, showBranch
import objectSelection as objSel
from efficiency import efficiency
from ROC import ROC
import eventSelectionTest
argParser = argparse.ArgumentParser(descript... |
import serial
import time
import sys
ser = serial.Serial()
ser.port = sys.argv[1]
ser.baudrate = 115200
ser.timeout = None;
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
try:
ser.open(... |
#!/usr/bin/env python
# Programmer: Chris Bunch (chris@appscale.com)
""" s3_storage.py provides a single class, S3Storage, that callers can use to
interact with Amazon's Simple Storage Service (S3). """
# Third-party libraries
import boto.s3.connection
import boto.s3.key
# S3Storage-specific imports
from magik.base... |
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import dataent, json
from dataent.utils import cint, quoted
from dataent.website.render import resolve_path
from dataent.model.document import get_controller, Document
from datae... |
# Copyright (c) 2013, Pullenti. All rights reserved. Non-Commercial Freeware.
# This class is generated using the converter UniSharping (www.unisharping.ru) from Pullenti C#.NET project (www.pullenti.ru).
# See www.pullenti.ru/downloadpage.aspx.
import io
from pullenti.unisharp.Utils import Utils
from pullent... |
import re, uuid
print ("The MAC address is : ", end="")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
|
import threading
_localdata = threading.local()
class Middleware:
"""
Put the user into current thread local data
"""
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
_localdata.log... |
# In[ ]:
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from osgeo import osr, gdal
import tensorflow as tf
from Funciones import *
from Entrenamiento import *
from Imagenes import *
# Import librarys
Mostrar_bienvenida()
global Diccionario
glob... |
from project import db
from project.com.vo.AreaVO import AreaVO
from project.com.vo.BloodGroupVO import BloodGroupVO
from project.com.vo.CityVO import CityVO
from project.com.vo.LoginVO import LoginVO
from project.com.vo.BloodBankVO import BloodBankVO
class EmergencyRequestVO(db.Model):
__tablename__ = 'emergency... |
from Tkinter import *
from PIL import Image, ImageTk
import re
import os
import zmq
import urllib2
import json
import graphanalysis as g
import datetime
#alert number constants
ALERT_INVALID_INPUT = 0
ALERT_NO_NETWORK_CONNECTION = 1
ALERT_NO_SERVER_CONNECTION = 2
ALERT_FAILED_SENTIMENT_ANALYZER = 3
ALERT_FAILED_GET_TW... |
#! /usr/bin/env python
import random
import matplotlib.pyplot as plt
def pick_char(l):
return l[random.randint(0,len(l)-1)]
def init():
alphabet = [chr(i) for i in range(0x61,0x7B)]
alphabet.append(chr(0x20))
return alphabet
def tuples2lists(l_tuples):
size_tuple = len(l_tuples[0])
l_lis... |
#solution:
def print_rangoli(size):
my_str = 'abcdefghijklmnopqrstuvwxyz'
for i in range(size-1, -size, -1):
print ('-'.join(my_str[size-1:abs(i):-1]+my_str[abs(i):size]).center(4*size-3,'-'))
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
|
import logging
import requests
import time
import ujson
import urllib
class RequestError(Exception):
def __init__(self, method, url, params, data, status_code, response_text, error=None):
self.status_code = status_code
message = '[%s %s%s%s] %s: "%s" %s' % (
method,
url,
... |
from rest_framework import serializers
from django.contrib.auth.models import User, Group
from tips.models import Tip
class TipSerializer(serializers.ModelSerializer):
author = serializers.RelatedField(read_only=True)
user = serializers.ReadOnlyField(source='user.username')
class Meta:
model = ... |
from platypus import NSGAII, Problem, Integer
from Library.DataClass import *
from Library.RiskCalc import *
from Library.RabbitMQProducer import *
def calc_total_value(universe: Universe, weights: [float]):
total = 0
for i in range(universe.count):
total += universe.universe_set[i].last_price ... |
import sys
from Controllers.ControllerMain import ControllerMain
class MainView:
def __init__(self, argv):
self.controller = ControllerMain(self)
self.controller.set_sys_argv(argv)
def show_data(self, data):
print(data)
if __name__ == '__main__':
view = MainView(sys.argv) |
"""
Revision ID: e98384408eae
Revises: 2e3b3ca8a665
Create Date: 2020-11-12 16:00:06.798935
"""
# revision identifiers, used by Alembic.
revision = 'e98384408eae'
down_revision = '2e3b3ca8a665'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adju... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.