text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 18 18:46:47 2016
@author: ceciliaLee
Steps: 1) transform lists of text into a vector of numbers.
2) calculate conditional probabilities from these vectors
3) create a classifier
"""
from numpy import *
## Prepare: making word vectors from text
def load_Dat... |
#coding: utf-8
import MeCab
import pandas as pd
#日本語エンコードする場合はencoding="utf-8"のオプションを忘れずに。
import codecs
from collections import Counter
def simple_parser(t):
tagger = MeCab.Tagger('-Ochasen')
tagger.parse('')
node = tagger.parseToNode(t)
a = []
while node:
a.append(node.surface)
... |
#!/bin/python3
from random import *
import re
def r():
return randrange(1,7,1)
def raw_pwrd():
return [[r() for x in range(5)] for y in range(6)]
def scrub(data):
ls = []
for lst in data:
scrubbed = ""
for elem in lst:
scrubbed += str(elem)
ls.append(scrubbed +"\t(... |
#! /usr/bin/python3
""" Demonstrate a function can have attribute which can be manipulated within the wrapper function
or may be also somewhere else
"""
def call_counter(func):
def helper(x):
helper.calls += 1
return func(x)
helper.calls = 0
return helper
@call_counter
def succ(x):
return x + 1
print(succ.c... |
import jieba
import datetime
from dateutil.relativedelta import relativedelta
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import time
import Levenshtein
# 计算jaccard系数
def jaccrad(model, reference): # terms_reference为源句子,terms_model为候选句子
#jieba.set_dictionary("dict.txt")
#jieba.initialize()
... |
import boto3
class ClientLocator(object):
def __init__(self, client):
#Ohio: us-east-2
self._client = boto3.client(client, region_name='us-east-2')
def get_client(self):
return self._client
class EC2Client(ClientLocator):
def __init__(self):
super().__init__('ec2')
... |
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, UpSampling2D
def autoencoder():
input_shape=(784,)
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=input_shape))
model.add(Dense(784, activation='sigmoid'))
return model
def deep_autoenco... |
#This example uses Python 2.7 and the python-request library.
import datetime
from requests import Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json,csv,time
from nomics import getVolumes
import os.path
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurren... |
# from lshash import LSHash
# import numpy as np
# from PIL import Image
# import skimage.io
# from skimage import transform,data
# import os
# import time
# class LSH():
# def __init__(self,path,lsh):
# #lsh = LSHash(7,2500)
# pathDir = os.listdir(path)
# txt_list = []
# ... |
#!/usr/bin/python
import turtle
length = 0
angle = 90
while length < 200:
turtle.forward(length)
turtle.right(angle)
length = length + 10 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import math
def calc(x):
return str(math.log(abs(12 * math.sin(int(x)))))
driver = webdriver.Chrome()
driver_wait = We... |
import os
import sys
for i in range(0,5):
a="pkurun-cnlong 1 20 python clustergwtest.py %s %s %s %s"%(i,sys.argv[1],sys.argv[2],5)
os.system(a)
os.system('sleep 1')
|
"""
CLI utility to manage the library
Install/uninstall colors and parts
"""
import argparse
# from . import install_part
# from . accessory_types import AccessoryType
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--factory-reset",
help="Reset the l... |
import os
import time
i=0
while True:
numero=str(i)
texto= str("echo 'numero es tal %s' >> datos.txt " % numero)
os.system(texto)
print (texto)
time.sleep(2)
i=i+1
|
# -*- coding: utf-8 -*-
import logging
import json
from django.views.generic import View
from django.shortcuts import render, redirect
from django.http import JsonResponse
from lorry.models import LorryModel
logger = logging.getLogger(__name__)
class IndexView(View):
def get(self, request):
return red... |
kase = int(input())
d, stat = {}, 'good'
p1 = list(input().split())
p2 = list(input().split())
for i in range(kase):
if p1[i] not in d:
d[p1[i]] = p2[i]
d[p2[i]] = p1[i]
if p1[i] in d and (d[p1[i]] != p2[i] or d[p1[i]] == p1[i]):
stat='bad'
break
print(stat)
|
import math
import numpy as np
import cv2
import geo_transform as tps
import tensorflow as tf
def restore_original_image_from_array(x, data_format=None):
mean = [103.939, 116.779, 123.68]
# Zero-center by mean pixel
if data_format == 'channels_first':
if x.ndim == 3:
x[0, :, :] += mean... |
#
#
# 0===============================0
# | PLY files reader/writer |
# 0===============================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# function to read/write .ply files
#
# ---------------------... |
#Question-1(a)
#Newton Raphson method
from Own_library import *
import math
def derivative(f, x, h):
return (f(x+h) - f(x-h)) / (2.0*h) # might want to return a small non-zero if ==0
def f(x):
return (math.log(x)- math.sin(x)) # just a function to show it works
q1a_3 = open("Q1a_Newton_raphson.txt","... |
#__author__="G"
#date: 2019/4/24
import logging
from common import contants
from common.config import config
from common.contants import log_dir
import time
class HandleLogger:
"""处理日志相关的模块"""
@staticmethod
def create_logger():
"""
创建日志收集器
:return: 日志收集器
"""
# 第一步:... |
from scipy.interpolate import interp1d
import numpy as np
from zhklib.common import getGRTSuffix
class Interpolators:
def __init__(self):
sensors_id = np.genfromtxt('calibration/Sensor_ID.txt',
skip_header=2,
delimiter='\t',
... |
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 1293, 322]
print(list1)
del list1[2]
print(list1)
# 一些操作符
print(len(list1))
print(list1 + [3, 4, 5, 5])
print(['hi!'] * 4)
print(3 in [3, 2, 3, 1])
for x in [1, 2, 3]:
print(x)
L = ['Google', 'Runoob', 'Taobao']
print(L[2])
print(L[-2])
print(L[1:])
# 函数
li... |
# -*- coding: utf-8 -*-
from PySide2 import QtWidgets, QtUiTools, QtGui
from PySide2.QtCore import QCoreApplication, QFile
import sys
import os
import socket
#импортируем свобственные классы
from classies.authenticate import Authenticate
from classies.pack import PackMessage
import sqlalchemy
#импортируем классы табл... |
class Solution:
def findLeaves(self, root: TreeNode) -> List[List[int]]:
res = []
self._dfs(root, res)
return res
def _dfs(self, node, res):
if not node:
return -1
l = self._dfs(node.left, res)
r = self._dfs(node.right, res)
d = max(l, r) ... |
#!/usr/bin/env python3
# Prepares the "sources.json" file for pomtiler.py and pomrender.py
import os, json
imgdict = {}
index = 1
for i in os.listdir("sources"):
imgdict[index] = i
index += 1
with open("sources.json","w") as outfile:
json.dump(imgdict,outfile)
|
# -*- coding: utf-8 -*-
import base64
from datetime import datetime, timedelta
import json
import logging
import socket
import struct
import sys
import threading
import traceback
_LOGGER = logging.getLogger('pyShelly')
try:
import http.client as httplib
except ModuleNotFoundError:
import htt... |
# Basic of Python
# Title : Tuples
# Date : 2020-06-22
# Creator : tunealog
# Tuples are Immutable
x = (1, 2, 3, 4)
y = ('a', 'b', 'c', 'd')
z = ("e", "f", 5, 6)
#(1, 2, 3, 4)
print(x)
#('a', 'b', 'c', 'd')
print(y)
#('e', 'f', 5, 6)
print(z)
#(1, 2, 3, 4, 'a', 'b', 'c', 'd')
print(x + y)
#################
a = ... |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import nose
from nose.plugins.base import Plugin
project_root = os.path.join(__file__, os.pardir, os.pardir)
project_root = os.path.abspath(project_root)
sys.path.append(project_root)
class ExtensionPlugin(Plugin):
name = 'ExtensionPlugin'
def optio... |
from django.http import HttpResponse
from django.template import loader
from .models import Shop
from django.views import generic
from django.views.generic import TemplateView
from django.contrib.gis.geos import fromstr
from django.contrib.gis.db.models.functions import Distance
import requests
import json
from django... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
支持向量机(SVM)算法,线性可区分
"""
from sklearn import svm
x = [[2, 0], [1, 1], [2, 3]] # 支持向量的定义
y = [0, 0, 1] # 标记的定义
# 创建分类器
clf = svm.SVC(kernel='linear')
# 建模
clf.fit(x, y)
# 打印出支持向量
print(clf.support_vectors_)
# 打印出超平面两边,每一边各有几个支持向量
print(clf.n_support_)
# 预测一个点在超平面... |
import requests
import json
import csv
# API : PIB US
url = "https://api.stlouisfed.org/fred/series/observations?" \
"series_id=GDP&api_key=09cefe3ef92e58d279f3d34f776aa262&" \
"file_type=json&" \
"observation_start=1999-01-01&" \
"observation_end=2017-12-31&" \
"frequency=q"
r = requests... |
tuplea = ("a", 1, "b")
print(tuplea)
print(tuplea[1])
appleb = tuplea +(1, 2, 3, 4, 5)
print(appleb)
for letter in 'Python':
print('letter :', letter)
for number in range(0,5):
print('number :',number)
for letter in appleb:
print(letter)
for l in range(0,len(appleb)):
print(appleb[l]) |
from typing import Any, Dict, Optional, Tuple
import torch
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.core import Tensor
class RandomChannelShuffle(IntensityAugmentationBase2D):
r"""Shuffle the channels of a batch of multi-dimensional images.
.. image:: _stat... |
import ply.yacc as yacc
import ply.lex as lex
from tokrules import tokens
import tokrules
class BaseNode(object):
def __init__(self):
self.flag = True
self.left = None
self.right = None
self.op = None
self.predicate = None
self.params = None
def __repr__(self):
... |
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
import torchvision.utils
from codebase.data_providers.aircraft import FGVCAircraft
from codebase.data_providers.pets2 import PetDataset
import torch.utils.data as Data
from codebase.data_providers.autoaugment import CIFAR1... |
from copy import deepcopy
from typing import Literal
import warnings
import numpy as np
def get_random_data_chunks(
recording,
return_scaled=False,
num_chunks_per_segment=20,
chunk_size=10000,
concatenated=True,
seed=0,
margin_frames=0,
):
"""
Extract random chunks across segments... |
'''
File name: dk_analysis.py
Author: Ali Salloum
Date created: 01/09/2020
Date last modified: 11/01/2021
Python Version: 3.6
'''
import random
import pickle
import sys
import numpy as np
import networkx as nx
import networkx.algorithms.community as nx_comm
import scipy.stats
import partition_algo... |
import sys
from functools import lru_cache
@lru_cache(None)
def dfs(n):
if n == 7: return True
if n < 10: return False
cur = n
last_v = None
num = []
while cur != 0:
v = cur % 10
cur = cur // 10
if last_v is not None:
num.append(abs(v-last_v))
last_v... |
# coding=utf-8
from annoying.decorators import ajax_request
from django.shortcuts import get_object_or_404
from core.models import User
__author__ = 'alexy'
# @ajax_request
# def ymap(request):
# request.encoding = 'utf-8'
# if request.is_ajax():
# query = City.objects.all()
# try:
# ... |
a = input()
b = input()
suma = a + b
print (suma)
# Uwtorzony zostal nowy string "suma", w wyniku polaczenia stringow a oraz b.
|
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from .logger import setup_logger
from .model import BiSeNet
import torch
import os
import os.path as osp
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
import cv2
def vis_parsing_maps(im, parsing_anno, stride, save_im=False, save_path... |
# Generated by Django 2.2.3 on 2019-07-29 04:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ticketing_system', '0003_auto_20190720_0604'),
]
operations = [
migrations.AlterField(
model_name='ticket',
name='ti... |
"""
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
["MaxQueue","pop_front","max_value"]
[[],[],[]]... |
from ZeroScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
"c042c.bin", # FileName
"c042c", # MapName
"c042c", # Location
0x0023, # MapIndex
"ed7113",
0x00002000, ... |
from os import environ
# Select GPU 0 only
# environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'
# environ['CUDA_VISIBLE_DEVICES']='0,1,2,3'
# environ['MKL_THREADING_LAYER']='GNU'
import numpy as np
import copy
import torch
import torch.nn as nn
from torch.autograd import Variable
from mjrl.utils.optimize_model import fit_data
... |
""" Tests for output of `dbt run` on the test project. """
import os
import subprocess
from pathlib import Path
from pytest import fixture
@fixture(scope="session")
def dbt_run(setup_db):
""" Fixture to call `dbt run`. """
engine, setup = setup_db
file_dir = Path(__file__).parent
os.chdir(file_dir / "... |
import cv2
capture = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
_, frame = capture.read()
fmask = fgbg.apply(frame)
cv2.imshow("Orignal Frame", frame)
cv2.imshow("F Mask", fmask)
if cv2.waitKey(30) & 0xff == 27:
break
capture.release()
cv2.destroyAllWind... |
import os, pickle, numpy as np
import keras
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.utils.np_utils import to_categorical
from keras import optimizers
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D
from keras.layers.normaliza... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'W:\projets\QGis plugins\menu_from_project\conf_dialog.ui'
#
# Created: Tue Feb 19 16:47:11 2013
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
_fromUtf8 = l... |
from django.shortcuts import render
from contact_us.forms import ContactUsForm
from django.views.generic import FormView, TemplateView
from django.urls import reverse_lazy
# Create your views here.
class ContactUs(FormView):
form_class = ContactUsForm
success_url = reverse_lazy('contact_us:thank_you')
tem... |
#!/usr/bin/python3
"""Write a Python script that fetches https://intranet.hbtn.io/status"""
from urllib.request import Request, urlopen
req = Request('https://intranet.hbtn.io/status')
with urlopen(req) as response:
html = response.read()
print("Body response:")
print("\t- type: {}".format(type(html)))
... |
#!/usr/bin/env python3
INTEREST_RATE = 0.04
PERIODS = 3
try:
P_0 = float(input('Enter your initial principal investment: '))
except ValueError as e:
print('ERROR: Principal amount must be a number.')
P_0 = float(input('Enter your initial principal investment: '))
balances = [P_0 * (1 + INTEREST_RATE)**i... |
from . import personas
from odoo import models, fields, api
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from datetime import timedelta
from pytz import timezone
from odoo.exceptions import UserError, ValidationError
hours = [
(0, '00:00'),
(1, '01:00'),
(2, '02:00')... |
"""
PlanterClasses that moves and makes decisions in the land
"""
from PiceClasses.Pice import Pice
from PiceClasses.Pice import Tile
from PlanterClasses.Vision import Vision
class Planter:
def __init__(self, bagSize: int, viwDistance: int, pice: Pice):
"""
PlanterClasses must be assigned a pice. ... |
from controller import Robot, Camera, Motor, Accelerometer, GPS, TouchSensor, Speaker
import os
import sys
try:
pythonVersion = 'python%d%d' % (sys.version_info[0], sys.version_info[1])
libraryPath = os.path.join(os.environ.get("WEBOTS_HOME"), 'projects', 'robots', 'robotis', 'darwin-op', 'libraries',
... |
import numpy
import matplotlib.pyplot as plot
import sys
class Edge:
def __init__(self, component, first, second):
self.node_one = first
self.node_two = second
self.component = component # The component this Edge belongs to
self.current_tracker = []
self.voltage_tracker = [... |
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s.isdigit():
return 0
if s=="" or s[0]=='0':
return 0
dp = [1,1]
for i in range(2,len(s)+1):
if 10 <= int(s[i-2:i]) <= 26 and s[i-1] != '0':
dp.append(dp[i-2] + dp[i-1])
elif in... |
#!/usr/bin/python
import sys
import json
from datetime import datetime
import ghApiClient
def allPulls(releaseDate):
result = ""
baseurl = "https://api.github.com/repos/swagger-api/swagger-inflector/pulls/"
content = ghApiClient.readUrl('repos/swagger-api/swagger-inflector/pulls?state=closed&base=v1&per... |
# Generated by Django 3.2.6 on 2021-08-21 04:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0003_usuario_telefone'),
]
operations = [
migrations.AlterField(
model_name='usuario',
name='cpf',
... |
list_a=[1,1,5,100,-20,-20,6,0,0]
#list_a=list(input("Enter a list:"))
print(list_a)
i=0;
count=0;
for i in range(0,len(list_a)):
if(i<len(list_a)-1):
if list_a[i] == list_a[i+1]:
count+=1;
print(count) |
def tubiao():
global clean_results
clean_results = []
for res in results:
if res not in stopwords:
clean_results.append(res)
c = Counter(clean_results)
clean = dict(c.most_common(6))
key = clean.keys()
value = clean.values()
plt.bar(key,height=value)
plt.xticks(n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
friendica.py
A python 3 module to access the Friendica API.
See https://github.com/friendica/friendica/wiki/Friendica-API for the
documentation of the friendica API.
Author: Tobias Diekershoff
All rights reserved.
Redistribution and use in source and binary forms... |
"""
BIRL algorithms with Optimization based inference. Includes;
- MAP
- Gradient Descent based approaches
-
"""
from __future__ import division, absolute_import
import numpy as np
from six.moves import range
from scipy.optimize import minimize
from .birl_base import BIRLBase
from ...utils.data_structur... |
__author__ = 'aouyang1'
from math import log
import numpy as np
class FisherTransform:
def __init__(self, backtest, dataseries, period):
self.bt = backtest
self.dataseries = dataseries
self.period = period
self.val = [] # 0 index is newest
self.tmp_series = [] ... |
#debugging -- removing the errors from code
#linting :allows us to detecct as we code
#num +4
#IDES and editors
#Pbd - python debugger
#it is a builtin module
import pdb
def add(num1,num2):
pdb.set_trace()
t = 4 * 5#interactive python debuuger in the python console
return num1 ... |
import MatrixReps
import Quarto_Game as QG
import torch
def testBaseLayout():
qG = QG.GameBoard()
piece = qG.takePieceFromPool('SHORT BLACK ROUND FILLED')
piece2 = qG.takePieceFromPool('SHORT WHITE SQUARE INDENTED')
piece3 = qG.takePieceFromPool('SHORT WHITE ROUND INDENTED')
piece4 = qG.takePieceF... |
from __future__ import annotations
from collections import Set
from Data.Player import Player
from typing import Dict
class Layer:
""" A Layer computes the likelihood distribution which indicates how likely someone is the 'Mol'. """
def compute_distribution(self, predict_season: int, latest_episode: int, trai... |
import unittest
from ..lib.database import MakoMemoryDatabase
from ..lib.schedule import *
from ..lib.reporting import *
from ..lib.table import *
from ..lib import MakoCRUD
import datetime
class TestMakoCRUD(unittest.TestCase):
def setUp(self):
self.db = MakoMemoryDatabase()
p1 = Schedule... |
classe = []
menu = 3
while True:
try:
total = int(input('Digite o número de alunos na sala: '))
break
except Exception:
print('Erro na digitação, tente novamente...')
continue
for n in range(total):
while True:
try:
aluno = str(input('Digite o nome do alun... |
class ServerError:
enum = { "SQL_ERROR": "00",
"CREATE_SESSION" : "01",
"INVALID_SESSION": "02",
"BAD_AUTH": "03",
"INVALID_REGISTER": "04",
"INVALID_ROUTE": "05",
"DUP_REGISTER": "06",
"CREATE_REGISTER": "07",
"NO_ERROR": "08",
"WRONG_USER": "... |
# coding: utf-8
# In[267]:
# imports
import re
import string
import operator
# In[268]:
# Utility functions, constants
# create dictionary to store results
# key: term
# value: dictionary: (docID, numOccurences)
postings_lists = dict()
# A convenience dictionary to quickly get term frequencies
term_fre... |
#coding:utf-8
import sys
TelephoneNumber = 'sssssssssss'
def TelephoneNumberF(str):
return TelephoneNumber + str
# def TelephoneNumberF():
# return TelephoneNumber
def simple():
print "Hello from Python"
print "Call Dir(): "
print dir()
print "Print the Path: "
print sys.path |
# https://www.codewars.com/kata/56a4872cbb65f3a610000026
#
# Take a number: 56789. Rotate left, you get 67895.
#
# Keep the first digit in place and rotate left the other digits: 68957.
#
# Keep the first two digits in place and rotate the other ones: 68579.
#
# Keep the first three digits and rotate left the rest: 685... |
"""11. 최대공약수를 구하는 함수를 구현하시오"""
a= input('최대공약수를 구하고자 하는 첫번째 수를 입력해주세요:')
a= int(a)
b= input('최대공약수를 구하고자 하는 두번째 수를 입력해주세요:')
b= int(b)
def chd(a, b):
if a < b:
(a, b) = (b, a)
while b != 0:
(a, b) = (b, a % b)
return a
print(chd(a, b))
|
import os
import shap
import pickle
import numpy as np
import matplotlib.pyplot as plt
def plot_shap(clean_df,input_df,shap_value,borough_path):
sum_col = ['NEIGHBORHOOD','TAXCLASS','BUILDINGCLASS']
sums = []
for col in sum_col:
for column in input_df.columns:
if ( col in column ):
... |
# -*- coding: utf-8 -*-
import sys
import cv2
import dlib
import os
# from dlib.examples.face_clustering import face_descriptor
import numpy as np
class face_compare(object):
def __init__(self):
pwd = os.getcwd()# 获取当前路径
model_path = os.path.join(pwd, 'model')
self.shape_predictor_path = o... |
# https://blog.csdn.net/soonfly/article/details/78361819
# yield/send
def gen():
print("enter gen")
value = 0
while True:
recv = yield value
if recv == 'e':
break
value = 'got %s' % recv
g = gen() # 这里并没有启动 gen 生成器
print(g.send(None)) # 这行启动了生成器(并且启动的时候只能传递None,传递其他值会... |
# Generated by Django 2.1.5 on 2019-02-02 03:54
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import rc
import numpy as np
# % matplotlib inline
# curve colors
N = 5
colors = cm.hsv(np.linspace(0, 1, N + 1))
LabelX = '$H_x$'
LabelY = '$U(H_z, H_x)$'
TitleName = LabelY + '$-$' + LabelX
fontAxis = 16
fontLegend = 16
fontTitle = 20
fig = p... |
import torch
import os
import numpy as np
from process.file_reading import entity_reading, relation_reading, data_loading
def init_embeddings(entity_file, relation_file):
entity_emb, relation_emb = [], []
with open(entity_file) as f:
for line in f:
entity_emb.append([float(val) for val in... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home.as_view(), name='home'),
path('about/', views.About.as_view(), name='about'),
path('public/', views.PublicList.as_view(), name='public'),
path('accounts/register/', views.RegisterView.as_view(), name='register'),
path('memor... |
# Generated by Django 3.1.7 on 2021-04-05 02:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0003_auto_20210405_1044'),
]
operations = [
migrations.AlterField(
model_name='paper',
name='pub_date',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the USBStor Windows Registry plugin."""
import unittest
from plaso.lib import definitions
from plaso.parsers.winreg_plugins import usbstor
from tests.parsers.winreg_plugins import test_lib
class USBStorPlugin(test_lib.RegistryPluginTestCase):
"""Tests f... |
import requests
import smtplib
url = "http://partners.api.skyscanner.net/apiservices/browseroutes/v1.0/DK/dkk/en-US/cph/anywhere/anytime/anytime?apikey=prtl6749387986743898559646983194"
response = requests.get(url)
data = response.json()
id_to_place = {}
places = data['Places']
for place in places:
id_to_place[p... |
from pwn import remote
l = []
def connect():
r = remote('crypto.chal.csaw.io', 5001)
print(r.recvuntil('\n').decode())
return r
def send(r, x):
r.sendline(x)
print(x)
def run(r):
x = r.clean()
print(x) # Enter plaintext
send(r, 'a' * 64)
print(r.recvunti... |
# _*_ encoding:utf-8 _*_
# --------------------------增加操作---------------------------
# 增
# append
# 作用
# 往列表中, 追加一个新的元素
# 在列表的最后
# 语法
# l.append(object)
# 参数
# object
# 想要添加的元素
# 返回值
# None
# 注意
# 会直接修改原列表
# nums = [1, 2, 3, 4]
# print(nums)
# print(nums.append(5))
# print(nums)
# ... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# 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 app... |
from __future__ import unicode_literals
from django.apps import AppConfig
class DjangoNewspaperConfig(AppConfig):
name = 'django_newspaper'
|
# Generated by Django 2.2 on 2019-04-13 20:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('aio', '0004_auto_20190414_0107'),
]
operations = [
migrations.AddField(
model_name='shelter',
name='contact',
... |
#! env bin/python
# codding = utf-8
from wsgiref.simple_server import make_server
import hashlib
import psycopg2
def new_link(long_link):
link_encode = str(long_link).encode('UTF-8')
link_bytes = bytes(link_encode)
link_hash = hashlib.md5(link_bytes)
md5_link = link_hash.hexdigest()
return md5_lin... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import os, sys
import socket
from subprocess import Popen, PIPE, STDOUT
import time
import json
module_path = os.path.dirname(os.path.abspath(__file__))
CHKPW_EXE = os.path.join(module_path, 'chkpw_new')
daemon_uds = './uds_socket'
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
def check_pw(user, pw, creat... |
"""Script to run a ladder simulation for Rock Paper Scissors."""
from math import ceil
from simulation.base_simulation import load_config
from simulation.base_type_logging_simulation import BaseLoggingSimulation
from battle_engine.rockpaperscissors import RPSEngine
from agent.rps_agent import RPSAgent
from agent.coun... |
import plum
from plum.types import register, PlumObject, HP, props
@register("plum.tasks.s2s.evaluator")
class S2SEvaluator(PlumObject):
batches = HP()
searches = HP(default={})
metrics = HP(default={})
loggers = HP(default={})
loss_function = HP(required=False)
checkpoint = HP(required=False... |
N = int(input())
A = list(map(int, input().split()))
B = 1
ans = 0
for i in range(N):
for j in range(32, 0, -1):
if A[i] % (2**j) == 0:
ans += j
A[i] = A[i] / (2**j)
print(ans)
|
print('Problem 5')
Problem 5
import tensorflow as tf
ans = []
a = tf.constant(1.12)
b = tf.constant(2.34)
c = tf.constant(0.72)
d = tf.constant(0.81)
f = tf.constant(19.83)
x = 1 + tf.divide(a,b) + tf.divide(c,tf.square(f))
ans.append(x)
s = tf.divide((b - a),(d - c))
ans.append(s)
r = tf.math.reciprocal( tf.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AntProdpaasGrmcoreSrInvalidModel(object):
def __init__(self):
self._env = None
self._program_code = None
self._sr_nos = None
self._suppliers = None
self._t... |
from django import forms
from .models import Post
# formularios
class PostsForm(forms.Form):
class Meta:
model = Post
fields = ['img', 'detail','user']
|
# Generated by Django 2.2.1 on 2019-05-26 15:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(au... |
# EFILTER Forensic Query Language
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.