text
stringlengths
2
999k
from math import sqrt import string ############################################################################################ # Important: Read over the information in the "Appendix: Utility Functions" in the Project # # Project Specification in order to better understand how to use the functions below. # ####...
import torch import torch.nn as nn __all__ = ['MultiCrossEntropyLoss'] class MultiCrossEntropyLoss(nn.Module): def __init__(self, size_average=True, ignore_index=-500): super(MultiCrossEntropyLoss, self).__init__() self.size_average = size_average self.ignore_index = ignore_index def...
from colorama import Fore def log_main(*args, **kwargs): __print_colorama(Fore.CYAN, *args, **kwargs) def log_success(*args, **kwargs): __print_colorama(Fore.GREEN, *args, **kwargs) def log_accent(*args, **kwargs): __print_colorama(Fore.MAGENTA, *args, **kwargs) def log_error(*args, **kwargs): _...
# Copyright 2019 The DDSP Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
from django.db import models from django.contrib.auth.models import User KEY_SIZE = 16 SECRET_SIZE = 16 class ConsumerManager(models.Manager): def create_consumer(self, name, description=None, user=None): """ Shortcut to create a consumer with random key/secret. """ consumer, creat...
# -*- coding: utf-8 -*- """ S3 Data Views @copyright: 2009-2018 (c) Sahana Software Foundation @license: MIT 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 restr...
import cherrypy import imp import helpers import homepage import traceback import os import sys APPS_PATH = '../apps/' USER_PATH = os.getenv('USER_DIR','/usbdrive') APPS_PATH_USER = USER_PATH+'/Web/' port = 80 try : port = int(sys.argv[1]) except: pass print("port: " + str(port)) print("USER_PATH:" +USER_PA...
#!/usr/bin/env python3 # Dependencies from the Python 3 standard library: import os import subprocess as sp from shutil import copyfile ## Set/create directories input_directory = os.path.abspath(os.path.join( os.getcwd(), os.pardir, os.pardir, 'big_data_input', 'RR_animation')) output_directory = os.path...
# Exercício Python #052 - Números primos # # Faça um pograma que leia um NÚMERO INTEIRO e diga se ele é ou não um NÚMERO PRIMO. # # Obs: eu NÃO consegui fazer esse exercício SEM ver a RESOLUÇÃO e de forma mais simples. Estude mais!!! total = 0 n = input('\033[0;30mDigite um número \033[1;32mINTEIRO\033[0;30m. Este pro...
import sys import ts as TS import instrucciones as Instruccion import tempfile from datetime import datetime from pprint import pprint lstResultado = [] contador = 1 x = 0 def inc(): global x x += 1 return x def calcularSelectGrupos(arbol,ts): global lstResultado global conta...
import math def gauss(n): return (((n * n) + n) / 2) def sumDivisibleBy(x, limit): return x * gauss(limit // x) no1 = int(input('First number: ')) no2 = int(input('Second number: ')) limit = int(input('Limit: ')) - 1 result = sumDivisibleBy(no1, limit) + sumDivisibleBy(no2, limit) - sumDivis...
from JumpScale import j import os import gzip import pwd import grp class StorScripts(): # create hexa directory tree # /00/00, /00/01, /00/02, ..., /ff/fe, /ff/ff def initTree(self, root): return """ import os root = "%s" for a in range(0, 256): lvl1 = os.pat...
# -*- coding: utf8 """Random Projection transformers. Random Projections are a simple and computationally efficient way to reduce the dimensionality of the data by trading a controlled amount of accuracy (as additional variance) for faster processing times and smaller model sizes. The dimensions and distribution of R...
import sys def init(v): global parents, maxi parents[v] = v maxi[v] = v def find(v): global parents if v == parents[v]: return v else: parents[v] = find(parents[v]) return parents[v] def union(a, b): global parents, ranks, maxi a = find(a) b = find(b) ...
""" (c) Copyright 2014,2015 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 applicable l...
import pytest from ruts import DiversityStats from ruts.constants import DIVERSITY_STATS_DESC from ruts.diversity_stats import calc_hdd, calc_mattr, calc_msttr, calc_ttr @pytest.fixture(scope="module") def ds(): text = "Тезаурусы - особый класс лексикографических ресурсов, для которых характерны следующие черты:...
from app.models.track import Track class Playlist: def __init__(self, id_, name, description, tracks): self.id = id_ self.name = name self.description = description self.tracks = tracks self.num_tracks = len(self.tracks) def from_spotify_playlist(spotify_playlist): ...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02a_right_menu_widget.ipynb (unless otherwise specified). __all__ = [] # Internal Cell from ipywidgets import HBox, Dropdown, Layout, VBox, Checkbox from functools import partial from typing import List, Optional, Callable from .custom_input.coordinates import Coordinat...
from sympy import symbols, Mul, sin, Integral, oo, Eq, Sum from sympy.core.expr import unchanged from sympy.stats import Normal, Poisson, variance from sympy.stats import Covariance, Variance, Probability, Expectation from sympy.stats.rv import probability, expectation def test_literal_probability(): X = Normal('...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = ty...
# -* coding: utf-8 -*- import tornado.escape import tornado.ioloop import tornado.web import yaml import json import traceback from db.database import Database class ExceptionHandler(tornado.web.HTTPError): pass class BaseHandler(tornado.web.RequestHandler): def get(self): raise ExceptionHandler(re...
class Solution: def addBinary(self, a: str, b: str) -> str: a = int(a, 2) b = int(b, 2) c = bin(a+b) c = c[2::] return c
"""Module for RPC-Service functionality """ from .requests import AsyncRequest, AsyncRequests from .client import WebSocketsClient from .background import BackgroundTask, BackgroundSubProcess __all__ = ['AsyncRequests', 'AsyncRequest', 'WebSocketsClient', 'BackgroundSubProcess']
import requests import random import string # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Dynamicweb 9.5.0 - 9.12.7 Unauthenticated Admin User Creation''', "description": '''Dynamicweb contains a vulnerability which allows an unauthenticated attacker to create a ...
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
""" This module implements the random module for ctfview backend. """ import ctf from ...interface import Random from .ctfview_tensor import CTFViewTensor class CTFViewRandom(Random): def seed(self, seed): ctf.random.seed(seed) def random(self, size): if size is None: return ctf...
import numpy as np import PrplxWrap import sys import pprint as pp import interpolate as ip import pylitho_exceptions as pyle import copy import Grid from PhysicalConstants import * reload(ip) reload(PrplxWrap) reload(pyle) reload(Grid) class Container(object): @property def T(self): return self._T ...
import logging import picar import cv2 import datetime from hand_coded_lane_follower import HandCodedLaneFollower #from objects_on_road_processor import ObjectsOnRoadProcessor _SHOW_IMAGE = True class DeepPiCar(object): __INITIAL_SPEED = 0 __SCREEN_WIDTH = 320 __SCREEN_HEIGHT = 240 def __init__(sel...
from unittest.mock import Mock from openslides_backend.action.action_handler import ActionHandler from openslides_backend.action.util.typing import Payload from .base import BaseActionTestCase class GeneralActionCommandFormat(BaseActionTestCase): """ Tests the interface to datastore-command with one WriteRe...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
# Generated by Django 3.0.6 on 2020-06-02 20:22 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('lots', '0009_auto_20200602_0221'), ] operations = [ migrations.AlterField( ...
"""Support for controlling GPIO pins of a Orange Pi.""" import logging from homeassistant.const import ( EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) _LOGGER = logging.getLogger(__name__) CONF_PIN_MODE = 'pin_mode' DOMAIN = 'orangepi_gpio' PIN_MODES = ['pc', 'zeroplus', 'zeroplus2', 'deo', 'neocore2'] ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend_crm.settings') try: from django.core.management import execute_from_command_line except ...
""" From https://gist.github.com/Spindel/1d07533ef94a4589d348 watchdogged.py; python teaching code for how to use the systemd watchdog Copyright (C) 2015 D.S. Ljungmark, Modio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by t...
import ipaddress from main import absorbdict from main import multiple dst_fw = [] # dst-fwのリストの生成 def decide_dst_fw(policy, append_list, dst_if): for if_ip_c in absorbdict.if_ip_dict: if dst_if.replace('"', '') == if_ip_c['if_name'].replace('"', ''): data = str( if_ip_c['ip...
import requests from nose.tools import (assert_equal, assert_is_instance, assert_raises, assert_false, assert_in, assert_is_none) import python_kemptech_api.generic import python_kemptech_api.models import python_kemptech_api.objects from python_kemptech_api import api_xml from python_kemptech_api import generic t...
import numpy as np import openpnm as op from networkx import complete_graph, random_layout from networkx import set_node_attributes, set_edge_attributes class NetworkXTest: def setup_class(self): ws = op.Workspace() ws.settings['local_data'] = True self.net = op.network.Cubic(shape=[2, 2,...
import random from fileio import * from util import timepunch from mapgen import prepareTilemap from towngen import loadTowns from draw import drawSphere from gfx import launch_game import ginit as g ########## TODO ########## # Move plane sprites to dedicated surface # Instead of redrawing all tiles on camera move, h...
import random from isobar.note import * from isobar.pattern import * class LSystem: def __init__(self, rule = "N[-N++N]-N", seed = "N"): self.rule = rule self.seed = seed self.string = seed self.reset() def iterate(self, count = 3): if self.rule.count("[") != self.rul...
#!/usr/bin/python # -*- coding: utf-8 -*- from analysis import Analysis from logs import Logs from trading import Trading from twitter import Twitter # Whether to send all logs to the cloud instead of a local file. LOGS_TO_CLOUD = True def twitter_callback(tweet): """Analyzes Trump tweets, makes stock trades, a...
from tkinter import * root=Tk() root.geometry("1600x800") sb=Scrollbar(root) sb.pack(side=RIGHT) lis=Listbox(root,yscrollcommand=sb.set) for line in range(100): lis.insert(END,"my values: "+str(line)) lis.pack(side=RIGHT) sb.config(command=lis.yview) root.mainloop()
#!/usr/bin/env python3 # Copyright (c) 2016-2018 The Bitcoin Core developers # Copyright (c) 2018-2019 The SBER developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import re import fnmatch import sys import subprocess impor...
import argparse import os import matplotlib.pyplot as plt import torch from torchvision.transforms import Compose, Resize, ToTensor, Normalize from torchvision.utils import save_image import lung_segmentation.importAndProcess as iap from models import model from models.unet_models import unet11, unet16 parser = argp...
"""Utility functions for geometrical entities. Contains ======== intersection convex_hull are_similar """ from __future__ import print_function, division from sympy import Symbol, Function, solve from sympy.core.compatibility import string_types, is_sequence def idiff(eq, y, x, n=1): """Return ``dy/dx`` assumi...
from __future__ import annotations from copy import deepcopy from dataclasses import dataclass, fields import spot from treelib import Tree from crome_logic.patterns import Pattern from crome_logic.specification import Cnf, Dnf, Specification from crome_logic.specification.boolean import Bool from crome_logic.specif...
import unittest.mock import unittest import os import pathlib from ons_csv_to_ctb_json_load import Loader from helper_funcs import conditional_mock_open, build_test_file HEADERS = ['Database_Mnemonic', 'Id', 'Database_Title', 'Database_Title_Welsh', 'Database_Description', 'Database_Description_Welsh', 'Can...
import logging from typing import Any, List, Text from rasa.core.actions.action import ( ACTION_BACK_NAME, ACTION_LISTEN_NAME, ACTION_RESTART_NAME) from rasa.core.constants import USER_INTENT_BACK, USER_INTENT_RESTART from rasa.core.domain import Domain from rasa.core.events import ActionExecuted from rasa.core.po...
import collections import os import sys import time import traceback import six from chainer import reporter as reporter_module from chainer import serializer as serializer_module from chainer.training import extension as extension_module from chainer.training import trigger as trigger_module from chainer.utils impor...
from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT, HTTP_201_CREATED, HTTP_206_PARTIA...
from insights.core.spec_factory import SpecSet, RegistryPoint class Specs(SpecSet): auditd_conf = RegistryPoint() audit_log = RegistryPoint() autofs_conf = RegistryPoint() blkid = RegistryPoint() bond = RegistryPoint(multi_output=True) branch_info = RegistryPoint() brctl_show = RegistryPoi...
import json import os from blacksheep.server.application import Application from blacksheep.server.authentication.jwt import JWTBearerAuthentication from blacksheep.server.responses import html from dotenv import load_dotenv from guardpost.authentication import Identity from guardpost.authorization import Policy from ...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest from pymatgen.analysis.magnetism.jahnteller import * from pymatgen.io.cif import CifParser test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files") class Jahn...
import re import numpy as np import pytest import pytz from pandas.core.dtypes.common import ( is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, is_datetime64tz_dtype, is_datetimetz, is_dtype_equal, is_interval_dtype, is_period, ...
""" ================ Using span_where ================ Illustrate some helper functions for shading regions where a logical mask is True. See `matplotlib.collections.BrokenBarHCollection.span_where`. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.collections as collections t = np.arange(0...
# Copyright (c) MONAI Consortium # 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, so...
# -*- coding: utf-8 -*- """ Created on Mon Jan 6 21:16:58 2020 some helper functions @author: skjerns """ import re from types import GeneratorType import numpy as np from collections import OrderedDict try: profile #a hack for not having to remove the profile tags when not testing except NameError: profile = lambd...
#!/usr/bin/env python # from operator import itemgetter import sys current_sum = 0.0 last_group = None current_count = 1 verbose = False # input comes from STDIN for line in sys.stdin: # Remove trailing '\n' line = line.strip() # Extract (key,value) vs = line.split('\t') # print vs[0] current...
""" This module and its submodules contains utilities for running external processes and interfacing with job managers. This module should contain functionality shared between Galaxy and the LWR. """ from galaxy.util.bunch import Bunch from .kill import kill_pid __all__ = [kill_pid, Bunch]
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt """Find lines in files that should be faithful copies, and check that they are. Inside a comment-marked section, any chunk of indented lines should be faithfully c...
import factory import pytz from django.conf import settings from factory.fuzzy import FuzzyChoice from faker import Faker from .models import ModelTest, RelatedModelTest class RelatedModelTestFactory(factory.django.DjangoModelFactory): class Meta: model = RelatedModelTest char_field = factory.Faker(...
def bubble(arr): n = len(arr) for i in range(n - 1): for j in range(n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] if __name__ == "__main__": arr = [5, 4, 3, 2, 1] bubble(arr) print(arr)
import unittest from app.models import News # News = news.News class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of the Movie class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_news= News('Ex Radio Presenter:...
"""Initialize a newly-created repository.""" import sys import os import shutil BOILERPLATE = ( 'AUTHORS', 'CITATION', 'CONTRIBUTING.md', 'README.md', '_config.yml', os.path.join('_episodes', '01-introduction.md'), os.path.join('_extras', 'about.md'), os.path.join('_extras', 'discuss....
# set a gradient as the fill color cmykRadialGradient( (100, 100), # startPoint (200, 200), # endPoint [(1, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, .2)], # colors [0, .2, 1], # locations 0, ...
from django.db import models from datetime import datetime # Create your models here. class Todo(models.Model): title = models.CharField(max_length=255) text = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title
"""add note column to payment Revision ID: 2f581d6350fd Revises: 7d27b5b2dc87 Create Date: 2019-11-03 08:09:30.992624 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2f581d6350fd' down_revision = '7d27b5b2dc87' branch_labels = None depends_on = None def upgr...
""" Mask R-CNN Common utility functions and classes. Copyright (c) 2017 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by Waleed Abdulla """ import sys import os import math import random import numpy as np import tensorflow as tf import scipy import skimage.color import skimage.io ...
"""Convert a path to an image to text using OCR based on tesseract""" from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as np class ImageOCRTextTransformer(CustomTransformer): _modules_needed_by_name = ['Pillow==5.4.1', "pytesseract==0.3.0"] _parallel_task = True #...
from datetime import ( date, datetime, ) from io import StringIO import numpy as np import pytest import pandas.util._test_decorators as td import pandas as pd from pandas import ( DataFrame, Index, MultiIndex, Series, bdate_range, ) import pandas._testing as tm def test_apply_issues():...
#! /usr/bin/env python3 import logging from sqapi.configuration import detector from sqapi.messaging.message import Message log = logging.getLogger(__name__) def download_data(config, message: Message): loc = message.data_location if not loc: err = 'Could not find "data_location" in message' ...
from contextlib import redirect_stdout from datetime import date, timedelta import io from unittest import skip, TestCase from unittest.mock import patch from todone.backend import ( DEFAULT_FOLDERS, ) from todone.backend.db import ListItem, MOST_RECENT_SEARCH, SavedList, Todo from todone.commands.list import ( ...
# Copyright 2017 The TensorFlow 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 # # Unless required by applicable ...
import logging from django.http import HttpResponse, Http404, HttpResponseRedirect from django.conf import settings from django.shortcuts import get_object_or_404, redirect from django.core import serializers from django.contrib import auth from django.contrib.auth.decorators import permission_required from django.for...
from . import Config from Config import *
import cvxpy as cp import numpy as np from sklearn.metrics import roc_auc_score ''' absFeatures: N*d absLabels: N*1, +1/-1 cmpFeatures: N*d - N*d cmpLabels: N*1, +1/-1 ''' class combinedLinear(object): def __init__(self, input_shape=(3, 224, 224)): self.input_shape = input_shape def get_log_svm_predi...
import random # your sentence is assigned to the variable sentence = input().split() # write your python code below random.seed(43) random.shuffle(sentence) # shows the message print(' '.join(sentence))
""" Various task & scope cancellation tests """ import asyncio import time import pytest from tests import run10 from traio import Scope @pytest.mark.asyncio async def test_task_catches_cancel(): """A nasty task catches all exceptions""" async def nasty(): while True: try: ...
""" Contains paths to locations on user's system where models and resources are to be stored. These all live in adeft's home folder which defaults to the hidden directory ".adeft" in the user's home directory but which can be specified by setting the environment variable ADEFT_HOME in the user's profile. """ import os...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from mephisto.abstractions.blueprint import TaskRunner, SharedTaskState from mephisto.data_model.assignment import Initi...
from tkinter import Frame, Label from gui.component.datagrid import DataGrid from gui.component.enrollmentdictionary import EnrollmentDictionary from gui.component.datasource import DataSource from gui.component.listener import Listener from gui.component.navigation_bar import NavigationBar from gui.component.sea...
import base64 import json import logging from html.parser import HTMLParser from http.client import HTTPConnection from markupsafe import escape from sqlalchemy import and_ from sqlalchemy.orm import eagerload, joinedload, lazyload, undefer from sqlalchemy.sql import expression from galaxy import ( model, uti...
"""A vanilla 3D resnet implementation. Based on Raghavendra Kotikalapudi's 2D implementation keras-resnet (See https://github.com/raghakot/keras-resnet.) """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) import six from math import ceil from keras.models import ...
""" Additional statistics functions with support for masked arrays. """ # Original author (2007): Pierre GF Gerard-Marchant __all__ = ['compare_medians_ms', 'hdquantiles', 'hdmedian', 'hdquantiles_sd', 'idealfourths', 'median_cihs','mjci','mquantiles_cimj', 'rsh', ...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os import subprocess import numpy as np import pytest from jina import Document, DocumentArray, Flow cur_dir = os.path.dirname(os.path.abspath(__file__)) def test_video_torch_encoder(): model_state...
""" wordcount example using the rdd api, we'll write a test for this """ from __future__ import print_function from operator import add def do_streaming_word_counts(lines): """ count of words in a dstream of lines """ counts_stream = (lines.flatMap(lambda x: x.split()) .map(lambda x: (x, 1)...
def isPalindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPalindrome(s[1:-1]) s = "aba" print isPalindrome(s)
# # Copyright (C) 2011, Martin Zibricky # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distribute...
################################################################################ # Copyright 2016-2021 Advanced Micro Devices, Inc. All rights reserved. # # 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 ...
# -*- encoding: utf-8 -*- # # Copyright © 2016-2018 Red Hat, Inc. # Copyright © 2014-2015 eNovance # # 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/LICE...
from inspect import isawaitable, signature from typing import Optional, Callable, List from .track import Track try: from discord import VoiceChannel, Guild except ImportError: try: from discordjspy import VoiceChannel, Guild except ImportError: raise ImportError("You don't have discord.py ...
# Copyright 2015 The TensorFlow 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 # # Unless required by applica...
# !/usr/bin/python x = "There are %d types of people." %10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." %(binary, do_not) print x print y print "I said : %r." %x print "I also said: '%s'." %y #we use %r for debugging since it displays the raw data of the variable hilarious = False jo...
import requests from bs4 import BeautifulSoup from newspaper import Article import pandas as pd linklist =[] filist =[] def mainclass(): url = "https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx6TVdZU0FtVnVHZ0pKVGlnQVAB?hl=en-IN&gl=IN&ceid=IN%3Aen/" code=requests.get(url) soup = Beau...
import os.path from pprint import pprint from azure.cognitiveservices.vision.contentmoderator import ContentModeratorClient from azure.cognitiveservices.vision.contentmoderator.models import ( Screen ) from msrest.authentication import CognitiveServicesCredentials SUBSCRIPTION_KEY_ENV_NAME = "CONTENTMODERATOR_SUB...
import logging import pkgutil import sys import unittest def all_names(): for _, modname, _ in pkgutil.iter_modules(__path__): yield "posthog.test." + modname def all(): logging.basicConfig(stream=sys.stderr) return unittest.defaultTestLoader.loadTestsFromNames(all_names())
import copy import pytest import torch from torch.testing import assert_allclose from transformers import AutoModel from transformers.models.bert.configuration_bert import BertConfig from transformers.models.bert.modeling_bert import BertEmbeddings from transformers.models.albert.configuration_albert import AlbertConf...
from setuptools import setup, find_packages with open('README.md', "r") as fid: #encoding='utf-8' long_description = fid.read() setup( name='cngi_prototype', version='0.0.67', description='CASA Next Generation Infrastructure Prototype', long_description=long_description, long_description_con...
import numpy as np def pick(dict, elements): new_dict = {} for el in elements: new_dict[el] = dict.get(el) return new_dict def get_by_path(dict, path: str): keys = path.split(".") value = dict for key in keys: if value is None: return None value = value.ge...
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module contains the main object used to identify the coordination environments in a given structure. If you use this module, please cite the following: David Waroquiers, Xavier Gonze, Gian-Marco Rignanese, Cathrin Wel...
#!/usr/bin/env python import sys import subprocess from setuptools import setup, find_packages def check_minimap2(): p = subprocess.Popen(['minimap2', '--version'], stdout=subprocess.PIPE) for line in p.stdout: line = line.decode() major, minor = line.strip().split('.') if int(major) >...