content
stringlengths
5
1.05M
nome = str(input('Digite seu nome completo: ')).strip() print('Silva' in nome.title())
from __future__ import print_function from optparse import make_option from datetime import datetime, timedelta import sys from textwrap import dedent from django.core.mail import mail_admins from django.contrib.auth.models import User from reversion.models import Revision from cobl.utilities import LexDBManagementComm...
def load_STNTable(fobj, kwArgCheck = None, debug = False, errors = "strict", indent = 0): # NOTE: see https://github.com/lw/BluRay/wiki/STNTable # Import standard modules ... import struct # Import sub-functions ... from .load_StreamAttributes import load_StreamAttributes from .load_StreamEntr...
import unicodedata def parse(dict_file): with open(dict_file, 'r', encoding='utf-8') as r: for line in r: for word in line.split("#")[1].split(","): word = unicodedata.normalize('NFKC', word.strip()) yield word def parse_lexemes(dict_file): with open(dict_...
#!/usr/bin/env python # Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list ...
import pyperclip class User: ''' class for passing all instances of the user ''' user_list = [] def __init__(self,user_name,account_name,email,password): ''' initiates properties of my objects Args: user_name:New username of the account '''...
from ecco.attribution import gradient_x_inputs_attribution import torch import pytest @pytest.fixture def simpleNNModel(): class simpleNNModel(torch.nn.Module): def __init__(self): super(simpleNNModel, self).__init__() self.w = torch.tensor([[10., 10.]]) def forward(self, ...
from sklearn import ensemble from model_man import get_models def create(): models = get_models() v_models = [(key, models[key].create()) for key in models.keys()] return ensemble.VotingClassifier( estimators=v_models, voting="hard" )
# -*- coding: utf-8 -*- """ A nested dict with both attribute and item access. NA stands for Nested and Attribute. """ import collections import copy class NADict: """A nested dict with both attribute and item access. It is intended to be used with keys that are valid Python identifiers. However, excep...
# -*- coding: utf-8 -*- # FreeCAD macro for woodworking # Author: Darek L (aka dprojects) # Version: 5.0 # Latest version: https://github.com/dprojects/getDimensions import FreeCAD # ####################################################### # SETTINGS ( SET HERE ) # ####################################################...
def get_length_of_missing_array(arr): if len(arr) == 0: return 0 else: lens = [] for i in arr: if i == None or len(i) == 0: return 0 lens.append(len(i)) lens.sort() prevInt = 0 for i in lens: ...
""" Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Ou...
# -*- coding: utf-8 -*- # Copyright 2021 Jacob M. Graving <jgraving@gmail.com> # # 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 requi...
from typing import Sequence, Hashable def find_field(d, candidates): """ Given a dict and a list of possible keys, find the first key which is included into this dict. Throws ValueError if not found. """ for c in candidates: if c in d: return c raise ValueError(f"Can't find any of: {candidates}") def find...
from zmodulo.plot.properties.color.color import Color class LineColor: """ A Z-Tree plot line color """ def __init__(self, color=None): """ Initializes the LineColor object :param color: line color :type color: Color """ if color is None: self.color...
from lin import db from lin.core import File from lin.exception import NotFound from pydash import uniq_by from sqlalchemy import Column, Integer, String from sqlalchemy.orm import aliased from app.models.base import Base class Category(Base): id = Column(Integer, primary_key=True) name = Column(String(50), ...
swaps=[] def heapify(data,n,vert): min=vert l=2*vert+1 r=2*vert+2 if l<n and data[l]<data[min]: min=l if r<n and data[r]<data[min]: min=r if min!=vert: data[vert],data[min]=data[min],data[vert] swaps.append([vert,min]) heapify(data,n,min) def main(): ...
from django.contrib import admin from .models import Report, ReportFiles, ReportIndex admin.site.register(Report) admin.site.register(ReportFiles) admin.site.register(ReportIndex)
#!/usr/bin/env python # encoding: utf-8 """ @author: anly_jun @file: github_trending @time: 16/10/17 下午2:23 """ import requests from bs4 import BeautifulSoup GITHUB = 'https://github.com' TRENDING_URL = GITHUB + "/trending" TRENDING_DEV_URL = TRENDING_URL + "/developers" USER_AGENT_BY_MOBILE = 'Mozilla/5.0 (Linux; A...
import requests from bs4 import BeautifulSoup as bs import time import random import os import pandas as pd from pathlib import Path pwd = os.getcwd() # Creating /details_page folder Path(pwd + '/details_pages').mkdir(parents=True, exist_ok=True) df = pd.read_csv(pwd + '\\dataframes\\Data - IT_Companies_Algiers.csv')...
def make_local_image( embedded_cid , filename, payload): """helper func that creates an image object. others may replace this with a specific solution. the important point is that it returns a link """ import models #my models module. you will probably replace this entire function with your own code ...
import json from mock import patch import jenkins from tests.base import JenkinsTestBase class JenkinsCancelQueueTest(JenkinsTestBase): @patch.object(jenkins.Jenkins, 'jenkins_open') def test_simple(self, jenkins_mock): job_name_to_return = {u'name': 'TestJob'} jenkins_mock.return_value = js...
from itertools import permutations l=list(map(int,input().split())) r=list(permutations(l)) print(r)
import typing import datetime import pandas as pd from .make_df import ComicDataFrame from lib.aws_util.s3.upload import upload_to_s3 from lib.aws_util.s3.download import download_from_s3 def store(df: ComicDataFrame) -> typing.NoReturn: dt = datetime.datetime.now() bucket = 'av-adam-store' save_dir = '/tmp/' ...
from .charge import Charge
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ChatAction #Google import gspread from oauth2client.service_account import ServiceAccountCredentials import os import pandas as pd INPUT_...
""" Manages creation of POVMs and geneartion of outcomes from measuring these POVM given a state Author: Akshay Seshadri """ import numpy as np import scipy as sp from scipy import stats import project_root # noqa from src.utilities.qi_utilities import generate_random_state, generate_POVM, generate_Pauli_ope...
#!/usr/bin/env python3 import logging import resource import sys logging.basicConfig(level=logging.INFO) import teether.project if __name__ == '__main__': if len(sys.argv) < 2: print('Usage: %s [flags] <code>' % sys.argv[0]) exit(-1) mem_limit = 4 * 1024 * 1024 * 1024 # 4GB resource.set...
#!/usr/bin/python3 from PyQt5.QtWidgets import * class ModulPU(QWidget): def __init__(self): super().__init__() self.layout = QGridLayout() self.setLayout(self.layout) ################################################################################################################# ############################...
# encoding: utf-8 # Copyright 2011 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. '''Service Binding: implementation''' from Acquisition import aq_inner, aq_parent from ipdasite.services import ProjectMessageFactory as _ from ipdasite.services.config import PROJEC...
from pathlib import Path from conanRunner import conanRunner def conanInstall(conanfile, installFolder): print("\n") conanfile = str(conanfile) installFolder = str(installFolder) args = ["install", conanfile, "--install-folder", installFolder] for s in conanRunner(args): print(s)
# coding: utf-8 """ Telstra Event Detection API # Introduction Telstra's Event Detection API provides the ability to subscribe to and receive mobile network events for registered mobile numbers associated with Telstra's mobile network, such as; SIM swap, port-in, port-out, new MSIDN, new mobile service and c...
import unittest import mock from factor_graph import FactorGraph, FactorGraphService, Node, Edge class TestFactorGraph(unittest.TestCase): pass class TestFactorGraphService(unittest.TestCase): ## mock FG for failure tests def test_create_success(self): factor_graph_service = FactorGraphService() ...
import configparser import inspect import logging import os import typing import numpy as np from ConfigSpace.configuration_space import Configuration from smac.runhistory.runhistory import RunHistory, RunKey from cave.utils.exceptions import NotApplicable def get_timeout(rh, conf, cutoff): """Check for timeout...
# encoding: utf-8 from .default import Config class DevelopmentConfig(Config): # App config DEBUG = True SQLALCHEMY_DATABASE_URI = "sqlite:///../db/dictionary.sqlite3"
# -*- coding: utf-8 -*- # # Copyright (C) 2017 KuraLabs S.R.L # # 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...
############################################################ # -*- coding: utf-8 -*- # # # # # # # # # ## ## # ## # # # # # # # # # # # # # # # ## # ## ## ###### # # # # # # # # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 fo...
import sysconfig import sys CFLAGS = "{} -I{} -I{} -fno-omit-frame-pointer".format( sysconfig.get_config_var("CFLAGS"), sysconfig.get_path("include"), sysconfig.get_path("platinclude"), ) if __name__ == "__main__": print(f'export CFLAGS="{CFLAGS}"')
#!/usr/bin/env python3 # This example demonstrates the interaction between different execution modes import mavlinkinterface # Needed to use the library from time import sleep # For waiting between commands # Create interface object, All calls will be made through this # execMode="queue" means that the "que...
from uuid import uuid4 import pytest from protean import BaseCommand, BaseEventSourcedAggregate from protean.exceptions import IncorrectUsageError from protean.fields import String from protean.fields.basic import Identifier class User(BaseEventSourcedAggregate): id = Identifier(identifier=True) email = Str...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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 ...
import dataclasses import logging from dataclasses import dataclass import tempfile import os from typing import Optional import loaders import synth from synth import ( # noqa: F401 grid_dataset, grid_dataset_path, dataset_fixtures_dir, ) import fv3fit from fv3net.diagnostics.offline import compute from ...
import gym from agents.random_agent import RandomAgent def main(episode_count): env = gym.make('CartPole-v0') agent = RandomAgent(env.action_space.n) for i in range(episode_count): observation = env.reset() # initialize the environment done = False step = 0 while not done:...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XX XXX XXXXXX XXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXX XXXX XXXXXXX XX X XXXXXXXXXXX XXXX XXXXXX XXX XXXXX XXXXXXXXXX XX XXXXXXX XX XXX XXXXXX XXXXXXXX XX XXXX XX XXX XXXXXXXXX XXXXXX XXX XXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXXX XXXXXXXXX...
""" zoom.mail email services """ import os import json import logging from smtplib import SMTP from mimetypes import guess_type from email import encoders from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.audio import MIMEAudio fro...
# SPDX-License-Identifier: MIT # Copyright (c) 2022 MBition GmbH from ..globals import logger from .compumethodbase import CompuMethod class TabIntpCompuMethod(CompuMethod): def __init__(self, internal_type, physical_type): super().__init__(internal_type, physical_type...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from hashlib import md5 from flask import Flask, request, redirect, current_app from time import gmtime from xmltodict import parse import requests import urllib app = Flask(__name__) app.config.from_pyfile('config.py', silent=True) app.config.from_pyf...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from catboost import Pool from sklearn.model_selection import StratifiedKFold from tqdm import tqdm class CatBoostCustomModel: def __init__(self, model, model_params={}): self.result = {} try: self.model = model self.model.set_params(**m...
from __future__ import unicode_literals import logging from inspect import ismethod from django.core.urlresolvers import (reverse, resolve, NoReverseMatch, Resolver404) from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.encoding i...
from sklearn.model_selection import GridSearchCV from luciferml.supervised import classification as cls def hyperTune(classifier, parameters, X_train, y_train, cv_folds, tune_mode, isReg): """ Takes classifier, tune-parameters, Training Data and no. of folds as input and Performs GridSearch Crossvalidation. ...
import os.path import logging from utils import make_id, get_resource from os.path import join logger = logging.getLogger(__name__) def apps_dir(): return os.path.dirname(os.path.abspath(__file__)) def load_app(app_def_file, app_id=None, parent_group="/"): """Loads an app definition from a json file and s...
from abc import ABCMeta import numpy as np from torch.utils.data import ConcatDataset, Dataset, WeightedRandomSampler from mmpose.datasets.builder import DATASETS from .mesh_base_dataset import MeshBaseDataset @DATASETS.register_module() class MeshMixDataset(Dataset, metaclass=ABCMeta): """Mix Dataset for 3D hu...
# coding: utf-8 # pylint: disable=missing-docstring # pylint: disable=invalid-name import os import glob import subprocess from setuptools import setup, find_packages about = {} HERE = os.path.abspath(os.path.dirname(__file__)) with open(file=os.path.join(HERE, 'src','dima', '__version__.py'), mode='r', encoding='u...
import logging from os.path import expanduser from git import InvalidGitRepositoryError from pythoncommons.file_utils import FileUtils from pythoncommons.git_wrapper import GitWrapper LOG = logging.getLogger(__name__) class FormatPatchSaver: """ A class used to export git-format-patch files from a git repo...
"""Test the Cloudflare config flow.""" from pycfdns.exceptions import ( CloudflareAuthenticationException, CloudflareConnectionException, CloudflareZoneException, ) from homeassistant.components.cloudflare.const import CONF_RECORDS, DOMAIN from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER...
#!/usr/bin/env python # Requires metasploit, snmpwalk, snmpstat and John the Ripper # _____ _ ____ _______ ____ __ # / ___// | / / |/ / __ \ / __ )_______ __/ /____ # \__ \/ |/ / /|_/ / /_/ / / __ / ___/ / / / __/ _ \ # ___/ / /| / / / / ____/ / /_/ / / / /_/ / /_/ __/ #/____/_/ |_/_...
nasc = int(input('Ano de nascimento: ')) idade = 2018 - nasc if idade <= 9: print('Categoria: Mirim') elif idade <= 14: print('Categoria: Infantil') elif idade <= 19: print('Categoria: Júnior') elif idade <= 20: print('Categoria: Sênior') elif idade >= 21: print('Categoria: Master')
#!/usr/bin/env python # coding:utf-8 """ Test functionality of Service elements. """ # -- standard library --------------------------------------------------------- from cgi import parse_header, FieldStorage from threading import Thread import unittest import tempfile import zipfile import socket import json import s...
import unittest from PySide2.QtWidgets import * from qtimgren.main_window import MainWindow from unittest.mock import Mock, patch import qtimgren.main_window import qtimgren.about import qtimgren.profile import qtimgren.profiles class TestMainWindow(unittest.TestCase): @classmethod def setUpClass(cls) -> None...
from airflow.plugins_manager import AirflowPlugin from freshdesk_plugin.operators.freshdesk_to_s3_operator import FreshdeskToS3Operator class freshdesk_plugin(AirflowPlugin): name = "freskdesk_plugin" operators = [FreshdeskToS3Operator] hooks = [] # Leave in for explicitness executors = [] mac...
import numpy as np import random import matplotlib.pyplot as plt from collections import deque class UniformNoise(object): def __init__(self, action_space, initial_exploration = 0.99, final_exploration = 0.05, decay_rate = 0.999): self.action_dim = action_space.shape[0] # Requires Space with...
# These dictionaries are applied to the generated attributes dictionary at build time # Any changes to the API should be made here. attributes.py is code generated # We are not code genning attributes that have been marked as obsolete prior to the initial # Python API bindings release attributes_codegen_method = { ...
from Components.Sources.Source import Source from Components.Network import iNetwork from Tools.Directories import fileExists from twisted import version from socket import has_ipv6, AF_INET6, inet_ntop, inet_pton def normalize_ipv6(orig): net = [] if '/' in orig: net = orig.split('/') if net[1] == "128": d...
from services.lib.config import Config from services.lib.db import DB from localization.base import BaseLocalization from localization.eng import EnglishLocalization from localization.rus import RussianLocalization from services.lib.utils import Singleton class LocalizationManager(metaclass=Singleton): def __init...
import cv2 import numpy as np img = cv2.imread("Resources/lena.png") kernel = np.ones((5,5),np.uint8) imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) imgBlur = cv2.GaussianBlur(imgGray,(7,7),0) imgCanny = cv2.Canny(img,150,200) imgDialation = cv2.dilate(imgCanny,kernel,iterations=1) imgEroded = cv2.erode(img...
from __future__ import annotations from collections import defaultdict from typing import Any, Dict, Optional, Tuple from .fields import Field, ModelField from .validation import Validation class ModelBase: __slots__ = () def __init__(self): pass @classmethod def get_xmltag(cls) -> str: ...
"""Extension for using climatecontrol with dataclasses.""" from dataclasses import is_dataclass from typing import Generic, Mapping, Type, TypeVar import dacite from climatecontrol.core import Climate as BaseClimate from climatecontrol.core import SettingsItem as BaseSettingsItem from climatecontrol.fragment import ...
from flask import Blueprint, request, Response, json from main.models import database import csv mypage_page = Blueprint('mypage', __name__) def read_csv(user_id): file = csv.reader(open('../main/recommendation/recommend_list/{}.csv'.format(user_id), 'r',encoding='utf-8')) lists = [] for row in file: ...
# Imports import numpy as np import matplotlib.pyplot as plt import os # Results directory directory = os.path.join("results", "cbis", "history") figs_directory = os.path.join("results", "cbis", "figures") # Models MODELS = ["densenet121", "resnet50", "vgg16"] # Training Formats TRAINING_MODE = ["baseline", "basel...
import scapy.all as scapy import time import termcolor class ConnectToTarget: def spoof(self,router_ip,target_ip,router_mac,target_mac ): packet1=scapy.ARP(op=2, hwdst=router_mac,pdst=router_ip, psrc=target_ip) packet2=scapy.ARP(op=2, hwdst=target_mac,pdst=target_ip, psrc=router_ip) scapy.send(packet1) scap...
"""Test stack """ import ARgorithmToolkit algo = ARgorithmToolkit.StateSet() stack = ARgorithmToolkit.Stack("st",algo) def test_declare(): """Test stack creation """ last_state = algo.states[-1] assert last_state.content["state_type"] == "stack_declare" def test_operations(): """Test stack operat...
__author__ = "Johannes Köster" __copyright__ = "Copyright 2017, Johannes Köster" __email__ = "johannes.koester@tu-dortmund.de" __license__ = "MIT" import os import re import shutil import subprocess as sp from datetime import datetime import time from snakemake.remote import AbstractRemoteObject, AbstractRemoteProvid...
import os import os.path import json import numpy as np import sys import itertools import random import argparse import csv BASE_DIR = os.path.dirname(os.path.abspath(__file__)) UTILS_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'utils')) sys.path.append(UTILS_DIR) sys.path.append(BASE_DIR) # sys.path.insert(1...
import unittest from Calculator import Calculator from CsvReader.CSVReader import CsvReader class MyTestCase(unittest.TestCase): def test_instantiate_calculator(self): calculator = Calculator() self.assertIsInstance(calculator, Calculator) def test_addition_method(self): calculator =...
import numpy as np import pandas as pd import xarray as xr import cubepy from pyplan_engine.classes.evaluators.BaseEvaluator import BaseEvaluator from pyplan_engine.classes.evaluators.CubepyEvaluator import CubepyEvaluator from pyplan_engine.classes.evaluators.IPythonEvaluator import IPythonEvaluator from pyplan_engine...
#! /usr/bin/env python # $Id: test_class.py 5174 2007-05-31 00:01:52Z wiemann $ # Author: Lea Wiemann <LeWiemann@gmail.com> # Copyright: This module has been placed in the public domain. """ Tests for the 'class' directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.Parser...
# coding:utf-8 # 将图片以小分片的形式裁剪下来 import tkFileDialog import cv2 from configurationInjection import configInjection import os config = configInjection() config.loadConfiguration() rois = config.rois[0] flag = True videopath = tkFileDialog.askopenfilename(initialdir="/home/zb/myfile/cutSave") count = 0 cap = cv2.VideoC...
# -*- coding: utf-8 -*- """form base classes for aloha-editor integration""" import floppyforms as forms from djaloha.widgets import AlohaInput from django.utils.encoding import smart_unicode class DjalohaForm(forms.Form): """Base class for form with aloha editor""" def __init__(self, model_class, lookup, ...
"""Replays RocketLeagueReplays API module """ import requests BASE_URL = 'https://www.rocketleaguereplays.com/api/replays/?page=' def get_replays(page_num): """ Requests a page of replay data from the RocketLeagueReplaysAPI :param page_num: Page number to request :return: list of matches returned ...
# -*- coding: utf-8 -*- import urwid PALETTE = [ ('red', 'dark red', ''), ('selectedred', 'dark red', 'yellow'), ('selected', '', 'yellow'), ] # Modify these as needed SIZES = {'small': (4, 3), 'medium': (6, 4), 'large': (8, 6)} card_size = 'large' class BaseCardWidget(urwid.WidgetWrap): def __init...
# coding: utf-8 """ ELEMENTS API The version of the OpenAPI document: 2 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from elements_sdk.configuration import Configuration class TapeFile(object): """NOTE: This class is auto generated by OpenAPI ...
from unittest import mock from django import forms from django.test import SimpleTestCase from django.utils.functional import lazy from phonenumber_field.formfields import PhoneNumberField ALGERIAN_PHONE_NUMBER = "+213799136332" class PhoneNumberFormFieldTest(SimpleTestCase): def test_error_message(self): ...
from pkg.command.azcli_cmd import AzCliCommand from pkg.entity._az_cli import AzCli from pkg.executor._executor import Executor from pkg.executor.azcli.command._azcli_cmd_executor import AzCliCommandExecutor class AzCliExecutor(Executor): def __init__(self): pass def run_az_cli(self, cmd: AzCli): ...
from logging import captureWarnings from operator import inv from typing import Container, Iterable, Union import uuid import time import math from datetime import datetime, timedelta, timezone from unittest import TestCase from unittest.mock import patch, MagicMock, ANY, call from botocore.exceptions import ClientErr...
import datetime import dateutil.parser import pytz from django.conf import settings from django.db.models import F, Q from django.http import ( Http404, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils imp...
from invoke import task from os.path import join, exists from os import makedirs from shutil import copy, rmtree from subprocess import run from tasks.util.env import ( BIN_DIR, GLOBAL_BIN_DIR, KUBECTL_BIN, AZURE_RESOURCE_GROUP, AZURE_VM_SIZE, AKS_CLUSTER_NODE_COUNT, AKS_CLUSTER_NAME, ) fro...
import sys class ModelSearchCriteria: def __init__(self, datatable_names: [str], column_names: [str], search_text: str ): self.datatable_names = datatable_names self.column_names = column_names self.search_text = search_text
#!/usr/bin/python # -*- coding: utf_8 -*- """Access and query Twitter's API with the simplistic twitter package (`pip install twitter`). """ from __future__ import print_function from __future__ import unicode_literals import csv import os import time from twitter import OAuth from twitter import Twitter def setup...
import jieba import jieba.analyse from gensim.test.utils import get_tmpfile import gensim.models.word2vec as word2vec from path import Path import argparse from utils import readlines,SeqSubSeq,toarry #文件位置需要改为自己的存放路径 #将文本分词 parser = argparse.ArgumentParser(description="precess tree file to a doc") parser.add_argume...
"""functions for working with tensorboard""" from pathlib import Path import pandas as pd from tensorboard.backend.event_processing.event_accumulator import EventAccumulator def logdir2df(logdir): """convert tensorboard events files in a logs directory into a pandas DataFrame events files are created by Sum...
import json import logging import os from datetime import datetime def coco_evaluation(dataset, predictions, output_dir, iteration=None): coco_results = [] for i, prediction in enumerate(predictions): img_info = dataset.get_img_info(i) prediction = prediction.resize((img_info['width'], img_inf...
from snovault import upgrade_step @upgrade_step('suspension', '1', '2') def suspension_1_2(value, system): if 'biosample_ontology' in value: del value['biosample_ontology'] @upgrade_step('suspension', '2', '3') def suspension_2_3(value, system): if 'url' in value: value['urls'] = [value['url']] del value['ur...
# -*- coding: utf-8 -*- from django.conf.urls import url from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase, override_settings from django.views.generic import CreateView, UpdateView, DeleteView, DetailView class CreateUserView(CreateView): ...
""" This set of functions is for analyzing all the articles in the PLOS corpus. A Jupyter Notebook is provided with examples of analysis. It can: * compare the articles indexed in Solr, PMC, and article pages * spot-check individual JATS fields for irregularities * create summaries of articles by type, publ...
import json import jk_json import jk_typing import jk_prettyprintobj from thaniya_common.cfg import CfgKeyValueDefinition from thaniya_common.cfg import AbstractCfgComponent from .BackupVolumeID import BackupVolumeID class _Magic(AbstractCfgComponent): MAGIC = "thaniya-volume-cfg" __VALID_KEYS = [ Cf...
import os from threading import Thread from sh import tail from pymouse import PyMouse from datetime import datetime, timedelta import subprocess WAS_MOVED_SCATTER = 0 # in seconds SHORT_PRESS = .15 MEDIUM_PRESS = .4 LONG_PRESS = .6 VERY_LONG_PRESS = 1 SCROLL_SENSITIVITY = 10 MOVE_SENSITIVITY = .8 MOVE_SCALING = 1....
#Write a Python program to add leading zeroes to a string. string = '5699' print() print(string.ljust(7, '0'))
from django.apps import AppConfig class DbSearchConfig(AppConfig): name = 'db_search'
import os import shutil import unittest import pandas as pd from python_tools.workflow_tools.qc.fingerprinting import ( read_csv, plot_genotyping_matrix ) class FingerprintingTestCase(unittest.TestCase): def setUp(self): """ Set some constants used for testing :return: "...