content
stringlengths
0
894k
type
stringclasses
2 values
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 from test_utils.label_to_str_voc import convert_label_to_str def render_boxs_info_for_display(image, net_out, select_index, net_score, image_size, label_out = None): v...
python
import unittest import numpy as np from sca.analysis import nicv class TestNicvUnit(unittest.TestCase): def test_calculate_mean_x_given_y_matrix(self): """ Tests whether the calculations of means work properly""" traces = np.array([[1, 2, 3], [4, 5, 6], [7, 0.4, 9], [2, 3, 12]]) plain = ...
python
# coding: utf-8 # In[ ]: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn import tree get_ipython().run_line_magic('matplotlib', 'inline') # In[ ]: def maybe_load_loan_data(threshold=1, path='../input/loan.csv', force='n'): def load_data(): da...
python
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as torch_models class PerceptualLoss(nn.Module): def __init__(self, rank): super(PerceptualLoss, self).__init__() self.rank = rank self.vgg19 = torch_models.vgg19(pretrained=True) self.vgg...
python
""" Generates a powershell script to install Windows agent - dcos_install.ps1 """ import os import os.path import gen.build_deploy.util as util import gen.template import gen.util import pkgpanda import pkgpanda.util def generate(gen_out, output_dir): print("Generating Powershell configuration files for DC/OS"...
python
#!/usr/bin/python3 #Self Written Module to Decrypt Files #========================================================= #This Module is Written to Reverse_Attack of Ransomeware #========================================================= # Reverse_Attack # |____*****TAKES 1 ARGUMENTS, i.e. KEY ***** # |____Initia...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # ****************************************************** # @author: Haifeng CHEN - optical.dlz@gmail.com # @date (created): 2019-12-12 09:07 # @file: memory_monitor.py # @brief: A tool to monitor memory usage of given process # @internal: ...
python
##ๅบๅˆ—่งฃๅŒ… dict={"name":"jim","age":"1","sex":"male"} key,value=dict.popitem(); print(key,value) #ไฝฟ็”จ*ๅทๆ”ถ้›†ๅคšไฝ™็š„ๅ€ผ a,b,*rest=[1,2,3,4]; print(a,b,rest) ##้“พๅผ่ต‹ๅ€ผ x=y=somfunction() ##ๅขžๅผบ่ต‹ๅ€ผ x+=1 ###ไปฃ็ ๅ—
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pydoc import subprocess import sys import signal from pkg_resources import get_distribution from termcolor import colored from projects import config from projects import gui from projects import paths from projects import projectfile __version__ = get_...
python
"""Frigate API client.""" from __future__ import annotations import asyncio import logging import socket from typing import Any, Dict, List, cast import aiohttp import async_timeout from yarl import URL TIMEOUT = 10 _LOGGER: logging.Logger = logging.getLogger(__name__) HEADERS = {"Content-type": "application/json;...
python
import jieba import jieba.posseg as pseg #่ฏๆ€งๆ ‡ๆณจ import jieba.analyse as anls #ๅ…ณ้”ฎ่ฏๆๅ– class Fenci: def __init__(self): pass #ๅ…จๆจกๅผๅ’Œ็ฒพ็กฎๆจกๅผ def cut(self,word,cut_all=True): return jieba.cut(word, cut_all=True) #ๆœ็ดขๅผ•ๆ“Žๆจกๅผ # def cut_for_search(self,word): # return jieba.cut_for_search(w...
python
''' Unit tests for the environments.py module. ''' import boto3 import json import pytest from mock import patch from moto import ( mock_ec2, mock_s3 ) from deployer.exceptions import ( EnvironmentExistsException, InvalidCommandException) import depl...
python
#!/usr/bin/env python3 # coding: utf-8 # print ใฎๅ‡บๅŠ›ๆ™‚ใซๆ—ฅๆœฌ่ชžใงใ‚‚ใ‚จใƒฉใƒผใŒๅ‡บใชใ„ใ‚ˆใ†ใซใ™ใ‚‹ใŠใพใ˜ใชใ„ import sys import io sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding='utf-8' ) # CGIใจใ—ใฆๅฎŸ่กŒใ—ใŸ้š›ใฎใƒ•ใ‚ฉใƒผใƒ ๆƒ…ๅ ฑใ‚’ๅ–ใ‚Šๅ‡บใ™ใƒฉใ‚คใƒ–ใƒฉใƒช import cgi form_data = cgi.FieldStorage( keep_blank_values = True ) # MySQLใƒ‡ใƒผใ‚ฟใƒ™ใƒผใ‚นๆŽฅ็ถš็”จใƒฉใ‚คใƒ–ใƒฉใƒช import MySQLdb con = None cur =...
python
#!/usr/bin/env python3 # coding: utf-8 import os import sys import re import numpy as np #==============================================================================# def atomgroup_header(atomgroup): """ Return a string containing info about the AtomGroup containing the total number of atoms, th...
python
from pydantic import BaseModel class ConsumerResponse(BaseModel): topic: str timestamp: str product_name: str product_id: int success: bool
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `te_python` module.""" import pytest import requests from te_python import te_python def test_te_python_initialization(): response = te_python.email_get_details('a53b7747d6bd3f59076d63469d92924e00f407ff472e5a539936453185ecca6c') assert isinstance(re...
python
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=64) surname = models.CharField(max_length=64) class Meta: app_label = 'person' db_table = 'person' ordering = ('surname', 'first_name')
python
from util.Tile import Tile from util.Button import Button from util.Maze import Maze from algorithms.BFS import BFS from algorithms.DFS import DFS from algorithms.GFS import GFS from algorithms.AStar import AStar from math import floor import pygame class Grid: def __init__(self, width, height, tile...
python
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
from discord.ext import commands from discord_bot.bot import Bot class Admin(commands.Cog): """Admin commands that only bot owner can run""" def __init__(self, bot: Bot): self.bot = bot @commands.command(name="shutdown", hidden=True) @commands.is_owner() async def shutdow(self, ctx: com...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
python
from ctypes import CDLL, sizeof, create_string_buffer def test_hello_world(workspace): workspace.src('greeting.c', r""" #include <stdio.h> void greet(char *somebody) { printf("Hello, %s!\n", somebody); } """) workspace.src('hello.py', r""" import ctypes lib = ctypes.CDLL('./g...
python
from gui import GUI program = GUI() program.run()
python
#!/usr/bin/env python3 # # RoarCanvasCommandsEdit.py # Copyright (c) 2018, 2019 Lucio Andrรฉs Illanes Albornoz <lucio@lucioillanes.de> # from GuiFrame import GuiCommandDecorator, GuiCommandListDecorator, GuiSelectDecorator import wx class RoarCanvasCommandsEdit(): @GuiCommandDecorator("Hide assets window", "Hide a...
python
#!/usr/bin/python3 """ Module installation file """ from setuptools import Extension from setuptools import setup extension = Extension( name='fipv', include_dirs=['include'], sources=['fipv/fipv.c'], extra_compile_args=['-O3'], ) setup(ext_modules=[extension])
python
import os import time import hashlib import gzip import shutil from subprocess import run from itertools import chain CACHE_DIRECTORY = "downloads_cache" def decompress_gzip_file(filepath): decompressed = filepath + ".decompressed" if not os.path.exists(decompressed): with gzip.open(filepath, 'rb') ...
python
from MainWindow import Ui_MainWindow from PyQt6 import QtWidgets import sys class CalcWindow(Ui_MainWindow, QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.equalButton.clicked.connect(self.calculation) self.cBu...
python
from tornado.web import HTTPError class APIError(HTTPError): def __init__( self, status_code: int, reason: str, message: str = None, details: dict = None, ): log_message = ': '.join(map(str, filter(None, [message, details]))) or None super().__init__( ...
python
#!/usr/bin/python # Report generator import api import fn import sys import dumper def main(argv): config = {} config["usagetext"] = ("repgen.py (-s SEARCHPREFIX|-a) [-c CONFIGFILE]\n"+ " This script generates a report for all servers if -a is used,\n"+ "or just the servers with SEARCH...
python
import os import logging import json from codecs import open from collections import Counter import numpy as np import spacy from tqdm import tqdm """ The content of this file is mostly copied from https://github.com/HKUST-KnowComp/R-Net/blob/master/prepro.py """ nlp = spacy.blank("en") def word_tokenize(sent): ...
python
''' Clase principal, contiene la logica de ejecuciรณn del servidor y rutas para consumo de la API ''' from entities.profile import Profile from flask import Flask, jsonify, request from flask_restful import Resource, Api from flask_httpauth import HTTPBasicAuth from datetime import datetime import pandas as pd import nu...
python
from glitchtip.permissions import ScopedPermission class ReleasePermission(ScopedPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin", "project:releases"], "POST": ["project:write", "project:admin", "project:releases"], "PUT": ["project:write", "project:admin...
python
# StandAlone Version """ Created on Thu Apr 2 19:28:15 2020 @author: Yao Tang """ import arcpy import os arcpy.env.overwriteOutput = True arcpy.env.addOutputsToMap = True ## Specify workspace(Usually the folder of the .mxd file) arcpy.env.workspace = "L:/Projects/3020/006-01/6-0 DRAWINGS AND FIGURES/6-...
python
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="crudini", version="0.9.3", author="Pรกdraig Brady", author_email="P@draigBrady.com", description=("A utility for manipulating ini fi...
python
def abc209d(): from collections import deque n, Q = map(int, input().split()) g = [list() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a, b = a - 1, b - 1 g[a].append(b) g[b].append(a) c = [-1] * n q = deque([0]) c[0] = 0 whil...
python
from sim.agents.agents import * from sim.agents.multiagents import *
python
# -*- coding: utf-8 -*- # Copyright (c) 2016, French National Center for Scientific Research (CNRS) # Distributed under the (new) BSD License. See LICENSE for more info. from pyqtgraph.Qt import QtCore import pyqtgraph as pg from pyqtgraph.util.mutex import Mutex import numpy as np from ..core import (Node, register_...
python
""" Copyright 2018 The Johns Hopkins University Applied Physics Laboratory. 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...
python
"Thread safe RLock defined for lru cache." # https://stackoverflow.com/questions/16567958/when-and-how-to-use-pythons-rlock def RLock(): """ Make the container thread safe if running in a threaded context. """ import threading return threading.RLock()
python
import logging _LOGGER = logging.getLogger(__name__) def decode(packet): """ https://github.com/telldus/telldus/blob/master/telldus-core/service/ProtocolEverflourish.cpp """ data = packet["data"] house = data & 0xFFFC00 house >>= 10 unit = data & 0x300 unit >>= 8 unit += 1 ...
python
# script to copy history from a FITS table to the FITS header # FITS images only, works in current directory # Argument: # 1) Name of input FITS # example: # Python scriptHi2Header.py myImage.fits import sys, Obit, Image, History, OSystem, OErr # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Hi2Header", 1, 100,...
python
#!/bin/python3 import math import os import random import re import sys # # Complete the 'superDigit' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. STRING n # 2. INTEGER k # def superDigit(n, k): if((len(n) == 1)and(k>1)): n,k = str...
python
# # Copyright 2015-2020 Andrey Galkin <andrey@futoin.org> # # 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...
python
import stringcase from importlib import import_module from .metadata import Metadata from .resource import Resource from .package import Package from . import helpers from . import errors class Pipeline(Metadata): """Pipeline representation API | Usage -------- | -------- Public | `from fricti...
python
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import re from contextlib import contextmanager from dataclasses import dataclass from textwrap import dedent from typing import Any from pants.engine.internals.engine_testutil import ( ...
python
# Copyright 2016 Pavle Jonoski # # 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 writing...
python
f = open('3_input.txt').read().splitlines() def life_support_rating(o2, co2): return o2 * co2 def filter(list, i=0, co2=False): # where `i` is the bit position if len(list) == 1: return list[0] count = 0 for item in list: count += int(item[i]) dom_num = 1 if count >= len(list) / 2 ...
python
import pytest import numpy from thinc.layers import Embed from ...layers.uniqued import uniqued from numpy.testing import assert_allclose from hypothesis import given from hypothesis.strategies import integers, lists, composite ROWS = 10 # This test uses a newer hypothesis feature than the skanky flatmap-style # I us...
python
from datasets.SOT.dataset import SingleObjectTrackingDatasetSequence_MemoryMapped from ._common import _check_bounding_box_validity class SOTSequenceSequentialSampler: def __init__(self, sequence: SingleObjectTrackingDatasetSequence_MemoryMapped): assert len(sequence) > 0 self.sequence = sequence ...
python
from django.db import models from django.urls import reverse class ImportantDate(models.Model): date = models.DateField() desc = models.CharField(max_length=100) def __str__(self): return "{} - {}".format(self.date, self.desc) def get_absolute_url(self): return reverse('formschapter:...
python
from django.contrib import admin from purchasing.models import PurchasedOrder class PurchasedOrderAdmin(admin.ModelAdmin): readonly_fields = ['expiration_date'] admin.site.register(PurchasedOrder)
python
from typing import Dict, Optional from sqlalchemy import column, literal_column, select from panoramic.cli.husky.core.sql_alchemy_util import ( quote_identifier, safe_identifier, sort_columns, ) from panoramic.cli.husky.service.blending.blending_taxon_manager import ( BlendingTaxonManager, ) from pano...
python
import theano import theano.tensor as T import treeano from treeano.sandbox.nodes import bttf_mean fX = theano.config.floatX @treeano.register_node("bachelor_normalization") class BachelorNormalizationNode(treeano.NodeImpl): hyperparameter_names = ("bttf_alpha", "alpha", ...
python
print("My name is John")
python
# -*- coding: utf-8 -*- # Copyright 2013 Simonas Kazlauskas # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation from os import path, makedirs from hashlib import sha1 from gi.repository...
python
# Edit by Tianyu Ma # coding: utf-8 """ ===== Third step: merge csv files ===== """
python
import json import string import csv fname = './data/obama_speech.txt' fhand = open(fname, 'r') text = fhand.read() lines = text.split('\n') line_count = len(lines) word_count = 0 for line in lines: words = line.split() for word in words: if word == " ": continue word_count += 1 pr...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-10-23 21:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Words...
python
# forๅพช็Žฏๆ˜ฏไธ€็ง้ๅކๅˆ—่กจ็š„ๆœ‰ๆ•ˆๆ–นๅผ, ไฝ†ๅœจforๅพช็Žฏไธญไธๅบ”ไฟฎๆ”นๅˆ—่กจ, ๅฆๅˆ™ๅฐ†ๅฏผ่‡ดPython้šพไปฅ่ทŸ่ธชๅ…ถไธญ็š„ๅ…ƒ็ด . # ่ฆๅœจ้ๅކๅˆ—่กจ็š„ๅŒๆ—ถๅฏนๅ…ถ่ฟ›่กŒไฟฎๆ”น, ๅฏไฝฟ็”จwhileๅพช็Žฏ. # ๅœจๅˆ—่กจไน‹้—ด็งปๅŠจๅ…ƒ็ด  unconfirmed_users = ['alice', 'brian', 'candace'] # ๅพ…้ชŒ่ฏ็”จๆˆทๅˆ—่กจ confirmed_users = [] # ๅทฒ้ชŒ่ฏ็”จๆˆทๅˆ—่กจ # ้ๅކๅˆ—่กจๅฏน็”จๆˆท่ฟ›่กŒ้ชŒ่ฏ while unconfirmed_users: # ๅฝ“ๅˆ—่กจไธไธบ็ฉบๆ—ถ่ฟ”ๅ›žTrue, ๅฝ“ๅˆ—่กจไธบ็ฉบๆ—ถ, ่ฟ”ๅ›žFalse current_user = unconfirmed_users.pop() # ๅ–...
python
from datetime import datetime from lib import d,t def main(): r = t.t() r = (r+(' '+(d.d()))) print(f'{r} :)') return(0x01) if(__name__==('__main__')): main()
python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Script to help in managing Usenet hierarchies. It generates control # articles and handles PGP keys (generation and management). # # signcontrol.py -- v. 1.4.0 -- 2014/10/26 # # Written and maintained by Julien ร‰LIE. # # This script is distributed under the MIT License. P...
python
with open('p11_grid.txt', 'r') as file: lines = file.readlines() n = [] for line in lines: a = line.split(' ') b = [] for i in a: b.append(int(i)) n.append(b) N = 0 for i in range(20): for j in range(20): horizontal, vertical, diag1, diag2 = 0, 0,...
python
# -*- coding: utf-8 -*- # # COMMON # page_action_basket = "ะšะพั€ะทะธะฝะฐ" page_action_enter = "ะ’ะพะนั‚ะธ" page_action_add = "ะ”ะพะฑะฐะฒะธั‚ัŒ" page_action_cancel = "ะžั‚ะผะตะฝะฐ" page_action_yes = "ะ”ะฐ" page_action_save = "ะกะพั…ั€ะฐะฝะธั‚ัŒ" page_action_action = "ะ”ะตะนัั‚ะฒะธะต" page_action_modify = "ะธะทะผะตะฝะธั‚ัŒ" page_action_remove = "ัƒะดะฐะปะธั‚ัŒ" page_message_e...
python
#!/usr/bin/env python3 # -*-coding: utf-8 -*- """ .. invisible: _ _ _____ _ _____ _____ | | | | ___| | | ___/ ___| | | | | |__ | | | |__ \ `--. | | | | __|| | | __| `--. \ \ \_/ / |___| |___| |___/\__/ / \___/\____/\_____|____/\____/ Created on October 14, 2014 โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ...
python
from typing import List # ------------------------------- solution begin ------------------------------- class Solution: def canWinNim(self, n: int) -> bool: return n % 4 == 0 # ------------------------------- solution end - -------------------------------- if __name__ == '__main__': input = 4 print("In...
python
bat = int(input('bateria = ')) def batery (bat): if bat == 0: print('morri') elif bat > 0 and bat < 21: print('conecte o carreador') elif bat > 20 and bat < 80: print('carregando...') elif bat > 79 and bat < 100: print('estou de boa') elif bat == 100: print('p...
python
#coding:utf8 ''' Created on 2016ๅนด4ๆœˆ20ๆ—ฅ @author: wb-zhaohaibo ''' import MySQLdb print MySQLdb conn = MySQLdb.Connect( host="127.0.0.1", port=3306, user="root", passwd="admin", db="testsql...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script for updating pymoprhy2 dictionaries (Russian and Ukrainian). Please note that it is resource-heavy: it requires > 3GB free RAM and about 1GB on HDD for temporary files. Usage: update.py (ru|uk) (download|compile|package|cleanup) ... update.py (ru|uk) al...
python
import Selenium_module as zm print("Zillow Downloader") url = input("URL: ") image_links, title = zm.get_links(url) zm.get_images(image_links, title) zm.cleanup_exit()
python
from flask_wtf import FlaskForm from datetime import datetime from wtforms import BooleanField, DateTimeField, HiddenField, SelectField, StringField, SubmitField, ValidationError from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.validators import Required, Optional from .. models import Element, E...
python
import numpy as np import os import cv2 import sys import time import dlib import glob import argparse import voronoi as v def checkDeepFake(regions): return True def initialize_predictor(): # Predictor ap = argparse.ArgumentParser() if len(sys.argv) > 1: predictor_path ...
python
r""" FSS-1000 few-shot semantic segmentation dataset """ import os import glob from torch.utils.data import Dataset import torch.nn.functional as F import torch import PIL.Image as Image import numpy as np class DatasetFSS(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize)...
python
# The Python print statement is often used to output variables. # To combine both text and a variable, Python uses the '+' character: x = "awesome" print("Python is " + x) # You can also use the '+' character to add a variable to another variable: x = "Python is " y = "awesome" z = x + y print(z) # For numbers, the '...
python
from keras.applications.resnet50 import ResNet50 as RN50 from keras.preprocessing import image from keras.models import Model from keras.layers import Flatten from keras.layers import Dense, GlobalAveragePooling2D from keras import backend as K from keras.utils import plot_model from keras.preprocessing.image import Im...
python
import ctypes # Implements the Array ADT using array capabilities of the ctypes module. class Array : # Creates an array with size elements. def __init__( self, size ): assert size > 0, "Array size must be > 0" self._size = size # Create the array structure using the ctypes module. ...
python
#!/usr/bin/env python3 # Copyright (c) 2021 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 # # U...
python
# Unit test set_out_sample_residuals ForecasterAutoreg # ============================================================================== import numpy as np import pandas as pd from skforecast.ForecasterAutoreg import ForecasterAutoreg from sklearn.linear_model import LinearRegression def test_predict_interval_output_w...
python
import os import gzip import cPickle from config import config for fold in range(5): filename = os.path.join(config.data_dir, 'atis.fold' + str(fold) + '.pkl.gz') with gzip.open(filename, 'rb') as f: train_set, valid_set, test_set, dicts = cPickle.load(f) labels2idx_, tables2idx_, words2idx_ =...
python
import unittest from bsim.connection import * class TestConnectionMethods(unittest.TestCase): def test_data(self): c = Connection(debug=False) c.delay_start = [0, 0, 3, 0, 1, 0, 0, 0, 0, 2, 0, 0] c.delay_num = [1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0] c.rev_delay_start = [0, 0, 0, 1, ...
python
class History(object): def __init__(self, name, userID): self.name = name self.userID = userID self.history = [] def logMessage(self, lastMessage): if len(self.history) > 10: self.history.pop() self.history.append(lastMessage) def getLastMessages(self, n...
python
import logging __title__ = 'django_nine.tests.base' __author__ = 'Artur Barseghyan' __copyright__ = '2015-2019 Artur Barseghyan' __license__ = 'GPL-2.0-only OR LGPL-2.1-or-later' __all__ = ( 'LOG_INFO', 'log_info', ) logger = logging.getLogger(__name__) LOG_INFO = True def log_info(func): """Logs some...
python
import os import datetime import MySQLdb con = MySQLdb.connect(host='DBSERVER', user='DBUSER', passwd='DBPASSWD', db='DB') cur = con.cursor() cur.execute("SHOW TABLES") data = "SET FOREIGN_KEY_CHECKS = 0; \n" tables = [] for table in cur.fetchall(): tables.append(table[0]) for table in tables: if table != "f...
python
from .data_parallel import CustomDetDataParallel from .sync_batchnorm import convert_model
python
import os from setuptools import setup setup(name='NNApp01', version='0.1.0', description='NN Programming Assignment ', author='Dzmitry Buhryk', author_email='dzmitry.buhryk@gmail.com', license='MIT', install_requires=['flask', 'werkzeug'], tests_require=['requests', 'flask',...
python
from multiprocessing import Process import envServer from distutils.dir_util import copy_tree from random import shuffle import sys sys.path.append("../pyutil") sys.path.append("..") import signal import parseNNArgs import traceback import threading import pickle import shutil import glob import os import random im...
python
#!/usr/bin/env python3 #-*- encoding: UTF-8 -*- def main(): try: nota1 = float(input("1ยช nota: ")) nota2 = float(input("2ยช nota: ")) except: print("Apenas valores numรฉricos devem ser informados!") if(nota1 < 0 or nota1 > 10 or nota2 < 0 or nota2 > 10): print("Notas invรกlidas...
python
from . import util ut = util.Util() reload(util) class ViewerMarlin(): def open_file(self, path): with open(path) as f: l = f.readlines() # print(type(l)) # print(len(l)) # print(l) return l def get_value_move(self, str_): ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of tofbot, a friendly IRC bot. # You may redistribute it under the Simplified BSD License. # If we meet some day, and you think this stuff is worth it, # you can buy us a beer in return. # # Copyright (c) 2011,2015 Etienne Millon <etienne.millon@gmail....
python
# Copyright 2016 Peter Dymkar Brandt 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 applicable ...
python
from numpy import absolute, isnan, where from scipy.spatial.distance import correlation def compute_correlation_distance(x, y): correlation_distance = correlation(x, y) if isnan(correlation_distance): return 2 else: return where(absolute(correlation_distance) < 1e-8, 0, correlation_di...
python
# This sample tests the case where a subclass of Dict uses # a dictionary literal as an argument to the constructor call. from collections import Counter, defaultdict from typing import Callable, Generic, Mapping, Optional, TypeVar c1 = Counter({0, 1}) reveal_type(c1, expected_text="Counter[int]") for i in range(256...
python
# Sequรชncia dos termos numรฉricos de uma funรงรฃo arbitrรกria. # Printa a sequรชncia dos termos da funรงรฃo X^2 atรฉ um termo escolhido. n = int(input()) for i in range(0,n): print(i*i) i = i+1 # Printa a sequรชncia dos termos da funรงรฃo X^3 atรฉ um termo escolhido y = int(input()) for i in range (0,y...
python
from bisect import bisect from contextlib import closing, contextmanager from itertools import accumulate, chain, islice, zip_longest from multiprocessing import Lock, RawValue, Process from os import cpu_count from re import sub from sys import argv, stdout output_file = open("bench_output-fasta_bg.txt", mode="wb", b...
python
# ______ _ _ _ _ _ _ _ # | ___ \ | | | | (_) (_) | | (_) # | |_/ / __ ___ | |__ __ _| |__ _| |_ ___| |_ _ ___ # | __/ '__/ _ \| '_ \ / _` | '_ \| | | / __| __| |/ __| # | | | | | (_) | |_) | (_| | |_) | | | \__ \ |_| | (__ # \_| |_| \___/|_.__/ \__,_|...
python
# -*- coding: utf-8 -*- """ drift - Logging setup code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Set up logging based on config dict. """ from __future__ import absolute_import import os import logging from logging.handlers import SysLogHandler import logging.config import json import datetime import s...
python
# -*- coding: utf-8 -*- ''' Created on 2017/09/14 @author: yuyang ''' import os import urllib import uuid from docx.shared import Pt from docx.shared import RGBColor from docx.shared import Inches JPEG_EXTENSION = '.jpg' PNG_EXTENSION = '.png' GIF_EXTENSION = '.gif' SPLIT_STRING = '///' def add_author(document, a...
python
""" Views for the app """ from __future__ import absolute_import from __future__ import division import os import uuid from auth import constants from auth.forms import \ CategoryForm, \ CountryForm, \ CurrencyForm, \ GatewayForm, \ LoginVoucherForm, \ MyUserForm, \ NetworkForm, \ Ne...
python
# Copyright (c) Naas Development Team. # Distributed under the terms of the Modified BSD License. import os c = get_config() c.NotebookApp.ResourceUseDisplay.track_cpu_percent = True c.NotebookApp.ResourceUseDisplay.mem_warning_threshold = 0.1 c.NotebookApp.ResourceUseDisplay.cpu_warning_threshold = 0.1 # We rely o...
python
#FUNร‡ร•ES (FUNCTION) #EXEMPLO SEM O USO DE FUNร‡รƒO :( rappers_choice = ["L7NNON", "KB", "Trip Lee", "Travis Scott", ["Lecrae", "Projota", "Tupac"], "Don Omar"] rappers_country = {"BR":["Hungria", "Kamau", "Projota", "Mano Brown", "Luo", "L7NNON"], "US":["Tupac", "Drake", "Eminem", "KB", "Kanye West", "Lecrae", "Tra...
python
from __future__ import print_function import numpy as np import time, os, sys import matplotlib.pyplot as plt from scipy import ndimage as ndi from skimage import color, feature, filters, io, measure, morphology, segmentation, img_as_ubyte, transform import warnings import math import pandas as pd import argparse impor...
python