content
stringlengths
5
1.05M
#!/usr/bin/env python # Following some previous people's work in # https://www.javatpoint.com/python-tkinter-frame # https://www.python-course.eu/tkinter_checkboxes.php # https://stackoverflow.com/questions/30774281/update-matplotlib-plot-in-tkinter-gui import netCDF4 as ncdf import numpy as np from scipy import int...
mark = float(input('mark on test?')) if mark >= 50: print('congratulations you passed') else: print('sorry you failed')
# Generated by Django 2.1.7 on 2019-03-29 15:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('paytm', '0005_paytm_history_user'), ] operations = [ migrations.AlterField( model_name='paytm_history', name='MERC_U...
__author__ = "Frédéric BISSON" __copyright__ = "Copyright 2022, Frédéric BISSON" __credits__ = ["Frédéric BISSON"] __license__ = "mit" __maintainer__ = "Frédéric BISSON" __email__ = "zigazou@protonmail.com" import re from testdata import pdf_file_uris # Generate the ALL rule. print("ALL:", end="") for pdf_test in pd...
from flask import Blueprint from flask import session from flask import request from flask import redirect from flask import url_for from flask import render_template from pyotp import random_base32 from pyotp import TOTP from app import db from app.models import TwoFactor from app.check import is_two_factor_enabled ...
import sys def filter_xml (infile, outfile): import re out_string = '' replacement = '<.*?>' with open(infile) as instream: instring = instream.read() xml_pattern = re.compile('(?s)<style>.*?</style>') alt_pattern = re.compile('<[^>]*>') final_pattern = re.compile('&nbsp...
from builtins import range import ROOT masseb = [] massee = [] f1 = ROOT.TFile("plots_data.root") t1 = f1.Get("zeeUncalibTree/probe_tree") e = t1.GetEntries() masseb.append(ROOT.TH1F("masseb1", "", 80, 70, 110)) massee.append(ROOT.TH1F("massee1", "", 80, 70, 110)) for z in range(e): t1.GetEntry(z) if(abs(t1....
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders #Get configuration parameters import config fromaddr = config.fromaddr toaddr = config.toaddr #Create a MIME Multipart object msg = MIMEMultipart() msg['Fr...
from django.contrib import admin from .models import Post from simple_history.admin import SimpleHistoryAdmin #admin.site.register(SimpleHistoryAdmin) admin.site.register(Post, SimpleHistoryAdmin)
import pytest def test_something(): a = 5 b = 10 assert a + b == 11 class TestMultiple: def test_first(self): assert 5 == 5 def test_second(self): assert 10 == 10
import argparse import torch import dgl from dgl.data import CoraGraphDataset, CiteseerGraphDataset, PubmedGraphDataset from dgl.nn import LabelPropagation def main(): # check cuda device = f'cuda:{args.gpu}' if torch.cuda.is_available() and args.gpu >= 0 else 'cpu' # load data if args.dataset == 'Co...
#! /usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import url, include import delivery import tasks urlpatterns = [ url(r'^$', delivery.delivery_list, name='delivery'), url(r'^add/$', delivery.delivery_add, name='delivery_add'), url(r'^list/$', delivery.delivery_list, name='delivery_list')...
import base64 import hashlib import hmac import logging from binascii import hexlify from datetime import datetime from functools import reduce from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple from urllib.parse import quote as url_quote from httpx import URL, AsyncClient, Response from ._ut...
from .integrals import Integrals
import intake from ._version import get_versions __version__ = get_versions()["version"] del get_versions # Look up a driver class by its name in the registry. catalog_class = intake.registry["bluesky-mongo-normalized-catalog"] bluesky_cartpole_catalog_instance = catalog_class( metadatastore_db="mongodb://local...
"""Summary: Webscraper for ign.com """ import requests from bs4 import BeautifulSoup from typing import List, Tuple, Dict from .BaseScraper import BaseScraper class Ign(BaseScraper): def __init__(self): super().__init__() self.url = 'http://www.ign.com/comics' def _raw_scrape(self): "...
import io import os import PySimpleGUI as sg from PIL import Image import pytesseract # include the file types that should be allowed in your app file_types = [ ("PNG (*.png)", "*.png"), ("JPEG (*.jpg)", "*.jpg"), ("All files (*.*)", "*.*") ] def ocr_core(filename): """ This function will handle ...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : bruteforce.py @Time : 2021/11/23 23:48:49 @Author : Roderick Chan @Email : ch22166@163.com @Desc : bruteforce methods ''' from pwnlib.util.hashes import * from pwnlib.util.iters import bruteforce, mbruteforce from pwncli.utils.misc import errlo...
# ^ Importing The Modules import pyfiglet import mysql.connector print(pyfiglet.figlet_format("WELCOME")) # & Connecting to Database mydb = mysql.connector.connect( host="localhost", user="root", password="deepraj02", database="schoolmanagement" ) mycursor = mydb.cursor() # * F...
''' Kth largest element Given an array A of random integers and an integer k, find and return the kth largest element in the array. Note: Try to do this question in less than O(N * logN) time. Input Format : The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it...
#! python3 """What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?""" from itertools import permutations from time import time def self_permutations(it): l = len(it) for i in range(l): if l > 1: for p in self_permutations(it[:i] + it[i + 1:]): ...
n = int(input()) i = s = 1 while s < n: s += 6 * i i += 1 print(i)
from tensorflow.keras.preprocessing import image from tensorflow.keras.models import model_from_json, load_model from sklearn.externals import joblib import tensorflow as tf from tensorflow.keras import backend as k import numpy as np config =tf.compat.v1.ConfigProto( device_count={'GPU': 1}, intra_op_paralleli...
# Copyright (c) 2020 The Khronos Group 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 setuptools import find_packages, setup VERSION = __import__('flat_responsive').__version__ setup( name='django-flat-responsive', packages=find_packages(), version=VERSION, author='elky', author_email='mail@elky.me', description=('An extension for Django admin that makes interface mobile f...
import os import shutil from django import forms from django.contrib import admin, messages from django.contrib.admin.options import csrf_protect_m from django.contrib.auth.models import Permission, Group, User from django.db import transaction from django.shortcuts import render_to_response from django.template.conte...
import subutai import subuco import hashlib import datetime import os import stat import tarfile from shutil import copyfile from subprocess import call from time import sleep from subprocess import run, Popen, PIPE # This file provides functions and classes specific to # Linux platform def GetVirtualMachineName():...
import sys sys.path.insert(0, '..') from img import TiffSequence # 4 images path = [ '../../tif/20170407054917_MSG2.tif', '../../tif/20170407055416_MSG2.tif', '../../tif/20170407055916_MSG2.tif', '../../tif/20170407060416_MSG2.tif' ] sequence = TiffSequence(path) print("Number of images into sequenc...
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] spar = scol = maior = 0 for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f"Digite um valor para ({l}, {c}): ")) if matriz[l][c] % 2 == 0: spar += matriz[l][c] for l in range(0, 3): for c in range(0, 3): print(f"[{...
from .insidebars import InsideBars from .pattern import Pattern from .stairstep import HigherHighs
from django.shortcuts import render from database.query.submissions import get_user_submissions as database_get_user_submissions def submission_ajax_page(request, username, start, end): ret = database_get_user_submissions(username, start=int(start), end=int(end)) return render(request, 'html/submissions_ajax...
# Copyright 2019 AUI, Inc. Washington DC, USA # # 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 ...
#import nothing nullfunc = lambda: None #from types import CodeType, FunctionType CodeType = nullfunc.__code__.__class__ FunctionType = nullfunc.__class__ # Thanks @chilaxan def sizeof(obj): return type(obj).__sizeof__(obj) IS_PY2 = not 2/3 BYTES_HEADER_LEN = sizeof(b"")-1 TUPLE_HEADER_LEN = sizeof(()) INT64_MA...
from django.conf import settings from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.core.mail import send_mail from django.db.models import Avg from django.shortcuts import get_object_or_404 from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters, per...
from json import load import sys sys.path.append('.') import json from tqdm import tqdm from collections import OrderedDict import pickle from itertools import chain import argparse from entity_linker.bert_entity_linker import BertEntityLinker from entity_linker.BERT_NER.bert import Ner from entity_linker import surfa...
print('-=-' * 30) print(' MAIOR E MENOR NÚMERO ') print('-=-' * 30) print('''Digite três números e eu informarei qual o maior e qual o menor!''') print('-' * 5) num1 = float(input('Digite o primeiro número: ')) num2 = float(input('Digite o segundo número: ')) num3 = float(input('Digite o terceiro número: ')) pr...
import albumentations as A from albumentations.core.transforms_interface import DualTransform from augments.tearAug import TearAug from augments.addBird import AddBird augmentations_dict = { 0: AddBird, 1: A.Blur, 2: A.ChannelDropout, 3: A.ChannelShuffle, 4: A.CLAHE, 5: A.CoarseDropout, 6: ...
from django.shortcuts import render from django.views.generic import CreateView from django.urls import reverse_lazy from .forms import CreationForm class SignUp(CreateView): form_class = CreationForm success_url = reverse_lazy('posts:index') template_name = 'users/signup.html'
import math import time from dataclasses import dataclass from typing import List, Tuple from PIL import Image, ImageDraw, ImageFilter from seedsigner.gui.renderer import Renderer from seedsigner.helpers.qr import QR from seedsigner.models.qr_type import QRType from seedsigner.models.threads import BaseThread, Thread...
from typing import List import pandas as pd from pycaret.classification import * from prefect import task, Flow from typing import List @task def split_df() -> List[pd.DataFrame]: # Read data games = pd.read_csv('data/games') # Split into train and test cutoff = round(games.shape[0]*0.75) train = ...
# Copyright 2020-present Kensho Technologies, LLC. """Code for generating gRPC stubs in Kensho-approved way""" import itertools import grpc from eagr.client import client_side_middleware from eagr.client.client_tracing import wrap_grpc_client_channel DEFAULT_CHANNEL_OPTIONS = { # We want to round-robin between ...
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting import os try: os.chdir(os.path.join(os.getcwd(), 'TEAD\MiniProyecto1\censusincomeanalysis')) print(os.getcwd()) except: pass #%% [markdown] # - 48842 instances...
import tensorflow as tf import numpy as np tf.compat.v1.enable_eager_execution() # Weight Quantization - Input/Output=float32 converter = tf.lite.TFLiteConverter.from_saved_model('saved_model') converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE] tflite_quant_model = converter.convert() with open('head_pose...
## Import libraries import os from PIL import Image import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import skimage import scipy.ndimage.interpolation as sci_int import scipy.ndimage.morphology as sci_morph from skimage import data, color, img_as_uint from skimage.transform import re...
from keras.applications import VGG16 from keras import layers from keras import models from keras import optimizers from keras.preprocessing.image import ImageDataGenerator from keras.utils import plot_model import matplotlib.pyplot as plt from keras import backend as K import tensorflow as tf class VGG16Training(obj...
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField, SelectField from wtforms.validators import Required class AddPitchForm(FlaskForm): title = StringField("Pitch Title", validators = [Required()]) pitch = TextAreaField("Go", validators = [Required()]) category = Sel...
from django.contrib import admin from core.models import * @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): fields=('archived', 'user',) list_display=('id', 'user', 'created_at', 'updated_at',)
#!/usr/bin/env python import networkx as NX import numpy from draggableNode import DraggableNode from graph import Graph class GraphTest(Graph): def __init__(self, parent = None): Graph.__init__(self, parent, False) files = ['file'+str(x)+'.step' for x in xrange(5)] self.nodes = ...
#!/usr/bin/env python # coding: utf-8 from ase.visualize import view import numpy as np import matplotlib.pyplot as plt from pymatgen.io.ase import AseAtomsAdaptor from waterstructureCreator.load_dictionaries import import_slab_structures, import_bulk_structures from waterstructureCreator.construct_supercells impor...
# Generated by Django 3.1.4 on 2021-01-11 13:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtail_wordpress_importer', '0058_customfield_sub_fields'), ] operations = [ migrations.CreateModel( ...
#! /usr/bin/env python # -*- encoding: UTF-8 -*- """Example: Use transformInterpolations Method on Arm and Torso""" import qi import argparse import sys import motion import almath def main(session): """ Use transformInterpolations Method on Arm and Torso. """ # Get the services ALMotion & ALRobotPo...
"""Submodule to handle web requests in opsdroid.""" import json import logging import ssl from aiohttp import web from opsdroid import __version__ _LOGGER = logging.getLogger(__name__) class Web: """Create class for opsdroid Web server.""" def __init__(self, opsdroid): """Create web object.""" ...
import fn import json import os import cv2 import numpy as np import torch origin = os.path.dirname(os.getcwd()) target_json = "/alphapose/alphapose-results.json" origin = origin + target_json print(origin) # with open(origin, encoding='utf-8') as f: # line = f.readline() # d = json.loads(line) # print...
""" Copyright 15/06/2017 UNSW Testing - Abu Tholley 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...
from transformers import GPT2LMHeadModel, GPT2Tokenizer import torch class GPT2LMSegmentModel(GPT2LMHeadModel): """ This class is use to override the prepare_inputs_for_generation of GPT2LMHeadModel --> the vanilla generate function from huggingface does not allow to specify the token type id of the input, becaus...
import unittest from mock import Mock, patch from pyVmomi import vim from common.vcenter.task_waiter import SynchronousTaskWaiter task = Mock(spec=vim.Task) class helper: @staticmethod def change_to_success(a): task.info.state = vim.TaskInfo.State.success return @staticmethod def cha...
import abc from collections.abc import Iterable from typing import Optional from discord import Reaction, Message, Member, RawReactionActionEvent from discordmenu.embed.emoji import DEFAULT_EMBED_MENU_EMOJI_CONFIG, EmbedMenuEmojiConfig class ReactionFilter: def __init__(self, reaction_filter: Optional["ReactionF...
from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import pgettext_lazy from saleor.core.utils im...
from office365.runtime.client_result import ClientResult from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.resource_path import ResourcePath from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation from office365.sharepoint.base_...
"""An example file that produces a custom parameters for the LULESH example.""" from maestrowf.datastructures.core import ParameterGenerator from atomsci.ddm.utils import hyperparam_search_wrapper as hsw import os #--------------------------------------------------------------------- def get_custom_generator(env, **k...
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """HTTP Handlers.""" import datetime import itertools import json import time import webapp2 from google.appengine.api import app_identity from...
""" ==================== Plot Activation Foci ==================== Plot spheroids at positions on the surface manifold according to coordinates or vertex ids. """ import os import os.path as op from numpy import arange from numpy.random import permutation import nibabel as nib from surfer import Brain print(__doc__)...
""" Module containing code to work with Rapid observational data """ from netCDF4 import Dataset, num2date, date2num import datetime import numpy as np import metric.utils class RapidObs(object): """ Template class to interface with observed ocean transports """ def __init__(self, f, time_avg=None, mindt=No...
from torchwisdom.optim.callback import * from torchwisdom.metrics import * from torchwisdom.callback import * from torchwisdom.utils.data.collector import * from torch.optim.optimizer import Optimizer from torchwisdom.trainer import * from torchwisdom.envi import * from typing import * from fastprogress import master_b...
from os.path import dirname, join ROOT_DIR = dirname(__file__) UPLOAD_DIR = join(ROOT_DIR, 'static', 'uploads') class Config: SECRET_KEY = '716030d5aff7e2140d6f1f52847ab80ffc93559d06708c449f834d04ff54cb4a' SQLALCHEMY_TRACK_MODIFICATIONS = False ROOT_DIR = ROOT_DIR UPLOAD_DIR = UPLOAD_DIR class Tes...
from django.conf.urls import url from api import views from bin import powerstrip # api urls urlpatterns = [ url(r'^$', views.view_api), url(r'beamer/$', views.view_beamer), url(r'beamer/on/$', views.view_beamer_on), url(r'beamer/off/$', views.view_beamer_off), url(r'beamer/change_state/$', views.view_be...
import os import re import types #import unittest PACKAGE = 'mini_charge.models' MODEL_RE = r"^.*.py$" # Search through every file inside this package. model_names = [] model_dir = os.path.dirname(__file__) for filename in os.listdir(model_dir): if not re.match(MODEL_RE, filename) or filename == "__init__.py": ...
from passlib.hash import pbkdf2_sha256, bcrypt_sha256 class PasswordManager: def __init__(self): self.plain_password = None self.encrypted_password = None def create_password(self, plain_password): self.plain_password = plain_password self.encrypted_password = pbkdf2_sha256.en...
from __future__ import annotations import datetime from typing import List, Tuple, Union, Dict class InvalidDistributionSliceException(Exception): pass class WeeklyDistribution: HOURS_IN_WEEK = 168 def __init__( self, hour_fraction_pairs: List[Union[Tuple[int, float], Tuple[int...
import unittest from refract import Array, String class ArrayTests(unittest.TestCase): def setUp(self): self.title = String(content='title') self.hello = String(content='hello') self.array = Array(content=[self.title, self.hello]) def test_initialisation(self): self.assertEqua...
print '****Welcome to Sehir Online Market****' print 'Please log in by proving your user credentials' log_in_dict={'username':['ahmet','meryem'],'password':['sehir123','4444']} UserName=raw_input('username: ') while UserName != log_in_dict['username'][0] and UserName != log_in_dict['username'][1]: print 'Your usern...
import discord import random from mcstatus import MinecraftServer from discord.ext import commands import datetime from urllib import parse, request import re import requests import json import base64 import urllib.parse from discord.ext import commands import requests from bs4 import BeautifulSoup from t...
# !/usr/bin/env python3 # -*- coding:utf-8 -*- # @Datetime : 2019/11/13 上午11:49 # @Author : Fangyang # @Software : PyCharm from PyQt5.QtWidgets import ( QWidget, QHBoxLayout, QFrame, QSplitter, QStyleFactory, QApplication ) from PyQt5.QtCore import Qt import sys class Example(QWidget): def __init__(s...
# Generated by Django 3.2.12 on 2022-04-29 16:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notifications', '0001_initial'), ] operations = [ migrations.AlterField( model_name='notification', name='verb', ...
import logging, browserid, json, sys from pylons import config, request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect from pylons.decorators import rest from lr.lib.base import BaseController, render from lr.lib import oauth, bauth from lr.lib.signing import lrsignatur...
import os import shutil import argparse import random import torch import numpy as np from torch_geometric.data import Batch from easydict import EasyDict from tqdm.auto import tqdm from rdkit import Chem from scipy.special import softmax from models.maskfill import MaskFillModel from models.frontier import FrontierNe...
""" Management of BOSS infrastructure Usage: bossmngr checkconfig Options: --prefix=<prefix> Prefix to delete --field=<field> Field to search in """ import sys SUCCESS = 0 FAILED = 1 def main(): import docopt from utils.check_config import print_check_config opt = docopt.docopt(__doc__) if...
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.utils.domutils from pyxb.utils import six from xml.dom import Node import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns="urn:t...
import numpy as np import os import tempfile from Parser import * class ControllerFunctionError(Exception): def __init__(self, message, error): super(Exception, self).__init__(message) self.errors = error class Controller(): ''' This class wraps some of the controller functionality from pyZDDE into m...
import Token class TokenConsumer: def __init__(self, tokens: Token): self.tokens = tokens self.position = 0 def end_of_tokens(self): return self.position == len(self.tokens) def current(self): return self.tokens[self.position] def next(self): if self.posi...
import cupy as cp import pytest from cupy.testing import assert_allclose from skimage.data import camera, binary_blobs from cupyimg.scipy.ndimage import fourier_shift from cupyimg.skimage.registration._phase_cross_correlation import ( phase_cross_correlation, _upsampled_dft, ) from cupyimg.skimage import img_a...
numbers = list(map(int, input("Podaj 5 cyfr: ").split())) try: if len(numbers) != len(list(dict.fromkeys(numbers))) or len(numbers) > 5 or len(numbers) < 5: raise ValueError else: i = 0 divs = 0 while i < 4: x = numbers[0 + divs] y = numbers[1 + divs] ...
x = "a" y = "b" print("x < y" if x < y else "x > y")
class Settings(): def __init__(self): self.number_to_picture_dict = {0: 'image/0.png', 2: 'image/2.png', 4: 'image/4.png', 8: 'image/8.png', 16: './image/16.png', 32: './image/32.png', 64: './image/64.png', 128: './image/128.png'...
"""Holds handlers to manage error tracebacks using.""" import pretty_errors from dbt_coves.utils.flags import DbtCovesFlags class DbtCovesTraceback: """Consumes CLI flags (from DbtCovesFlags consumer) and sets up traceback pretty formatting.""" def __init__(self, flags: DbtCovesFlags) -> None: """Tr...
### The answer is: words=["turtle","pineapple","tech","penguin","free","python","classes"] words_in_list=len(words)
from thermal_barrierlife_prediction.model_cnn import ModelCNN from thermal_barrierlife_prediction.estimator import Estimator class EstimatorCNN(Estimator): def init_model(self, **model_args): """ Initializes and compiles the model. """ input_shapes = (self.data['greyscale'].shape...
from time import time from imgfeature import ResizeImFeature import pandas as pd def imhash(gray): dt = gray.flatten() xlen = len(dt) avg = dt.mean() avg_list = ['0' if i < avg else '1' for i in dt] return ''.join(['%x' % int(''.join(avg_list[x: x+4]), 2) for x in range(0, xlen, 4)]) def hamming(h...
# Generated by Django 2.2.2 on 2019-06-05 10:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flexible_payments', '0004_auto_20190604_1551'), ] operations = [ migrations.AddField( model_name='transaction', name...
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
""" Copyright (c) 2011, 2012, Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this l...
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 applicabl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 4 10:09:11 2019 @author: sitaram Example: python hierarchical_clustering_cluster.py -f ~/dblp_clustering.csv -c ~/dblp_clustering_results.csv workflow: -> To calculate intra cluster edge count between clusters """ import pandas as pd import num...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 朔のキャッシュをmikaのデータベースへインポートします # 使い方: # python3 cache2db.py path/to/cache/dir # OR # python3 cache2db.py --exclude-removed path/to/cache/dir # DBの設定 DB_NAME = 'mika' DB_USER = 'root' DB_PASSWD = 'root' from mysql.connector import connect as mysqlConnect import...
import logging from datetime import timedelta from core import Feed from core.errors import ObservableValidationError from core.observables import File, Hash, Url # Deprecated class UrlHausPayloads(Feed): default_values = { "frequency": timedelta(hours=1), "name": "UrlHausPayloads", "sour...
from .objects.timeseries import fixTimestamps, Timeseries, DatapointArray def getQuery(ts, kwargs): fixTimestamps(kwargs) if isinstance(ts, Merge): kwargs["merge"] = ts.query return kwargs if isinstance(ts, Timeseries): ts = ts.id elif not isinstance(ts, str): raise Exc...
""" Defines the ScatterInspector tool class. """ # Enthought library imports from traits.api import Any, Bool, Enum, Event, HasStrictTraits, Str # Local, relative imports from .select_tool import SelectTool HOVER_EVENT = "hover" SELECT_EVENT = "select" DESELECT_EVENT = "deselect" class ScatterInspectorEvent(HasS...
import torch from espnet2.layers.sinc_conv import BarkScale from espnet2.layers.sinc_conv import LogCompression from espnet2.layers.sinc_conv import MelScale from espnet2.layers.sinc_conv import SincConv def test_log_compression(): activation = LogCompression() x = torch.randn([5, 20, 1, 40], requires_grad=T...
"""Here you can control the config parameters to run Kytos controller. Basically you can use a config file (-c option) and use arguments on command line. If you specify a config file, then and option configured inside this file will be overridden by the option on command line. """ import json import os import uuid im...
from celery import task, shared_task from crawler import download from crawler.models import * import os from crawler.views import count_words from crawler.pdf import * import nltk from tqdm import tqdm @shared_task def tag(id): try: doc = Document.objects.filter(id=id).first() if doc is not No...