text stringlengths 38 1.54M |
|---|
from ..types import Action, ComponentType, DataElement, DataType, Instance, InstanceElement, Topology
from ..connector import DynizerConnection
from ...common.errors import LoaderError
from typing import Sequence
import xml.etree.ElementTree as ET
import itertools
class XMLAbstractElement:
"""
Abstract XML ele... |
import codecs
import socket
import traceback
from struct import *
from modules.api import definitions
from modules.data import variables
buffSize = 128
''
class HIL_socket:
def __init__(self, ip, port):
"""
:param family:
:param type:
"""
self.family = s... |
import pymysql
connector = pymysql.connect(
host='localhost',
db='sdb',
user='root',
passwd='root',
charset='utf8',
)
cursor = connector.cursor()
sql = "insert into test_table values('1','python')"
cursor.execute(sql)
sql = "insert into test_table values('2','パイソン')"
cursor.exe... |
#coding: utf-8
import numpy as np
'''
计算信息增益
powerd by ayonel
'''
class InformationGain:
def __init__(self, X, y):
self.X = X
self.y = y
self.totalSampleCount = X.shape[0] # 样本总数
self.totalSystemEntropy = 0 # 系统总熵
self.totalClassCountDict = {} ... |
from __future__ import annotations
from decimal import Decimal
from fava.beans import create
from fava.core.inventory import CounterInventory
def test_add() -> None:
inv = CounterInventory()
key = ("KEY", None)
inv.add(key, Decimal("10"))
assert len(inv) == 1
inv.add(key, Decimal("-10"))
ass... |
from flask import Blueprint, jsonify, render_template, request
from . import db, app
from .models import Program
from datetime import datetime
import flask_jwt_extended as jwt
from sqlalchemy.exc import IntegrityError, OperationalError
from .auth import decode_identity, gain_access
main = Blueprint('main', __name__)
... |
'''
Python 中定义函数有两种方法,一种是用常规方式 def 定义,函数要指定名字,第二种是用 lambda 定义,不需要指定名字,称为 Lambda 函数。
Lambda 函数又称匿名函数,匿名函数就是没有名字的函数,函数没有名字也行?当然可以啦。有些函数如果只是临时一用,而且它的业务逻辑也很简单时,就没必要非给它取个名字不可。
关键字lambda表示匿名函数,冒号前面的x表示函数参数。
匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函... |
import json
import unittest
from app import db
from apps.news.patches import (
patch_item, add, copy, move, remove, replace
)
from apps.news.models import News, NewsCategories, NewsCategoriesMapping
from apps.utils.time import get_datetime
class TestNewsPatchesFailures(unittest.TestCase):
def setUp(self):
... |
class UnionFind():
def __init__(self, n):
self.parents = [-1] * n
self.n = n
self.rank = [0] * n
def find(self, a):
if self.parents[a] < 0:
return a
self.parents[a] = self.find(self.parents[a])
return self.parents[a]
def union(self, a, b):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 9 22:03:53 2018
@author: raja
"""
from nltk.tree import ParentedTree
def find_path1(text,e1_from,e2_to):
e1_from=e1_from.split()[0]
e2_to=e2_to.split()[0]
def get_lca_length(location1, location2):
i = 0
while i < len(l... |
#!/usr/bin/env python
# Written by Min-Su Shin in Department of Astronomy, University of Michigan.
# Feel free use or revise the code.
import sys, urllib, string
import xml.dom.minidom
wsid = 000000 # parameter : wsid of your account on CASJobs
pw = "00000" # parameter : password for your account on CASJobs
tb_name... |
# file deepcode ignore NoHardcodedCredentials/test: Secrets are all just examples for tests. # noqa: E501
import logging
import warnings
from collections import deque
from contextlib import contextmanager
from pathlib import Path
import fakeredis
import pytest
import sqlalchemy
import uuid
from _pytest.capture impor... |
import _wingpio as gpio
import time
led_pin_one = 5
led_pin_two = 6
sensor_pin = 4
pinOneValue = gpio.HIGH
pinTwoValue = gpio.LOW
gpio.setup(led_pin_one, gpio.OUT, gpio.PUD_OFF, gpio.HIGH)
gpio.setup(led_pin_two, gpio.OUT, gpio.PUD_OFF, gpio.HIGH)
def work():
count = 0
gpio.setup(sensor_pin, gpio.OUT)
gp... |
# -*- coding: utf-8 -*-
"""URLs for default BEL resources.
This script is susceptible to rate limits from the GitHub API, so don't run it over and over!
"""
import logging
import os
from bel_resources.github import get_famplex_url, get_github_url
HERE = os.path.abspath(os.path.dirname(__file__))
logging.basicConf... |
'''
import traditional assets
'''
## create name for financial tickers
tkr_fin = ['Stocks', 'Bonds', 'Gold']
## background information on stocks bonds gold
name_bonds = "Vanguard Total Bond Market ETF"
url_bonds = "https://www.morningstar.com/etfs/ARCX/BND/quote.html"
name_stocks = "SP500"
url_stocks = "https://sto... |
# -*- encoding: utf-8 -*-
"""
Created on Jun 14, 2012
@author: Steve Ivy <steveivy@gmail.com>
@co-author: yangming <yangming@appfirst.com>
http://www.appfirst.com
Updated for Python 3 May 14, 2014 by michael@appfirst.com
Python client for AppFirst Statsd+
this file expects local_settings.py to be in the same dir, w... |
# -*- coding: utf-8 -*-
# @Time : 2020/7/25 15:27
# @Author : wangmengmeng
while True:
try:
print(int(input(),8))
except:
break |
# -*- coding: utf-8 -*-
"""
***************************************************************************
MonthlyMean.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Riccardo Lemmi
Email : riccardo at reflab dot com
*********************... |
import sys
sys.path.append("./python/")
import os
import json
import random
import string
from flask import Flask, request, render_template, jsonify
from ips_python.script import process_query
from ips_python.constants import (
VECTORIZER_FILENAME,
TERM_DOCUMENT_MATRIX_FILENAME,
PROCESSED_RECORDS_FILENAM... |
from PyQt4 import QtGui, QtCore
class TextChangingButton(QtGui.QPushButton):
"""Button that changes its text to ON or OFF and colors when it's pressed"""
def __init__(self, parent = None):
super(TextChangingButton, self).__init__(parent)
self.setCheckable(True)
self.setFont(QtGui.QFont... |
from astropy.io import ascii
import matplotlib.pyplot as plt
tabla1=[]
tabla2=[]
tabla3=[]
tabla4=[]
tabla5=[]
tabla6=[]
tabla7=[]
tabla8=[]
tabla9=[]
tabla10=[]
tabla11=[]
tabla12=[]
tabla13=[]
tabla14=[]
tabla15=[]
tabla16=[]
tabla17=[]
tabla18=[]
tabla19=[]
tabla20=[]
tabla21=[]
tabla22=[]
tabla23=[]
tabla24=[]
tab... |
#!/usr/bin/env python
import unittest
from flysight_manager import config
import flysight_manager.log
flysight_manager.log.suppress_logs()
class TestableConfiguration(config.Configuration):
CONFIG_FILE = 'flysight-manager.ini.example'
class TestConfigParser(unittest.TestCase):
def test_config(self):
... |
from django.contrib import admin
from .models import Revendedor
class RevendedorAdmin(admin.ModelAdmin):
list_display = ['nome', 'cpf', 'email']
list_filter = ('nome', 'cpf', 'email')
search_fields = ('nome', 'cpf', 'email')
ordering = ['nome', 'cpf', 'email']
save_as = True
admin.site.register(... |
import csv
import numpy as np
from classes_needed import *
def main():
# set initial parameters
robotSpeed = 3
# Create an initial matrix for shape and scale values for different zones and times
# col = zone, row = hours
los_matrix = np.zeros((1, 2), dtype='f,f').tolist()
# _____parameters ... |
#!/usr/bin/python
import sys
import re
SYNSETS_MAP_PATH = "/home/robin/Documents/NUS/Lectures/sem_3/Advanced_AI/Project/Data/Images/synsets.txt"
NAMES = sys.argv[1:]
f = open(SYNSETS_MAP_PATH, "r")
text = f.read()
f.close()
f = open("synsets.txt", "w")
synsets = []
for name in NAMES:
p = re.compile("n[0-9]+ ... |
places = {
'an':'andaman-nicobar-islands-an-',
'ap':'andhra-pradesh-ap-',
'ar':'arunachal-pradesh-ar-',
'cg':'chhattisgarh-cg-',
'ch':'chandigarh-ch-',
'dd':'daman-and-diu-dd-',
'dl':'delhi-dl-',
'dn':'dadra-nagar-haveli-dn-',
'ga':'goa-ga-',
'gj':'gujarat-gj-',
'h... |
from django.urls import path
from . import views
urlpatterns = [
path('v1/productos/', views.ProductoList.as_view(), name='producto_list_api'),
path('v1/productos/<str:codigo>', views.ProductoDetalle.as_view(), name='producto_detalle'),
] |
# Generated by Django 2.2.2 on 2019-06-20 19:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_auto_20190617_1811'),
]
operations = [
migrations.AlterModel... |
import os
import fnmatch
FOLDER = '/haproxy'
root = os.getcwd() + FOLDER
print(root)
for path, subdirs, files in os.walk(root):
for name in files:
# print(name)
if fnmatch.fnmatch(name, '*.c'):
path = os.path.join(path, name)
# print(name)
try:
... |
import plotly.figure_factory as ff
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("data.csv")
data = df["temp"].tolist()
#fig = ff.create_distplot([data], ["name"], show_hist=False)
#fig.show()
pm = statistics.mean(data)
ptsd = statistics.stdev(data)
#print(pm)
#print(p... |
# checkio.py
def non_unique(data):
freqDist = {}
for val in set(data):
freqDist[val] = 0
for val in data:
freqDist[val] += 1
for val, freq in freqDist.items():
if freq == 1:
del(data[data.index(val)])
def roman_numeral(data):
values = [1000, 900, 500, 400, 1... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
DEBUGE = False
TESTING = False
SECRET_KEY = "12345"
#SQLALCHEMY_DATABASE_URL = os.environment['DATABASE_URL']
|
#!/usr/bin/env python3
from librip.gens import gen_random
from librip.iterators import Unique
data0 = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
data1 = gen_random(1, 3, 10)
# Реализация задания 2
data2= ['a', 'A', 'A', 'a', 'C', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
d0 = Unique(data0)
for x in d0:
print(x, end=', ')
print('\n... |
import json
with open('./problemset.json','r',encoding='utf8')as fp:
json_data = json.load(fp);
result=json_data["result"];
problems=result["problems"];
problemStatistics=result["problemStatistics"];
cnt=0;
for i in problems:
cnt+=1;
print(cnt,i); |
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
from MenuOfChoices import MenuOfChoices
MENU_OF_CHOICES = MenuOfChoices()
class FinancesUI():
def __init__():
pass
def set_sale_to_emp(Finances):
emp_id... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from .models import Station
class StationAdmin(admin.ModelAdmin):
fieldsets = [
(None,{'fields':['content']}),
('location', {'fields':['... |
import socket
import sys
import struct
# The following libraries should be installed before executing
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric... |
# Filename: MD_ImmuNet_Scraper_Window.py
# Author: Zheng Guo
# Date: 10-16-2020
# Purpose: Scraping member's immunization registration information from the MD Immunet site based on a given list of members.
# Class list: - Person (measYr, memberId, memberIdSkey, fname, lname, lnameSuffix, dob, gender, stateRes, meas)
... |
import json
import random
import binascii
import base64
from Crypto.Cipher import AES
import requests
url = 'https://music.163.com/weapi/cloudsearch/get/web?csrf_token='
headers = {
"Host":"music.163.com",
"Connection":"keep-alive",
"Origin":"https://music.163.com",
"User-Agent":"Mozilla/... |
from threading import Thread
from webserver.zenwebserver import ZenWebServer
from kivy.logger import Logger
from components.config import Config
class FlaskThread(Thread):
"""
Start the Flask Application on a background thread to blocking the GUI.
"""
def __init__(self, ctrl, config):
super().... |
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from config import config
class Net(nn.Module):
def __init__(self, input_length, output_length, tune_config):
super(Net, self).__init__()
self.tune_config = tune_config
config_layers = self.get_config("hi... |
from app import db,app
from flask_marshmallow import Marshmallow
ma = Marshmallow(app)
class Estado_Grupo(db.Model):
id=db.Column(db.Integer, primary_key=True,nullable=False)
nombre=db.Column(db.String(50),nullable=False)
def __init__(self, nombre):
self.nombre = nombre
db.create_all()
class S... |
import random
def main():
hidden = [str(x) for x in random.sample(range(1, 7), 4)]
#print(hidden)
while(True):
print("Please enter 4 digits")
guess = list(input())
if len(guess)!=4:
continue
res = ""
for h, g in zip(hidden, guess):
#p... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
from bs4 import BeautifulSoup
from argparse import ArgumentParser
from platform import python_version_tuple
import json
import pandas as pd
import re
import requests
import time
if python_version_tuple()[0] == u'2':
def input(prompt): return raw_input(prompt.encode('ut... |
from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
from block import Block
import hashlib
import json
import base64
class Transaction(object):
def __init__(... |
import cv2
import time
import numpy as np
# for the lcm communication for camera
import sys
CAMERA_LENGTH = 640
CAMERA_WIDTH = 480
CMAERA_CHANNEL_1 = "CAMERA_COORD1"
CMAERA_CHANNEL_2 = "CAMERA_COORD2"
# trans matrix from base of cam1 to cam2
# [[ 1. 0. 0. 500.]
# [ 0. 1. 0. 0.]
# [ 0. 0. ... |
import copy
import random
import os
import ui
import util
import main
PLANET_ICON = u"\U0001FA90"
BORDER_ICON = '█'
WALL_ICON = u"\u2593"
QUIZ_ICON = u'\u001b[33;1m★ \u001b[0m'
MEME_ICON = '⚝'
DOOR_ICON = "@"
ENEMY_SHOTS_NUMBER = 3 #quantity of position occupied by one shot
ENEMY_SHOT_ICON = "\u001b[36;1... |
# Atomic Data 2003/3/26-3/28
AtomData = {
"Vc":{"Z":0 ,"LMX":2 ,"RWS": 1.500,"PeriodicTable":( 1, 0),"Mass":0.000 ,"Name":"Vacancy"},
"H" :{"Z":1 ,"LMX":2 ,"RWS": 1.390,"PeriodicTable":( 1, 1),"Mass":1.008 ,"Name":"Hydrogen"},
"He":{"Z":2 ,"LMX":2 ,"RWS": 2.550,"PeriodicTable":( 1, 18) ,"Mass":4.003 ,"Nam... |
# Negetive number check
def check(num):
return True if (num<0) else False
print(check(-2))
### The function does check and return the negatives from a list
lst = [4,-5,4, -3, 23, -254]
def neg(lst):
return [num for num in lst if num <0]
# or the above statement can be written as= return sum([num < 0... |
from db import db # importing SQLAlchemy Object
class Device(db.Model):
""" Referring the tablename along with column as required and create if not exists."""
__tablename__ = 'devicedesc'
id = db.Column(db.Integer, primary_key=True)
device_id = db.Column(db.Integer)
password = db.Colum... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, get_object_or_404, render_to_response
from .models import Organization, Location, Item
from django.views.generic import ListView, CreateView, DetailView, UpdateView
from .forms import OrganizationForm, LocationForm, ItemForm
... |
ans = 0
def is_palindrome(n):
s = str(n)
r = s[::-1]
if r == s:
return True
return False
for x in range(999, 901, -1):
for y in range(999, 901, -1):
if is_palindrome(x*y):
print(x*y)
exit()
|
# Program to convert temperature to celsius from faremheit
f = int(input('Enter Temperature In Farenheit : '))
c = (f-32)*5/9
print('Temperature In Celsius Is', c) |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# from phonenumber_field.modelfields import PhoneNumberField
user_type= [
('prime', 'PRIME'),
('non prime', 'NON PRIME'),
]
class UserRegisterForm(UserCreationForm):
email= forms.Ema... |
import config
from modle import dzzhkl_molde
import json, logging
import requests
# 电子账户开立
def dzzhkl(req):
data = dzzhkl_molde.dzzhkl_modle(req)
header = config.header
url = config.url['jinjian_url']
req = requests.post(url, headers=header, data=json.dumps(data))
if req.status_code == 200:
... |
ciphertext = input("enter ciphertext: ")
for i in range(0, len(ciphertext), 2):
print(ciphertext[i:i+2], end=" ") |
# (c) Copyright 2018 SUSE LLC
# 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
#
# Unless required by ... |
import networkx as nx
from typing import Optional
from bokeh.io import output_file, show
from bokeh.models import (
BoxSelectTool,
Circle,
NodesOnly,
EdgesAndLinkedNodes,
HoverTool,
MultiLine,
NodesAndLinkedEdges,
Plot,
Range1d,
TapTool,
BoxZoomTool,
ResetTool,
Wheel... |
import torch
from torch import Tensor, nn as nn
def multiclass_hinge_loss(outputs: Tensor, targets: Tensor, margin=1., reduction='mean', device='cpu') -> Tensor:
assert outputs.shape[0] == targets.shape[0]
batch_size = outputs.shape[0]
num_classes = outputs.shape[1]
# TODO to be revisited when PyTorc... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # '3,2' #'3,2,1,0'
from data_util import *
# from unet_5_scale_more_aug.model import SaltNet as Net
# from resnet34.model_resnet34_bn import SaltNet as Net
from seresnet50.model_se_resnext50_bn import SeResNeXt50Unet as Net
# from resnet_aug0.model import... |
# region imports
import win32com.client
import openpyxl
from openpyxl.utils import coordinate_from_string, column_index_from_string
from openpyxl.worksheet import cell_range
import re
import tkinter as tk
# endregion
# region class imports
import Scraper
import Interface
from Interface import interface
# endregion
de... |
import numpy as np
import json
import os
import sys
import eval_helpers
def computeDist(gtFrames,prFrames):
assert(len(gtFrames) == len(prFrames))
nJoints = eval_helpers.Joint().count
distAll = {}
for pidx in range(nJoints):
distAll[pidx] = np.zeros([0,0])
for imgidx in range(len(gtFrame... |
# Formulario de registro de Usuario usando Python y Tkinter
# Vamos a importar tkinter desde tkinter import *
#importar tkinter como tk
from tkinter import *
# creacion de sen_data para recuperar los datos que se guardan en las variables y paa que el boton de enviar informacion funcione
def send_data():
nombred... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 19:51:43 2018
@author: Matheus
"""
from rake_nltk import Rake
# função para ranquear as palavras do texto
def GetRelevanteKeyWords(text, quantity, language):
r = Rake(language=language)
r.extract_keywords_from_text(text)
r.get_ranked_phrase... |
import sys,os
import multiprocessing
from tqdm import tqdm
from functools import reduce
import pickle
from shutil import rmtree
sys.path.append("..")
from util.utility import split_equal, preprocess_sentence
from edit_distance.substring_distance import Sub_dist
base_path = os.path.abspath(os.path.realpath(os.path.dirna... |
"Interface to Phantom"
from amuse.community import (
CodeInterface,
LegacyFunctionSpecification,
legacy_function,
LiteratureReferencesMixIn,
)
from amuse.community.interface.gd import (
GravitationalDynamicsInterface,
GravitationalDynamics,
# GravityFieldInterface,
GravityFieldCode,
)
... |
import turtle
myTurtle = turtle.Turtle()
myTurtle.shape('turtle')
#mySecondTurtle = turtle.Turtle()
myList = [1,2,3,5,8]
print(myList)
print(myList[0])
print(myList[4])
def printMyList():
print('In the function')
for i in range(0, len(myList)):
print(myList[i], end=' ')
# calling the function
print... |
from flask import Flask, jsonify, request
import json
import requests
from requests.auth import HTTPBasicAuth
import tango_credentials_prod as tango_credentials
import logging
import socket
from logging.handlers import SysLogHandler
# Set up logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
syslog =... |
test = int(input())
while test > 0 :
str1 = input()
str1 = list(str1)
l = []
l.append(str1[0])
for i in range(1,len(str1)) :
if str1[i] != l[-1] :
l.append(str1[i])
print(''.join(map(str,l)))
test -= 1
|
from odoo import models, fields, api, _
class reschedule_booking(models.TransientModel):
_inherit = 'reschedule.booking'
@api.multi
def reschedule_booking(self):
res = super(reschedule_booking, self).reschedule_booking()
self.env[self._context.get('active_model')].sudo().browse(... |
import logging
class OneLineFormatter(logging.Formatter):
def format(self, record) -> str:
result = super(OneLineFormatter, self).format(record)
result = result.replace('\n', '|')
return result
|
from django.contrib import admin
from .models import Debt, Payment
# Register your models here.
admin.site.register(Debt)
admin.site.register(Payment)
|
# coding:utf-8
from datetime import date, timedelta, datetime
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify as djslugify
from math import ceil
from random import choice
from string ... |
import torch.nn as nn
import math
import torch
import torch.utils.model_zoo as model_zoo
from torchvision import datasets, transforms, models
#__all__ = ['vgg16_bn']
model_urls = {
'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
'resnet18': 'https://s3.amazonaws.com/pytorch/models/resn... |
# Sparki_Myro testing
from __future__ import print_function
from sparki_learning import *
com_port = None # replace with your COM port or /dev/
setDebug(DEBUG_INFO)
while not com_port:
com_port = input("What is your com port or /dev/? ")
init(com_port)
for x in timer(15):
print("x = " + str(x))
fo... |
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin)
from django.utils import timezone
from unavis import managers
class UserModel(AbstractBaseUser, PermissionsMixin):
"""
```UserModel``` defines all th... |
#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author: Jeff Zhang
@date: 2017-08-30
"""
import autograd.numpy as np
from autograd.scipy.misc import logsumexp
from autograd.convenience_wrappers import value_and_grad as vgrad
from functools import partial
def EM(init_params, data, callback=None):
def EM_upd... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import svd
X = plt.imread("YOUR_IMAGE.jpg").astype(np.float)
X /= 256.0
X = X.mean(axis=2) # make X black and white
plt.imsave("YOUR_IMAGE_IN_BLACK_AND_WHITE.jpg", np.dstack([X]*3))
# CODE GOES HERE
|
"""
def __init__(self,
criterion="gini", 基尼系数
splitter="best",
max_depth=None, 树的深度大小
min_samples_split=2, # 减枝
min_samples_leaf=1, # 减枝
min_weight_fraction_leaf=0.,
max_features=None,
... |
# -*- coding: utf-8 -*-
# @Time : 2020/5/15 10:52
# @Author : 永
# @File : text.py
# @Software: PyCharm
import re
li = ['\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', '/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t', '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-\n\t\t\t... |
"""
Util
calcRatio
removeDuplicateLInks
trimDomainStr -- remove all but the domain
trimLinkStr -- limit to filename length ?
isMimeTypeValid
isPageExpired
"""
import sys, json, os
import requests
import requests_cache
from datetime import datetime
from Writer import Write... |
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
def pytest_addoption(parser):
parser.addoption(
"--browser_name", action="store", default="chrome"
)
@pytest.fixture(scope="class")
def setup... |
import os, sys
import awesomeengine
import behaviors
import editor_behaviors
import modes
def go():
if getattr(sys, 'frozen', False):
root = sys._MEIPASS
else:
root = os.path.dirname(os.path.abspath(__file__))
e = awesomeengine.Engine(os.path.join(root, 'res'))
e.behavior_manager.reg... |
"""A Future class similar to the one in PEP 3148."""
__all__ = (
'Future', 'wrap_future', 'isfuture',
)
import concurrent.futures
import contextvars
import logging
import sys
from types import GenericAlias
from . import base_futures
from . import events
from . import exceptions
from . import format_helpers
isf... |
# Generated by Django 3.2.5 on 2021-07-24 01:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0014_review_model'),
]
operations = [
migrations.RemoveField(
model_name='shipment',
name='customer',
),
... |
class Barracks(object):
'''
def generate_knight(self):
#print("generate_knight")
return Knight(400, 5, 3, 1, "short sword")
def generate_archer(self):
#print("generate_knight")
return Archer(200, 7, 1, 3, "short bow")
'''
def generate_unit(self, unit_type, level):
... |
import statistics as s
#OR: from statistics import mean as m
#print(m(exList))
#OR: from statistics import mean, stdev
#print(mean(exList))
#print(stdev(exList))
#OR: from statistics import mean as m, stdev as s
#OR: from statistics import * #the * imports all functions from statistics
exList = [5,6,2,1,6,7,2,2... |
def bball_sub(heights, counter, team):
while not ((counter == 5) or (len(heights) == 0)):
height = heights[0]
heights = t(heights)
if height > 180:
team[counter] = height
counter += 1
def t(heights):
temp = []
for i in range(1, len(heights)):
temp.app... |
"""
@author: Scarlett Zhang
This file has 2 classes:
InvalidFireRecordException
FireDumper
"""
import logging
from typing import Any
from typing import List, Dict, Tuple
import rootpath
rootpath.append()
from backend.data_preparation.dumper.dumperbase import DumperBase
from backend.connection import Connection
from ... |
from django.shortcuts import render
# Create your views here.
def index(request):
my_dict = {'index':"hello from second app"}
return render(request,'second_app/index.html',context=my_dict) |
import torch
import torch.nn as nn
import torch.nn.functional as F
from gcake.models.gake import GAKE
from gcake.models.modules import Graph
from config import Config # TODO: remove device
class GAKEGraphEncoder(nn.Module):
def __init__(self, triples, num_entity, num_relation, dim):
super().__init__()
... |
"""References:
Guangcan Mai, Kai Cao, Pong C. Yuen and Anil K. Jain.
"On the Reconstruction of Face Images from Deep Face Templates."
IEEE Transactions on Pattern Analysis and Machine Intelligence (TPAMI) (2018)
Alec Radford, Luke Metz and Soumith Chintala.
"Unsupervised Representation Learning with Deep Convolution... |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class DataQualityOperator(BaseOperator):
check_sql = """
SELECT
COUNT(*)
FROM
{table}
WHERE
{where}
"""
ui_color = '#89DA59'
@appl... |
import logging
import sqlite3
import sqlite3 as sqlite
from dataclasses import astuple
from typing import Generator
import psycopg2
from psycopg2.extensions import connection as _connection
from psycopg2.extras import DictCursor
from sqlite_to_postgres.db_settings import DSL
from sqlite_to_postgres.tables_db_ps impor... |
import compas
import compas_rhino
from compas.datastructures import Mesh
from compas.rpc import Proxy
from compas_rhino.artists import MeshArtist
numerical = Proxy('compas.numerical')
fd_numpy = numerical.fd_numpy
compas_rhino.clear()
mesh = Mesh.from_obj(compas.get('faces.obj'))
mesh.update_default_vertex_attribut... |
import pytest
from server.database import db_session as session, engine
from server import app
from sqlalchemy import event
from server.database import SeedData
@pytest.fixture
def client():
app.testing = True
test_client = app.test_client()
def teardown():
pass
return test_client
@pytest.... |
import re
def solution(dartResult):
bonus={'S':1,'D':2,'T':3}
option={'':1,'*':2,'#':-1}
p=re.compile('(\d+)([SDT])([*#]?)')
dart=p.findall(dartResult)
for i in range(len(dart)):
if dart[i][2]=='*' and i:dart[i-1]*=2
dart[i]=int(dart[i][0])**bonus[dart[i][1]]*option[dart[i][2]]
r... |
#Import TwythonError now too!
from twython import Twython, TwythonError
app_key = "2UbDfKCaAz8oRNwWbygDVVtNe"
app_secret = "MvWUHfAUHa1v6pOnabXJ4KpBvp4BG8xane4Ktjj3hG7qeyCUjx"
oauth_token = "898316520794841090-Gt7sN0L9SWSkVnwaKr4lMOJxDIoNgDT"
oauth_token_secret = "GZIK6KaVsitTHiyr7T7MZZMG8YWZd2O9DZuyJMp1Zxuqp"
#Let's... |
#Animación de la epidemia a través de agentes.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as patches
import os
colores = ['blue','red', 'green', ]
archivo = "data/animacion.txt"
####################################################... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Dojo(models.Model):
"""docstring for Dojos"""
name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=2)
def __repr_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.