content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from pathlib import Path
from typing import List, Tuple
import numpy as np
from relaxations.interval import Interval
from relaxations.linear_bounds import LinearBounds
def load_spec(spec_dir: Path, counter: int) -> List[Tuple[List[Interval], Interval, LinearBounds]]:
parameters = list()
interval_bounds = li... | python |
import cv2
import numpy as np
def parse_mapping(ground_truth):
map = {}
f = open(ground_truth, "r")
for line in f.readlines():
label = line.strip().split(",")[1]
if label not in map:
map[label] = len(map)
def parse_data(ground_truth):
images = {}
label_dict = {}
f ... | python |
# 入力フレーズに対してコサイン類似度を求めていく
# 類似度の結果をjson, pklで出力
from sentence_transformers import SentenceTransformer
import numpy as np
import torch
from torch import nn
import pickle
import json
# 今回の入力
key_phrase = 'pulls the trigger'
# データセットの読み込み
with open('combined_word2id_dict.pkl', 'rb') as f:
phrase_dict = pickle.load(f... | python |
s = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0 and c % 2 == 1:
s += c
cont += 1
print(f'A soma de {cont} valores múltiplos de 3 entre 1 e 501 é {s}')
| python |
import math
import numpy as np
import os
from scipy import ndimage
from scipy.interpolate import RegularGridInterpolator as rgi
import common
import argparse
import ntpath
# Import shipped libraries.
import librender
import libmcubes
from multiprocessing import Pool
use_gpu = True
if use_gpu:
import libfusiongpu ... | python |
arr=list(map(int,input().rstrip().split()))
fff=list(map(int,input().rstrip().split()))
a=0
for i in range(len(arr)):
a=a+abs(arr[i]-fff[i])
print(a)
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-12-04 12:13
from __future__ import absolute_import, unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('icds_reports', '0080_merge_20181130_1818'),
]
operations = [
migr... | python |
import storage
import nomadlist
import wikivoyage
def build(cities=None):
index_guides(cities or index_cities())
return True
def index_cities():
cities = nomadlist.list_cities()
storage.upsert_cities(cities)
return cities
def index_guides(cities):
city_docs = map(build_guide, cities)
... | python |
# -*- coding: utf-8 -*-
"""
@Created on: 2019/5/23 16:23
@Author: heyao
@Description:
"""
import os
import warnings
from knowledge_graph.local_config import DevelopmentConfig
try:
from knowledge_graph.production_config import ProductionConfig
except ImportError:
warnings.warn("you dont have production conf... | python |
"""Dataset setting and data loader for MNIST."""
import torch
from torchvision import datasets, transforms
import params
def get_svhn(train):
print("SVHN Data Loading ...")
train_dataset = datasets.SVHN(root='/home/hhjung/hhjung/SVHN/', split='train',
transform=tran... | python |
from collections import namedtuple
ConnectArgsType = namedtuple('ConnectArgsType', [
'verify', 'verify_expiration', 'key', 'audience', 'issuer', 'algorithm', 'auth_header_prefix', 'decode_options'
])
CONNECT_ARGS = ConnectArgsType(
verify=None,
verify_expiration=None,
key=None,
audience=None,
... | python |
#!/usr/bin/python3
"""
This module contains the function is_same_class
"""
def is_same_class(obj, a_class):
"""return true if obj is the exact class a_class, otherwise false"""
return (type(obj) == a_class)
| python |
from libtad.base_service import BaseService
from libtad.datatypes.places import Place
from libtad.common import XmlUtils
import libtad.constants as Constants
import xml.etree.ElementTree as ET
from urllib.parse import ParseResult, urlunparse, urlencode
from urllib.request import urlopen, Request
from ssl import SSLCont... | python |
#!/usr/bin/env python3
# zeroex00.com
# rfc1413
import argparse
import socket
import sys
import threading
master_results = []
master_banners = {}
master_errors = []
def main(args):
if not args.query_port and not args.all_ports:
print("[!] you must specify at least one port or -a")
exit(2)
... | python |
import json
import sys
from twisted.internet import reactor, defer
from twisted.web.client import getPage, HTTPClientFactory
try:
from twisted.internet import ssl
except ImportError:
ssl = None
class Jar:
def __init__(self, name_long, name_short, url):
self.name_long = list(name_long)
s... | python |
import base64
import configparser
import click
import requests
from logbook import *
# from requests.cookies import RequestsCookieJar
import controller as ctrl
from config.base_settings import CAPTCHA_MODEL_NAME, TIMEOUT, USE_PROXY
from controller.url_config import url_captcha, url_login
# from service.log import in... | python |
constants.physical_constants["neutron to shielded proton mag. mom. ratio"] | python |
""" Test for building manifests for COMBINE archives
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2021-07-19
:Copyright: 2021, Center for Reproducible Biomedical Modeling
:License: MIT
"""
from biomodels_qc.utils import EXTENSION_COMBINE_FORMAT_MAP
import os
import unittest
class CombineArchiveCreationTestCase(uni... | python |
from . import CostFunctions
from . import ActivationFunctions
from . import PyNet
#from . import tfNet #got rid of tensorflow
from . import Autoencoder
from .NeuralNetwork import NeuralNetwork ,NeuralNetworkArray
from .EvolutionaryNeuralNetwork import EvolutionaryNeuralNetwork,PyEvolutionaryNeuralNetwork
from .Tests i... | python |
{
"targets": [
{
"target_name": "node_ovhook",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"./src",
],
'defin... | python |
import ephem
from datetime import datetime
import pandas as pd
import numpy as np
import requests
from flask import Flask, render_template, session, redirect, request
import folium
import geocoder
app = Flask(__name__)
def get_latlng():
#Get user lat long via IP address
myloc = geocoder.ip('me')
return... | python |
from bcc import BPF
# Hello BPF Program
bpf_text = """
#include <net/inet_sock.h>
#include <bcc/proto.h>
// 1. Attach kprobe to "inet_listen"
int kprobe__inet_listen(struct pt_regs *ctx, struct socket *sock, int backlog)
{
bpf_trace_printk("Hello World!\\n");
return 0;
};
int kprobe__ip_rcv(struct pt_regs... | python |
from tensornetwork.block_sparse import index
from tensornetwork.block_sparse import charge
from tensornetwork.block_sparse import blocksparsetensor
from tensornetwork.block_sparse import linalg
from tensornetwork.block_sparse.blocksparsetensor import (BlockSparseTensor,
... | python |
from SuperImpose import SuperImpose
class SuperImposeFields(SuperImpose):
'''
SuperImpose subclass implementing specific functionality to
super-impose all field images on background image
'''
@staticmethod
def run_super_impose_on_all_fields(back_rgba_img, fields_img_loc_dict):
'''
... | python |
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.index, name ='index'),
path('<int:article_id>/', views.detail, name ='detail'),
path('<int:article_id>/leave_comment/', views.leave_comment, name ='leave_comment'),
] | python |
# JEWELS AND STONES LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def numJewelsInStones(self, jewels, stones):
# creating a variable to track the count.
count = 0
# creating a for-loop to iterate for the elements... | python |
[
{
'inputs': ['formula'],
'output': 'Property Band gap'
}, {
'inputs': ['formula', 'Temperature (Property Band gap)'],
'output': 'Property Band gap'
}, {
'inputs': ['formula'],
'output': 'Property Color'
},{
'inputs': ['formula', 'Property Band ga... | python |
#-*- encoding:utf-8 -*-
import json
import unittest
import responses
try:
from unittest import mock
except:
import mock
from nta import (
NaverTalkApi
)
from nta.models import(
CompositeContent, Composite, ElementData, ElementList,
ButtonText, ButtonLink, ButtonCalendar, QuickReply
)
class TestN... | python |
from flask import Flask, request, Response
import requests, json
app = Flask(__name__)
@app.route('/webhook', methods=["POST"])
def webhook():
print("Request received!")
print(request.json);
return relay(request.json)
def relay(data):
print("Relaying Request with data :" + json.dumps(data... | python |
import unittest.mock as mock
from mtsync.action import ActionKind
from mtsync.connection import Connection
from mtsync.imagined import Imagined
from mtsync.settings import Settings
from mtsync.synchronizer import Synchronizer
from rich.console import Console
from testslide import StrictMock
from testslide.dsl import c... | python |
# Generated by Django 2.0.2 on 2018-08-15 16:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0040_page_draft_title'),
('pymba', '0006_auto_20180316_1857'),
]
operations = [
migr... | python |
'''
This script has functions in it which are used in network which evaluate images.
If this script here is run it returns the object_dc-score of each segmented object by the predicition with respect to the groundtruth
'''
import os
import skimage
import scipy
import numpy as np
import matplotlib.pyplot as plt
######... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 06:41:54 2016
@author: piotr at nicecircuits.com
"""
from libraryManager.library import libraryClass
from libraryManager.part import part
from footprints.footprintSmdQuad import footprintQfp
from footprints.footprintSmdDualRow import footprintTssop
from libraryManager... | python |
'''
Pattern:
Enter the number of rows: 5
A
A B A
A B C A B
A B C D A B C
A B C D E A B C D
'''
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
print(' '*(number_rows-row),end=' ')
for column in range(1,row+1):
pri... | python |
disliked_ids = {
"items" : [ {
"track" : {
"album" : {
"name" : "W Hotel (feat. Smokepurpp, Blueface)"
},
"id" : "3Ap32KanuR59wfKcs9j2pb",
"name" : "W Hotel (feat. Smokepurpp, Blueface)"
}
}, {
"track" : {
"album" : {
"name" : "Me Molesta"
},
"id... | python |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... | python |
#! /usr/bin/python
import sys
import os
import sqlite3
import datetime
import threading
import Queue
class SQLiteThread(threading.Thread):
def __init__(self, config, logger):
threading.Thread.__init__(self)
self.setDaemon(True)
self.filename = config.get_setting("sqlite_filename", "") ... | python |
"""
Unit tests for our validators
"""
from dbas.database.discussion_model import ReviewDelete
from dbas.tests.utils import TestCaseWithConfig, construct_dummy_request
from dbas.validators.core import has_keywords_in_json_path, spec_keyword_in_json_body
from dbas.validators.reviews import valid_not_executed_review
cl... | python |
#!/usr/bin/python
import pymysql
import config
def add_feedback(email,f_text):
conn,cursor=config.connect_to_database()
sql="insert into feedbacks(email,f_text) values('%s','%s')"%(email,f_text);
try:
cursor.execute(sql)
conn.commit()
return "11"
except:
conn.rollback()
return "0"
def check_same_feedback... | python |
import unittest
from point import Point
class PointTests(unittest.TestCase):
"""Tests for Point."""
def test_attributes(self):
point = Point(1, 2, 3)
self.assertEqual((point.x, point.y, point.z), (1, 2, 3))
point.x = 4
self.assertEqual(point.x, 4)
def test_string_repres... | python |
from bigchaindb_driver import BigchainDB
from bigchaindb_driver.crypto import generate_keypair
from time import sleep
from sys import exit
def asset_creation(farmer, tomatos, tomatos_metadata, bdb):
prepare_cr_tx = bdb.transactions.prepare(
operation = 'CREATE',
signers = farmer.public_key,
asset = tomatos,
... | python |
from __future__ import print_function
from memorytestgame.lib.game import Game
import time
import unittest
class GameTestCase(unittest.TestCase):
LEDS = ()
SWITCHES = ()
COUNTDOWN = 0
GAME_TIME = 0
SCORE_INCREMENT = 1
game = None
def setUp(self):
self.game = Game(self.LEDS, s... | python |
"""
Otrzymujesz liste liczb oraz liczbe n. Lista reprezentuje ceny sznurka o dlugosci
rownej indeksowi powiekszonemu o 1. Zaleznosc miedzy cenami i dlugoscia sznurka jest
przypadkowa. Przykladowo sznurek o dlugosci rownej 2 jednostkom moze kosztowac tyle
samo co sznurek o dlugosci rownej 3 jednostkom i byc piec razy dr... | python |
# PhotoBot 0.8 beta - last updated for NodeBox 1rc4
# Author: Tom De Smedt <tomdesmedt@trapdoor.be>
# Manual: http://nodebox.net/code/index.php/PhotoBot
# Copyright (c) 2006 by Tom De Smedt.
# Refer to the "Use" section on http://nodebox.net/code/index.php/Use
from __future__ import print_function
ALL = ['canvas', '... | python |
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | python |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | python |
from ..container import container
from ..parallel import rank0_obj
import logging
logger: logging.Logger = rank0_obj(container.get(logging.Logger))
# logger: logging.Logger = container.get(logging.Logger)
| python |
from django.contrib import admin
from personal.models import ToDo
from .to_do import ToDoAdmin
admin.site.register(ToDo, ToDoAdmin)
| python |
from swagger_server.models.beacon_concept import BeaconConcept # noqa: E501
from swagger_server.models.beacon_concept_with_details import BeaconConceptWithDetails # noqa: E501
from swagger_server.models.beacon_concept_detail import BeaconConceptDetail
from swagger_server.models.exact_match_response import ExactMatchR... | python |
import pyautogui as pt
import pyperclip as pc
from pynput.mouse import Controller, Button
from time import sleep
from whatsapp_responses import response
#Mause click workaround for MAc os
mouse = Controller()
#Instruction for our whatsapp Bot
class WhatsApp:
#define the starting values
def __init__(self, sp... | python |
import json
import logging
import os
import uuid
from datetime import datetime, timedelta
import boto3
import telegram
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
logger = logging.getLogger()
if logger.handlers:
for handler in logger.handlers:
logger.removeHandler(handler)
logging.basic... | python |
import pandas as pd
from IPython import embed
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print('please input params: <tnse.csv> file')
exit(1)
path = sys.argv[1]
df = pd.read_csv(path)
filtered_df = []
i=0
for idx, r in df.iterrows():
if(r['domain']=='a... | python |
class TimePattern(object):
def __str__(self):
raise NotImplementedError('Please implement __str__ function')
class SimpleTimer(TimePattern):
def __init__(self, seconds=0, minutes=0, hours=0):
self.seconds = seconds
self.minutes = minutes
self.hours = hours
def __str__(se... | python |
from setuptools import setup, find_packages
setup(
name = "cascade",
version = "0.1",
packages = find_packages(),
install_requires = ['progressbar', 'imaplib2'],
author = "Oz Akan",
author_email = "code@akan.me",
description = "Cascade copies e-mails between IMAP servers",
license = "Ap... | python |
# Fichier permettant de moduler les differentes methodes de clustering
try:
# Import generaux
import numpy as np
import pylab
import sys
import platform
import matplotlib.pyplot as plt
import re
# Import locaux
import kmeans
import rkde
except:
exit(1)
... | python |
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, PasswordField
from wtforms import HiddenField, TextAreaField, FileField, SubmitField
from wtforms.validators import DataRequired, NumberRange
ATTR_DATA = 'data'
ATTR_ACTION = 'action'
ATTR_MANAGER = 'manager'
ATTR_KEY_LEN = 'length'
ATTR_K... | python |
# coding=utf-8
import random
from common import constant
from common import errcode
from dao.sms.sms_dao import SmsDao
from handlers.base.base_handler import BaseHandler
from mycelery.tasks import send_sms_task
class SmsChangePhoneHandler(BaseHandler):
methods = ['POST']
def __init__(self):
expect_r... | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1_unlinked = []
... | python |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/labelbox/1_CocoExporter.ipynb (unless otherwise specified).
__all__ = ['UnknownFormatError', 'coco_from_json', 'make_coco_metadata', 'add_label', 'append_polygons_as_annotations',
'label_to_polygons', 'LOGGER']
# Cell
"""
Module for converting labelbox.... | python |
# Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | python |
"""
authentication/views.py
Created on Oct. 23, 2017
by Jiayao
"""
from __future__ import (absolute_import)
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.contrib.auth import (authenticate, login, logout)
fro... | python |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a,b,c,d=[int(input())for _ in[0]*4]
print('10'[a!=d or (a<1 and d<1 and c>0)]) | python |
from flask import Blueprint
from flask import Response
from flask import abort
from flask import g
from flask import jsonify
from flask import request
from flask import current_app
from gleague.api import admin_required
from gleague.api import login_required
from gleague.core import db
from gleague.models import Match... | python |
# Notes: copied inspect.py, dis.py, and opcodes.py into Jython dir (replacing stub inspect.py)
# Opcode will not work as using JVM, but required by dis.py, which was required by inspect.py
# only want functionality of getting source lines.
# Also copied textwrap.py?
# support for using tk
import java.io
from java.lang... | python |
from selenium.webdriver.support.ui import Select
class ContactHelper:
def __init__(self, app):
self.app = app
def open_contact_page(self):
wd = self.app.wd
if not (wd.find_element_by_title("Search for any text") and wd.find_element_by_name("add")):
wd.find_element_by_link_... | python |
def XXX(self, root: TreeNode) -> int:
if root is None:
return 0
m = 10 ** 5 # m为最小深度
def bfs(d, node):
nonlocal m
if node.left is None and node.right is None:
m = min(m, d)
return
bfs(d + 1, node.left) if node.left else None
bfs(d + 1, node.r... | python |
# Copyright 2022 The Balsa 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 applicable law or agreed to in wr... | python |
#!/usr/bin/python
# Copyright 2017 Telstra Open Source
#
# 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 appl... | python |
# Copyright 2020 University of Groningen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | python |
import pandas as pd
from koapy import KiwoomOpenApiContext
from koapy.backend.cybos.CybosPlusComObject import CybosPlusComObject
kiwoom = KiwoomOpenApiContext()
cybos = CybosPlusComObject()
kiwoom.EnsureConnected()
cybos.EnsureConnected()
kiwoom_codes = kiwoom.GetCommonCodeList()
cybos_codes = cybos.GetCommonCodeLi... | python |
xs = [1, 2] | python |
# Copyright 2010-2011 Josh Kearney
#
# 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 agre... | python |
from django import forms
from django.forms import ModelForm
from auctions.models import Listing, Comment, Bid, Category
categories = Category.objects.all().values_list('slug_name', 'name')
class CreateListing(ModelForm):
name = forms.ChoiceField(choices=categories, required=False)
class Meta:
... | python |
from .utils import find_closest_equivalent, Snapshot
from .find_init_weights import find_weights
| python |
import schema229
import os
'''
Unit tests
'''
def test_resolve_ref():
schema = schema229.A229Schema(os.path.join(os.path.dirname(__file__),'..','build',"schema","ASHRAE229.schema.json"))
node = schema.resolve_ref("ASHRAE229.schema.json#/definitions/ASHRAE229")
assert('title' not in node)
def test_get_sc... | python |
#!/usr/bin/python2
from math import sqrt
from decimal import Decimal
def check_prime(num):
if not num % 2:
return False
for i in xrange(3, int(sqrt(num) + 1), 2):
if not num % i:
return False
return True
def reverse(num):
rev_num = 0
while num:
rev_num = 10 ... | python |
# Space: O(n)
# Time: O(n)
import collections
class Solution:
def topKFrequent(self, nums, k):
counts = collections.Counter(nums)
res = sorted(counts.keys(), key=lambda x: counts[x], reverse=True)[:k]
return res
| python |
import multiprocessing
import os
import signal
import sys
import time
import WarBackend as War
from blessings import Terminal
def cleanexit(sig, frame):
if os.system("clear") != 0:
os.system("cls")
print("\nStopping...")
sys.exit()
signal.signal(signal.SIGINT, cleanexit) # Catches ^c and stops
term = Te... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 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
#
... | python |
#!/usr/bin/env python
""" This is the base class to start the RESTful web service hosting the Blackboard API. """
import logging.config
from logging.handlers import RotatingFileHandler
from time import strftime
from flask import Flask, Blueprint, request, jsonify
from blackboard_api import settings
from blackboard_... | python |
"""
decoded AUTH_HEADER (newlines added for readability):
{
"identity": {
"account_number": "1234",
"internal": {
"org_id": "5678"
},
"type": "User",
"user": {
"email": "test@example.com",
"first_name": "Firstname",
"is_active":... | python |
"""
Plot a traced WE trajectory onto 2D plots.
# TODO: integrate into h5_plot
"""
import numpy as np
import matplotlib.pyplot as plt
import h5py
def get_parents(walker_tuple, h5_file):
it, wlk = walker_tuple
parent = h5_file[f"iterations/iter_{it:08d}"]["seg_index"]["parent_id"][wlk]
return it-1, parent
... | python |
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class Passthrough(BaseEstimator, TransformerMixin):
"""
Class for passing through features that require no preprocessing.
https://stackoverflow.com/questions/54592115/appending-the-columntransformer-result-to-the-original-data-wi... | python |
from bs4 import BeautifulSoup as soup
html = """
<html>
<body>
<ul>
<li><a href="http://www.naver.com">NAVER</a></li>
<li><a href="http://www.daum.net">DAUM</a></li>
</ul>
</body>
</html>
"""
content = soup(html, "html.parser")
links = content.find_all("a")
for a in l... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
from .base import AttackMetric
from ...tags import *
from ...text_process.tokenizer import Tokenizer
class JaccardWord(AttackMetric):
NAME = "Jaccard Word Similarity"
def __init__(self, tokenizer : Tokenizer):
"""
Args:
tokenizer: A tokenizer that will be used in this metric. ... | python |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def main():
return render_template("main_better.html")
# getting basic user data
@app.route('/ask/', methods=['POST', 'GET'])
def ask():
if request.method == 'GET':
return render_template('ask.html')
else:
... | python |
from keras.layers import Layer
from keras_contrib.layers.normalization.instancenormalization import InputSpec
import numpy as np
import matplotlib.image as mpimg
from progress.bar import Bar
import datetime
import time
import json
import csv
import os
import keras.backend as K
import tensorflow as tf
from skimage.tra... | python |
import time
from umqtt.simple import MQTTClient
def sub_cb(topic, msg):
print((topic, msg))
c = MQTTClient("uqmtt_client", "localhost")
c.connect()
c.subscribe(b"foo_topic")
c.publish(b"foo_topic", b"hello")
while 1:
c.wait_msg()
c.disconnect()
| python |
import math
import os
import pickle
import sys
import gym
import numpy as np
import quaternion
import torch
from torch.nn import functional as F
from torchvision import transforms
import skimage.morphology
from PIL import Image
import matplotlib
if matplotlib.get_backend() == "agg":
print("matplot backend is {}".... | python |
from django.apps import AppConfig
class StandardizingApiConfig(AppConfig):
name = 'standardizing_api'
| python |
# Generated by Django 3.2.9 on 2021-11-28 04:44
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Place',
fields=[
('id... | python |
import torch
import torch.nn as nn
from graphgallery.nn.layers.pytorch import GCNConv, Sequential, activations, InnerProductDecoder
class GAE(nn.Module):
def __init__(self,
in_features,
*,
out_features=16,
hids=[32],
acts=['relu'... | python |
"""
TODAS AS QUESTÕES SENDO COMPUTADAS BEM COMO AS SUAS ALTERNATIVAS
E A SUA DEVIDA RESPOSTA CORRETA. DICIONÁRIO EM PYTHON.
"""
questionsX = {
'Pergunta 1': {
'pergunta': 'Qual é o século que ocorreu o período chamado iluminismo, o século das luzes?',
'alternativas': {'a': 'XIX -> Século 19', 'b': ... | python |
# flag = 'r2con{Sit down next to my friendLight matchStay}'
var_60h = 0xDEADBEEFDEADBEEFCAFE1337CAFE13370102030405060708090A.to_bytes(26, 'big')
var_40h = 0xDEADBEEFCAFE13371337CAFE133713370102030405060708090A.to_bytes(26, 'little')
First_arr = [ 0x97, 0xCD, 0xD2, 0xD6, 0xC0, 0xC7, 0xCD, 0x84, 0xEC, 0x91, 0xAD, 0x62, ... | python |
import tensorflow as tf
from absl import flags, app
from libs.inference import YoloInf
from libs.evals.coco import GetCocoEval
FLAGS = flags.FLAGS
flags.DEFINE_string('ckpt', default=None, help='Checkpoint file path')
flags.DEFINE_string('img_prefix', default=None, help='Image directory path to evaluate', short_name=... | python |
import torch
import torch.nn as nn
import numpy as np
import sys
sys.path.append('..')
from networks import HSwish, HSigmoid, Swish, Sigmoid
def compute_memory(module, inp, out):
if isinstance(module, (nn.ReLU, nn.ReLU6, nn.ELU, nn.LeakyReLU)):
return compute_ReLU_memory(module, inp, out)
elif isinstance(module, n... | python |
#!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
This scripts is used to generate graphs from smiles for the D-GIN publication.
"""
# ===========================... | python |
import math
import itertools
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import scipy.stats as ss
import scikit_posthocs as sp
from dash_table.Format import Format, Scheme
from Bio import Phylo
from ete3 import Tree
from plotly.subplots import make_subplots
# -... | python |
import logging
import os
import subprocess
from datetime import datetime, timezone, timedelta
from pathlib import Path
import django_rq
import novaclient
import vm_manager
from vm_manager.constants import INSTANCE_DELETION_RETRY_WAIT_TIME, \
INSTANCE_DELETION_RETRY_COUNT, \
INSTANCE_CHECK_SHUTOFF_RETRY_WAIT_T... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.