content stringlengths 5 1.05M |
|---|
"""Creates a progress dialog using the Windows API."""
# TODO: Add support for having a message (label)
# TODO: Add support for making it cancellable.
import win32api
import win32con
import win32gui
import commctrl
class ProgressDialog:
"""Create a dialog using the Windows API that can be used to show the
pr... |
from pygame import *
import pprint
import covid
import WebScrape
import destination
#global font variable
font.init()
title_font = font.SysFont('Calibri', 80)
body_font = font.SysFont('Calibri', 50)
testbodysurface = body_font.render("Test", False, (0,0,0))
'''Images'''
icon_covid = image.load("I... |
import datetime
import pytest
import structlog
from covidactnow.datapublic.common_fields import DemographicBucket
from covidactnow.datapublic.common_fields import CommonFields
from api.can_api_v2_definition import Actuals
from api.can_api_v2_definition import FieldAnnotations
from api.can_api_v2_definition import Fie... |
def test_in_project_roots(tmpdir):
from _pydevd_bundle import pydevd_utils
import os.path
import sys
assert pydevd_utils._get_library_roots() == [
os.path.normcase(x) for x in pydevd_utils._get_default_library_roots()]
site_packages = tmpdir.mkdir('site-packages')
project_dir = tmpdir.m... |
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Information pop-up for vimiv.
Shows the current version, the icon, gives a link to the GitHub site and the
possibility to display the licence.
"""
from gi.repository import GLib, Gtk
class Information():
"""Class containing information on vimiv."""
def g... |
class RopMemAccess(object):
"""Holds information about memory accesses
Attributes:
addr_dependencies (set): All the registers that affect the memory address.
data_dependencies (set): All the registers that affect the data written.
addr_constant (int): If the address is a constant it is s... |
import re
import json
import base64
import uuid
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.sites import requests
from django.core.paginator import Paginator
from django.http import HttpResponse, H... |
"""
Author: Ta Chun Liu, Sir Walter Bodmer FRS
Program: __INIT__.PY
Date: 03/April/2021
"""
__version__ = "0.1"
from .GMM_scs import *
|
#!/usr/bin/python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gdb
import pwngef.config
import pwngef.commands
from pwngef.commands import GenericCommand
import pwngef.arch
import pwngef.proc
from pwngef.color import message
from pwngef.color impo... |
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--file', type=str, help='txt file with paths')
args = parser.parse_args()
if not args.file:
raise NotImplementedError("Please list file")
HDFS_DIR_PREFIX='file://'
HDFS_DIR='/ailabs/vash/grid_game/'
HDFS_LOCAL_DIR='/Users/vashishtmadh... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import pandas
__author__ = "Jan Janssen"
__copyright__ = "Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH ... |
from .core import where, old_where
__version__ = "2016.08.31"
|
from django.contrib.postgres import fields as psql_fields
from django.db import migrations
# This query generates full text search index based
# the following data ranked from A to D:
# - Namespace name (weight A
# - Collection name (weight A)
# - Collection tags (weight B)
# - Collection content names (weight... |
# -*- coding: utf-8 -*-
# File: streamlit_app.py
# Project: 'ATOM test'
# Created by Gennady Matveev (gm@og.ly) on 13-12-2021.
# Copyright 2021. All rights reserved.
# Inspiration/adopted from:
# https://towardsdatascience.com/from-raw-data-to-web-app-deployment-with-atom-and-streamlit-d8df381aa19f
#Import libr... |
# -*- coding: utf-8 -*-
import unittest
from pycolorname.ral.classic.wikipedia import Wikipedia
class WikipediaTest(unittest.TestCase):
def setUp(self):
self.uut = Wikipedia()
self.uut.load(refresh=True)
def test_data(self):
self.assertEqual(len(self.uut), 213)
# We check ... |
import pandas as pd
import us
from can_tools.scrapers import DatasetBaseNoDate, CMU
from can_tools.scrapers.official.base import ArcGIS
class Texas(DatasetBaseNoDate, ArcGIS):
"""
Get cases, deaths, and testing data on all TX counties from
the TX ArcGIS dashboard
"""
ARCGIS_ID = "ACaLB9ifngzawsp... |
"""Thin wrapper of CUDA Driver API.
There are four differences compared to the original C API.
1. Not all functions are ported.
2. Errors are translated into CUDADriverError exceptions.
3. The 'cu' prefix of each API is omitted and the next character is set to
lower case.
4. The resulting values are returned direc... |
import logging as log
import pandas as pd
import numpy as np
from pprint import pprint
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.externals import joblib
from main import DATA, loadData, getLabels, splitAndScale, addEwma, addRsi
FIBOS = [5, 13, 34]
def main():
for item in DATA:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 06 20:17:45 2016
@author: vhd
"""
from Tkinter import *
import hangman
root = Tk()
root.title ("Mega Microgames Collection")
mainframe = Frame(root, height = 200, width = 500)
mainframe.pack_propagate(0)
mainframe.pack(padx = 5, pady = 5)
intro = Label(mainframe, tex... |
from __future__ import print_function
"""
Directions:
Install the required libraries:
pip install pyramid
pip install pyramid_session_multi
pip install pyramid_session_redis
Run the app:
python single_file_app.py
In another window, make some requests:
curl http://0.0.0.0:6543 -I
curl http... |
import os
import json
import numpy as np
import luigi
import h5py
from ..utils import volume_utils as vu
from ..cluster_tasks import WorkflowBase
from .. import copy_volume as copy_tasks
class BigcatLabelAssignment(luigi.Task):
tmp_folder = luigi.Parameter()
dependency = luigi.TaskParameter()
input_path... |
"""CMS signals tests"""
import pytest
from cms.factories import (
ResourcePageFactory,
HomePageFactory,
BootcampIndexPageFactory,
BootcampRunPageFactory,
ResourcePagesSettingsFactory,
)
pytestmark = pytest.mark.django_db
@pytest.mark.parametrize(
"page_factory",
[
HomePageFactory... |
# Computation Graphs
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="2"
print("Tensorflow version is " + str(tf.__version__))
# *********************
# *** Example ***
# *********************
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)
d = tf.multiply(a,b)
e = tf.add(c,b)
... |
import os
import sys
docs_dir, _ = os.path.split(__file__)
sys.path.append(os.path.dirname(docs_dir))
SECRET_KEY = "."
INSTALLED_APPS = ["djstripe"]
# Do not remove the code below. See note in docs/index.md.
setup = None
import django # noqa
from django.apps import apps # noqa
from django.conf import settings # n... |
from hikari import Member, Embed, Permissions, MessageFlag
from lightbulb import Plugin, Context, SlashCommand, OptionModifier, command, option, implements, add_checks, guild_only, has_guild_permissions
from core.funcs import is_higher
plugin = Plugin("Moderation")
plugin.add_checks(guild_only)
@plugin.command()
@a... |
import unittest
from CN import *
class TestCNMethods(unittest.TestCase):
def setUp(self):
self.a = CN(1, 1)
self.b = CN(2, 2)
self.c = CN(10, 4)
self.d = CN(-10, 25)
self.e = CN(-10, -25)
self.f = CN(9, 9)
self.g = CN(9, -9)
self.h = CN(0, 0)
def test_getRe(self):
self... |
from poetry.core._vendor.six import string_types
# enum compat
try:
from poetry.core._vendor.enum import Enum
except:
class Enum(object): pass
# no objects will be instances of this class
# collections compat
try:
from collections.abc import (
Container,
Hashable,
Iterable,
... |
from detectron2.engine import DefaultTrainer
from detectron2.evaluation import COCOEvaluator
import os
class CocoTrainer(DefaultTrainer):
@classmethod
def build_evaluator(cls, cfg, dataset_name, output_folder=None):
if output_folder is None:
os.makedirs('coco_eval', exist_ok=True)
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#! /usr/bin/env python3
import freq_gen
import argparse
import os
letters = ['a', 'b', 'c', 'd']
fstep=61.0
header = """
namespace iClickerChannels
{
// MSB to LSB RegFrf
"""
struct_format = """
const iClickerChannel_t %s =
{
{ 0x%s, 0x%s, 0x%s },
{ 0x%s, 0x%s, 0x%s },
}; //%s
"""
... |
"""messages.api tests."""
import pytest
import messages.api
from messages.api import send
from messages.api import message_factory
from messages.email_ import Email
from messages.slack import SlackWebhook
from messages.slack import SlackPost
from messages.telegram import TelegramBot
from messages.text import Twilio
f... |
# SPDX-License-Identifier: MIT
import textwrap
from .asc import *
from ..hw.uat import UAT, MemoryAttr, PTE, Page_PTE, TTBR
from ..fw.agx.initdata import InitData as NewInitData
from ..fw.agx.channels import *
from ..fw.agx.cmdqueue import *
from ..fw.agx.controllist import *
from m1n1.proxyutils import RegMonitor
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from operator import attrgetter
from ryu.app import simple_switch_13
from ryu.controller.handler import set_ev_cls
from ryu.controller.handler import MAIN_DISPATCHER,DEAD_DISPATCHER
from ryu.controller import ofp_event
from ryu.lib import hub
class FlowMonitor(simple_swit... |
from flask import Blueprint, make_response, jsonify, request
from kafka.admin import KafkaAdminClient, NewTopic
from flask_jwt_extended import (
jwt_required, create_access_token, get_jwt_identity)
from werkzeug.exceptions import abort
from twilio.rest import Client
from random import randint
from ..models.users im... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import random
from typing import Dict, List
import mmcv
import numpy as np
import pytest
import torch
from mmdeploy.codebase import import_codebase
from mmdeploy.utils import Backend, Codebase
from mmdeploy.utils.test import (WrapModel, check_backe... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
:mod:`textacy.io.utils`: Functions to help read and write data to disk in a variety of formats.
"""
import bz2
import gzip
import io
import itertools
import logging
import lzma
import os
import pathlib
import re
import shutil
import tarfile
import urllib
import zipfile
from typing import IO, Iterable, Optional, Tup... |
from importlib.machinery import SourceFileLoader
from pathlib import Path
from setuptools import setup, find_packages
constants = SourceFileLoader('constants', 'bgprocess/constants.py').load_module()
readme = (Path(__file__).parent / 'README.md').read_text()
setup(
name="bgprocess",
version=constants.__vers... |
# Major, minor, revision
VERSION = (1, 1, 1)
def get_version():
return "%s.%s.%s" % VERSION
__version__ = get_version()
|
vowels = ["a", "e", "i", "o", "u"]
meats=["beef", "porkchop", "bologna", "chicken", "salami", "sausage", "ham", "turkey"]
weirdmeats=["soylent green", "vortex meat", "frog meat", "rattlesnake meat", "spam", "crawdad meat", "racoon meat", "kangaroo meat", "pheasant meat", "opossum meat", "oyster", "clam", "gizzard", "ha... |
#!/usr/bin/env python3
"""buy.py: a prototype for an online purchasing support tool
## target features
- organization and persistence of all buying data
- repl for buying support
- webscraping of vendor's prices
- inventory of purchased items
- report generation (xlsx, html, pdf..)
- quote comparison
- shippi... |
import numpy as np
import tensorflow as tf
from draw import Draw
from plot_data import draw_steps
from hparams import setup_hparams
import sys
import fire
def main(hps, ckpt_path, img_path, nrow, ncol, **kwargs):
hps = setup_hparams(hps, kwargs)
model = Draw(hps)
model.load_weights(ckpt_path)
# print(... |
import asyncio
import faust
app = faust.App(
'myapp',
broker='kafka://localhost:9092',
store='memory://',
value_serializer='raw',
)
# Models describe how messages are serialized:
# {"account_id": "3fae-...", amount": 3}
class Order(faust.Record):
account_id: str
amount: int
greetings_topic ... |
import argparse
import cv2
import numpy as np
from classes import CLASSES_90
from sort import Sort
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
help="Video path, stream URI, or camera ID ", default="demo.mp4")
parser.add_argument("-t", "--threshold", type=float, defaul... |
"""
Python 异常学习
"""
try:
print(1/1)
except ZeroDivisionError :
print(1/3)
else:
print(1/2)
try:
print("连接数据库")
raise IOError("数据库连接异常")
except IOError as e:
print(e)
finally:
print("关闭数据库连接")
try:
print(1/0)
except Exception as e :
print("Exception 异常",e)
except ZeroDivisionError... |
from utils.ospathex import list_files
from xml.etree import ElementTree
from os import path
ns = '{http://schemas.microsoft.com/developer/msbuild/2003}'
def find_resource(filename):
tree = ElementTree.parse(filename)
root = tree.getroot()
androidResources = root.findall('{ns}ItemGroup/{ns}AndroidResource'... |
from sqlalchemy.ext.declarative import declarative_base
from flask.ext.sqlalchemy import SQLAlchemy, _BoundDeclarativeMeta, _QueryProperty, Model
class ValidationModel(Model):
@property
def valid(self):
self.errors = {}
for attr in dir(self):
if attr.startswith('validate_'):
validate_attr ... |
# Generated by Django 2.2.14 on 2020-08-04 23:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='userprofile',
old_name='past_user',
... |
"""
Module containing the SecureStompMessenger class, used for communicating
using the STOMP protocol.
"""
from encrypt_utils import encrypt_message, decrypt_message, verify_message, \
sign_message, verify_certificate, from_file, get_certificate_subject, \
check_cert_key, message_hash
import get_brokers
impo... |
import random
from typing import List, Tuple, Callable
from common.game_objects import Game, Snake, Board, Direction
from common.algos.algos import a_star
from common.point_utils import get_all_valid_neighbours, get_manhattan_distance, get_all_neighbours
from common.heuristics import is_edge, in_hazard_sauce, in_bigge... |
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import authenticate, login as dj_login, logout as dj_logout
from django.contrib.auth.models import User
from djan... |
import argparse
import os.path
import sys
import matplotlib.pyplot as plt
import keras
from utils import dataset_reader, die, ask_for_hyperparameters
from cnn_model import Autoencoder, split_dataset, reshape
# plot loss for pre-trained model only, no need to plot other hyperparameters
def plot_loss(hist):
# plo... |
import requests
from TestException import MethodException
class Requests:
def __init__(self):
self.url = ''
self.method = ''
self.headers = {}
self.body = {}
self.files = None
def init_request(self, url, method, headers, body, files=None):
"""
初始化请求类
... |
import face_recognition as fr
import cv2 as cv
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import os
Tk().withdraw
loadimg = askopenfilename()
targetimg = fr.load_image_file(loadimg)
targetencode = fr.face_encodings(targetimg)
##Training the model by providing the images
def encodeface(imag... |
from matplotlib import use as use_backend
use_backend("Agg")
import matplotlib.pylab as plt
plt.ioff()
# from insilico_Exp import *
from ZO_HessAware_Optimizers import *
import time
import sys
orig_stdout = sys.stdout
# model_unit = ('caffe-net', 'fc6', 1)
# CNN = CNNmodel(model_unit[0]) # 'caffe-net'
# CNN.select_uni... |
"""
MIT License
Copyright (c) 2022 Eduardo Rodrigues
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, publ... |
from __future__ import print_function, division
import os
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
from torch.utils.data import DataLoader
import pytorch_lightning as pl
import cv2
import albumentations as A
from matplotlib import pyplo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# coding=utf-8
import sys
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import TwistStamped
from offb_posctl.msg import controlstate # 发布自定义消息
from scipy.in... |
from disnake.ui.item import *
from disnake.ui.item import __dict__ as __original_dict__
locals().update(__original_dict__)
|
# -*- coding: utf-8 -*-
#
# This file is part of Flask-Collect-Invenio.
# Copyright (C) 2012 - 2016 Kirill Klenov.
# Copyright (C) 2021 TU Wien.
#
# Flask-Collect-Invenio is free software; you can redistribute it and/or modify
# it under the terms of the Revised BSD License; see LICENSE file for
# more details.
... |
# encoding: utf-8
from .defaults import _C as cfg
|
import discord
from discord.ext import commands
import asyncio
import datetime
from config import instar_token, instar_info, category_name, seat_amount, channel_names, role_names, format_time
import Uno
class OccupiedUNOSeats(commands.CheckFailure):
pass
def check_seats():
async def predictate(ctx):
... |
#!/usr/bin/env python3
"""Advent of Code 2020 Day 12 - Rain Risk."""
with open ('inputs/day_12.txt', 'r') as f:
instructions = [row.strip() for row in f.readlines()]
coords = [0, 0]
directions = {0: 'E', 1: 'S', 2: 'W', 3: 'N'}
current_direction = 0
for instruction in instructions:
action = instruction[0]
... |
'''
Created on 14 Jun 2015
FOUND A BUYER!!!
@author: NoNotCar
'''
import Terrain
import Img
import pygame
class Buyer(object):
forward=True
iscat=False
doc="ABBA JAV"
def buy(self,world,tx,ty,p):
return True
def get_img(self,world):
return Terrain.Img.blank32
def rotate(self):
... |
import copy
import typing
import requests.adapters
import urllib3
import mlrun.api.schemas
import mlrun.api.utils.projects.remotes.member
import mlrun.errors
import mlrun.utils.singleton
from mlrun.utils import logger
class Client(metaclass=mlrun.utils.singleton.Singleton,):
def __init__(self) -> None:
... |
# -*- coding: utf-8 -*-
'''
Master Reborn Add-on
Copyright (C) 2017 Master Reborn
This program 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 version 3 of the License, or
(at your option) any later versio... |
""" version which can be consumed from within the module """
VERSION_STR = "0.0.8"
DESCRIPTION = "pyfakeuse helps you fool development environments and code inspectors"
APP_NAME = "pyfakeuse"
LOGGER_NAME = "pyfakeuse"
|
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# 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, merg... |
import tensorflow as tf
class WeighPerClass(tf.keras.layers.Layer):
def __init__(self, initializer="ones", **kwargs):
super(WeighPerClass, self).__init__(**kwargs)
self.initializer = tf.keras.initializers.get(initializer)
def build(self, input_shape):
self.kernel = self.add_weight(
... |
"""
Setup script for LO-PHI Analysis scripts
(c) 2015 Massachusetts Institute of Technology
"""
# Native
import os
from distutils.core import setup, Extension
import lophi.globals as G
def get_packages(rel_dir):
packages = [rel_dir]
for x in os.walk(rel_dir):
# break into parts
b... |
#!/usr/bin/env python3
import os
import sys
import shm
import cv2
import numpy as np
from collections import namedtuple
from conf.vehicle import VEHICLE, is_mainsub
from vision import options
from vision.modules.base import ModuleBase
from vision.framework.feature import outer_contours, contour_area, contour_centroid,... |
#!/usr/bin/env python3
# Boston Cleek
# 9/21/20
# Action server for Sawyer gripper
import rospy
import actionlib
import intera_interface
from math import fabs
from control_msgs.msg import (
GripperCommandAction,
GripperCommandFeedback,
GripperCommandResult,
)
# import matplotlib.pyplot as plt
class Gri... |
market_filepath = './img/market2.png'
check_filepath = './img/check.png'
tp_matrix_filepath = './transition_probabilities.csv'
icon_size = 40
step = int(icon_size / 4)
min_customer_count = 10
max_customer_count = 30
initial_customer_count = 5
initial_section = 'entrance'
coordinates = {
'drinks': {'x': (100, 2... |
from .vgg import *
from .resnet import *
from .resnext import *
from .densenet import *
from .googlenet import *
from .mobilenet import *
from .nasnet import * |
import datetime
import enum
import re
import time
from typing import Any, Dict
import attr
def to_camel_case(snake_str):
# type: (str) -> str
"""Convert snake_case to camelCase.
Adapted from this response in Stackoverflow:
http://stackoverflow.com/a/19053800/1072990
"""
components = snak... |
#!/usr/bin/python3
import numpy as np
from scipy.special import ellipeinc
# Demagnetization factor N/4π for an ellipsoid with semi-axes a, b, and c.
#
# J. A. Osborn.
# "Demagnetizing factors of the general ellipsoid".
# Phys. Rev. 67, 351 (1945).
# https://doi.org/10.1103/PhysRev.67.351
#
# General ellipsoid
# Equa... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import threading
import serial
from sensor_msgs.msg import Imu
print("--------Ultrasonic and 9 Degree of Freedom Listener-----------")
US_9d0F_serial = serial.Serial('/dev/ttyUSB1', 115200, timeout=.1)
bus_codes = {
"L": "UFL", #ultrasonic le... |
# -*- coding: utf-8 -*-
from linkchecker.settings import LINKCHECKER_FIELD_TYPES, LINKCHECKER_LINK_TO
class BaseLinkChecker(object):
model = NotImplementedError
queryset = None
fields = None
excluded = []
object_url = None
def get_model(self, **kwargs):
return self.model
def ge... |
import sys
import subprocess
import hashlib
### Quick utility script to generate sample output hashes for a sample script specified on command line ###
try:
prog_name = "sample_problems/{0}/{1}.py".format(sys.argv[1], sys.argv[1])
except IndexError:
print("Error: incorrect number of clargs supplied")
sys.... |
import gc
import uos
import flashdev
if flashdev.fdev0:
try:
uos.mount(flashdev.fdev0, '/', fstype=uos.VfsLittleFS)
except OSError:
print("Performing initial setup")
uos.VfsLittleFS.mkfs(flashdev.fdev0)
vfs = uos.VfsFat(flashdev.fdev0)
uos.mount(vfs, '/flash')
uo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 12:28:58 2020
@author: bressler
"""
import SBCcode as sbc
import runlistscatalogue as rlc
runsName = 'bgJuly11and12'
runs = rlc.bgJuly11and12
with open('/nashome/b/bressler/sbcoutput/%s_merged_oldPMT.txt'%runsName,'w') as fout:
with open("... |
import frappe
import json
from frappe import _
fields = ["name", "full_name", "profession", "bio", "image"]
@frappe.whitelist(allow_guest=True)
def get_expert_list(page_index=0, page_size=10):
"""Returns expert List"""
try:
response = frappe._dict()
all_records = frappe.get_all("Playfunction Expert")
expert_... |
from array import array
from itertools import repeat
high_low4 = lambda x: ((x >> 4) & 15, x & 15)
def make_array(typecode, n):
initializer = repeat(0, n)
return array(typecode, initializer)
|
from unittest import mock
from django.test import TestCase
from elasticsearch_django.index import (
_prune_hit,
bulk_actions,
create_index,
delete_index,
prune_index,
scan_index,
update_index,
)
from .models import ExampleModel, ExampleModelManager
class IndexFunctionTests(TestCase):
... |
from typing import Awaitable, Callable, Dict, Union
from .dialogue.rules import MMDialogueStateRule, SimpleDialogueStateRule
from .models.mindmeld import DialogueState, ProcessedQuery
DialogueQuery = Union[ProcessedQuery, str]
SimpleHandler = Callable[[DialogueState], Awaitable[DialogueState]]
QueryHandler = Callable... |
import numpy as np
from sklearn.datasets import fetch_mldata
def load_dataset(name):
"""
Loads a multi-label classification dataset.
Parameters
----------
name : string
Name of the dataset. Currently only 'yeast' is available.
"""
if name == 'yeast':
data = fetch_mldata('y... |
import sys
digit_string = int(sys.argv[1])
step = 1
string = []
for i in range(digit_string):
space_count = digit_string - i - 1
step_count = digit_string - space_count
# print(space_count, end = "")
# print(step_count)
for y in range(space_count):
print(" ", end = "")
for z in range(... |
# openpoiservice/server/models.py
from openpoiservice.server import db, ops_settings
from geoalchemy2 import Geography
import logging
logger = logging.getLogger(__name__)
class Pois(db.Model):
__tablename__ = ops_settings['provider_parameters']['table_name']
logger.info('table name for pois: {}'.format(__ta... |
# coding=utf-8
import datetime
import logging
import traceback
from config import config
def parse_frequency(s):
if s == "never" or s is None:
return None, None
kind, num, unit = s.split()
return int(num), unit
class DefaultScheduler(object):
queue_thread = None
scheduler_thread = None
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Jeroen Hoekx <jeroen.hoekx@dsquare.be>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
module: jboss
short_des... |
# Copyright © 2020 baneon - MIT License
# See `LICENSE` included in the source distribution for details.
code = {
# Exceptions
143: 'No available device detected',
144: 'No available devices detected',
145: 'No available Wi-Fi networks detected',
146: 'No active connection detected',
200: 'OK... |
from typing import Any, Callable, Dict, List, Tuple, Union
import pandas as pd
from ._base import (
_NonTrainableUnivariateModel,
_TrainableMultivariateModel,
_TrainableUnivariateModel,
)
from .data import to_events
from .metrics import f1_score, iou, precision, recall
class _NonTrainableUnivariateDetec... |
# Generated by Django 2.0.3 on 2018-03-10 09:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('human', '0010_auto_20180215_1343'),
]
operations = [
migrations.AlterModelOptions(
name='relationship',
options={'or... |
answer = input("Solve a problem: 4 * 100 - 54 = ")
print("Your answer: ", answer)
print("Right answer: ", 346)
|
from .utils import create_line_profile, get_value_from_config
enable_serializer_profiler = get_value_from_config("ENABLE_SERIALIZER_PROFILER", True)
def line_profiler_viewset(viewset):
"""
Decorator to profile all methods from a viewset line by line.
For all methods that were called during a request, an ... |
""""
File description
"""
import colorama
import logging
from copy import copy
__author__ = "Tommaso Mazza"
__copyright__ = "Copyright 2019, The rhapsodizer_project Project"
__version__ = "0.0.1"
__maintainer__ = "Tommaso Mazza"
__email__ = "bioinformatics@css-mendel.it"
__status__ = "Development"
__date__ = "29/10/... |
# 3rd party modules
import matplotlib.pyplot as plt
import numpy as np
# local modules
from callables import Constant
from callables import Circular
import draw
import wt_oscillators
def main():
sr = 1000
dur = 1.0
#--------------------------------------------------------------------------
# dr... |
from .conversions import *
import cv2
from enum import Enum
import numpy as np
class InsertionType(Enum):
NAIVE = 0
COLOR_TRANSFER = 1
POISSON_BLENDING_NORMAL = 2
POISSON_BLENDING_MIXED = 3
def insert_image(background_image_path,
foreground_image_path,
result_image... |
"""
LLDB Formatters for LLVM data types.
Load into LLDB with 'command script import /path/to/lldbDataFormatters.py'
"""
import lldb
import lldb.formatters.Logger
def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand('type category define -e llvm -l c++')
debugger.HandleCommand('type synthet... |
"""Random symmetric positive definite matrices."""
from typing import Sequence
import numpy as np
import scipy.stats
from probnum.typing import IntArgType
def random_spd_matrix(
rng: np.random.Generator,
dim: IntArgType,
spectrum: Sequence = None,
) -> np.ndarray:
"""Random symmetric positive defin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.