content stringlengths 5 1.05M |
|---|
'''
Created on september 28, 2017
a rule-based business dialog simulator
user:query bot:current bot:accumulate bot:response
ask[category] | slot:[category] | slot:[category] | api_call request property1
... |
# -*- coding: utf-8 -*-
from odoo import fields, models, api, _
import logging
import rpc_functions as rpc
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
class DataUploading(models.TransientModel):
_name = 'rpc.data.uploading'
_description = u"数据上传-上传"
REPEATTYPE = [
... |
from help import Help
from music import Music
import os
import discord
from discord.ext import commands
import json
from dotenv import load_dotenv
load_dotenv()
with open("config.json", "r") as config_file:
config = json.load(config_file)
prefix = config["PREFIX"]
intents = discord.Intents.default()
intents... |
# -*- coding: utf-8 -*-
"""
Basic Unittests
#####################
"""
from __future__ import absolute_import
import os
import unittest
import tempfile
from datetime import datetime
from collections import deque
from main import Task, App
class TestTask(unittest.TestCase):
"""Test unit operations of the Task class... |
#!/usr/bin/env python
"""
cubic spline planner
Author: Atsushi Sakai
"""
import math
import numpy as np
import bisect
from scipy.spatial import distance
class Spline:
"""
Cubic Spline class
"""
def __init__(self, x, y):
self.b, self.c, self.d, self.w = [], [], [], []
self.x = x
... |
"""
The "lf"-record
===============
Offset Size Contents
0x0000 Word ID: ASCII-"lf" = 0x666C
0x0002 Word number of keys
0x0004 ???? Hash-Records
"""
import io
from aiowinreg.filestruct.hashrecord import NTRegistryHR
class NTRegistryRI:
def __init__(self):
self.magic = b'ri'
self.keys_cnt = None
self.hash_re... |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com>
# All Rights Reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Fo... |
"""
Utility files for configs
1. Take the diff between two configs.
"""
import os
import pickle
import ml_collections
def load_config(config_fpath):
if os.path.isdir(config_fpath):
config_fpath = os.path.join(config_fpath, 'config.pkl')
else:
assert config_fpath[-4:] == '.pkl', f'{config_fpa... |
from setuptools import setup, find_packages
setup(
name="minesweeper",
version="0.1.0",
description="Inefficient Minesweeper Solver",
long_description="A very inefficient minesweeper solver.",
author="rhdzmota",
packages=find_packages(where="src"),
package_dir={
"": "src"
},
... |
#############################################################
#
# Multi-Dimensional Robust Synthetic Control Tests
# (based on SVD)
#
# Generates two metrics and compared the RMSE for forecasts
# for each metric using RSC against mRSC.
#
# Test are based on random data so it is advised to run
# several times.... |
#!/usr/bin/env python3
# The infinite monkey theorem : The theorem states that a monkey hitting keys at random on a
# typewriter keyboard for an infinite amount of time will almost surely type a given text,
# such as the complete works of William Shakespeare. Well, suppose we replace a monkey with
# a Python function.... |
from .settings import *
REMOTE_TEST_RESET_URL = '/_new_test'
MIDDLEWARE_CLASSES = (
'api_test.middleware.api_test.ApiTestMiddleware', # must be first
) + MIDDLEWARE_CLASSES
INSTALLED_APPS += (
'api_test',
) |
#! /usr/bin/env python
import glob
import os
from optparse import OptionParser
import pprint
import re
import sys
f_trial_re = re.compile(r"parallel trial.* \((\d+)\) failed")
s_trial_re = re.compile(r"parallel trial.* \((\d+)\) solved")
ttime_re = re.compile(r"Total time = ([+|-]?(0|[1-9]\d*)(\.\d*)?([eE][+|-]?\d+)?... |
#!/usr/bin/env python
from __future__ import print_function
from builtins import *
from past.utils import old_div
import cli
import re
import argparse
from csr_aws_guestshell import cag
csr = cag()
def print_cmd_output(command, output, print_output):
if print_output:
col_space = old_div((80 - (len(comman... |
# link: https://leetcode.com/problems/partition-equal-subset-sum/
# solution explanation: https://leetcode.com/problems/partition-equal-subset-sum/discuss/462699/Whiteboard-Editorial.-All-Approaches-explained.
class Solution(object):
def __init__(self):
self.st = {}
def canPartition(self, nums):
... |
# coding: utf-8
# Copyright (C) zhongjie luo <l.zhjie@qq.com>
import pandas as pd
import numpy as np
import os
import json
def check_duplicate(df, col_name):
temp = df.reset_index()
result = temp.duplicated(subset=col_name, keep=False)
index = np.argwhere(result).reshape(-1)
return df.iloc... |
from common.checks import APTPackageChecksBase
from common.plugins.storage import (
CephChecksBase,
CEPH_PKGS_CORE,
CEPH_SERVICES_EXPRS,
StorageChecksBase,
)
YAML_PRIORITY = 0
class CephPackageChecks(StorageChecksBase, APTPackageChecksBase):
@property
def output(self):
if self._outpu... |
def main() -> None:
N = int(input())
points = [tuple(map(int, input().split())) for _ in range(N)]
assert 4 <= N <= 100
assert all(len(point) == 2 for point in points)
assert all(points[i] != points[j] for i in range(N) for j in range(i + 1, N))
assert all(0 <= point[0] <= 10**9 and 0 <= point[... |
import easygui
easygui.msgbox('Selecione o arquivo de origem', 'Origem')
origfile = easygui.fileopenbox()
arq = open(origfile, 'r')
arqdest = open(origfile + '.changed', 'w')
substituiparam = 0
achouparam = 0
log = 1 # 1=on 0=off
def findparam(x):
global achouparam
global substituiparam
if (x.find("... |
f1 = 'general'
f2 = 'perfectionism_certainty'
f3 = 'responsibility_and_threat_estimation'
f4 = 'importance_and_control_of_thought'
f5 = 'complete_performance'
option_numbers = 7
factors_names = ('raw',f1,f2,f3,f4,f5)
factors = {
1 :(f1,)
, 2 :(f1,)
, 3 :(f2,)
, 4 :(f2,)
, 5 :(f3,)
, 6 :(f3,)... |
from flask import Blueprint, Response, request
import logging
import jinja2
import jinja2.utils
from mr_provisioner.models import Machine, MachineEvent
from mr_provisioner import db
from sqlalchemy.exc import DatabaseError
from collections import namedtuple
mod = Blueprint('preseed', __name__, template_folder='templ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import sys
from _pydevd_bundle import pydevd_comm
from ptvsd.socket import Address
from ptvsd.daemon import Daemon, DaemonStoppedError, DaemonClosedError
from ptvsd... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Определим универсальное множество
word = input("Введите слово: ")
vowels = set("a,e,i,o,u,y")
word_set = set(word.lower())
print('Гласных {} '.format(len(word_set.intersection(vowels))))
|
# Copyright 2013-2021 The Meson development team
# 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 agree... |
# Generated by Django 3.2.7 on 2021-10-27 18:37
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
('tracks', '0006_auto_20211025_1631'),
]
operations = [
migrations.C... |
#!/usr/bin/python
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_addr = ('',8080)
sock.bind(server_addr)
while 1:
data, addr = sock.recvfrom(4096)
print >> sys.stderr, data
|
from django.shortcuts import render, get_object_or_404
from db.models import Category, Post
from .forms import ContactForm
from django.core.mail import send_mail
# from django.http import HttpResponse
# from django.template.loader import get_template
# from django.core.mail import EmailMessage
# from django.template i... |
#Django 生成器
import os
def info(project_name, mysite_name, app_name, db):
# project_name = str(input('請輸入專案名稱:'))
# mysite_name = str(input('請輸入Mysite名稱:'))
# app_name = str(input('請輸入App名稱:'))
# db = str(input('資料庫 / 預設:1 Mysql:2 :'))
project_path = '/Users/weichenho/Desktop' ... |
# -*- coding: utf-8 -*-
__author__ = "Mark McClain"
__copyright__ = "Mark McClain"
__license__ = "mit"
from unittest import TestCase
from awslambda import LambdaBaseSsm
from unittest.mock import patch
import boto3
from moto import mock_ssm
class LambdaBaseSsmImpl(LambdaBaseSsm):
def handle(self, event, context... |
response.view = 'generic.html' # use a generic view
tables_list = UL([LI(A(table,_href=URL("app","grid",args=table))) for table in db.tables if not table.startswith("auth_")])
pages_dict = {
"myInventoryItems":URL("app","grid",args=["inventoryItem","inventoryItem"],vars={"keywords": 'inventoryItem.idSeller = "%s"... |
# Copyright (c) 2021 Koichi Sakata
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pylib-sakata",
version="0.1.2",
author="Koichi Sakata",
author_email="",
description="Control system design and analysis package",
long_description=... |
"""
Integration tests for the :func:`esmvalcore.preprocessor.regrid.regrid`
function.
"""
import unittest
import iris
import numpy as np
import tests
from esmvalcore.preprocessor import extract_point
from tests.unit.preprocessor._regrid import _make_cube
class Test(tests.Test):
def setUp(self):
"""Pre... |
def superTuple(name, attributes):
"""Creates a Super Tuple class."""
dct = {}
#Create __new__.
nargs = len(attributes)
def _new_(cls, *args):
if len(args) != nargs:
raise TypeError("%s takes %d arguments (%d given)." % (cls.__name__,
... |
import sandstone.models.mlp
import sandstone.models.linear
import sandstone.models.rnn
|
from time import sleep
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import sentiwordnet as swn, stopwords, wordnet
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk
import pandas as pd
import re
from datetime import datetime
nltk.downlo... |
import unittest
from huobi.impl.utils import *
from huobi.model.constant import *
from huobi.impl.restapirequestimpl import RestApiRequestImpl
from huobi.impl.utils.timeservice import convert_cst_in_millisecond_to_utc
data = '''
{
"code": 200,
"success": "True",
"data": [
{
"id": 1499184000,
"amount": 1... |
"""SniTun reference implementation."""
import asyncio
from contextlib import suppress
from itertools import cycle
import logging
from multiprocessing import cpu_count
import select
import socket
from typing import Awaitable, Iterable, List, Optional, Dict
from threading import Thread
import async_timeout
from .listen... |
import torch
import torch.nn as nn
from torch.distributions import Normal, kl_divergence
from .utils import ModuleTraits
class Baseline(nn.Sequential):
def __init__(self, dim_in=784, dim_out=784):
super().__init__(
nn.Linear(dim_in, 500),
nn.GELU(),
nn.Linear(500, 500)... |
from django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
table_fields = []
supported_views = ["detailed", "list", "gallery"]
extra_context = {}
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
... |
from matplotlib import pyplot as plt
from jax import random
from scipy.spatial.transform import Rotation as R
from optimism.JaxConfig import *
from optimism import EquationSolver as EqSolver
from optimism import Objective
from optimism.test import TestFixture
from optimism.test.MeshFixture import MeshFixture
from opti... |
from importlib.resources import path
import functools
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self, NN_ARCHITECTURE):
super(Net, self).__init__()
# Define a fully connected layers model with three inputs (frequency, flux density, duty ratio)
# and one output (... |
from .Param import VelocityParameter, SlownessParameter, SlothParameter
|
from yoyo import step
transaction(
step(
"""ALTER TABLE transfer_meter ADD COLUMN month VARCHAR;""",
"""ALTER TABLE transfer_meter DROP COLUMN month;"""),
step("""CREATE UNIQUE INDEX transfer_meter_month_idx ON transfer_meter(month);"""))
|
import tensorflow as tf
from base.base_model import BaseModel
from utils.alad_utils import get_getter
import utils.alad_utils as sn
class SENCEBGAN(BaseModel):
def __init__(self, config):
super(SENCEBGAN, self).__init__(config)
self.build_model()
self.init_saver()
def build_model(sel... |
# Funzioni
import operator
# Moduli
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.template import RequestContext
from django.contrib.auth.models import User
from django.http import HttpResponse
# Database
from ftft.canzoni.models import canzone, licenze
fr... |
#!/usr/bin/env python
import mmap
import os
from os import path
import sys
import time
def parse_adr(adr):
"""
Converts an IP address + port in the form aaaaaaaa:pppp to the form
a.b.c.d:p.
"""
ip_raw, port_raw = adr.split(":")
# Split into a list of the octets.
ip_hexs = [ip_raw[idx: idx... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-11-07 00:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0003_load_initial_data'),
]
operations = [
migrations.AddField(... |
#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = "https://cn.investing.com/equities/apple-computer-inc-historical-data"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(response.text, 'html.parser')
html = soup.find(id = "curr_table").... |
"""
Demonstration of Earnshaw's theorem
Ahmed Al-kharusi
Please check the simulation yourself. You may find mistakes!
See the references
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#The moving charge
position_velocity_xi = np.array([0, 0])
posi... |
from __future__ import absolute_import
import numpy
from targets.marshalling.marshaller import Marshaller
from targets.target_config import FileFormat
class NumpyArrayMarshaller(Marshaller):
type = numpy.ndarray
file_format = FileFormat.numpy
def target_to_value(self, target, **kwargs):
"""
... |
"""/**
* @author [Jai Miles]
* @email [jaimiles23@gmail.com]
* @create date 2020-05-06 15:10:52
* @modify date 2020-06-16 15:11:39
* @desc [
TODO:
- Consider is_instance(data, (tuple, list)) vs has_attr(__iter__)??
##########
# README.md Example.
##########
linear_nlg is a naive natural ... |
# @Title: 子集 (Subsets)
# @Author: 18015528893
# @Date: 2021-02-28 12:23:12
# @Runtime: 44 ms
# @Memory: 15.2 MB
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
def backtrack(path, start):
result.append(list(path))
if len(path) >= len(num... |
#!/usr/bin/env python
# a stacked bar plot with errorbars
from pylab import *
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be l... |
from typing import Dict, List, Any, Optional
from .featurizing import Featurizing, featurizing
# from ..operation import DatasetOperation, dataset_operation
from typing import Callable, Mapping
from .plugins.summarization.sum_attribute import *
from .plugins.summarization.extractive_methods import _ext_oracle
from .p... |
#!/usr/bin/python
#
# Watch for changes to amazon/google product reviews.
#
CONFIG=".review-scraper"
VERBOSE=False
AMAZON_REVIEWS_URL="http://www.amazon.com/Bitiotic-Freeform-Backgammon/product-reviews/B00A7KD23K/ref=dp_db_cm_cr_acr_txt"
GOOGLE_PROD_URL="https://play.google.com/store/apps/details?id=com.bitiotic.fre... |
#!/usr/bin/env python3
import pyasmtools
def fac_iter(arg_n: int) -> int:
res = 1
for cur_n in range(1,arg_n+1):
res *= cur_n
return res
fac_iter = pyasmtools.TraceMe(fac_iter)
print( "fac_iter(7):", fac_iter(7))
|
from PyQt5 import QtWidgets, QtCore, QtGui
from collections import OrderedDict
class ZmqSetupWindow(QtWidgets.QMainWindow):
"""Sub window for zmq settings"""
zmqSetupChanged = QtCore.pyqtSignal(OrderedDict)
def __init__(self, parent=None):
super(ZmqSetupWindow, self).__init__(parent)
se... |
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the
diagram below).
Now consider if some obstacles are added to th... |
"""
Database Cleanup to be run every day.
Condenses high resolution report data into averages and anomalies.
Stores the averages and anomalies in separate DB table.
Data to Clean
| |
v v
__________________________________________
Previous 48H | Previous 24H | Now |
xxx | xxx | ... |
print("Added python, too much code.")
|
import logging
import socket
from ipaddress import IPv4Address
from ipaddress import ip_network
from saturn import state
from saturn.protocol import TcpClient
from saturn.socks import reply
from .base import SocksRequest
class SocksRequestConnect(SocksRequest):
action_id = 1
async def go(self):
asse... |
#open the file for writing
f = open("myfile.txt","w")
print("Enter Text (Type # when you are done)")
s=''
while s != '#':
s = input()
f.write(s+"\n")
f.close |
"""
Funções para uma string
Leia uma string e retorne o maximo de função
"""
x = input('Digite algo: ')
# funcao .is
print(f'Tipo primitivo: {type(x)}')
print('É numero:', x.isnumeric())
print('É alfabético:', x.isalpha())
print('É alfanúmero:', x.isalnum())
print('Está em maiusculo:', x.isupper())
print('Está em min... |
import importlib
from django.conf import settings
from django.template import loader
from django.utils.text import slugify
def get_action(state_machine_name, trigger, task):
def _add_action_id(action):
action["id"] = slugify(action["title"])
def _add_action_form(action, task):
template = loa... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
import os
from maskrcnn_benchmark.config import cfg
from my_predictor import COCODemo
import time
vis = True
def main():
config_file = '/media/kevin/办公/xizang/1119_outputs/1119_infer_configs.yaml'
opts = ["MOD... |
import io
import logging
import os
import sqlite3
from datetime import datetime
from shutil import copyfile
from django.conf import settings
from django.core.management import call_command
from django.db.utils import DatabaseError
logger = logging.getLogger(__name__)
def common_clean(db_name, db_file):
# let's ... |
from pygame import mixer
mixer.init()
mixer.music.load('ex021.mp3')
mixer.music.play()
input()
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
__doc__ = """pytest-based ptvsd tests."""
import colorama
import pytest
# This is only imported to ensure that the module is actually installed and the
# timeout se... |
def mergesort(arr):
if len(arr)>1:
mid=len(arr)//2
l=arr[:mid]
r=arr[mid:]
mergesort(l)
mergesort(r)
i=j=k=0
while i<len(l) and j <len(r):
if l[i]<r[j]:
arr[k]=l[i]
i+=1
else:
arr[k]=r[j]
... |
import dataclasses
@dataclasses.dataclass
class NonPublicMetrics():
impression_count: int
url_link_clicks: int
user_profile_clicks: int
|
def API_error(description):
"""Create an API error message."""
return {"status": "error", "error": description}
def API_fatal(description):
"""Create an API fatal error message."""
return {"status": "fatal", "error": description}
def API_response(*args, **kwargs):
"""Create an API response using p... |
'''Test script for Homework 3, Computational Photonics, SS 2020: FDTD method.
'''
import numpy as np
from finite_difference_time_domain import fdtd_3d, Fdtd3DAnimation
from matplotlib import pyplot as plt
import time
# dark bluered colormap, registers automatically with matplotlib on import
import bluered_d... |
#!/usr/bin/python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Created by: Anderson Brito
# Email: andersonfbrito@gmail.com
# Python version: Python 3
#
# domAnnot.py -> Given a set of peptides annotated with CDS positions,
# this code creates GFF annotations for Pfam do... |
import discord
from discord.ext.commands.converter import EmojiConverter as ec
from discord.ext.commands.converter import PartialEmojiConverter
from emoji import UNICODE_EMOJI_ENGLISH
from redbot.core import commands
from redbot.core.bot import Red
old_tick = commands.context.TICK
old_get_context = Red.get_context
... |
"""Deep Pictorial Gaze architecture."""
from typing import Dict
import numpy as np
import scipy
import tensorflow as tf
from core import BaseDataSource, BaseModel
from datasources import UnityEyes
import util.gaze
class DPG(BaseModel):
"""Deep Pictorial Gaze architecture as introduced in [Park et al. ECCV'18]."... |
# Copyright 2018, Michael DeHaan LLC
# License: Apache License Version 2.0
# -------------------------------------------------------------------------
# urls.py - the standard web routes configuration file for Django
# --------------------------------------------------------------------------
from django.conf.url... |
import unittest
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
import onnx
import onnx_chainer
from chainer import testing
from onnx_chainer.testing import test_mxnet
MXNET_OPSET_VERSION = {
'elu': (1, 6),
'hard_sigmoid': (6,),
'leaky_relu': (6,),
'log_softm... |
import json
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path, 'metafile.schema.json')) as f:
metafile=json.load(f) |
print('\033[1;93m-=-\033[m' * 15)
print(f'\033[1;31m{"LARGEST AND SMALLEST ON THE LIST":^45}\033[m', )
print('\033[1;93m-=-\033[m' * 15)
numbers = list()
largest = 0
big_position = list()
small_position = list()
numbers.append(int(input(f'Type a number for the position {0}: ')))
smallest = numbers[0]
for i in range(... |
d = {
'0': [" "],
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
n = int(input())
for i in range(n):
t = input()
prev = ''
print("Case #{}: ".format(i + 1... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-05-07 01:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('standard', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
from math import sqrt
import numpy as np
from PIL import Image
def load_image(filepath: str) -> Image:
return Image.open(filepath).convert("L")
def grad_inf(ims: Image) -> Image:
pixs = np.asarray(ims).astype("uint8")
pixd = pixs.copy()
height, width = pixs.shape
for j in range(1, height-1):
... |
# Copyright (c) 2013, Minda Sai Pvt LTd and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
import math
from calendar import monthrange
from datetime import datetime,timedelta,date
from frappe.utils import add_days, add_months,ge... |
'''
The snippet contains:
How to declare and use a class with attributes and methods
How to declare a class using inheritance
grab from
http://glowingpython.blogspot.com/2011/04/how-to-define-class-using-inheritance.html
'''
class Point2D:
""" a point in a 2D space """
name = "A dummy name" # attribute
def __in... |
#!/usr/bin/python3
import os
import subprocess
import json
from iot_message.exception import DecryptNotFound
from iot_message.exception import NoDecodersDefined
__author__ = 'Bartosz Kościów'
class Message(object):
"""Class Message"""
protocol = "iot:1"
chip_id = None
node_name = None
encoders = ... |
# MicroTosca types
# MicroTOSCA node types
MICROTOSCA_NODES_SERVICE = 'micro.nodes.Service'
MICROTOSCA_NODES_DATABASE = 'micro.nodes.Datastore'
MICROTOSCA_NODES_COMMUNICATIONPATTERN = 'micro.nodes.CommunicationPattern'
MICROTOSCA_NODES_MESSAGE_BROKER = 'micro.nodes.MessageBroker'
MICROTOSCA_NODES_MESSAGE_ROUTER = 'mi... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 Ryan Mackenzie White <ryan.white4@canada.ca>
#
# Distributed under terms of the license.
"""
"""
class NullDataError(ValueError):
"""
"""
class MissingDataError(ValueError):
"""
"""
class ParserWarning(Warning)... |
# -*- coding: utf-8 -*-
import abc
from libs.code import Code
class Query(object):
def __init__(self, meta_param: dict, parsed_query_param: dict):
self.meta_param = meta_param
self.parsed_query_param = parsed_query_param
self.type_ = meta_param["type"] if "type" in meta_param else None
... |
import numpy as np
import argparse
import csv
import os
import time
import h5py
import librosa
import multiprocessing
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
from utils.utilities import (mkdir, float32_to_int16, freq2note, get_filename, get_process_groups, read_lst, write_lst)
from utils.tar... |
from __future__ import unicode_literals
import unittest
from rest_framework import status, test, settings
from django.core.urlresolvers import reverse
from nodeconductor.structure.tests import factories as structure_factories
from nodeconductor.support.serializers import CommentSerializer
class JiraTest(test.APITr... |
from Aula52.model.endereco_model import EnderecoModel
from Aula52.dao.base_dao import BaseDao
class EnderecoDao(BaseDao):
def __init__(self):
super().__init__("01_MDG_ENDERECO")
def listar_todos(self):
tuplas = super().listar_todos()
lista = []
for e in tuplas:
mode... |
"""restart: Restart nginx or flask in the dev container
'dsco restart' will restart both the nginx service and the flask service
running inside the development container. To restart just one of those
use the corresponding flag: --nginx or --flask
"""
import os
from pathlib import Path
from cookiecutter.main import co... |
#!/usr/bin/env python3
# Goshu IRC Bot
# written by Daniel Oaks <daniel@danieloaks.net>
# licensed under the ISC license
# Quite a lot of this module was taken, with permission, from
# https://github.com/electronicsrules/megahal
# In particular, the regexes and the display layout. Thanks a bunch, bro!
import re
imp... |
#############################################################################
# Author: Muhammed S. ElRakabawi (elrakabawi.github.io)
# Paper: Yin, C. (2017). Encoding DNA sequences by integer chaos game representation
# License: MIT
#############################################################################
import a... |
#!/usr/bin/env python3
# Et eksempelprogram som viser integrasjon med ID-porten og
# APIer fra skatteetaten.
import base64
import webbrowser
import random
import time
import json
from urllib.parse import urlparse, parse_qs, quote
from base64 import urlsafe_b64encode, urlsafe_b64decode
from hashlib import sha256
from ... |
import cv2
def heightANDdepth(flame, pixel_to_meters, data, roi):
"""
This function calculates the flame height and thickness
Parameters:
----------
flame: contour of the flame
np.ndarray
pixel_to_meters: ratio of meters per pixel
float
data: needs to be i... |
import uuid
from test_helper import get_result
import floto
import floto.api
import floto.decider
def test_07():
domain = 'floto_test'
rs = floto.specs.retry_strategy.InstantRetry(retries=2)
timer_a = floto.specs.task.Timer(id_='TimerA', delay_in_seconds=15)
task_1 = floto.specs.task.ActivityTask(do... |
print('''Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
No final, mostre o conteúdo da estrutura na tela.''')
aluno = dict()
aluno['nome'] = str(input('Insira o nome: '))
aluno['nota'] = float(input('Insira a nota: '))
if aluno['nota'] < 7:
aluno['nota'] = 'repro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 10:07:12 2017
@author: adriana
The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example,
gcd(2, 12) = 2
gcd(6, 12) = 6
gcd(9, 12) = 3
gcd(17, 12) = 1
A clever mathe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.