text stringlengths 38 1.54M |
|---|
import datetime
import sys
import numpy as np
import pandas as pd
from WindPy import w
MIN_RETURN = 5
MIN_YEARS = 5
REPORT_DATE = '20191231'
REPORT_DATE_PRE = '20190930'
if __name__ == '__main__':
fund_list = []
fund_list_all = []
try:
file_object = open('./funds.txt', mode='r', encoding='UTF-8')... |
# -*- coding: utf-8 -*-
"""
Zoidberg could be use in two different ways:
a) CL:
python zoidberg args
b) python module:
from zoidbderg import Zoidberg
"""
import os
import sys
HERE = os.path.abspath(os.path.dirname(__file__))
sys.path.append('..')
sys.path.append(HERE)
from twisted.internet... |
#!/usr/bin/env python
'''Module that defines a parser class for block-structured data, as well as
auxilary classes for exceptions. Can be called directly to perform
unit tests'''
import io
import re
import sys
import unittest
import parser_errors as err
import block
class BlockParser:
'''Parser class to p... |
# # Twitter API
# pip install tweepy
import tweepy
import pandas as pd
import time
#use own credentials from twitter developer account
consumer_key = "cyURof8onxNo63Tdbc8d3mB4T"
consumer_secret = "JnKzJsPuLxi0Fa7BB26l7XTpwOYnoXD37Rqio0SpWsLi7QPN1n"
access_token = "1220785803078643713-9tG4OWTEa3ykTPm26l59u... |
# Generated by Django 2.0.8 on 2018-12-13 04:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('readersclub', '0004_auto_20181213_0116'),
]
operations = [
migrations.AlterModelOptions(
name='review',
options={'ordering':... |
from django.db import models
class Location(models.Model):
name = models.CharField(
max_length=255,
verbose_name="Name",
blank=True
)
description = models.TextField(
max_length=None,
verbose_name="Description",
blank=True
)
address1 = models.CharFiel... |
# -*- coding: utf-8 -*-
import re
import HTMLParser #转换网页代码
import datetime#简单处理时间
class Parse(object):
def __init__(self, content):
self.content = content.replace('\r', '').replace('\n', '')
self.initRegex()
self.addRegex()
def initRegex(self):
self.regDict = {}
self.re... |
valor_float = float(input("Digite o valor que você quer sacar, se necessário digite quantos cents: "))
valor_int = int(valor_float)
print(valor_int)
# Parte cédula
valor_dinheiro = valor_int
total = valor_dinheiro
céd = 100
totcéd = 0
while True:
if total >= céd:
total -= céd
totcéd += 1
else:... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
CONFIGURABLE_OPTIONS = ['--db', '--cms-version', '--django-version', '--i18n',
'--reversion', '--languages', '--timezone', '--use-tz',
'--permissions', '--bootstrap', '--templates',
... |
import sys
import os
import numpy as np
import random
from makedata import Dataset_WPDP,addBug
from functions.metrics import accuracy, precision, recall, f_measure, auc
import config
from datasetConfig import dsconf
from makeCPDPohv import CPDPdict
from util.alarm import Sound
from DNN.NeuralNetwork import NeuralNetw... |
import pandas
import numpy
from sklearn.metrics import confusion_matrix
from scipy.stats import mode
import scipy.io
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sn
from xgboost import XGBClassifier
import pickle
import joblib
X = joblib.load('C:/Users/russo/OneDrive/Documents/GitHub/Intelligent... |
# Ao testar sua solução, não se limite ao caso de exemplo.
x = float(input('Digite um numero para x: '))
y = float(input('digite um numero para y: '))
if (x>0 and y>0):
print('Q1')
elif (x<0 and y<0):
print('Q3')
elif (x>0 and y<0):
print('Q4')
elif (x<0 and y>0):
print('Q2')
elif ((x==0) and (y>0) or(x==0) and (y... |
import sys
import lcddriver
display = lcddriver.lcd()
display.lcd_display_string(" ", 1)
s1="received:"+sys.argv[1]
display.lcd_display_string(s1, 1) |
import importlib.resources
import jinja2
_templates = {
name[: name.rfind(".")]: jinja2.Template(
importlib.resources.read_text("structy_generator.templates", name),
lstrip_blocks=True,
keep_trailing_newline=True,
)
for name in importlib.resources.contents("structy_generator.templa... |
from usecases.login import LoginDependencies, LoginTokens, login
from usecases.signup import SignupDependencies, signup
from db.sqlite import SQLiteDB
from security.bcrypt_hasher import BCryptHasher
from security.pyjwt_generator import PyJWTGenerator
db = SQLiteDB('flask.db')
hasher = BCryptHasher()
jwtGenerator = Py... |
# Generated by Django 3.1.6 on 2021-02-18 12:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Money_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... |
import binascii
import json
def main():
TestJSON()
def TestJSON():
return
if __name__ == "__main__":
main()
|
import allure
from ui_tests.data import BASE_TIMEOUT
from ui_tests.ui.locators.pages_locators import MainPageLocators
from ui_tests.ui.pages.base_page import BasePage
class MainPage(BasePage):
locators = MainPageLocators()
@allure.step('Open redirect page')
def open_redirect_page(self, locators, expect... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 技术支持:dwz.cn/qkEfX1u0 项目实战讨论QQ群6089740 144081101
# CreateDate: 2019-12-29
def gcd(q,p):
# 求最大公约数
while q != 0:
p, q = q, p%q
return p
def is_coprime(x, y):
result = gcd(x, y)
return gcd(x, y) == 1
if __name__ == '__main__':
print(gcd(1... |
import datetime as dt
class Timer:
def __init__(self):
self.start_time = None
def start(self):
self.start_time = dt.datetime.now()
def stop(self):
end_time = dt.datetime.now()
print('duration : %s' % (end_time - self.start_time))
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/4/17 23:16'
import requests
"""
Python快速获取图片文件大小
https://www.v2ex.com/t/67865
https://blog.csdn.net/pud_zha/article/details/8809878
HTTP之Content-Length
"""
# url = 'https://pic.huodongjia.com/event/2017-12-20/1513755021.78.jpg'
# url = '... |
import json
import re
jsn_dict = {}
with open("jawiki-country.json") as fp:
for jsn_fp in fp:
jsn = json.loads(jsn_fp)
jsn_dict[jsn["title"]] = jsn["text"]
pattern = re.compile(r"^.*\[\[File:(.*?)\|.*\|.*\]\].*$",re.MULTILINE)
matches = pattern.findall(jsn_dict["イギリス"])
for match in matches:
pr... |
# %load q03_logistic_regression/build.py
# Default Imports
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from greyatomlib.logistic_regression_project.q01_outlier_removal.build import outlier_removal
f... |
from numpy import *
from matplotlib.pyplot import *
def a(t):
return 1.0
def b(t, c, u0):
return c + a(t)*(c*t+u0)
def f_linear(un, tn, u0, c=1.23):
return -a(tn)*un + b(tn, c, u0)
def f_exp(un, tn, u0):
return -un + 1
def analytical_exp(t):
return 1-exp(-t)
def forwardEuler(f,tn,un, dt):
return un + dt*f(un,... |
"""Forms of the ``django_libs`` app."""
from django import forms
class PlaceholderForm(forms.Form):
"""Form to add the field's label as a placeholder attribute."""
def __init__(self, *args, **kwargs):
super(PlaceholderForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
... |
import json
import aiohttp
from urllib.parse import urljoin
from aiologger import Logger
logger = Logger.with_default_handlers()
class DPCheck:
def __init__(self, server_url, token, unti_id, dp_competence_uuid, lrs_culture_value) -> None:
super().__init__()
self.server_url = server_url
s... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = 'Diego Linayo'
import os
def arbol(path , nivel= 0 ):
try:
# Los archivos ordenados alfabeticamente
files = sorted(
(os.path.join(path, filename) for filename in os.listdir(path)),
key=lambda s: s.lower()
)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0004_auto_20160429_1250'),
]
operations = [
migrations.AlterModelOptions(
name='article',
... |
from django.contrib import admin
from .models import Product, ProductImage
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImageAdmin]
class Meta:
model = Product
|
# Copyright 2022 The TensorFlow 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 applica... |
# @Author: Bartosz Nowakowski
# @Github: https://github.com/rolzwy7
#
# Copyright (c) 2018 Bartosz Nowakowski
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including ... |
# Generated by Django 3.1.7 on 2021-04-10 05:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_post_image'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
field... |
# coding=utf-8
from __future__ import absolute_import, division, print_function
import logging
import argparse
import os
import random
import numpy as np
import time
from datetime import timedelta
from PIL import Image
from torchvision import transforms
import torch
import torch.distributed as dist
... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.Homepage, name='Homepage'),
path('login',views.Login, name='Login'),
path('index',views.Index, name='Index'),
path('view_profile',views.View_Profile, name='View_Profile'),
# path('test',views.index, name='base'),
# ... |
# SPDX-FileCopyrightText: 2020 - Sebastian Ritter <bastie@users.noreply.github.com>
# SPDX-License-Identifier: Apache-2.0
'''
Created on 05.10.2020
@author: Sͬeͥbͭaͭsͤtͬian
'''
from java.lang.Object import Object
class Properties(Object):
'''
classdocs
'''
properties = {}
def __init__(self):
... |
#!/usr/bin/python3
import sys
import json
import datetime
target = sys.argv[1] # target -> word (airplane)
# Initialization
print ('%s\t%s' % (target, "0"))
print ('%s\t%s' % ("Weekend", "0"))
for item in sys.stdin:
row = json.loads(item)
if (
row["word"] == target and # word
all(x.isalpha() or x.isspace... |
#! /usr/bin/env python
#
#This file is used to get the flow and system parameters for the simulation.
import tkMessageBox as tkmb
from Tkinter import Frame, Label, Entry, OptionMenu, Button, Text, \
DoubleVar, StringVar, IntVar
from capsim_object_types import CapSim... |
#Context Manager - Criando e usando gerenciadores de contexto.
arq = 'D:\\GitHub\\Curso_Python\\Udemy\\Secao4\\aula110\\abc.txt'
# A forma mais comum de abrir e fechar aquivos texto
'''file = open(arq, 'w')
file.write('Alguma coisa')
file.close()'''
# Outra forma de manipular arquivos
"""
with open(arq, 'w') as fil... |
from graphviz import Digraph
import tree
def create_graph(root, graph_name, show_prob=False, format='svg', view=True):
if type(root) != type(tree.Node('', [])):
print("Error: root argument {} is not of type tree.Node!")
else:
filename = "{}.{}".format(graph_name, format)
graph = Digraph... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import os
import time
import os.path
import hashlib
import xmltodict
from odictliteral import odict
from remove_hairs import remove_hairs
from marcxml_par... |
import json
import re
from copy import copy
from logging import Formatter, LogRecord
class PlainFormatter(Formatter):
"""Remove all control chars from the log and format it as plain text, also restrict the max-length of msg to 512."""
def format(self, record):
"""
Format the LogRecord by remo... |
#! /usr/bin/env python
import sys
import os
lastkey = None
curkey = None
sumvalue = 0
for line in sys.stdin:
items = line.strip().split('\t', 1)
if items[0] == curkey:
sumvalue += int(items[1])
else:
if curkey != None:
print curkey + "\t%d" % sumvalue
curkey = items[0]
... |
#!/usr/bin/env python3
import itertools
import pyttsx3
import random
import sys
import time
# [ [i.languages, i.id] for i in n.voice.getProperty("voices") ] - retrieves languages
CURRENT_LANGUAGE_CODES = {
"it_IT": "com.apple.speech.synthesis.voice.luca", # Modern Standard Italian
"el_GR": "com.apple.speech.... |
from day_13 import get_data_from_input, time_til_next_departure
def find_timestamp_with_desired_offset(current_timestamp, bus_id, current_offset, desired_offset, increment):
"""Advance by increment until current offset --> desired offset for bus ID"""
timestamp = current_timestamp
while current_offset != ... |
# Thomas Horak (thorames)
# classifier.py
import re
import sys
import csv
import json
# import operator
import spacy
import math
import random
# import numpy as np
import sklearn.ensemble
import sklearn.metrics
from sklearn import svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from nlt... |
class_dict = {
"0":{
"label_id":"n01440764",
"cn_main_class":"鱼",
"cn_class_name":"丁鲷",
"en_class_name":"tench, Tinca tinca"
},
"1":{
"label_id":"n01443537",
"cn_main_class":"鱼",
"cn_class_name":"金鱼",
"en_class_name":"goldfish, Carassius auratu... |
#!/usr/bin/python
#imports
import argparse, re, os
#declare args
parser=argparse.ArgumentParser(description=(
'A limited c preprocessor designed to work with fake_libc_include. '+
'#include, #ifdef, #ifndef, #else, and #endif are supported. '+
'#if and #elif will always evaluate as false. '+
'#define must be of t... |
# -*- coding: utf-8 -*-
import enum
import math
import sqlalchemy
from flask_admin.babel import gettext
from flask_babelex import lazy_gettext
from portal.cache import cache
from portal.models import db
from portal.permission.models import Permission
from portal.user import RolesEnum
from portal.utils import ranges
f... |
import csv
import numpy as np
import numpy
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from... |
import pandas as pd
import lib.dataparse
import sys
from itertools import groupby
def triangle_infidelity_1():
df2 = pd.read_excel("triangle-infidelity.xls")
df = lib.dataparse.dataframe().reset_index()
dfp = df[df["theme"] == u"extramarital affair"]
df2.set_index("sid", inplace=True)
dfp.set_inde... |
#!/usr/bin/python3.6
""" For every image from the test set, searches for the top-20 closest images from the train set. """
import os
import sys
from glob import glob
from typing import Iterator, Iterable, List, Optional, Tuple
import numpy as np
import pandas as pd
import faiss
from sklearn.model_selection import t... |
from setuptools import setup
setup(
name='nengo_learn_assoc_mem',
packages=['nengo_learn_assoc_mem'],
version='0.0.1',
author='Terry Stewart',
description='Nengo model of learning an associative memory',
author_email='terry.stewart@gmail.com',
url='https://github.com/tcstewar/nengo_learn_as... |
import simpy
class SimpleFlash(object):
def __init__(self, recorder, confobj = None):
self.recorder = recorder
self.conf = confobj
self.data = {} # ppn -> contents stored in a flash page
def page_read(self, pagenum, cat):
self.recorder.put('physical_read', pagenum, cat)
... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from workstation.config import WorkstationConfig as config
from utils import logger, BaseCommand
from workstation.decorators import try_except
class CreateUserCommand(BaseCommand):
@try_except
def do_create_user(self, input_string):
self.setu... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import logging
import smtplib
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.header import Header
import json
def _get_mail_content(warnings):
content = ''
for r... |
"""
Nada para ver aqui. Siga em frente...
"""
import unittest
def generic_assignment_tester(id_tarefa):
import os
import subprocess
read_path = 'src'
some_file = 'tarefa_%d.c' % id_tarefa
ext = '.exe' if os.name == 'nt' else ''
output_file = os.path.join(read_path, some_fil... |
import tkinter as tk
from tkinter import PhotoImage, filedialog
from tkinter.constants import BOTH, BOTTOM, LEFT, RIGHT, YES
from PIL import ImageTk, Image
class App(tk.Tk):
def __init__(self):
super().__init__()
#memory variable
self.title('image loader')
self.fileName = str
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 16:41:15 2018
@author: changguozhen
"""
# ## 3.6 pandas读写结构化数据
# 模块是可以实现一项或多项功能的程序块,Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用
# In[ ]:
# 可以通过安装第三方包来增加系统功能,也可以自己编写模块。引入模块有多种方式
# In[ ]:
import pandas as pd
df = pd.DataFrame({'key': ['b', 'b', 'a', ... |
from Altas_Equipos_Y_Componentes.models import DiscoDuro, EquipoYArticulos, MemoriaRam
from django.forms import ModelForm
class CreationForm(ModelForm):
class Meta:
model = EquipoYArticulos
fields = "__all__"
def __init__(self, *args, **kwargs):
super(CreationForm, self).__init__(*a... |
# from pymongo import MongoClient
# import os
# account = os.environ["MONGO_ROLE_ACCOUNT"]
# password = os.environ["MONGO_ROLE_PASSWORD"]
# client = MongoClient('mongodb+srv://' + account + ':' + password +
# '@cluster0-hptar.gcp.mongodb.net/test?retryWrites=true')
# db = client['nthuCourse_databa... |
from setuptools import setup
setup(
name="",
package_data={("sphinx_argon"): [
"theme.conf",
"*.html",
"static/css/*.css"
]},
include_package_data=True,
entry_points={
"sphinx.html_themes": [
"sphinx_argon = sphinx_argon"
]
}
)
|
# -*- coding: utf-8
from django.apps import AppConfig
class GroupsCacheConfig(AppConfig):
name = 'groups_cache'
verbose_name = 'Groups Cache'
verbose_name_plural = 'Groups Cache'
def ready(self):
from . import signals
|
'''
Created on 18/11/2011
@author: dev
'''
import random
from TetrisPlayer import TetrisPlayer
class FilePlayer(TetrisPlayer):
def __init__(self, fileName):
self.fileName = fileName
self.__hfile = NotImplemented
self.__opened = False
self.__oldGameDice = NotImplemented
... |
"""
This is the meme generator module. This module includes a class ImageCaptioner
that generates memes wit the image,body and author provided.
"""
from QuoteEngine.QuoteModel import QuoteModel
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import random
import os
class ImageCaptioner(obj... |
from flask import Blueprint, render_template
blueprint_query_builder = Blueprint("blueprint_query_builder", __name__)
@blueprint_query_builder.route("/query_builder")
def query_builder():
"""A function which handles requests of the '.query_builder'-
route for the webapp.
:return Rendered template of ... |
# -*- encoding:utf-8 -*-
# Copyright © 2015-2016, THOORENS Bruno - http://bruno.thoorens.free.fr/licences/tyf.html
from . import reduce
import math, fractions, datetime
###############
# type encoders
cast = lambda value, mini, maxi: int(max(min(value, maxi), mini))
_m_short = 0
_M_short = 2**8
def _1(value):
if isi... |
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
from .pins import (
Pin,
)
from .pins.data import (
PiBoardInfo,
PinInfo,
pi_info,
)
from .exc import (
GPIOZeroError,
DeviceClosed,
BadEventHandler,
BadWaitTime,
BadQueueLen,
... |
"""
Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, m... |
from osbot_jupyter.api.CodeBuild_Jupyter_Helper import CodeBuild_Jupyter_Helper
from osbot_jupyter.api.Docker_Jupyter import Docker_Jupyter
from osbot_jupyter.api.Jupyter_API import Jupyter_API
from osbot_jupyter.api.Jupyter_Kernel import Jupyter_Kernel
from osbot_jupyter.api.Jupyter_Session import Jupyter_Se... |
import gpt_2_simple as gpt2
import os
import requests
import tensorflow as tf
import pickle
import pandas as pd
import time
# Choose GPU
os.environ['CUDA_VISIBLE_DEVICES']='0'
# Limit memory usage
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
def load_pickle(f... |
# First python
print('hello,world')
print("Enter name:")
name = input()
print('nice to meet you ' + name)
print("the lenth of you name is: ")
print(len(name))
print('enter age:')
age = input()
print('you will be ' + str(int(age) + 1) + ' in a year')
print('Enter age:')
age = input()
if int(age) ==35 :
print('right... |
# SLAMAgents.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.eecs.... |
import numpy as np
import pdb
from scipy import sparse
from scipy.optimize import fmin_ncg
import pdb
import time
# for hinge loss SVM
def hessian_vector_product_hinge(label, ypred, x, v, scale_factor=1.0):
mask = np.ones_like(label)
mask[ypred * label >= 1] = 0
mask[ypred * label <= 0] = 0
t = label ... |
import unittest
from math import comb
from swiss import Logic
from datetime import datetime
from pathlib import Path
import random
import logging
import os
logging.basicConfig(filename='test.log', filemode='w', level=logging.INFO)
logger = logging.getLogger(__name__)
class TestBasicSwiss(unittest.TestCase):
def... |
# Generated by Django 3.0.8 on 2020-10-29 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='brand',
fields=[
... |
num = input()
result = 0
for i in range(4):
a = int(num[i])
result = result + a
print(result) |
import logging
logger = logging.getLogger(__name__)
from .cRIOExceptions import cRIOURLError, cRIOBadRequest, cRIOWebServiceInactive
def r200(response):
logger.debug(f"Status code: {response.status_code} - Succes.")
return response
def r400(response):
logger.critical(f"Status code: {response.status_code}... |
# first of all import the socket library
import socket
import random
import sys
# next create a socket object
s = socket.socket()
print("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345 + random.randint(1,100) #genera... |
from Crypto.Random import random
import challenge39
import challenge43
# Doesn't check for 0 values for r and s.
def relaxedSign(message, pub, priv):
H = challenge43.hash(message)
(p, q, g, y) = pub
k = random.randint(1, q-1)
x = priv
r = pow(g, k, p) % q
kInv = challenge39.invmod(k, q)
s =... |
"""
Copyright (c) 2017-2019 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 applicable law or agreed to i... |
import tensorflow as tf
from tensorflow.keras.layers import Reshape, Input, Conv1D, Add, Activation
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import *
def shape_list(x):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.... |
# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/vuplusvideoreset/__init__.py
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_LANGUAGE
import os, gettext
PluginLanguageDomain = 'vuplusvideoreset'
PluginLanguagePath = 'Extensions/vuplusvideores... |
from protocolbuffers import Dialog_pb2
from distributor.shared_messages import create_icon_info_msg, IconInfoData
from interactions.utils.tunable_icon import TunableIcon
from sims4.localization import TunableLocalizedStringFactory
from sims4.tuning.tunable import TunableList
from ui.ui_dialog import UiDialogOk
import s... |
# -*- coding: utf-8 -*-
from odoo import fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
iface_order_merge = fields.Boolean(
string="Order Merge",
help="Enables Order Merging in the Point of Sale",
default=True,
)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2022 shmilee
import os
import unittest
import tempfile
import numpy as np
from matplotlib.gridspec import GridSpec
fielddata = np.array([[np.sin(m / 20) * np.cos(n / 20) for m in range(100)]
for n in range(66)])
fieldx, fieldy = np.meshgrid(*[np.aran... |
# Generated by Django 3.0.6 on 2020-09-16 22:33
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('base', '0012_auto_20200916_1611'),
]
operations = [
migrations.DeleteModel(
name='Criptocurren... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apicultur.service import Service
class TransitiveVerb(Service):
# # http://apicultur.io/apis/info?name=VerbTransitive_Onoma_es&version=1.0.0&provider=molinodeideas
version = '1.0.0'
endpoint = 'onoma/conjugator/es/transitiveverb'
method = 'GET'
ar... |
import numpy as np
from mpi4py import MPI
import csv
import sys
import os
def matrix_multiply(A,B,rank,i):
n = int(sys.argv[1])
dimension = int(sys.argv[2])
rows = int(dimension/n)
columns = int(dimension/n)
C =np.zeros((dimension,dimension))
wt1 = MPI.Wtime()
for... |
"""
day: 2020-08-13
url: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnwzei/
题目名: 环形链表
题目描述: 判断链表中是否有环,使用整数pos来表示链尾连接到链表中的位置,如果pos是-1,则在链表中
没有环
思路:
1. 快慢指针:
一个快指针一个慢指针,如果是闭环必然会有一次循环会遇到,否则就结束
2. 集合:
判断节点是否在一个集合中,在则说明重复访问了同一个节点,否则将节点添加到集合中
"""
class ListNode:
def __init__(self, x):
... |
from threading import Thread
import grpc
import sys
sys.path.append('./grpc_out')
import currency_tracker_pb2
import currency_tracker_pb2_grpc as pb2_grpc
HOST = '127.0.0.1'
PORT = '50051'
class CurrencyTracker():
def __init__(self, name, currencies):
self.channel = grpc.insecure_channel(HOST + ':' + PORT)
... |
# Palabras Reservadas
# No se pueden utilizar como identificadores de variables, funciones o clases.
and, from, try
exec, print, elif
not, continue, in
assert, global, while
finally, raise, else
or, def, is, break
if, with, for, return
except, pass, del, lambda
class, import, yield |
def staircase(n):
for i in range(1, n + 1):
print(f'%{n - i}s' % '', end='')
for j in range(1, i + 1):
print('#', end='')
print()
staircase(6)
|
class WrongDirectionError(Exception):
"something tries to act on a wrong direction"
class ExhaustedError(Exception):
"An Anima cannot move towhere it wants"
|
import tensorflow as tf
import os, time, glob, sys
import random, ntpath
from importlib import import_module
import ops
tfe = tf.contrib.eager
def create_test_dataset(filenames):
dataset = tf.data.Dataset.from_tensor_slices((filenames))
dataset = dataset.map(ops.load_image, num_parallel_calls=4)
dataset ... |
# To write/use the array data structure we use the array module
# from array import *
# arrayName = array(typecode, [Initializers])
from array import *
array1 = array('i',[10,20,30,40,50,60]) # Here 'i' stands for Signed integer of size 2 bytes
for x in array1:
print(x)
|
class Dog:
isMamma = True
def __init__(self, name = "No Name", age = -1):
self.name = name
self.age = age
def bark(self):
print("whoof! whoof! whoof! whoof!" + self.name)
Lassie = Dog("Lassie", 12)
Lassie.bark()
# Dog Snoopy = Dog("Snoopy", 15)
print("--------------------------... |
from django.urls import path
from .views import *
from django.conf.urls.static import static
from django.conf import settings
urlpatterns=[
path("",store,name="store"),
path("cart/",cart,name="cart"),
path("checkout/",checkout,name="checkout"),
path("update_item/",update_item,name="update_item"),
]
ur... |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.testing.unit_test import unit_test
from bes.version.version_info import version_info
class test_version_info(unit_test):
def test_read_string(self):
text = '''\
BES_VERSION = u'1.0.0'
BES_A... |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
# This application object is used by the development server
# as well as any WSGI server configured to use this file.
# Cling for static files in production, as per
# https://devcenter.heroku.com/articles/django-assets
from django.core.wsgi import ... |
import scrapy
import re
from tpdb.BaseSceneScraper import BaseSceneScraper
class siteLoadMyMouthSpider(BaseSceneScraper):
name = 'LoadMyMouth'
network = 'Load My Mouth'
start_urls = [
'http://www.loadmymouth.com',
]
selector_map = {
'title': '//div[@class="title"]/text()',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.