content
stringlengths
5
1.05M
import pandas as pd from bokeh.io import show, curdoc from bokeh.layouts import layout from bokeh.models import ColumnDataSource, FactorRange from bokeh.plotting import figure from bokeh.sampledata.degrees import data from bokeh.themes import Theme data = data.set_index('Year') categories = data.columns.tolist() cate...
from django import template from django.forms.utils import flatatt from django.template.loader import render_to_string from django.utils.html import format_html, format_html_join from core.constants import VIDEO_DURATION_DATA_ATTR_NAME register = template.Library() def _get_poster_attribute(video): if video and...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import neurovault.apps.statmaps.models import neurovault.apps.statmaps.storage class Migration(migrations.Migration): dependencies = [ ('statmaps', '0073_auto_20161111_0033'), ] operations =...
#!/usr/bin/env python3 # # Copyright 2021 Xiaomi Corporation (author: Wei Kang) # # See ../../../LICENSE for clarification regarding multiple 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...
#!/usr/local/bin/python import os, sys, time space = ' ' # read file by filename def read_file(filename): f = open(filename, 'r') content = f.readlines() f.close() return content def handleTemp(temp): # extract content from <TEXT> and void <TEXT>content</TEXT> start = temp.find('<TEXT>') + ...
# -*- coding: utf-8 -*- from icemac.addressbook.interfaces import IPerson import icemac.addressbook.testing import pytest import zope.component.hooks # Fixtures to set-up infrastructure which are usable in tests, # see also in ./fixtures.py (which are imported via src/../conftest.py): @pytest.yield_fixture(scope='fu...
log_enabled = True # 1 = print everything # 2 = print few stuff # 3 = print fewer stuff log_level = 2 def log(message, message_type="info", level=3): if not log_enabled: return log_message_type_symbols = { "info": "[*]", "warning": "[!]", "error": "[x]", "success": "[+...
from diary.views import get_next_or_none from django.urls import reverse def test_get_next_or_none__last(note): assert get_next_or_none(note) is None def test_get_next_or_none__next_exists(note2): assert get_next_or_none(note2).title == 'My Title' def test_NoteListView(client, note): response = client.g...
# # Control an RFSpace SDR-IP, NetSDR, or CloudIQ. # # Example: # sdr = sdrip.open("192.168.3.125") # sdr.setrate(32000) # sdr.setgain(-10) # sdr.setrun() # while True: # buf = sdr.readiq() # OR buf = sdr.readusb() # # Robert Morris, AB1HL # import socket import sys import os import numpy import scip...
# # This file is part of Python Client Library for STAC. # Copyright (C) 2019 INPE. # # Python Client Library for STAC is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Python Client Library for STAC.""" from .stac import Stac from...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 NTT DOCOMO, INC. # 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.apach...
from __future__ import print_function import os import sys from distutils.dir_util import copy_tree from pathlib import Path import pytest from _pytest.pytester import Testdir from pytest import ExitCode from tests.util import RESOURCES pytest_plugins = "pytester" NB_VERSION = 4 import shutil @pytest.fixture def f...
import os import re import subprocess ######################################## # Globals ############################## ######################################## g_verbose = False IGNORE_PATHS = ("/lib/modules",) ######################################## # Functions ############################ ######################...
import random import time import cv2 from abc import ABC, abstractmethod from core.dataClasses.frame import Frame class ImageProcessingInt(ABC): """ Base Abstract class aka Interface for Image processing class """ @abstractmethod def process(self, _observer, _scheduler): """ Imp...
from .attckobject import AttckObject class AttckTactic(AttckObject): def __init__(self, attck_obj = None, **kwargs): '''The AttckTactic class is used to gather information about all Mitre ATT&CK Framework Tactics. To access this class directly you must first instantiate it and provide the appr...
from sys import argv script, input_file = argv def print_all(f): print(f.read()) # This will reset the position of the pointer to the start def rewind(f): f.seek(0) def print_a_line(line_no,f): print(line_no, f.readline()) current_file = open(input_file) print("First print the whole file: ") print_all...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Advent of Code 2020 # https://github.com/scorphus/advent-of-code-2020 # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2020, Pablo S. Blum de Aguiar <scorphus@gmail.com> SEA_MONSTER = ( ...
# 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...
#!/usr/bin/env python # # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility for static analysis test of dart packages generated by dart-pkg""" import argparse import errno import json import multip...
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean CLI v1.0. Copyright 2021 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache...
from django.shortcuts import render from django.http import HttpResponse from django.utils import translation from challenge.models import Challenge from codingPage.models import Log, Command from connections.models import Feedback def convert_to_code(data): translation = '' for char in data: action =...
#!/usr/bin/python import optparse, os, shutil, sys, tempfile, glob, shlex, vcf, pysam from subprocess import * import subprocess, math, random CHUNK_SIZE = 2**20 #1mb def createOutputHTML (outputF, sampleNames): ofh = open(outputF, "w") print outputF ofh.write( '<html>\n<head>\n<title>Galaxy - CNVKIT VCF...
from enum import Enum class ApiCode(Enum): SUCCESS = 1000 JINJA2_RENDER_FAILURE = 1001 DEPLOY_START_FAILURE = 1002 DEPLOY_STOP_FAILURE = 1003 DEPLOY_STATUS_FAILURE = 1004 DEPLOY_REPLAY_FAILURE = 1005 GET_FILE_FAILURE = 1006 GET_CONTAINER_FILE_FAILURE = 1007 COMMAND_EXEC_FAILURE = 1...
import torch import torch.nn as nn from torch_geometric.nn import global_mean_pool import torch.nn.functional as F from models.nn_utils import chebyshev class SCNLayer(nn.Module): def __init__(self, feature_size, output_size, enable_bias=True, k=1): super().__init__() self.k = k self.conv ...
import os from base64 import urlsafe_b64decode, urlsafe_b64encode from pathlib import Path from github import Github gh_access_token = '' def get_project_root(): """Returns project root folder.""" return Path(__file__).parent def gh_session(): """Returns a PyGithub session.""" if gh_access_token:...
""" Test DB.py in isolation. Call with twisted.trial eg. trial test_DB.py In the context of evoke, and by extension in evoke apps, only init_db and execute are used by external functions. The aim of the current exercise is to maintain the current interface whilst rationalising code and int...
import platform from global_graph_parser.G_grammarListener import G_grammarListener from graphviz import Digraph class MyListener(G_grammarListener): """ There are 2 methods (enter and exit) for each rule of the grammar. As the walker encounters the node for rule Choice, for example, it triggers enter...
def async_volunteer_group_adder(volunteer_group,volunteers): through_model = volunteers[0].groups.through dups = through_model.objects.all().filter(volunteergroup_id=volunteer_group.pk).values_list('volunteer_id', flat=True) data = [] for pk in volunteers.values_list('pk', flat=True): if pk n...
from django import forms from . models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment exclude = ["post"] labels = { "user_name": "Your Name", "user_email": "Your E-Mail", "text": "Your Comment", }
from django.core.management.base import BaseCommand, CommandError import pandas as pd import os import time import json from sdap.studies.models import ExpressionStudy, ExpressionData, Database, JbrowseData, Species from django.core.files import File from sdap.users.models import User from django.conf import settings...
""" The module for loading a dataset from a given file and parsing it into a dictionary. The offered functions allow to receive a list of pairs of samples with their labels """ import random def load_file(file_name, test_file): print(file_name); sample_folder = "../samples"; file_path = sample_folder + "/" + fi...
# Generated by the pRPC protocol buffer compiler plugin. DO NOT EDIT! # source: isolated.proto import base64 import zlib from google.protobuf import descriptor_pb2 # Includes description of the isolated.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.F...
from aiozk import protocol from aiozk.exc import TransactionFailed class Transaction: """Transaction request builder""" def __init__(self, client): """ :param client: Client instance :type client: aiozk.ZKClient """ self.client = client self.request = protocol...
from src.util.config import ( load_config, save_config, ) from argparse import ArgumentParser from typing import Dict from src.util.default_root import DEFAULT_ROOT_PATH def make_parser(parser: ArgumentParser): parser.add_argument( "--set-node-introducer", help="Set the introducer for nod...
from gym.spaces import Box, MultiDiscrete import logging import numpy as np import ray import ray.experimental.tf_utils from ray.rllib.agents.ddpg.ddpg_tf_policy import ComputeTDErrorMixin, \ TargetNetworkMixin from ray.rllib.agents.dqn.dqn_tf_policy import postprocess_nstep_and_prio from ray.rllib.agents.sac.sac_e...
import unittest from test.testutil import set_default_576_324_videos_for_testing, \ set_default_576_324_videos_for_testing_scaled, \ set_default_cambi_video_for_testing_b, \ set_default_cambi_video_for_testing_10b from vmaf.core.cambi_feature_extractor import CambiFeatureExtractor, CambiFullReferenceFeatur...
import os.path import sys base_path = os.path.abspath('..') aragog_app = os.path.join(base_path, 'app') sys.path.insert(0, aragog_app)
import os import sys from argparse import ArgumentParser from typing import List, Tuple from requests import HTTPError # noqa from adventofcode.config import ROOT_DIR from adventofcode.scripts.get_inputs import get_input from adventofcode.util.console import console from adventofcode.util.input_helpers import get_in...
########################### # # #327 Rooms of Doom - Project Euler # https://projecteuler.net/problem=327 # # Code by Kevin Marciniak # ###########################
from setuptools import setup package_name = "simdash" description = "A web based dashboard for visualizing simulations" with open("README.md", "r") as fh: long_description = fh.read() setup( name=package_name, description=description, maintainer="Parantapa Bhattacharya", maintainer_email="pb+pyp...
from django import views from django.contrib import admin from django.urls import path,include from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('profile', views.Profile_viewSet) router.register('posts', views.Post_viewSet) router.register('users', views.User...
# -*- coding: utf-8 -*- ''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms and co...
from gerais import * from tkinter import messagebox # ===================Usuarios============== # ====Verifica se usuario existe==== def existeUsuario(dic,chave): if chave in dic.keys(): return True else: return False # ====Insere usuario==== def insereUsuario(dic): email = input("Digite ...
from freezegun import freeze_time from rest_framework import test from waldur_mastermind.common.utils import parse_datetime from waldur_mastermind.marketplace import callbacks, models from waldur_mastermind.marketplace.tests import factories @freeze_time('2018-11-01') class CallbacksTest(test.APITransactionTestCase)...
#!/usr/bin/env python3 class TypedList: ''' List-like class that allows only a single type of item ''' def __init__(self, example_element, initial_list = []): self.type = type(example_element) if not isinstance(initial_list, list): raise TypeError("Second argument of TypedList must ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import List import torch from reagent import types as rlt from reagent.models.base import ModelBase from reagent.models.fully_connected_network import FullyConnectedNetwork class FullyConnectedCritic(ModelBase...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import * import apiclient from apiclient.discovery import build from django.core.mail import send_mail,EmailMessage from apiclient.errors import HttpError from oauth2client.tools import argparser from django.core...
def BSDriver(LoadCase): # BoundingSurface J2 with kinematic hardening # Written by Pedro Arduino, Mar. 22 2019 # Copyright Arduino Computational Geomechanics Group # Ported into Python/Jupyter Notebook by Justin Bonus, Jul. 2019 # # # LoadCase: # 1 ... proportionally increasing strai...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. import numpy as np from pandapower.control.controller.trafo_control import TrafoController class ContinuousTapControl(TrafoContro...
import os import pathlib import shlex import shutil import subprocess import sys import unittest from vtam.utils import pip_install_vtam_for_tests from vtam.utils.PathManager import PathManager class TestCommandExample(unittest.TestCase): """Will test main commands based on a complete test dataset""" def s...
from kivymd.app import MDApp from kivymd.uix.screen import Screen from kivymd.uix.button import MDRectangleFlatButton, MDFlatButton from kivy.lang import Builder from kivymd.uix.dialog import MDDialog import helpers class DemoAPP(MDApp): def build(self): self.theme_cls.primary_palette = "Green"...
import csv import logging import os from dataclasses import asdict from typing import List, TypeVar from analysis.src.python.data_collection.api.platform_objects import Object class CsvWriter: def __init__(self, result_dir: str, csv_file: str, field_names: List[str]): os.makedirs(result_dir, exist_ok=Tr...
from src.base.test_cases import TestCases class PartEqualSubSumTestCases(TestCases): def __init__(self): super(PartEqualSubSumTestCases, self).__init__() self.__add_test_case__("Example 1", ([1, 5, 11, 5]), (True)) self.__add_test_case__("Example 2", ([1, 2, 3, 5]), (False)) self._...
PALAVRA = "EXEMPLO" print(PALAVRA[0]) print(PALAVRA[2:5]) print(len(PALAVRA)) nova = PALAVRA + "s!!" print(nova) outra = "Novos" + nova print(outra) for i in range(len(PALAVRA)): print(PALAVRA[i]) lista = [2,4,7] lista [1] = 9 print(lista) print("O" in PALAVRA) print("o" in PALAVRA) #Eu tbm posso colocar: p...
from discordbot.minigamesbot import MiniGamesBot from discordbot.utils.private import DISCORD bot = MiniGamesBot("?") bot.run(DISCORD["TOKEN"])
import numpy as np import mistree as mist def test_PlotHistMST_rotate(): pmst = mist.PlotHistMST() pmst._get_rotate_colors() assert pmst.rotate_colors == 1 pmst._get_rotate_linestyles() assert pmst.rotate_linestyle == 1 def test_PlotHistMST_plot(): x = np.random.random_sample(100) y = np...
#!/usr/bin/python3 from tools import * from sys import argv from os.path import join import h5py import matplotlib.pylab as plt import numpy as np ###################################################### see old version at the end (easier to understand, but less generalized and not using pca) ########################...
# -*- coding: utf-8 -*- """ Contains a base class for a calltips mode. """ import logging from pyqode.core.api import Mode, TextHelper from pyqode.core.api.panel import Panel from pyqode.qt import QtCore, QtWidgets MAX_CALLTIP_WIDTH = 80 def _logger(): return logging.getLogger(__name__) class CalltipsMode(Mode...
from .queryset import *
import typing as t def client_id() -> str: """Application (client) ID of app registration""" return None def client_secret() -> str: """Application secret""" return None def authority() -> str: """The authority URL""" return 'https://login.microsoftonline.com/common' def scope() -> t.Uni...
from PIL import Image from pytesseract import pytesseract import argparse import xmltodict import json import cv2 import os import requests from puttext import puttext from nltk.tokenize import sent_tokenize import math filename = '../upload/table1.png' o_filename = '../upload/table2.png' conf_data = pytesseract.run_t...
# # Loop transformation submodule.that implements a combination of various loop transformations. # import sys import orio.module.loop.submodule.submodule, transformation import orio.module.loop.submodule.tile.tile import orio.module.loop.submodule.permut.permut import orio.module.loop.submodule.regtile.regtile import ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-04-23 11:07 from __future__ import unicode_literals import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('shop', '0002_product_im...
from collections import Iterator, Iterable import string from . import reader class Record: """ Simple namespace object that makes the fields of a GTF record available. Subclassed to create records specific to exons, transcripts, and genes """ __slots__ = ['_fields', '_attribute'] _del_lette...
import pdb def add_default_args(parser, root_dir, rand_seed=None, possible_model_names=None): # tng, test, val check intervals parser.add_argument('--eval_test_set', dest='eval_test_set', action='store_true', help='true = run test set also') parser.add_argument('--check_val_every_n_epoch', default=1, type...
#!/usr/bin/python ######################################################################################################################## # # Copyright (c) 2014, Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permi...
from .models import db from .utils import update_menus from diff_match_patch import diff_match_patch from flask import Markup, abort, g, redirect, render_template, request, send_file, url_for from flask_security.core import current_user import os def render(page, path, version): file, mimetype, fragment = page.sub...
import numpy as np import pandas import pickle import json import shutil import warnings from typing import Union, List import os from sfaira.consts import OCS from sfaira.data import load_store from sfaira.data.dataloaders import Universe from sfaira.estimators import EstimatorKerasEmbedding from sfaira.ui import Mod...
""" Defines the possible rewards for rollout. Can be augmented for more complex policies using simialr scheme as Rollout or UCT policies. Is defined through CLI in the Tree script. """ class RolloutRewards(object): """ Defines penalty and rewards for the rollout if it's in the chasis. """ def __init__(...
""" sentry.models.release ~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from jsonfield import JSONF...
import os from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name="restful-gpio", version="0.1.0", license="MIT", author="ykaragol", python_requires='>3.4.0', packages=["gpio"], install_requires=required )
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.TargetInfo import TargetInfo class AlipayMerchantServiceconsultBatchqueryModel(object): def __init__(self): self._begin_time = None self._end_time = None ...
import math from typing import List, Optional from PyQt5 import QtGui from PyQt5.QtCore import QCoreApplication, Qt from PyQt5.QtWidgets import (QApplication, QDesktopWidget, QMainWindow, QShortcut) from sqlalchemy.orm.exc import NoResultFound from src.error.invalid_reference import Invali...
from gi.repository import Gtk from gi.repository import Gio from gi.repository import Pango from internationalize import _ import os def create_function_str(name, *args): new_func = name + "(" for i, arg in enumerate(args): if i != 0: new_func += ", " new_func += repr(arg) new_...
# -*- coding: utf-8 -*- # # Copyright 2011-2018 Matt Austin # # 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...
def uncentime(jours): total = [0.01] for i in range(jours - 1): total.append(total[-1] * 2) return sum(total) print(uncentime(30))
a=1 for i in range(int(input())): print(f"{a} {a+1} {a+2} PUM") a+=4
import pandas as pd class Security(): ''' Generic Class that initializes an object to hold price and volume data on a particular financial security. ''' def __init__(self, dataframe, security_name, ticker): ''' Arguments --------- dataframe Pandas Dataframe. Co...
from pprint import pprint from intentBox import IntentAssistant i = IntentAssistant() i.load_folder("test/intents") print("\nADAPT:") pprint(i.adapt_intents) print("\nPADATIOUS:") pprint(i.padatious_intents) print("\nFUZZY MATCH:") pprint(i.fuzzy_intents)
""" 1013 : Contact URL : https://www.acmicpc.net/problem/1013 Input : 3 10010111 011000100110001 0110001011001 Output : NO NO YES """ def test(s): if len(s) == 0: return True if s.startswith('10'): i = 2 if i >= ...
""" Simple API implementation within a single GET request. Generally wrap these in a docker container and could deploy to cluster. I use cherryPy because it was so simple to run, but heard Flask was pretty good. So I decided to give it a try. Wanted to try out connecting pymongo to flask, but was spending too much tim...
# Copyright 2021 DeepMind Technologies Limited. 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 ...
import enum from EoraReader import EoraReader from PrimaryInputs import PrimaryInputs from DomesticTransactions import DomesticTransactions from os import listdir from os.path import isfile, join import pandas as pd class CountryTableSegment(enum.Enum): DomesticTransations = 1 PrimaryInputs = 2 class CountryTab...
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import E...
""" @author: Jim @project: DataBrain @file: exceptions.py @time: 2020/10/4 17:03 @desc: """ class StopException(BaseException): """ 停止爬 """ pass
import matplotlib matplotlib.use('Agg') import numpy as np, scipy as sci, os, pylab as pyl, sys, smtplib from trippy import pill from glob import glob from astropy.io import fits from astropy.wcs import WCS from datetime import datetime, timedelta # Send email. def sendemail(from_addr, to_addr_list, cc_addr_...
import collections import dataclasses import gc import multiprocessing import os import traceback from multiprocessing import Lock, Pipe, Pool, Process, Value from typing import Any, Callable, Dict, Iterable, List, Tuple from .exceptions import (UnidentifiedMessageReceivedError, WorkerHasNoUse...
from collections import defaultdict import numpy as np import torch class Filter(object): def __init__(self): pass def __call__(self, cube_acts, **kwargs): ''' Perform filter on an `activity_spec.CubeActivities` object, returns a filtered `activity_spec.CubeActivities` object...
import argparse import numpy as np import time import torch import json import torch.nn as nn import torch.nn.functional as FN import cv2 import random from tqdm import tqdm from solver import Solver from removalmodels.models import Generator, Discriminator from removalmodels.models import GeneratorDiff, GeneratorDiff...
from django.contrib import admin from django.contrib.admin import register from .models import Organization, Employee, Position, Phone, PhoneType from .forms import EmployeeAdminForm @register(Organization) class OrganizationAdmin(admin.ModelAdmin): pass @register(Employee) class EmployeeAdmin(admin.ModelAdmin)...
import os import subprocess from typing import Tuple import pandas as pd LABEL_MAPPING = { "Negative": 0, "Positive": 1, "I can't tell": 2, "Neutral / author is just sharing information": 2, "Tweet not related to weather condition": 2, } def load_data() -> Tuple[pd.DataFrame, pd.DataFrame, pd.D...
import itertools import random import re from dataclasses import dataclass from enum import Enum from typing import Dict, Iterable, Iterator, List, Tuple, cast FIELD_SIZE = 10 class GameError(Exception): """Game error.""" class CellState(Enum): UNKNOWN = "unknown" EMPTY = "empty" WOUNDED = "wounded...
""" Sams Teach Yourself Python in 24 Hours by Katie Cunningham Hour 4: Storing Text in Strings Exercise: 1. a) You're given a string that contains the body of an email. If the email contains the word "emergency", print out "Do you wnat to make this email urgent?" If it contains the word "joke", prin...
import sys sys.path.append('../') import codecs from docopt import docopt from dsm_creation.common import * def main(): """ Weeds Precision - as described in: J. Weeds and D. Weir. 2003. A general framework for distributional similarity. In EMNLP. """ # Get the arguments args = docopt("""Co...
class renderizar(object): def savarLegenda(self,legenda,local_legenda): with open(local_legenda, 'wt') as f: f.write(legenda) f.close() return True def criarArquivoHTML(self,titulo,local_video,local_legenda,token): with open('model/template.html','rt') as f: ...
from utils import * full_exps = [] for k, v in experiments.items(): full_exps.extend(f"{k}={vv}" for vv in v) print(full_exps)
from mock import patch print(patch.object) import mock print(mock.patch.object)
"""Generate a random key.""" import argparse import os from intervention_system.deploy import settings_key_path as default_keyfile_path from intervention_system.util import crypto def main(key_path): box = crypto.generate_box() crypto.save_box(box, key_path) if __name__ == '__main__': parser = argparse...
############################ USED LIBRARIES ############################ from tkinter import * from tkinter import messagebox import os, sys, time import mysql.connector import queries as q import datetime as d import functions as f from constants import DEBUG, HOST, USER, PASSWORD, DATABASE ###################...
#!/usr/bin/env python3 # Write a program that prints the reverse-complement of a DNA sequence # You must use a loop and conditional dna = 'ACTGAAAAAAAAAAA' rcdna = '' for i in range(len(dna) -1, -1, -1): nt = dna[i] if nt == 'A': nt = 'T' elif nt == 'T': nt = 'A' elif nt == 'C': nt = 'G' elif nt == 'G': nt =...