content stringlengths 5 1.05M |
|---|
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
import numpy as np
import torch
import torch.nn as nn
IMSIZE = 64
class VAE(nn.Module):
"""Multimodal Variational Autoencoder.
@param n_latents: integer
number of latent dimensions
"""
def __init__(self, n_latents, batch_size, training, imsize, use_cuda):
super(VAE, sel... |
import os, glob
from uuid import uuid4
from flask import Flask, request, render_template, send_from_directory
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
#loading and running the model
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app = Fl... |
from flask import Flask
app = Flask(__name__)
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/hello')
def hello_world():
return 'Hello from Phyton'
if __name__ == '__main__':
app.run(port=8080) |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from appcenter_sdk.api.distribute import distributeApi
from appcenter_sdk.api.alerting import alertingApi
from appcenter_sdk.api.account import accountApi
from appcenter_sdk.api.gdpr import gdprApi
from appcenter_sdk.api.build import... |
import svgwrite
if __name__ == "__main__":
drawing = svgwrite.Drawing(filename="text_on_line.svg", size=("100%", "100%"))
path = drawing.add(drawing.path(d="M 0 50 L 100 50", stroke="red", fill="none"))
text = drawing.add(drawing.text(""))
text_path = text.add(
svgwrite.text.TextPath(path.get... |
#DESAFIO 014: Escreva um programa que converta uma temperatura digitada em °C e converta para °F.
celsius = float(input('Informoe a temperatura em °C: '))
fahrenheit = ((celsius * 9)/5) + 32
msg = f'A temperatura de {celsius:.2f} °C corresponde a {fahrenheit:.2f} °F!'
print(msg) |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 08:58:37 2021
@author: michp-ai
"""
# This script is web automation for the Capstone project on ML rapid text labeling
# Before running this script in a different console start the web server by running main.py for the web app
# This is a simple demo script to illustr... |
from data_structures.doubly_linked_list_node import DoublyLinkedListNode
def test_doubly_linked_list_node():
node = DoublyLinkedListNode()
assert node.data is None
assert node.next is None
assert node.previous is None
node = DoublyLinkedListNode(1)
assert node.data == 1
assert node.previo... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Spotify AB
#
# 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... |
"""
This module defines core training functions for DeepD
"""
import tensorflow as tf
import numpy as np
import time
def get_mse(x, xhat):
mse = tf.reduce_mean(tf.square(x - xhat), name='MSE')
return mse
def get_xent(x, xhat):
xent = tf.compat.v1.losses.softmax_cross_entropy(x, xhat)
return xent
d... |
import win32con
import win32gui
import ctypes
from ctypes import wintypes
# container class for global hook
# this will store the HHOOK id and mouse information
class Hook:
def __init__(self):
self.hook = 0
self.m_struct = None
class MSLLHOOKSTRUCT(ctypes.Structure):
_fields_ = [("pt", wintypes.POINT),
("m... |
def y():
for i in range(10):
if i == 5:
return
yield i
for i in y():
print(i) |
import re
# 태그 제거
def relace_tag(content):
cleaner = re.compile('<.*?>')
cleantext = re.sub(cleaner, '', content)
return cleantext |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# author: jeremy.zhang(szujeremy@gmail.com, Shenzhen University, China)
import numpy as np
import SimpleITK as sitk
from skradiomics.utils.modules import FILTER_CLASSES
@FILTER_CLASSES.register_module(name='original')
def original_image(image, mask, settings, **kwargs):... |
import os.path
from typing import *
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
class Visualizer:
def __init__(
self,
show_figures: bool, save_directory: Optional[str],
figure_size: Tuple[float, float] = (4, 4),
color_dead: str = "w... |
from copy import copy
# def get_values(variables, seed=None, solution=None):
# if solution is not None:
# try:
# return [solution[x - 1] for x in variables]
# except IndexError:
# raise Exception('Solution have too few variables: %d' % len(solution))
# else:
# v... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'ArcSqlManagedInstanceLicenseType',
'ArcSqlServerLicenseType',
'ConnectionStatus',
'DefenderStatus',... |
import tensorflow as tf
import numpy as np
import data_reader
import modeleag as M
import network
import cv2
import os
MAXITER = 100000
class AIM(M.Model):
def initialize(self):
self.encoder = network.EncoderNet()
self.decoder = network.DecoderNet()
self.dis_z = network.DiscriminatorZ()
... |
from django.urls import path
from . import views
urlpatterns = [
path('othersclosets/', views.othersclosets, name="othersclosets"),
path('othersclosets_t/', views.subchoice, name="othersclosets_t"),
path('othersclosets_s/', views.search, name="othersclosets_s"),
] |
#!interpreter [optional-arg]
# -*- coding: utf-8 -*-
"""
file: tracklog.py
created: 1/1/2019
module: tracklog.py
project: pins_tiles
author: Dennis Schmitz
loads and saves tracklogs
"""
import logging
import os
import time
import dateutil
import matplotlib.pyplot as plt
import numpy as np
import... |
#!/usr/bin/env python2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import ctypes
import torch
# load seam-finding library:
FINDSEAM_LIB = ctypes.cdll.LoadLibrary(
'libexperimental_deeplearning_lvdmaaten_adver... |
# allow-warning: converting unicode literal to str
# currently broken:
# import os.path
import os
r1 = os.urandom(8)
r2 = os.urandom(8)
print len(r1), len(r2), type(r1), type(r2), r1 == r2
|
import boto3
import os.path
from flask import current_app as app
from werkzeug.utils import secure_filename
def s3_upload(source_file):
source_filename = secure_filename(source_file.data.filename)
# Connect to S3 and upload file.
s3 = boto3.client(
"s3",
aws_access_key_id=app.co... |
import io
import os
import re
import textwrap
import typing as tp
from statistics import mean
from string import ascii_letters
from subprocess import check_output
from PIL import Image, ImageDraw, ImageFont
from PIL.ImageFont import FreeTypeFont
from brother_ql import BrotherQLRaster, conversion
from brother_ql.backen... |
from datetime import datetime
import re
from sqlalchemy.dialects.postgresql import HSTORE
from sqlalchemy.schema import UniqueConstraint, CheckConstraint
from sqlalchemy.orm import validates
from validators import url as url_validator
from core.database import (
relationship,
Boolean,
Column,
DateTim... |
import torch
import torch.nn as nn
class Lovasz(nn.Module):
"""Lovasz Loss. Cf: https://arxiv.org/abs/1705.08790 """
def __init__(self):
super().__init__()
def forward(self, inputs, targets, classes_weights, tiles_weights, config):
N, C, H, W = inputs.size()
assert C >= 2, "Clas... |
from datetime import datetime
from core.config import SQLITE_URL
from models.models import LinkedLists, User
from tortoise.query_utils import Q
from tortoise.contrib.fastapi import register_tortoise
def init(app):
register_tortoise(
app,
db_url=SQLITE_URL,
modules={'models': ['models.model... |
# -*- coding: utf8 -*-
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678
# 上边一行用来对比一行代码是否超过80个字符,超过换行
import tkinter as tk
import random
import codecs
root = tk.Tk(className = '范例循环模型')
root.geometry('800x400')
count = 0 # 因为点击两次show按钮才完成一个完整的英译汉或者汉译英过程,这里通过count为0或1来判断
e_or_c = 0 ... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import logging
import sys
from xmind2testcase.zentao import xmind_to_zentao_csv_file
from xmind2testcase.testlink import xmind_to_testlink_xml_file
from xmind2testcase.utils import get_absolute_path, xmind_testcase_to_json_file
from webtool.application import launch
"""
A t... |
import logging
from elasticsearch import Elasticsearch
from crawlerx_server.settings import ELASTIC_SEARCH_USERNAME, ELASTIC_SEARCH_PASSWORD, ELASTIC_SEARCH_HOSTNAME, \
ELASTIC_SEARCH_PORT
class ELKConnection:
elk_uri = 'http://' + ELASTIC_SEARCH_USERNAME + ':' + ELASTIC_SEARCH_PASSWORD + '@' + ELASTIC_SEARC... |
import os
PROJECT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
SCRAP_TMP = os.path.join(DATA_DIR, "db_dump.tmp")
def split_dict(target_dict, nums):
"""
Split a dictionary whose value is a list into multiple smaller dictionary with same ke... |
import time
from concurrent.futures import ThreadPoolExecutor
import buzzard as buzz
import numpy as np
def work(i):
j = i % 9 + 1
assert buzz.env.significant == 42
with buzz.Env(significant=j):
assert buzz.env.significant == j
time.sleep(np.random.rand() / 100)
assert buzz.env.sig... |
from django import forms
from .models import Transaction
class TransactionForm(forms.Form):
name = forms.CharField(label='Your First name', max_length=20)
surname = forms.CharField(label='Your Last name', max_length=20)
email = forms.EmailField(label='Your e-mail', max_length=20)
price_range = forms.IntegerField(m... |
import warnings
import re
from xigt.mixins import (
XigtContainerMixin,
XigtAttributeMixin
)
from xigt.errors import XigtError
# name_re approximately follows the XML 1.0 spec for Name productions,
# so long as the re character classes correspond to XML productions.
# This also excludes colons in the name (b... |
##########################################################################
#
# Copyright (c) 2019, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
# encoding: utf-8
#
# munki.py
# Managed Software Center
#
# Created by Greg Neagle on 2/11/10.
# Copyright 2010-2014 Greg Neagle.
#
# 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
#
# ... |
'''
Created on 2018年10月30日
@author: yinyayun
'''
from loader.hook.DynamicLoadByHooks import DynamicLoadByHooks
if __name__ == '__main__':
base = '../package/demo'
dynamic = DynamicLoadByHooks(base)
print("-----create 001.ImportDemo")
ins1 = dynamic.create_ins('001', 'ImportDemo', 'ImportDemo')
pri... |
import argparse
class VerboseStore(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError('nargs not allowed')
super(VerboseStore, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace,... |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2022.03.11
# [Scraping Investopedia using selenium python - Stack Overflow](https://stackoverflow.com/questions/71443533/scraping-investopedia-using-selenium-python/71444720#71444720)
from selenium import webdriver
from selenium.webdriver.common.by imp... |
zhihu_headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
'referer': 'https://www.zhihu.com/',
'cookie' : '会出错呦'
} |
"""
title : node.py
description : Model of the node
author : Amanda Garcia-Garcia
version : 0
python_version : 3.6.1
"""
import Crypto
import binascii
from db import db
from Crypto.Hash import SHA, SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5, PKCS... |
from tests import ScraperTest
from recipe_scrapers.nihhealthyeating import NIHHealthyEating
# test recipe's URL
# https://healthyeating.nhlbi.nih.gov/recipedetail.aspx?linkId=17&cId=10&rId=247
class TestNIHHealthyEatingRecipesScraper(ScraperTest):
scraper_class = NIHHealthyEating
def test_host(self):
... |
# -*- coding: utf-8 -*-
"""
The socket api module.
======================
The module has the SocketApi class, that is a underlying class for socket.socket object.
"""
import socket
import struct
from . import protocol
from .utils import to_bytes
class SocketApi(object):
"""
The api to handle socket operati... |
import traceback
class ActionBase(object):
def __init__(self, *args, **kwargs):
pass
def _setup(self):
pass
def _execute(self):
pass
def _cleanup(self):
pass
def run(self):
try:
self._setup()
result = self._execute()
self._cleanup()
except:
result = False
traceback.print_exc()
retur... |
# pylint: disable=unused-variable
from cv2 import cv2
import numpy as np
import os
import time
import random
import sys
from tqdm import tqdm
import json
from core.match_func import sift
from core.match_func import match_template as match
import threading
class base_unit():
def __init__(self, device, templates):
... |
import logging
from os import getenv, environ
import boto3
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
DYNAMODB_TABLE: str = environ["DYNAMODB_TABLE"]
AWS_DEFAULT_REGION: str = getenv("AWS_DEFAULT_REGION", "... |
from django.db import models
from django.core.validators import MinValueValidator
class Topping(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Pizza(models.Model):
name = models.CharField(max_length=255, unique=True)
price = mod... |
# Copyright (c) 2020 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 in ... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from django.core.management.base import BaseCommand
from datawinners.main.couchdb.utils import all_db_names
from datawinners.main.ut_couch_fixtures import load_data, load_ft_data
from datawinners.main.database import get_db_manager
from datawinners.main.management.sync_change... |
###
# Copyright (c) 2002-2004, Jeremiah Fincher
# Copyright (c) 2010-2011, 2013, James McCoy
# Copyright (c) 2010-2021, The Limnoria Contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import ReadWordDict
import Lemmatizer
from nltk.stem.wordnet import WordNetLemmatizer
lmzer = WordNetLemmatizer()
lmdb = Lemmatizer.LemmaDB()
lmdb.load("../../DataBase/English/ECDICTData/lemma.en.txt")
def lemmatize(word):
res = lmdb.word_stem(word)
if res is None:
... |
# Lint as: python3
# Copyright 2018 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 ... |
#!/usr/bin/env python3
# coding: utf-8
import unittest
from .base_test import BaseTest
from .base_test import ThreadQueryExecutor
from .base_test import wait_checkpointer_stopevent
from .base_test import wait_bgwriter_stopevent
class EvictionTest(BaseTest):
def test_eviction_txn(self):
node = self.node
node.app... |
### import from ml_pipeline
import ml_pipeline
import py_starter as ps
import dir_ops as do
import os
file_Path = do.Path( os.path.abspath(__file__) )
name = file_Path.root.split( ml_pipeline.ML_Models.Models.SUFFIX )[0]
repo_Dir = file_Path.ascend()
custom_Model_module = do.Path.import_module_path( repo_Dir.... |
m = 1
num1 = float(input('Digite o primeiro valor: '))
num2 = float(input('Digite o segundo valor: '))
while m != 0:
print('''
Você deseja:
[1] Somar
[2] Multiplicar
[3] Maior entre eles
[4] Digitar novos valores
[5] Sair do programa
''', end='')
escolha = int(input('''
Escolha: '''))
if escolha == 1:
... |
from empire.python.typings import *
from tokenize import tokenize
from io import BytesIO
from empire.betsiamites.python.lexer.specialized_token import SpecializedToken
class PythonLexer:
def __init__(self, raw_code: str):
self._tokenized_lines: List[SpecializedToken] = list()
token_lines = toke... |
import random
import math
from vmengine import Program
chance0 = 0.08
chance1 = 0.1
chance2 = 0.01
chance3 = 0.008
defaultLength = 5
class Evolving(Program):
'''This class allows regular programs to be mutated and evaluated.'''
def __init__(self, code, fitness):
if code == []:
Progra... |
# Copyright (c) 2011-2016 Rackspace US, 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 ... |
from __future__ import absolute_import
#
# Partnerbox E2
#
# $Id$
#
# Coded by Dr.Best (c) 2009
# Support: www.dreambox-tools.info
#
# 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... |
import logging
from typing import List, Literal, Optional
from pydantic import Field
from pydantic.class_validators import validator
from pydantic.types import NonNegativeInt
from hydrolib.core.io.ini.models import INIBasedModel, INIGeneral, INIModel
from hydrolib.core.io.ini.util import (
get_split_string_on_del... |
import mlflow
import click
import logging
import pandas as pd
import time
import numpy as np
import torch
import pytorch_lightning as pl
from pathlib import Path
@click.command(help="Make predictions")
@click.option("--model_name", default='mnist_cnn', type=str)
@click.option("--model_version", default=1, type=int)
@... |
'''
Product Grad_Cam Heatmap
Paper https://arxiv.org/abs/1610.02391
Copyright (c) Xiangzi Dai, 2020
'''
import os
import cv2
import numpy as np
import torch
from torch.autograd import Function
from torchvision import models
import sys
from model import *
from Resnet import *
from matplotlib import py... |
from rlpyt.utils.collections import namedarraytuple
AgentInfo = namedarraytuple("AgentInfo", ["dist_info", "value"])
AgentInfoRnn = namedarraytuple("AgentInfoRnn", ["dist_info", "value", "prev_rnn_state"])
|
from models.modeling.deeplab import DeepLab as DeepLabV3Plus
from models import CAC
|
"""module for strict modifier."""
from .modifier import Modifier
from ..fdef import FDef, Strictness
class StrictModifier(Modifier):
"""A strict modifier marks object to disallow undefined keys."""
def define(self, fdef: FDef) -> None:
fdef._strictness = Strictness.STRICT
|
from django.urls import path
from api.views import category_views as views
urlpatterns = [
path('', views.getCategories, name="categories"),
path('create/', views.createCategory, name="category-create"),
path('<str:category_id>/', views.getCategory, name="category"),
path('update/<str:category_id>... |
import unittest
from pymote.algorithms.niculescu2003.trilaterate import Trilaterate
from pymote.simulation import Simulation
from pymote.sensor import TruePosSensor
from pymote.networkgenerator import NetworkGenerator
from pymote.algorithms.niculescu2003.dvhop import DVHop
class TestNiculescu2003(unittest.Tes... |
import unittest
import sympy
from means.util.sympyhelpers import to_sympy_matrix, assert_sympy_expressions_equal, sympy_expressions_equal
from means.util.sympyhelpers import substitute_all
class TestSympyHelpers(unittest.TestCase):
def test_substitute_all_on_matrix(self):
to_substitute = to_sympy_matrix(... |
from dataclasses import dataclass
from datetime import date, datetime
from enum import Enum
from typing import List, Optional
from uuid import UUID
from jsonmarshal import json_field
class EntityType(Enum):
INDIVIDUAL = "INDIVIDUAL"
COMPANY = "COMPANY"
class CountryOfIncorperation(Enum):
AFG = "AFG"
... |
import sys
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
from tiva import TivaController
Tiva = TivaController(units_per_cm=1, arm1_cm=45, arm2_cm=20,
x_offset_cm=33, y_offset_cm=-10, bufsize=8)
n_steps = 50
plot = 'point'
clear = True
if plot == 'random':
x = np.random.randint(... |
import json
path = input("Path of the file (add .json): ")
print("Opening the json file")
config = json.load(open(path))
var_import = """from flask import Flask, jsonify
app = Flask(__name__)
"""
list_func = []
print("Creating the Flask APIs template")
for elem in config['api']:
parameters = []
... |
import torch
from ..ops import sqrtm
from ..rand import definite
from unittest import TestCase
from torch.autograd import gradcheck
class MatrixSquareRootTest(TestCase):
'''Test sqrtm and MatrixSquareRoot.'''
seed = None
dims = 20
sigma = 10
dtype = torch.float64
device = torch.device('cpu')
... |
from flask import Flask,request
import jwt
import os
app = Flask(__name__)
key ="this is a secret key for encryption"
@app.route('/')
def index():
return("<b>Welcome, send post request <a href='/login'>here</a> to check api")
@app.route("/login/", methods=["POST","GET"])
def login():
email ="dummy@email"
p... |
from twitter import search_tweets
from slack import read_last_id, post_message
from const import post_message_template, result_header_template, query_strings
from secret_info import slack_channel_id, slack_direct_message_id
from jinja2 import Template
def post_tweets_to_slack(tweets):
"""
Search tweets and po... |
from dataclasses import dataclass
from typing import Dict, List, Optional
from .result_type import ResultType
@dataclass(frozen=True)
class Queries:
value: float
captured_queries: List[Dict[str, str]]
diff: Optional[float] = None
def from_dict(d):
return Queries(value=d["value"], diff=None, ... |
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from .configs.settings import DEBUG, MEDIA_ROOT, MEDIA_URL
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('djangosige.apps.base.urls')),
url(r'... |
import os
def fileids(n):
"""
Function to edit test.fileids.
"""
os.system("truncate -s 0 test.fileids")
f = open("./test.fileids", "w+")
for i in range(1, (int(n) + 1)):
f.write("test" + str(i) + "\n")
f.close()
def transcription(n):
"""
Function to edit test.transcription.
"""
... |
# coding=utf-8
# Copyright 2018-2020 EVA
#
# 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 ... |
from regex import (
extract_course_times,
split_on_multiple_chars,
get_all_hashtags_and_links,
match_first_paragraph,
find_double_words,
match_ip_v4_address,
)
def test_extract_course_times():
expected = ["01:47", "32:03", "41:51", "27:48", "05:02"]
assert extract_course_times() == exp... |
"""
Calibration Plot Widget
-----------------------
"""
from collections import namedtuple
import numpy as np
from AnyQt.QtWidgets import QListWidget
import pyqtgraph as pg
import Orange
from Orange.widgets import widget, gui, settings
from Orange.widgets.evaluate.utils import check_results_adequacy
from Orange.wi... |
from ..utils import Object
class ChangeImportedContacts(Object):
"""
Changes imported contacts using the list of current user contacts saved on the device. Imports newly added contacts and, if at least the file database is enabled, deletes recently deleted contacts.Query result depends on the result of the ... |
from PIL import Image
import numpy as NP
from matplotlib import pyplot as plt
i=Image.open('i5.jpg')
iar=NP.asarray(i)
#print iar
b= len(iar)
p=0
for ii in iar:
for jj in ii:
p+=1
#print p
'''a=[]
for j in iar:
for k in j:
a.append(k[0])
#print a
s=int(NP.sum(a)/len(a))'... |
import torch
import torch_sparse
from kplex_pool import kplex_cpu, cc_cpu
def connected_components(edge_index, num_nodes=None):
"""Find the connected components of a given graph.
Args:
edge_index (LongTensor): Edge coordinate matrix.
num_nodes (int, optional): Number of nodes. Defaults to ... |
import time
#from datetime import datetime as dt
from dateutil import tz
import datetime
dt = datetime.datetime
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# SETUP-UP
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
""" CHOOSE YOUR OS (Windows OR Linux) """
my_OS = "Wind... |
import atexit
import numpy as np
import os
import cv2
import dlib
import keras
from keras import backend as K
dlib_detectors = []
keras_model = None
is_initialized = False
@atexit.register
def onExit():
global dlib_detectors
global keras_model
if keras_model is not None:
del keras_model
... |
# -*- coding: utf-8 -*-
"""
@author: Aghiles Salah
"""
import numpy as np
from .base_method import BaseMethod
from ..utils.common import safe_indexing
from ..experiment.result import CVResult
class CrossValidation(BaseMethod):
"""Cross Validation Evaluation Method.
Parameters
----------
data: ... ,... |
import numpy as np
from sklearn.svm import SVC
from controller.c_stock_daily import CStockDaily
class StockDailySvm(object):
def __init__(self):
self.name = 'Svm'
@staticmethod
def train():
StockDailySvm.model = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
d... |
'''
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__... |
from captcha.fields import ReCaptchaField
from crispy_forms import helper
from crispy_forms.layout import Submit, Hidden
from django import forms
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.translation import ugettext_lazy as _
... |
"""
This is default module controller
It define default routes
"""
from flask import render_template
from flask import request
from flask import flash
from flask import redirect
from flask import url_for
from flask_login import login_user
from flask_login import logout_user
from flask_login import current_user
from a... |
# md5 : 2581a649cb309fd3ce31a3eec84539cb
# sha1 : fa0797344e6bb57e08eb6b59c2985462b340fa53
# sha256 : 2deaf7a4b008d62eeb1799576fe1faf311c0fc538622c63f4ceaee1d30b71a8b
ord_names = {
1: b'??0CStringManager@@QAE@ABV0@@Z',
2: b'??0CStringManager@@QAE@XZ',
3: b'??0DataStorageWrapper@@AAE@V?$shared_ptr@VDataStor... |
import os
import pkg_resources
import functools
import comtypes.client
import contextlib
def raises_error(callable, exception=Exception):
try:
callable()
except exception:
return True
return False
def typelibs_generated():
import_SG = functools.partial(
__import__, 'comtypes.... |
from __future__ import absolute_import
#
# Copyright (c) 2020 Juniper Networks, Inc. All rights reserved.
#
import gevent
import logging
import requests
from testtools.matchers import Equals
import unittest
from flexmock import flexmock
import sseclient
from . import test_case
from vnc_api.vnc_api import *
from cfgm_... |
from .base import IODescriptor
from .file import File
from .json import JSON
from .text import Text
from .image import Image
from .numpy import NumpyNdarray
from .pandas import PandasSeries
from .pandas import PandasDataFrame
from .multipart import Multipart
__all__ = [
"File",
"Image",
"IODescriptor",
... |
import os
import copy
import shutil
import datetime
import numpy as np
from functools import wraps
from time import time
from pyaspect.specfemio.headers import ForceSolutionHeader
from pyaspect.specfemio.headers import SolutionHeader
from pyaspect.specfemio.headers import StationHeader
from pyaspect.specfemio.header... |
from django.urls import include, path
from rest_framework import routers
from .viewsets import (
DeviceViewSet,
NotificationSettingsViewSet,
ParameterViewSet,
TestHistoryViewSet,
TestViewSet,
)
router = routers.DefaultRouter()
router.register("devices", DeviceViewSet, basename="device")
router.reg... |
def _generate_function(identifier):
class Function:
def __init__(self, field='*'):
self.field = field
def evaluate(self):
if hasattr(self.field, 'evaluate'):
field = self.field.evaluate()
else:
field = self.field
return... |
import numpy as np
import cv2
import tritonclient.grpc as grpc_client
import tritonclient.http as httpclient
MODEL_NAME = 'thymio_model'
URL = 'localhost:8000/v2/models/'
TRITON_CLIENT = httpclient.InferenceServerClient(url=URL)
INPUT_NAME = "input_tensor:0"
def get_bytes_img_request(batch=1):
img = np.random.r... |
from flask import Flask, render_template, session, request, redirect
app = Flask(__name__)
app.secret_key = 'my_secret_key'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process/<id>', methods = ['POST'])
def process(id):
print ("I love flask! And {}".format(id))
return re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.