text stringlengths 8 6.05M |
|---|
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'exclude_with_action',
'type': 'none',
'msvs_cygwin_shell': 0,
'actions': [{
'actio... |
#Written by Michael Disyak - Feb 2017
#This class represents a general value function and has the ability to
# recieve updates to relevant incoming data streams and learn using TD(lambda) and GTD(lambda) algorithms
# This class is designed to be used in conjunction with the Plotter class and a control file that implem... |
"""
Simulate N(t) = ceiling(lambda * t), with lambda normally distributed.
In "Learning to time: a perspective", Appendix, they simulate two 'walks'
with lambda = {0.8,1.2} sampled from N(1,0.2)
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def n_t(t, mean, sd):
""... |
import tensorflow as tf
from models import blocks
from utils.logger import deep_log
class Net:
@deep_log
def __init__(self, dropout, num_output, num_conv, num_fc, cnn_config=None):
print 'Initializing a net ...'
self.dropout = dropout
self.num_output = num_output
self.num_conv... |
import unittest
from poker.card import Card
from poker.validators import StraightFlushValidator
class StraightFlushValidatorTest(unittest.TestCase):
def setUp(self):
self.seven_of_spades = Card(rank = "7", suit = "Spades")
self.eight_of_spades = Card(rank = "8", suit = "Spades")
self.nine_... |
from poker.validators import RankAndSuitValidator
class ThreeOfAKindValidator(RankAndSuitValidator):
def __init__(self, cards):
self.cards = cards
self.name = "Three of a Kind"
def is_valid(self):
return self._rank_count(3) == 1
def valid_cards(self):
copy = self.cards... |
import socket
UDP_IP = "192.168.1.210"
UDP_PORT = 5005
MESSAGE = b'123456'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
|
import string
var1=input("Enter the string or the number(integer number) you wnat to check: ")
var1=var1.split(' ')
var1=''.join(var1)
if var1[::-1]==var1:
print("it is a palindrome")
else:
print("it's not a palindrome") |
from django.contrib import admin
from django.urls import include, path
from django_js_reverse.views import urls_js
from pages.views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('admin/', admin.site.urls),
path('notes/', include('notes.urls')),
path('notebooks/', inc... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-20
# @Author : mizxc
# @Email : xiangxianjiao@163.com
import os
from flask import current_app, request, flash, render_template, redirect, url_for
from flask_login import login_required, current_user
from . import bpAdmin
from project.common.dataPreprocess import strLengt... |
A, B = input().split()
A = float(A)
B = float(B)
avg = (A + B) / 2
if avg >= 7:
print("Aprovado")
elif avg >= 4:
print("Recuperacao")
else:
print("Reprovado")
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import pygame
import OpenGL.GL as gl
import numpy as np
#local imports
from common import DEFAULT_FLASH_RATE, correct_gamma
from screen import Screen
from checkerboard import CheckerBoard
class TripleCheckerBoardSinFlasher(Screen):
def setup(self,
... |
# -*- coding: utf-8 -*-
#########################################
# IPTV List Updater #
# by Nobody28 & satinfo #
#########################################
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ActionMap import NumberActionMap
fr... |
#### Class 04
#### Using Selenium: An Example
from selenium import webdriver
from bs4 import BeautifulSoup as bs
from selenium.webdriver.common.keys import Keys
import time
def start_chrome(webpage):
driver = webdriver.Chrome()
driver.get(webpage)
return driver
def define_search(driver):
## search el... |
def driver(input):
helper(input, 0, [])
def helper(input, idx, soFar):
if (idx == len(input)):
print(soFar)
else:
helper(input, idx+1, soFar)
soFar.append(input[idx])
helper(input, idx+1, soFar)
soFar.pop(-1)
driver([1, 3, 5, 7]) |
from redbot.core import commands, checks
from redbot.core.utils.chat_formatting import text_to_file
import random
from .words import words, words2, flags
from .country import country
import re
import subprocess
import discord
class Utilities(commands.Cog):
def __init__(self, bot):
self.bot = bot
#... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
all_path = []
... |
from django import forms
class loginform(forms.Form):
username=forms.CharField(label="Username",max_length=50,required=True)
password = forms.CharField(label="Password",widget=forms.PasswordInput,required=True)
|
import pandas as pd
import numpy as np
from osmread import parse_file, Node
import matplotlib.pyplot as plt
from tqdm import tqdm
import csv
import os
housing_df = pd.read_csv('./data/out/datall.csv')
def decode_node_to_csv():
# Dictionary with geo-locations of each address to use as strings
for entry in par... |
A = [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0]
# N = 0
# 0, 1, 0, 1, ...
# 0, 0, 0, ..., 1 - only one jump
# 1, 1, 1, 1 - with best score == 1
# check empty
# 0, 0, 0, 0, ...
def solution(A):
A.append(1) # add value for last point - opposite riverbank
fib_numbers = get_fib_numbers_up_to(26) # there are 26 fib numb... |
from django.test import TestCase
from django.test.utils import override_settings
import mock
from jenkinsapi import jenkins
from jenkins.tasks import build_job, push_job_to_jenkins, import_build
from .factories import (
JobFactory, JenkinsServerFactory, JobTypeFactory)
class BuildJobTaskTest(TestCase):
def... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-10 10:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myblog', '0002_blogspost_summary'),
]
operations = [
migrations.AlterField(
... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
dataset1=pd.read_csv('tamil_movie_reviews_train.csv') |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
from lxml import etree
class OpenStreetMap :
def __init__ (self) :
self.bounds = None
self.nodes = []
self.ways = []
self.relations = []
def fromXML (self, xml) :
root = etree.fromstring(xml)
self.bounds = OSM... |
# Copyright 2017 The Forseti Security Authors. 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 ap... |
def typeList(list1, list2):
checkCount = 0
if len(list1) == len(list2):
for i in range(0, len(list1)):
for j in range (i, i + 1):
if list1[i] != list2[j]:
print "The lists are not the same."
checkCount += 1
if checkCount == 0:
print "The lists are the same."
else:
... |
'''
print("====This is a intersting words game====")
temp = input("不妨猜一下我现在想的数字是:")
guess = int(temp)
if guess == 8:
print("哈哈,你真厉害哦!")
print("不过,猜中也没啥卵用,没有任何奖励的。")
else:
print("猜错啦哦,我想的是8,不信你去试试看哦")
print("游戏技结束,不玩了。")
import random
secret = random.randint(1,10)
print("==== This is the second words game... |
# URI widget
import re
import zeam.form.ztk.compat
from zeam.form.base.markers import Marker, NO_VALUE
from zeam.form.base.widgets import FieldWidget
from zeam.form.ztk.fields import Field, registerSchemaField
from grokcore import component as grok
from zope.i18nmessageid import MessageFactory
from zope.interface im... |
import scrapy.cmdline
scrapy.cmdline.execute(['scrapy','crawl','mybaike']) |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/4/8 19:07
# @Author :'liuyu'
# @Version:V 0.1
# @File :
# @desc :
from transformers import XLNetTokenizer, TFXLNetModel
import os
import tensorflow as tf
from tensorflow.python.keras.backend import set_session
from queue import Queue
from threading import Th... |
import sys
import socket
import threading
import time
import bcrypt
import json
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from base64 import b64decode, b64encode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
running = True
testing_client = True
""" #==================================... |
import math
import sys
import time
import torch
import torchvision.models.detection.mask_rcnn
import utils
from coco_eval import CocoEvaluator
from coco_utils import get_coco_api_from_dataset
def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq, scaler=None):
model.train()
metric_logg... |
# ---------------------------------------------fibonacci function--------------------------------------------------
"""
fibonacci for sum serise with first value 0 for n=0 and 1 for n =1
implimenting function using : recursion.
"""
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1 ... |
property_names = [line.rstrip('\n')
for line in open('graph_txt_files/txt_functions/invariants.txt')]
|
import sys
import os
def newick_to_nexus(input_newick_path, output_nexus_path):
with open(output_nexus_path, "w") as writer:
writer.write("#NEXUS\n")
writer.write("BEGIN TREES;\n")
writer.write(" TREE tree1 = " + open(input_newick_path).readlines()[0].replace("\n", "") + "\n")
writer.write("END TR... |
from django.conf.urls import url
from API import views
urlpatterns = [
url(r'^dealers/todos$', views.dealer_list),
url(r'^dealers/ciudad/(?P<ciudad>[\w\-]+)$', views.dealer_city),
url(r'^dealers/region/(?P<pk>[0-9]+)$', views.dealer_region),
url(r'^dealers/catalogo$', views.add_libro_catalogo),
url... |
from .base import *
# from .local import *
# from .production import *
# try:
# from .local import *
# except:
# pass
# Design the video
# for teacher
# 1)creating a new profile
# Tips:
# load images that thanks tutor for good work done
# load images with your certificates
# 2)Search for openings
# 3)mes... |
class CQueue:
def __init__(self):
self.input_stack = []
self.output_stack = []
def append_tail(self, value: int) -> None:
self.input_stack.append(value)
def delete_head(self) -> int:
if not self.output_stack:
while self.input_stack:
self.output_s... |
#!/usr/bin/env python3
import os
import numpy as np
import pandas as pd
# SETTTINGS
cd = os.path.join(os.path.dirname(__file__))
pd.set_option('display.width', 10000)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
# INITIAL DATA FRAMES
gas_df = pd.read_csv(os.path.join(cd, 'EIA_Re... |
from django import forms
class Mpesaform(forms.Form):
phone = forms.CharField(widget=forms.NumberInput(attrs={
'class': 'form-control', 'placeholder':'254725696052'
}))
|
'''
:Date: Jul 1, 2011
:authors: Gary Belvin
'''
from binascii import a2b_hex
from charm.schemes.pkenc.pkenc_rsa import RSA_Enc, RSA_Sig
from charm.toolbox.conversion import Conversion
from charm.toolbox.securerandom import WeakRandom
import unittest
from random import Random
debug = False
class Test(unittest.TestCase... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis"
# Import libraries
import os
import cv2
import numpy as np
def remove_dots(img, se_size):
"""
Description: remove dots
If se_size not specified, it is assumed to be in the center
Input: img, se_siz... |
#!/usr/bin/env python
import sys
import rospy
from core_api.srv import *
global_namespace = ''
def setpoint_local_position(lx, ly, lz, yaw=0.0, tolerance= 1.0, async = False, relative= False, yaw_valid= False, body_frame= False):
global global_namespace
rospy.wait_for_service('/'+ global_namespace +'/navigation/pos... |
#!/usr/bin/python
# -*-coding:Utf-8 -*
from requests import get
import textwrap
from bs4 import BeautifulSoup
from dateutil.parser import parse
from dateutil import relativedelta
from dateutil.tz import *
import datetime
from clize import clize, run # sert à pouvoir passer des arguments au script
import pickle
import ... |
import ssh
server = ssh.Connection(host='10.100.52.148', username='mayank', private_key='mayank')
result = server.execute('ls')
print(result) |
cdef = []
cdef.append(
"""
typedef struct _MonoDomain MonoDomain;
typedef struct _MonoAssembly MonoAssembly;
typedef struct _MonoImage MonoImage;
typedef struct _MonoMethodDesc MonoMethodDesc;
typedef struct _MonoMethod MonoMethod;
typedef struct _MonoObject MonoObject;
MonoDomain* mono_jit_init(const char *root_... |
# -*- coding: utf-8 -*-
#
# Last modification: 4 July. 2019
# Author: Rayanne Souza
import numpy as np
import matplotlib.pyplot as plt
import itertools
from keras.models import load_model
from sklearn.metrics import classification_report
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from sk... |
# -*- coding: utf-8 -*-
import scrapy
from tools.items import DianpingItem
from datetime import datetime
# from scrapy_tools.storage.rabbitmq import RabbitMQSignal
"""
'append',
'count',
'css',
'extend',
'extract',
'extract_first',
'extract_unquoted',
'index',
'insert',
'pop',
're',
're_first',
'remove',
'reverse',
'se... |
"""update
Revision ID: 48deb381adcc
Revises: 18076d8ef708
Create Date: 2015-12-05 21:15:57.393419
"""
# revision identifiers, used by Alembic.
revision = '48deb381adcc'
down_revision = '18076d8ef708'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please ... |
#!/usr/bin/env python
"""
pyjld.builder.tools
@author: Jean-Lou Dupont
"""
__author__ = "Jean-Lou Dupont"
__email = "python (at) jldupont.com"
__fileid = "$Id: tools.py 24 2009-04-02 01:54:53Z jeanlou.dupont $"
__all__ = ['findPackage','extractNsPackage', 'findPackages', 'getShortAndLongDescription',
... |
import sys, curses, argparse
from curses import wrapper
filepath, width, height, row, column, max_height = None, None, None, None, None, None
max_window_widths = None
lines = list()
def get_args():
parser = argparse.ArgumentParser(description='View a window of a file\'s text')
parser.add_argument('-F', help='filep... |
def rotten_tomato_score(actor_name,cur):
import pymysql, json, requests
from bs4 import BeautifulSoup
userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
headers = {
'User-Agent':userAgent
}
#adjust ac... |
__copyright__ = """ Copyright (c) 2021 HangYan. """
__license__ = 'MIT license'
__version__ = '1.0'
__author__ = 'topaz1668@gmail.com'
import os
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--push_list', dest='push_list', type=list, default=[])
args = parser.parse_args()
# ME... |
import requests
q = requests.get('https://www.thenationalnews.com/image/policy:1.906316:1567597962/sp05-Man-City-Trophy-Tour.jpg?f=16x9&w=940&$p$f$w=0ee2b1c')
print(q.content)
with open ('chelsea.jpeg','wb') as n:
n.write(q.content)
n.close() |
# 前缀和 + 维护最左最优边界
# 三次遍历做准备工作
class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
n = len(s)
preSum = [0] * (n+1)
for i in range(1, n+1):
preSum[i] = preSum[i-1] + (1 if s[i-1] == '*' else 0)
left, right = [0] * n, [0] * n
... |
# coding: utf-8
# In[1]:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import glob
import os
import numpy as np
import pandas as pd
import sys
import cv2
i... |
"""
Program: labelDemo.py
Page: 263
Author: Chris
Simple python GUI window illustrating the input and output fields
"""
from breezypythongui import EasyFrame
class TextFieldDemo(EasyFrame):
"""Converts an input string to uppercase and displays the result"""
def __init__(self):
"""Sets up the window and the label"... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
... |
# Generated by Django 2.2.1 on 2019-08-26 15:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('snippets', '0017_delete_... |
# RGB色彩空间 RGB三个颜色取值(0~255)可形成一个三维空间(立方体)
# color space(锥状空间)
# HSV(柱状空间 )360 180 180可以进行归一化等操作转化为HSV
import cv2 as cv
import numpy as np
def extract_object():
capture = cv.VideoCapture('D:/DOC/python Opencv learning/test.mp4')
while True:
ret, frame = capture.read() # ret是读取函数的返回值,若读到最后一帧读不出来... |
from flask import redirect, url_for, request, render_template, flash
from app import app
import sqlite3 as sql
@app.route('/')
@app.route('/index')
def index():
if request.args:
logged_in = request.args['logged_in']
user = request.args['user']
if logged_in:
r... |
n, x = map(int, input().split())
ice_cream = x
distress_child = 0
for _ in range(n):
sign, amount = input().split()
if sign == '+':
ice_cream += int(amount)
elif sign == '-' and ice_cream >= int(amount):
ice_cream -= int(amount)
elif sign == '-' and ice_cream<int(amount):
distr... |
# 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 2**1000?
# Comments Section:
# - Straigh forward algorithm
def problem16():
value = str(2**1000)
sum = 0
for i in value:
sum += int(i)
return sum
|
from faker import Faker
fake = Faker()
import csv, datetime, os
fake = Faker(['es_ES'])
total= 13
today = datetime.date.today()
output="database-"+ str(today) + ".csv"
data = []
count = 0
for _ in range(total):
count +=1
name = fake.name()
address = fake.address()
color = fake.color(... |
import json
def greet_user():
"""Great the user by name."""
username = get_username()
if username:
prompt = input("Are you " + username + " (y/n)? ")
if prompt == 'y':
print("Welcome back, " + username + "!")
elif prompt == 'n':
username = newuser()
... |
import os
import torch
import copy
from torch.utils.data import DataLoader
import utils.DataProcessing as DP
import utils.LSTMClassifier as LSTMC
import torch.optim as optim
import torch.nn as nn
from torch.autograd import Variable
use_plot = True # Give the tag that whether you want to save data an... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2019-01-13 13:52
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('course', '0018_widget'),
... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.engine.target import Field, Target
class PyenvInstallSentinelField(Field):
none_is_valid_value = True
alias = "_sentinel"
help = "<internal>"
default = False
... |
def adjust(coin, price):
q, r = divmod(price, coin)
return price if not r else (q + 1) * coin
|
import spacy
nlp = spacy.load('de')
doc = nlp(u'Ich bin ein Berliner.')
print(' '.join('{word}/{tag}'.format(word=t.orth_, tag=t.pos_) for t in doc))
|
'''
Base class for public-key encryption
Notes: This class implements an interface for a standard public-key encryption scheme.
A public key encryption consists of four algorithms: (paramgen, keygen, encrypt, decrypt).
'''
from charm.toolbox.schemebase import *
class PKEnc(SchemeBase):
def __init__(self):
... |
from django.contrib import admin
from blog.models import *
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
#fields = ('title','desc','content',)
list_display=('title','desc','click_count','user','category')
list_display_links=('title','desc',)
list_editable = ('click_count',)
... |
# -*- coding: utf-8 -*-
# @Time : 2019/12/10 16:54
# @Author : Jeff Wang
# @Email : jeffwang987@163.com OR wangxiaofeng2020@ia.ac.cn
# @Software: PyCharm
import numpy as np
import cv2
img = cv2.imread('./picture/beach.png')
"""0. 彩色图像处理基础
0. 功能:符合人眼视觉,简化目标物区分,根据颜色目标识别。
1. 领域:全彩色,伪彩色... |
import os, pickle
import numpy as np
import pandas as pd
from statsmodels.distributions import ECDF
import model_run
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.metrics as skm
from statsmodels.graphics.gofplots import qqplot
import argparse
parser = argparse.ArgumentPars... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
import platform
# for rendering graph on remote server.
# see: https://qiita.com/TomokIshii/items/3a26ee4453f535a69e9e
if platform.system() != "Darwin":
mpl.use('Agg')
import warnings
warnings.filterwarnings('ignore', category=FutureWarning,... |
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.db import models
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, **extra_fields):
"""
Create and save a user with the given email, usernam... |
import numpy as np
from ActivationFunctions import *
from LossFunctions import *
"""
Our Dense class creates the layer, taking as parameters the folowing:
- layerSize: the size of the actual layer
- activation: this specifies the activation function we'll use for this layer
- weightBounds: ... |
l=[]
n=int(input("enter no.of elements :"))
for i in range(n):
i=int(input("enter element :"))
l.append(i)
print(max(l))
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
import pygame
import OpenGL.GL as gl
import OpenGL.GLU as glu
import numpy as np
import itertools
import fractions
import copy
import numpy as np
#local imports
from common import SETTINGS, COLORS, VSYNC_PATCH_HEIGHT_DEFAULT, VSYNC_PATCH_WIDTH... |
# -*- coding:utf-8 -*-
from model.user import User
def load():
return User()
|
"""Treadmill commaand line helpers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Disable too many lines in module warning.
#
# pylint: disable=C0302
import codecs
import copy
import functools
import io
impor... |
from morphing_agents.mujoco.ant.designs import sample_uniformly
from morphing_agents.mujoco.ant.designs import DEFAULT_DESIGN
from morphing_agents.mujoco.ant.elements import LEG_UPPER_BOUND
from morphing_agents.mujoco.ant.elements import LEG_LOWER_BOUND
from morphing_agents.mujoco.ant.elements import LEG
from morphing_... |
#!/usr/bin/python
def get_data(filename):
f = open(filename, "r")
line = f.readline()
case_count = int(line)
case_list = []
for i in xrange(case_count):
button_list = []
line = f.readline()
pieces = line.split()
button_count = int(pieces.pop(0))
case_list.app... |
#!/usr/bin/python
import argparse
from glob import glob
import json
import os
from shutil import copyfile
def parse_args():
info = "Combines FASC files from PyRosetta job distributor and converts \
them into a more convenient csv table. Also extracts best decoys by a \
given criterion if desired."
pars... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import Iterable
from pants.backend.build_files.utils import _get_build_file_partitioner_rules
from pants.core.goals.fmt import FmtFilesRequest
from pants.core.util_rules.part... |
def move(srcStack, dstStack):
print('Before move:', srcStack, ',', dstStack)
top = srcStack.pop(0)
assert len(dstStack) == 0 or dstStack[0] > top
dstStack.insert(0, top)
print('After move:', srcStack, ',', dstStack)
def move_stack(stacks, size, src, dst, oth):
if size == 1:
m... |
import requests
import pandas as pd
import matplotlib.pyplot as plt
######################################################################################################
#Generic parameters for inrinio
api_key='xxxx---Use your own API Key----xxxx'
stock_quote='AAPL'
indicator='$indicator$'
hist_data_url=f'https://a... |
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from parseridge.parser.modules.attention.positional_encodings import PositionalEncoder
from parseridge.parser.modules.attention.self_attention_layer import SelfAttentionLayer
from parseridge.parser.modules.data_parallel impo... |
"""
Created by Alex Wang on 2018-03-13
图像复原美化:
inpaint水印去除
"""
import cv2
import numpy as np
def test_image_inpaint():
"""
cv2.inpaint(src, inpaintMask, inpaintRadius, flags[, dst]) → dst
Parameters:
* src – Input 8-bit 1-channel or 3-channel image.
* inpaintMask – Inpainting mask, 8-bit 1-channel ... |
#2-3 exercise
name = "Nell"
print("Dear " + name + ", matter compilers are dream makers and world killers.")
#2-4 exercise
character = " sir finkle mcGraw "
print(character.title())
newChar = character.title()
print("\t*" + newChar.rstrip() + "*")
print("\t\t*" + character.lstrip() + "*")
print("\t\t\t*" + newChar.str... |
#!/usr/bin/python
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
pVals = self.trValueArray(p)
qVals = self.trValueArray(q)
if pVals == [] and qVals == []:
return... |
from wtforms import TextAreaField, BooleanField, StringField, IntegerField, PasswordField, SubmitField, validators
from flask_wtf import FlaskForm
# NoneOf(values, message=None, values_formatter=None)
class AdminConfigForm(FlaskForm):
temp_chaudiere_failure = IntegerField(
'Temp Ch... |
#Program to find the electricity bill of a customer
units=int(input("Enter the units consumed in a month"))
if(units<=50):
amount=units*.50
elif(units<=150):
amount = 25 + ((units-50) * 0.75)
elif(units<=250):
amount = 100 + ((units-150) * 1.20)
else:
amount = 220 + ((units - 250) * 1.50)
sur_charge = a... |
"""winss services management.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import os
import six
from treadmill import fs
from .. import _service_base
from .. import _utils
class LongrunService... |
import tweepy
import datetime
consumer_key = 'placeholder_key_123'
consumer_secret = 'placeholder_secret_345'
access_token = 'placeholder_token_678'
access_token_secret = 'placeholder_token_secret_910'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
a... |
import sys
if len(sys.argv) == 1 or sys.argv[1] == '-v':
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
verbose = sys.argv[-1] == '-v'
print('What is the image pixel width?')
w = int(sys.stdin.readline())
print('What is the image pixel height?')
h = int(sys.stdin.readline())... |
import unittest
from entity.category import Category
from entity.product import Product
from entity.manufacturer import Manufacture
class CategoryTestCase(unittest.TestCase):
def setUp(self) -> None:
self.category = Category("Category 1")
self.manufacturer = Manufacture()
self.manufacture... |
from __future__ import division
from layer import *
from neuron import *
import math
import png
class DeepNeuralNetwork:
def __init__(self, NEURONS, TYPE = "mainNet"):
self.layers = []
self.bias = Neuron()
self.type = TYPE
self.layers.append(InputLayer(NEURONS[0]))
for i in range(1,len(NEURONS)):
self.la... |
__author__ = 'aoboturov'
from load_data import log, count_by_user_attribute
import pandas as pd
pd.set_option('display.width', 300)
pd.set_option('display.max_colwidth', 200)
print(log.ua.unique())
print(count_by_user_attribute(log, ['ua']))
print(count_by_user_attribute(log, ['sex']))
"""
sex
female 58376
ma... |
from django.db import models
class Cart(models.Model):
session = models.CharField(max_length=100, db_index=True, unique=True)
created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
updated = models.DateTimeField(auto_now=True, verbose_name='Дата изменения')
def get_total(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.