content stringlengths 5 1.05M |
|---|
import frappe
# TODO sanitize req input
def remove_this (doctype,args,kwargs) :
kwargs.pop('cmd', None)
removed = frappe.db.delete (
doctype,
kwargs
)
return frappe.db.commit() |
import logging
import re
import json
logger = logging.getLogger(__name__)
log = logger
BOOT_DISK_CMD = "findmnt -v -n -T / -o SOURCE"
def run(ceph_cluster, **kw):
"""
Rolls updates over existing ceph-ansible deployment
Args:
ceph_cluster (ceph.ceph.Ceph): ceph cluster object
**kw(dict):
... |
import abc
import hashlib
import struct
import bip32utils
import ecdsa
import rlp
import time
from eth_account.internal.transactions import serializable_unsigned_transaction_from_dict, encode_transaction, \
UnsignedTransaction
from eth_account.messages import defunct_hash_message
from snet_cli._vendor.ledgerblue.c... |
from os import getenv
from typing import BinaryIO, Iterable, Optional, Union
import requests
from qiniu import Auth, put_data, put_file
class YPService:
"""云片"""
def __init__(self, api_key: str):
self.api_key = api_key
def single_send(self, mobile: str, text: str) -> dict:
"""单条发送,返回云片响应... |
user_input = str(input())
user_input = user_input.split()
n, m, a = [int(i) for i in user_input]
new_length = int(n / a)
new_width = int(m / a)
if n % a != 0:
new_length += 1
if m % a != 0:
new_width += 1
print(new_length * new_width)
|
import abc
import asyncio
import collections
import concurrent
import datetime
import logging
import time
import asab
from .abc.connection import Connection
from .abc.generator import Generator
from .abc.sink import Sink
from .abc.source import Source
from .analyzer import Analyzer
from .exception import ProcessingEr... |
from django.db import models
class Articles(models.Model):
title = models.CharField(max_length = 120)
post = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
def __str__(self):
return self.title
|
from sys import platform
import getpass
from gyomu.user_windows import _WindowsUser
from gyomu.user import DummyUser, User
class UserFactory:
_current_user: 'User' = None
@staticmethod
def get_current_user() -> 'User':
if UserFactory._current_user is not None:
return UserFactory._cur... |
from django import template
import markdown
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(name='markdown')
def markdown_filter(text):
return mark_safe(markdown.markdown(text, extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite',
... |
from django import template
register = template.Library()
@register.simple_tag
def dfirtrack_version():
versionnumber = 'v0.2.0'
return versionnumber
|
import json
import math
import time
from collections import defaultdict
from django.apps import apps
from django.conf import settings
from django.db import connection
from pretix.base.models import Event, Invoice, Order, OrderPosition, Organizer
from pretix.celery_app import app
if settings.HAS_REDIS:
import dja... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 13:40:32 2020
@author: frederik
"""
import cv2
locator = 0
for x in range(255):
cap = cv2.VideoCapture(locator)
if (cap.isOpened() is True):
print("Found camera %s", locator)
locator += 1
if (cap.isOpened() is... |
# __author__ = 'WeiFu'
from __future__ import print_function, division
import sys, pdb, random
from ruler import *
from Abcd import *
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from tuner import *
from processarff import *
from sk import rdivDemo
import weka.core.j... |
"""
=============================
gprof_nn.bin.run_preprocessor
=============================
This module implements a CLI interface to run the preprocessor on a
range of L1C files.
"""
import argparse
import logging
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from quantnn.qrnn import ... |
"""
Data Import | Cannlytics
Authors:
Keegan Skeate <keegan@cannlytics.com>
Created: 6/16/2021
Updated: 6/16/2021
TODO:
- Import model fields from organization's settings in Firestore so
the user can upload custom data points.
"""
import pandas as pd
from cannlytics.firebase import update_document
def impor... |
import librosa
import constants
def custom_mfcc(data):
fs= constants.fs
mfcc_data = librosa.feature.mfcc(y=data, sr=fs, n_mfcc=12, n_fft=len(data), hop_length=len(data)+2)[:, 0]
centroid = librosa.feature.spectral_centroid(y=data, sr=fs, n_fft=len(data), hop_length=len(data)+2)[:, 0]
return mfcc_data,... |
# Author: Stephen Mugisha
# FSM exceptions
class InitializationError(Exception):
"""
State Machine InitializationError
exception raised.
"""
def __init__(self, message, payload=None):
self.message = message
self.payload = payload #more exception args
... |
import torch
import wandb
from torch.utils.data import DataLoader
from src.utils import save_models, saving_path_rrn, get_answer, names_models
from src.utils import BabiDataset, batchify, get_answer_separately
from collections import defaultdict
REASONING_STEPS = 3
def train(train_stories, validation_stories, epochs... |
import json
import os
import pickle
import pandas as pd
import sqlalchemy
class StringFolder(object):
"""
Class that will fold strings. See 'fold_string'.
This object may be safely deleted or go out of scope when
strings have been folded.
"""
def __init__(self):
self.unicode_map = {}
... |
'''
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related docu... |
from preprocessing_functions import preprocessing_functions as pf
import h5py as h5
import glob
# from hdfchain import HDFChain
blacklist = pf.blacklist
colblacklist = pf.colblacklist
dataPath = '~/sync/bachelorarbeit/daten/sim/'
#hardcoded nomissingvalues can be replaced by variable
#different types of data need to ... |
"""
Copyright 2013, 2014 Ricardo Tubio-Pardavila
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 ... |
class CurrentStatusCoins():
BTC = 0
ETH = 0
XRP = 0
def get_current(self):
return {
"BTC": self.BTC,
"ETH": self.ETH,
"XRP": self.XRP
}
def set_coins(self, new_values):
self.BTC = new_values["BTC"]
self.ETH = new_values["ETH"]
... |
#!/usr/bin/python3
import json
import datetime
import smbus
import socket
import math
import time
from collections import OrderedDict
from pysolar import solar
import pytz
import os.path
import sys
from dual_g2_hpmd_rpi import motors, MAX_SPEED
#480 is Positive 100% voltage
#-480 is Negative 100% voltage
#240 is Posit... |
import os
import json
import requests
from PIL import Image
def get_imgur_client_id():
"""
gets the imgur client id key from config.txt file.
"""
with open('config.txt', 'r') as f:
client_id = f.read()
return client_id
def create_download_dir():
"""
creates a download directory ... |
# Copyright (c) 2020 Matthew Earl
#
# 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, modify, merge, publish, distr... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import cgi
import cgitb
import os
from templates import secret_page
cgitb.enable()
class FollowingTheTAsInstructionsError(Exception):
def __init__(self):
Exception.__init__(
self, ("You must edit secret.py to change the username, password, "
... |
from .iterators import Iterable, Iterator, It
|
import re
# Example plugin for EditorFunctions type plugins
#
# The plugin allows to install new menu items and toolbar items and register a
# a function with each that is called. The function must accept one argument which
# is the instance of PersonalWikiFrame providing access to the editor and the data stor... |
import urllib
from pymd5 import md5, padding
query = open('3.3_query.txt').read()
command3 = open('3.3_command3.txt').read()
print 'Query : ', query
token = query.split('=')[1].split('&')[0]
print 'Token : ', token
parameters = query.split('&')
print 'Parameters : ', parameters
message = parameters[1] + '&' + para... |
import logging
import sys
from io import BytesIO
from pyfbx import FBXSerializationException
from pyfbx.serializers import BytesSerializer
logger = logging.getLogger("tests")
def test_serialize_deserialize_sequence():
bytes_serializer = BytesSerializer()
test_bytes = "bytes".encode("utf-8")
... |
from . import base
__all__ = ["Jaccard", "SorensenDice"]
class Jaccard(base.MultiOutputClassificationMetric):
"""Jaccard index for binary multi-outputs.
The Jaccard index, or Jaccard similarity coefficient, defined as the size of the intersection
divided by the size of the union of two label sets, is us... |
from django.conf.urls import url
from . import views
app_name = 'words'
urlpatterns = [
url(r'^$', views.AbbreviationListView.as_view(),
name='abbreviation_browse'),
url(r'^detail/(?P<pk>[0-9]+)$', views.AbbreviationDetailView.as_view(),
name='abbreviation_detail'),
url(r'^create/$', views... |
#encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytest
from xml.etree import cElementTree as ET
from bslib.xml import Request, Collection, Result, ResultList, StatusElement, Comments
import os.path
def _a(path):
return os.path.join(
os.path.dirname(
... |
import os
import click
from .config_json_parser import ClpipeConfigParser
from .batch_manager import BatchManager, Job
import logging
@click.command()
@click.option('-config_file', required = False ,type=click.Path(exists=False, dir_okay=False, file_okay=True), default=None,
help='A config file. Optional... |
from win32com.shell import shell, shellcon
import os
import glob
import operator
import re
import time
import win32api
import win32con
import win32process
import pythoncom
import logging
unlearn_open_undo = []
my_documents_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, 0, 0)
LEARN_AS_DIR = os.path.join(my_d... |
import socket
import re
import uuid
from struct import pack, unpack
from select import select
def poll(sock, timeout):
return sock in select([sock], [], [], timeout)[0]
class SendError(Exception):
pass
class ReceiveError(Exception):
pass
class Client(object):
re_aggregate_response = re.compile(r'Agg... |
class circularQueue(object):
def __init__(self, size):
self.__size = size
self.__queue = [None]*size
self.__head = 0
self.__tail = 0
def enqueue(self, item):
print("TAIL", self.__tail)
if not(self.__isBefore()):
self.__queue[self.__tail] = i... |
from flask import Blueprint, jsonify, request, url_for
from shorty.services.base import Services
from shorty.services import error_handler
from shorty.services.error_handler import CustomError
api = Blueprint('api', __name__)
@api.route('/shortlinks', methods=['POST'])
def create_shortlink():
data = request.get_... |
import gzip
try:
from Magphi.exit_with_error import exit_with_error
except ModuleNotFoundError:
from exit_with_error import exit_with_error
EXIT_INPUT_FILE_ERROR = 3
def check_if_gzip(input_files, file_logger):
"""
Check if genome files given as input at gzipped, by trying to open them with zgip's op... |
# Copyright 2019 VMware, Inc.
# SPDX-License-Indentifier: Apache-2.0
from .exception import TemplateEngineException
from .tags.tag_map import get_tag_map
class TagResolver(object):
"""
`TagResolver` resolves a template tag.
"""
# All template tag names start with TAG_MARKER
TAG_MARKER = '#'
#... |
import sys
from collections import defaultdict as d
import re
from optparse import OptionParser, OptionGroup
# Author: Martin Kapun
# edits by Siyuan Feng
######################################################### HELP #########################################################################
usage = """python3 %p... |
import json
import os
from common.file_helpers import mkdirs_exists_ok
from selfdrive.hardware import PC
class MissingAuthConfigError(Exception):
pass
if PC:
CONFIG_DIR = os.path.expanduser('~/.comma')
else:
CONFIG_DIR = "/tmp/.comma"
mkdirs_exists_ok(CONFIG_DIR)
def get_token():
try:
with open(os.pa... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import re
def convert_string_to_snake_case(s):
"""
Changes String to from camelCase to snake_case
:param s: String to convert
:rtype: String
:rertuns: String converted to snake_case
"""
a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
return a.sub(r'_\1', s).lower()
def con... |
import numpy as np
from scipy.signal import savgol_filter
def get_filtered_data(df, filter="No filter"):
# clean lists by removing sensitivity, removing IC ratio, removing empty values and converting strings
# with ratios to floats.
# x
l = df["Parameter"].to_list()
l_time = []
for string in ... |
def _assert(bool_, err_string=''):
"""
Avoid using asserts in production code
https://juangarcia.co.uk/python/python-smell-assert/
"""
if not bool_:
raise ValueError(err_string)
|
"""
iterative ptychographical reconstruction assuming vector wavefields
the algorithm is developed using the theory outlined in,
"Ptychography in anisotropic media, Ferrand, Allain, Chamard, 2015"
"""
import jones_matrices as jones
import numexpr as ne
import numpy as np
import optics_utils as optics
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tasker
#
# Copyright (c) 2020 Lorenzo Carbonell Cerezo <a.k.a. atareao>
#
# 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 Softwar... |
#!/usr/bin/env python
import sys
sys.path.append('..')
from libs.helpers import get_input
from functools import lru_cache
@lru_cache(maxsize=None)
def add(n1, n2):
return n1 + n2
@lru_cache(maxsize=None)
def mul(n1, n2):
return n1 * n2
@lru_cache(maxsize=None)
def div(n1, n2):
return int(n1 / n2)
@lru_... |
#!/usr/bin/env python
import os.path
import argparse
import random
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
import stats.methods as methods
from stats.utils import *
################
# Declarations #
################
SYM_X, SYM... |
import tempfile
import unittest
from pyadt import Connection
from pyadt import exceptions as e
class TestConnectionInit(unittest.TestCase):
"""Unit tests for Connection.__init__"""
def test_attribute_declaration(self):
obj = Connection("DataSource")
self.assertEqual(obj.datasource, "DataSour... |
"""axiodl URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
#!/usr/bin/env python
# coding: utf-8
# # Collaboration and Competition
import os
import sys
from collections import deque
import matplotlib.pyplot as plt
import numpy as np
import random
import time
import torch
from unityagents import UnityEnvironment
sys.path.insert(0, os.path.dirname(__file__))
from constants im... |
import pytest
import numpy as np
from bbox import BBox2D, BBox2DList
from bbox.box_modes import XYXY, XYWH
class TestBBox2DList(object):
@classmethod
def setup_class(cls):
cls.n = 10
cls.l = [BBox2D(np.random.randint(0, 1024, size=4))
for _ in range(cls.n)]
cls.bbl = B... |
"""Asynchronous Python client for ZAMG weather data."""
from .zamg import ZamgData
__all__ = [
"ZamgData",
]
|
'''
Copyright 2017-present, Airbnb Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... |
# 3Sum
class Solution:
def threeSum(self, nums):
nums.sort()
ans = []
length = len(nums)
i = 0
while i < length:
if i > 0 and nums[i] == nums[i - 1]:
i += 1
continue
j = i + 1
k = length - 1
tar... |
from ccxt.base.errors import BadRequest
from decimal import Decimal, InvalidOperation
def _convert_float_or_raise(f, msg):
try:
val = _convert_float(f)
except InvalidOperation:
raise BadRequest('{} needs to be a number'.format(msg))
if not val.is_finite():
raise BadRequest('{} need... |
# Copyright 2022 Sony Semiconductors Israel, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
from typing import Optional, Tuple
from paramak import RotateMixedShape
import math
class CapsuleVacuumVessel(RotateMixedShape):
"""A cylindrical vessel volume with constant thickness that has addition
spherical edges.
Arguments:
outer_start_point: the x,z coordinates of the outer bottom of the
... |
from what_apps.contact.models import ContactInfo, PhoneNumber
def setup(userprofile=None):
rusty_contact = ContactInfo.objects.create(
address="7 somewhere ave.",
address_line2="apt. 69",
city="New Paltz",
state="New York",
postal_code=12561
... |
#!/usr/bin/env python3
import argparse
import os
from lxml import etree
from itertools import zip_longest
from funcy import collecting
from tqdm import tqdm
import json
import re
import fnmatch
NSMAP = {'fb2': 'http://www.gribuser.ru/xml/fictionbook/2.0'}
MAX_PATH_DEPTH = 128
def parse_args():
p = argparse.Argum... |
# Elizabeth A. Barnes and Randal J. Barnes
# March 3, 2021
# v1.1
import numpy as np
import random
import scipy.stats as stats
import matplotlib.pyplot as plt
#----------------------------------------------------------------
def get_data(EXPINFO, to_plot=False):
# make the data
slope = EXPINFO['slope... |
#!/usr/bin/env python
# This is a reimplementation of the default real-time feedback experiment
# distributed with AFNI, implemented in realtime_receiver.py, using WX and
# Matplotlib for generating the GUI and plotting the results.
#
# This replaces the default GUI toolkit with PsychoPy, and will draw the
# same resu... |
from bddrest import response, when, status, given
from card_holder.models import Foo
from card_holder.tests.helpers import LocalApplicationTestCase
class TestFoo(LocalApplicationTestCase):
@classmethod
def mockup(cls):
session = cls.create_session()
# Adding 5 Foos
for i in range(5)... |
#!/usr/bin/env python
import argparse
def get_new_flaky_test_names(known_flakys_tests, current_run_flakys_tests):
return [flaky for flaky in set(current_run_flakys_tests) - set(known_flakys_tests)]
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Diff two files with flaky tests to g... |
from urllib.parse import urlparse
from django.core.validators import integer_validator
from rest_framework import serializers
from datahub.company.constants import BusinessTypeConstant
from datahub.company.models import Company
from datahub.company.serializers import CompanySerializer
from datahub.company.validators ... |
"""
Some constants.
"""
VERSION = "0.1.0"
BAT = "bat"
LIGHT_THEME = "GitHub"
LEFT_SIDE, RIGHT_SIDE = range(2)
|
import base64
import time
import cv2
def init():
"""
This method will be run once on startup. You should check if the supporting files your
model needs have been created, and if not then you should create/fetch them.
"""
# Placeholder init code. Replace the sleep with check for model files requir... |
from django.apps import AppConfig
class AweConfig(AppConfig):
name = "awe"
|
import pandas as pd
from itertools import product
# TODO switch back the allow_output_mutation=True once bug
#@st.cache
def cache_game_data(q, f, _db):
returned_games = pd.DataFrame(list(_db.games.find(q, f)))
return returned_games
def get_teams_list(_db):
"""Get a list of all the teams with at least ... |
import unittest
import redis
import time
from concurrent.futures import ProcessPoolExecutor
r = redis.Redis(host='localhost', port=6379)
dt = '2020-04-25'
user_pin = 'mythling'
vec = [-0.23724064818168949520, 0.03306523783586075987, -0.08497630252384760774, 0.00895396226354287957,
0.10745647159054654007, -0.06... |
from monstro.core.exceptions import MonstroError
class FormError(MonstroError):
pass
class ValidationError(FormError):
def __init__(self, error, field=None):
self.error = error
self.field = field
super().__init__(self.__str__())
def __str__(self):
if self.field:
... |
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
ans = 0
for i in range(3):
ans+=abs(l1[i]-l2[i])
if ans==3:
print("NO")
else:
print("YES") |
from collections import defaultdict
from math import ceil
from transformers.tokenization_utils import _is_control
from bootleg.symbols.constants import CLS_BERT, PAD, PAD_BERT, SEP_BERT
def determine_windowsX(
sentence, spans, aliases_seen_by_model, maxlen, mincontext, sanity_check=False
):
"""Truncate <sen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from .events import events as event
from .events import *
class LibraryListener(object):
ROBOT_LISTENER_API_VERSION = 2
def start_suite(self, name, attrs):
dispatch('scope_start', attrs['longname'])
def end_suite(self, name, attrs):
dispatch... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Lehrstuhl fuer Angewandte Mechanik, Technische
# Universitaet Muenchen.
#
# Distributed under BSD-3-Clause License. See LICENSE-File for more information
#
"""
"""
import numpy as np
import scipy as sp
import time
import amfe
gmsh_input_file = amfe.amfe_dir('meshes/gm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from wdom.util import reset
from wdom.document import get_document
class TestInitialize(unittest.TestCase):
def test_initialize(self):
from wdom.server import _tornado
old_doc = get_document()
old_app_tornado = _tornado.get_a... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui/gui.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWi... |
import vis
import utils
import met_funcs
import plotly_vis
import MetMastData
import pandas as pd
import matplotlib.pyplot as plt
from colour import Color
import plotly
from plotly import tools
#import plotly.tools as tls
import plotly.plotly as py
import plotly.graph_objs as go
# Place input files here
#inputfiles_he... |
import sys
import math
import operator
import json
"less than 1000 because document names overlap after removing - and _ and these files have same content"
N=0
docTokenCountMapping={}
avdl=0
def get_term_BM25_score(ni,fi,qfi,dl):
k1=1.2
b=0.75
k2=100
score=0.0
if fi==0:
score=0.0
e... |
# Generic CNN classifier that uses a geojson file and gbdx imagery to classify chips
import numpy as np
import os, random
import json, geojson
from mltools import geojson_tools as gt
from mltools.data_extractors import get_data_from_polygon_list as get_chips
from keras.layers.core import Dense, Dropout, Activation, F... |
# Generated by Django 2.2.2 on 2019-08-23 04:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('result', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='listcommit',
name='platform',
... |
import pathlib
from traitlets.config import Configurable
from traitlets import (
Unicode,
Dict,
default
)
from jhubctl.utils import SubclassError
class Cluster(Configurable):
"""Base class for Kubernetes Cluster providers.
To create a new provider, inherit this class and
replace the folowi... |
import re
import sys
import os
from os import listdir
import shutil
placeholder = '{{ cookiecutter.placeholder }}'
output_terms = '{{cookiecutter.filename}}.md'
output_component = '{{cookiecutter.component_name}}.js'
# todo read both files, rewrite Terms.js
# todo generate pdf from terms_and_conditions.md
componen... |
t = int(input())
for i in range(t):
a,b = input().split()
a = int(a)
b = int(b)
if b == 0:
print(a+1)
continue
if a == 0:
print(1)
continue
print(b*2 + a +1)
|
import datetime
import json
from flask_restplus import fields
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import sqltypes
db = SQLAlchemy()
class Marshaling:
# 用来给sqlalchemy模型自动生成序列化规则,供flask-restplus使用
# 偷懒用的,不放心还是可以直接手写模型,没有影响
type_mapper = {
sqltypes.String: fields.String,
... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... |
#!/usr/bin/pyhon
#
# boxy2edf v0.2
# Copyright 2016 Paolo Masulli - Neuroheuristic Research Group
#
#
# This file is part of boxy2edf.
#
# boxy2edf is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio... |
import copy
import json
import logging
import math
import pickle
import random
from collections import Counter
import numpy as np
from srdatasets.datasets import __datasets__
from srdatasets.utils import (__warehouse__, get_datasetname,
get_processed_datasets)
logger = logging.getLogger... |
'''
Restart CrySPY
'''
import os
from .. import utility
from ..BO import bo_restart
from ..EA import ea_append
from ..gen_struc.random.random_generation import Rnd_struc_gen
from ..IO import io_stat, pkl_data
from ..IO import read_input as rin
from ..LAQA import laqa_restart
from ..RS import rs_restart
def restart(... |
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
"""
Class to generate summary from events received
"""
import json
from .logger import Logger
from .json_display import JsonDisplay
from collections import defaultdict
from collections import OrderedDict
import textwr... |
"""An Agent that mimics the most recent possible action done by a player."""
import sys, random
if "." not in __name__:
from utils.game import *
from utils.network import *
from Agent import Agent
from HonestAgent import HonestAgent
from RandomAgent import RandomAgent
else:
from .utils.game im... |
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
#e.g., /polls/
url(r'^$', views.index, name='index'),
#e.g., /polls/1/
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
#e.g., /polls/1/results
url(r'^(?P<poll_id>\d+)/results/$', views.result... |
from pdb import set_trace as T
import numpy as np
from signal import signal, SIGINT
import sys, os, json, pickle, time
import ray
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
f... |
#author: Bryan Bishop <kanzure@gmail.com>
#date: 2012-01-02
#url: http://hax.iimarck.us/files/rbheaders.txt
import json
import os
from __future__ import print_function
#parse hex values as base 16 (see calculate_pointer)
base = 16
# TODO: load the rom based on config.rom_path
rom_filename = os.path.join(os.getcwd(),... |
number_cakes= int(input("Enter the number of cake(s) you want to buy"))
cake_price = 4.50
bill=cake_price * number_cakes
if number_cakes == 1:
print('The price of a cake is ', bill,' pounds.')
elif number_cakes > 1:
print('The price of', number_cakes, 'cakes is', bill,'pounds.')
else:
print('Error: the numb... |
import collections
import typing
from typing import Dict, List, Optional
import math
import numpy as np
import tensorflow.keras.backend as K
MAXIMUM_FLOAT_VALUE = float('inf')
KnownBounds = collections.namedtuple('KnownBounds', ['min', 'max'])
class MinMaxStats(object):
"""A class that holds the min-max values of t... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.