edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
import re import sys import copy import types import inspect import keyword import builtins import functools import _thread __all__ = ['dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING', # Helper functions. 'fields',...
import re import sys import copy import types import inspect import keyword import builtins import functools import _thread __all__ = ['dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING', # Helper functions. 'fields',...
from typing import Any, Dict, IO, Mapping, Optional, Sequence, Tuple, Union import cyvcf2 import logging import numpy as np log = logging.getLogger(__name__) # have to re-declare here since only exist in cyvcf2 stub and fails on execution Text = Union[str, bytes] Primitives = Union[int, float, bool, Text] def _nump...
from typing import Any, Dict, IO, Mapping, Optional, Sequence, Tuple, Union import cyvcf2 import logging import numpy as np log = logging.getLogger(__name__) # have to re-declare here since only exist in cyvcf2 stub and fails on execution Text = Union[str, bytes] Primitives = Union[int, float, bool, Text] def _nump...
def rchop(s, ending): return s[: -len(ending)] if s.endswith(ending) else s def lchop(s, beginning): return s[len(beginning) :] if s.startswith(beginning) else s def ordinal_en(n: int): # https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement return f'{n}{'tsnrhtdd'[(n//10%10!=1)*(n...
def rchop(s, ending): return s[: -len(ending)] if s.endswith(ending) else s def lchop(s, beginning): return s[len(beginning) :] if s.startswith(beginning) else s def ordinal_en(n: int): # https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement return f'{n}{"tsnrhtdd"[(n//10%10!=1)*(n...
import logging import warnings from collections import OrderedDict import transaction from pyramid.events import NewRequest import pyramid.tweens from enum import Enum from kinto.core.utils import strip_uri_prefix logger = logging.getLogger(__name__) class ACTIONS(Enum): CREATE = "create" DELETE = "delete...
import logging import warnings from collections import OrderedDict import transaction from pyramid.events import NewRequest import pyramid.tweens from enum import Enum from kinto.core.utils import strip_uri_prefix logger = logging.getLogger(__name__) class ACTIONS(Enum): CREATE = "create" DELETE = "delete...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from awsglue.blueprint.workflow import Workflow, Entities from awsglue.blueprint.job import Job from awsglue.blueprint.crawler import * import boto3 from botocore.client import ClientError import datetime def g...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from awsglue.blueprint.workflow import Workflow, Entities from awsglue.blueprint.job import Job from awsglue.blueprint.crawler import * import boto3 from botocore.client import ClientError import datetime def g...
import random from ..core import Basic, Integer from ..core.compatibility import as_int class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilt...
import random from ..core import Basic, Integer from ..core.compatibility import as_int class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilt...
#!/usr/bin/env python import argparse import copy import traceback from os import listdir from os.path import isfile, join #from cv_bridge import CvBridge import math import matplotlib.pyplot as plt import pandas as pd import random # u import numpy as np import cv2 as cv import rospy # Brings in the SimpleAction...
#!/usr/bin/env python import argparse import copy import traceback from os import listdir from os.path import isfile, join #from cv_bridge import CvBridge import math import matplotlib.pyplot as plt import pandas as pd import random # u import numpy as np import cv2 as cv import rospy # Brings in the SimpleAction...
#!/usr/bin/env python3 import os import re import datetime import json import copy # Parses the md file, outputs html string def createArticle(mdFileName:str, isBlog=True): """ mdFileName: md file name isBlog: boolean Returns: { article, postTitle, postSubject, timeCreated } article: the blog post in HTM...
#!/usr/bin/env python3 import os import re import datetime import json import copy # Parses the md file, outputs html string def createArticle(mdFileName:str, isBlog=True): """ mdFileName: md file name isBlog: boolean Returns: { article, postTitle, postSubject, timeCreated } article: the blog post in HTM...
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # This file is part of Wizard # MIT License # Copyright (c) 2021 Leo brunel # 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 So...
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # This file is part of Wizard # MIT License # Copyright (c) 2021 Leo brunel # 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 So...
from financialmodelingprep.decorator import get_json_data BASE_URL = 'https://financialmodelingprep.com' class calendars(): BASE_URL = 'https://financialmodelingprep.com' API_KEY = '' def __init__(self, API_KEY): self.API = API_KEY @get_json_data def earning_calendar(self): ''' ...
from financialmodelingprep.decorator import get_json_data BASE_URL = 'https://financialmodelingprep.com' class calendars(): BASE_URL = 'https://financialmodelingprep.com' API_KEY = '' def __init__(self, API_KEY): self.API = API_KEY @get_json_data def earning_calendar(self): ''' ...
""" CS 229 Machine Learning Question: Reinforcement Learning - The Inverted Pendulum """ from __future__ import division, print_function import matplotlib matplotlib.use('TkAgg') from env import CartPole, Physics import matplotlib.pyplot as plt import numpy as np from scipy.signal import lfilter """ Parts of the code...
""" CS 229 Machine Learning Question: Reinforcement Learning - The Inverted Pendulum """ from __future__ import division, print_function import matplotlib matplotlib.use('TkAgg') from env import CartPole, Physics import matplotlib.pyplot as plt import numpy as np from scipy.signal import lfilter """ Parts of the code...
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python3 """Zeff record config generator for HousePrice records.""" import logging import urllib.parse import csv LOGGER = logging.getLogger("zeffclient.record.generator") def HousePriceRecordGenerator(arg: str): """Return house primary key value.""" with open(arg, "r") as csvfile: for ...
#!/usr/bin/env python3 """Zeff record config generator for HousePrice records.""" import logging import urllib.parse import csv LOGGER = logging.getLogger("zeffclient.record.generator") def HousePriceRecordGenerator(arg: str): """Return house primary key value.""" with open(arg, "r") as csvfile: for ...
#!/usr/bin/python import os import sys import time import signal import importlib import argparse import subprocess import xml.etree.ElementTree as ET import xml.dom.minidom import board import timer class Server(object): """ Othello server, implements a simple file-based playing protocol """ def ...
#!/usr/bin/python import os import sys import time import signal import importlib import argparse import subprocess import xml.etree.ElementTree as ET import xml.dom.minidom import board import timer class Server(object): """ Othello server, implements a simple file-based playing protocol """ def ...
"""Scans directories for files that satisfy a specific mask and updates version tags of all actions. Example: python3 update_actions.py live.yml action.y*ml folder/*.y*ml """ import argparse import re from pathlib import Path from typing import Dict, List, Optional from github import Github ACTION_PATTERN = r"...
"""Scans directories for files that satisfy a specific mask and updates version tags of all actions. Example: python3 update_actions.py live.yml action.y*ml folder/*.y*ml """ import argparse import re from pathlib import Path from typing import Dict, List, Optional from github import Github ACTION_PATTERN = r"...
from pipeline import * def make_index_html(D):# {{{ source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np...
from pipeline import * def make_index_html(D):# {{{ source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np...
# SPDX-License-Identifier: MIT import itertools, fnmatch from construct import * from .utils import AddrLookup, FourCC, SafeGreedyRange __all__ = ["load_adt"] ADTPropertyStruct = Struct( "name" / PaddedString(32, "ascii"), "size" / Int32ul, "value" / Bytes(this.size & 0x7fffffff) ) ADTNodeStruct = Struc...
# SPDX-License-Identifier: MIT import itertools, fnmatch from construct import * from .utils import AddrLookup, FourCC, SafeGreedyRange __all__ = ["load_adt"] ADTPropertyStruct = Struct( "name" / PaddedString(32, "ascii"), "size" / Int32ul, "value" / Bytes(this.size & 0x7fffffff) ) ADTNodeStruct = Struc...
#Import Libraries #Web Scraping tools from bs4 import BeautifulSoup as bs from selenium import webdriver #from splinter import Browser #DataFrame tools import pandas as pd #Misc tools for web scraping import time import requests #Function to initianilze browser. def init_browser(): #Settings for headless mode....
#Import Libraries #Web Scraping tools from bs4 import BeautifulSoup as bs from selenium import webdriver #from splinter import Browser #DataFrame tools import pandas as pd #Misc tools for web scraping import time import requests #Function to initianilze browser. def init_browser(): #Settings for headless mode....
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # TheCyberUserBot - Luciferxz import io import re import userbot.modules.sql_helper.blacklist_sql as sql from userbo...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # TheCyberUserBot - Luciferxz import io import re import userbot.modules.sql_helper.blacklist_sql as sql from userbo...
import typing as t from abc import ABC, abstractmethod from types import SimpleNamespace from .exceptions import BadMethod, FinalizationError, NoMethod, NotFound from .line import Line from .patterns import REGEX_TYPES from .route import Route from .tree import Tree from .utils import parts_to_path, path_to_parts # T...
import typing as t from abc import ABC, abstractmethod from types import SimpleNamespace from .exceptions import BadMethod, FinalizationError, NoMethod, NotFound from .line import Line from .patterns import REGEX_TYPES from .route import Route from .tree import Tree from .utils import parts_to_path, path_to_parts # T...
# Copyright (c) 2021 Cybereason Inc # This code is licensed under MIT license (see LICENSE.md for details) import json import requests import oci import io import base64 import logging import hashlib from fdk import response from cybereason_connection import get_cybereason_connection from cybereason_machine_suspicio...
# Copyright (c) 2021 Cybereason Inc # This code is licensed under MIT license (see LICENSE.md for details) import json import requests import oci import io import base64 import logging import hashlib from fdk import response from cybereason_connection import get_cybereason_connection from cybereason_machine_suspicio...
import aiohttp from flask import Flask from aio_executor import run_with_asyncio app = Flask(__name__) async def get_random_quote(): async with aiohttp.ClientSession() as session: async with session.get('https://api.quotable.io/random') as response: quote = await response.json() return f'...
import aiohttp from flask import Flask from aio_executor import run_with_asyncio app = Flask(__name__) async def get_random_quote(): async with aiohttp.ClientSession() as session: async with session.get('https://api.quotable.io/random') as response: quote = await response.json() return f'...
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import glob import json import urllib.parse import urllib.request import webbrowser from typing import Dict from .checker import * from .database import MongoDBHandler from .helper import handle_dot_in_keys from ..cl...
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import glob import json import urllib.parse import urllib.request import webbrowser from typing import Dict from .checker import * from .database import MongoDBHandler from .helper import handle_dot_in_keys from ..cl...
frase = str(input('Digite uma frase: ')).upper().strip() print(f'A letra "A" aparece {frase.count('A')} vezes na frase.') print(f'A primeira letra A apareceu na posição {frase.find('A')+1}.') print(f'A última letra A apareceu na posição {frase.rfind('A')+1}.') ## .join(frase.split()) juntar tudo, remover espaços
frase = str(input('Digite uma frase: ')).upper().strip() print(f'A letra "A" aparece {frase.count("A")} vezes na frase.') print(f'A primeira letra A apareceu na posição {frase.find("A")+1}.') print(f'A última letra A apareceu na posição {frase.rfind("A")+1}.') ## .join(frase.split()) juntar tudo, remover espaços
"""Tests for the Renault integration.""" from __future__ import annotations from types import MappingProxyType from typing import Any from unittest.mock import patch from renault_api.kamereon import schemas from renault_api.renault_account import RenaultAccount from homeassistant.components.renault.const import DOMA...
"""Tests for the Renault integration.""" from __future__ import annotations from types import MappingProxyType from typing import Any from unittest.mock import patch from renault_api.kamereon import schemas from renault_api.renault_account import RenaultAccount from homeassistant.components.renault.const import DOMA...
import re import textwrap from core.exceptions import InvalidMemoryAddress, MemoryLimitExceeded class Hex: def __init__(self, data: str = "0x00", _bytes: str = 1, *args, **kwargs) -> None: self._bytes = _bytes self._base = 16 self._format_spec = f"#0{2 + _bytes * 2}x" self._format...
import re import textwrap from core.exceptions import InvalidMemoryAddress, MemoryLimitExceeded class Hex: def __init__(self, data: str = "0x00", _bytes: str = 1, *args, **kwargs) -> None: self._bytes = _bytes self._base = 16 self._format_spec = f"#0{2 + _bytes * 2}x" self._format...
from typing import TYPE_CHECKING, List, Optional, Dict, Any from dis_snek.client.const import MISSING from dis_snek.client.utils.attr_utils import define, field from dis_snek.client.utils.converters import optional from dis_snek.models.discord.asset import Asset from dis_snek.models.discord.enums import ApplicationFla...
from typing import TYPE_CHECKING, List, Optional, Dict, Any from dis_snek.client.const import MISSING from dis_snek.client.utils.attr_utils import define, field from dis_snek.client.utils.converters import optional from dis_snek.models.discord.asset import Asset from dis_snek.models.discord.enums import ApplicationFla...
import re import sys from collections import defaultdict from typing import TYPE_CHECKING, AbstractSet, List, NamedTuple, Optional from dagster.core.definitions.dependency import DependencyStructure, Node from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvalidSubsetError from dagster.utils im...
import re import sys from collections import defaultdict from typing import TYPE_CHECKING, AbstractSet, List, NamedTuple, Optional from dagster.core.definitions.dependency import DependencyStructure, Node from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvalidSubsetError from dagster.utils im...
# makes a string of 50 equals signs for a line break separator = "=" * 50 if True: print("hi") else: print("no") # creates a 2d list with 10 rows car_park = [[] for i in range(10)] # filling the car park for i in range(10): for j in range(6): car_park[i].append("E") # e stands for empty # creates the interfa...
# makes a string of 50 equals signs for a line break separator = "=" * 50 if True: print("hi") else: print("no") # creates a 2d list with 10 rows car_park = [[] for i in range(10)] # filling the car park for i in range(10): for j in range(6): car_park[i].append("E") # e stands for empty # creates the interfa...
import numpy as np import cv2 import random import warnings import scipy from scipy.linalg.basic import solve_circulant import skimage import skimage.transform from distutils.version import LooseVersion import torch import math import json from torch.functional import Tensor np.random.seed(42) def load_points_datase...
import numpy as np import cv2 import random import warnings import scipy from scipy.linalg.basic import solve_circulant import skimage import skimage.transform from distutils.version import LooseVersion import torch import math import json from torch.functional import Tensor np.random.seed(42) def load_points_datase...
from celescope.mut.__init__ import __ASSAY__ from celescope.tools.multi import Multi class Multi_mut(Multi): def mapping_mut(self, sample): step = 'mapping_mut' fq = f'{self.outdir_dic[sample]['cutadapt']}/{sample}_clean_2.fq{self.fq_suffix}' cmd = ( f'{self.__APP__} ' ...
from celescope.mut.__init__ import __ASSAY__ from celescope.tools.multi import Multi class Multi_mut(Multi): def mapping_mut(self, sample): step = 'mapping_mut' fq = f'{self.outdir_dic[sample]["cutadapt"]}/{sample}_clean_2.fq{self.fq_suffix}' cmd = ( f'{self.__APP__} ' ...
from flask import Flask, jsonify, request, render_template, Response, send_file # from prefix_and_wsgi_proxy_fix import ReverseProxied from base64 import urlsafe_b64encode import gpxpy.gpx import geojson import werkzeug.exceptions import os from werkzeug.datastructures import Headers from db_functions import get_waypoi...
from flask import Flask, jsonify, request, render_template, Response, send_file # from prefix_and_wsgi_proxy_fix import ReverseProxied from base64 import urlsafe_b64encode import gpxpy.gpx import geojson import werkzeug.exceptions import os from werkzeug.datastructures import Headers from db_functions import get_waypoi...
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Weight_Editor: @staticmethod def weights_entrypoint(): weapon_data, skin_data, skin_choice, weapon...
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Weight_Editor: @staticmethod def weights_entrypoint(): weapon_data, skin_data, skin_choice, weapon...
# -*- coding: UTF-8 -*- # # copyright: 2020-2021, Frederico Martins # author: Frederico Martins <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Discogs data handler. This module handles Discogs data. The following is a simple usage example:: from .discogs import Discogs d = Discogs('my_discog...
# -*- coding: UTF-8 -*- # # copyright: 2020-2021, Frederico Martins # author: Frederico Martins <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Discogs data handler. This module handles Discogs data. The following is a simple usage example:: from .discogs import Discogs d = Discogs('my_discog...
""" Define typing templates """ from abc import ABC, abstractmethod import functools import sys import inspect import os.path from collections import namedtuple from collections.abc import Sequence from types import MethodType, FunctionType import numba from numba.core import types, utils from numba.core.errors impor...
""" Define typing templates """ from abc import ABC, abstractmethod import functools import sys import inspect import os.path from collections import namedtuple from collections.abc import Sequence from types import MethodType, FunctionType import numba from numba.core import types, utils from numba.core.errors impor...
import os import re import sys import importlib from aq.cli.commands import AQCommand class Command(AQCommand): description = "Displays this help message" def run(self): print("\nAzure Query CLI\n") print("This tool provides an easy to use CLI implementation of the Microsoft Graph API REST ...
import os import re import sys import importlib from aq.cli.commands import AQCommand class Command(AQCommand): description = "Displays this help message" def run(self): print("\nAzure Query CLI\n") print("This tool provides an easy to use CLI implementation of the Microsoft Graph API REST ...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not ...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not ...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module for kanging stickers or making new ones. Thanks @rupansh""" import io import math import random imp...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module for kanging stickers or making new ones. Thanks @rupansh""" import io import math import random imp...
from __future__ import unicode_literals import datetime import logging from inspect import isclass from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist from django.db.models import Q, ForeignKey from .fields import SlickReportField from .helpers import get_field_from_query_text from .registry i...
from __future__ import unicode_literals import datetime import logging from inspect import isclass from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist from django.db.models import Q, ForeignKey from .fields import SlickReportField from .helpers import get_field_from_query_text from .registry i...
# flake8: noqa E501 import json conditional_token_abi = json.loads( '[{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"nam...
# flake8: noqa E501 import json conditional_token_abi = json.loads( '[{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"nam...
""" Prepare all X-ray structures for FAH # Projects 13430 : apo Mpro monomer His41(0) Cys145(0) 13431 : apo Mpro monomer His41(+) Cys145(-) 13432 : holo Mpro monomer His41(0) Cys145(0) 13433 : holo Mpro monomer His41(+) Cys145(-) 13434 : apo Mpro dimer His41(0) Cys145(0) 13435 : apo Mpro dimer...
""" Prepare all X-ray structures for FAH # Projects 13430 : apo Mpro monomer His41(0) Cys145(0) 13431 : apo Mpro monomer His41(+) Cys145(-) 13432 : holo Mpro monomer His41(0) Cys145(0) 13433 : holo Mpro monomer His41(+) Cys145(-) 13434 : apo Mpro dimer His41(0) Cys145(0) 13435 : apo Mpro dimer...
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 from random import shuffle from unittest import TestCase import warnings from tsfresh.feature_extraction.feature_calculat...
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 from random import shuffle from unittest import TestCase import warnings from tsfresh.feature_extraction.feature_calculat...
""" Copyright 2021 Nirlep_5252_ 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, software d...
""" Copyright 2021 Nirlep_5252_ 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, software d...
r""" From previous experiments, we saw that ephemeral pseudo-labelling helped boost accuracy despite starting with only 20 points. We could kick-start BALD with 85% accuracy with 24 iterations but it seems like using 80% accuracy at 10 iterations is a good trade-off. It's harder to gain more accuracy as the number of i...
r""" From previous experiments, we saw that ephemeral pseudo-labelling helped boost accuracy despite starting with only 20 points. We could kick-start BALD with 85% accuracy with 24 iterations but it seems like using 80% accuracy at 10 iterations is a good trade-off. It's harder to gain more accuracy as the number of i...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import time from contextlib import contextmanager from threading import Lock from typing import Dict, Tuple from pants.base.exiter import PANTS_FAILED_...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import time from contextlib import contextmanager from threading import Lock from typing import Dict, Tuple from pants.base.exiter import PANTS_FAILED_...
from snappy import ProductIO, HashMap, GPF import os def apply_orbit_file(product): parameters = HashMap() parameters.put("Apply-Orbit-File", True) operator_name = "Apply-Orbit-File" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def ther...
from snappy import ProductIO, HashMap, GPF import os def apply_orbit_file(product): parameters = HashMap() parameters.put("Apply-Orbit-File", True) operator_name = "Apply-Orbit-File" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def ther...
# -*- coding: utf-8 -*- # author: https://github.com/Zfour import json import yaml from bs4 import BeautifulSoup from request_data import request data_pool = [] def load_config(): f = open('_config.yml', 'r', encoding='utf-8') ystr = f.read() ymllist = yaml.load(ystr, Loader=yaml.FullLoader) return...
# -*- coding: utf-8 -*- # author: https://github.com/Zfour import json import yaml from bs4 import BeautifulSoup from request_data import request data_pool = [] def load_config(): f = open('_config.yml', 'r', encoding='utf-8') ystr = f.read() ymllist = yaml.load(ystr, Loader=yaml.FullLoader) return...
#!/usr/bin/env python import logging import numpy as np import time from flask import Flask, request, jsonify from os import getenv import sentry_sdk sentry_sdk.init(getenv("SENTRY_DSN")) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogg...
#!/usr/bin/env python import logging import numpy as np import time from flask import Flask, request, jsonify from os import getenv import sentry_sdk sentry_sdk.init(getenv("SENTRY_DSN")) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogg...
#!/usr/bin/env python import argparse import logging import os import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import gevent from gevent.lock import Semaphore from typing_extensions import Literal from rotkehlchen.accounting.accountant import Accountant from rotkehlche...
#!/usr/bin/env python import argparse import logging import os import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import gevent from gevent.lock import Semaphore from typing_extensions import Literal from rotkehlchen.accounting.accountant import Accountant from rotkehlche...
""" MIT License Copyright (c) 2020 Airbyte 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 use, copy, modify, merge, publish, distr...
""" MIT License Copyright (c) 2020 Airbyte 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 use, copy, modify, merge, publish, distr...
import sqlite3 from os import listdir import pandas as pd from transfer_data import pick_path def database_pipeline(path): connection = sqlite3.connect("./baseData/allPlayerStats.db") cursor = connection.cursor() # See this for various ways to import CSV into sqlite using Python. Pandas used here beca...
import sqlite3 from os import listdir import pandas as pd from transfer_data import pick_path def database_pipeline(path): connection = sqlite3.connect("./baseData/allPlayerStats.db") cursor = connection.cursor() # See this for various ways to import CSV into sqlite using Python. Pandas used here beca...
import re from io import StringIO from pathlib import Path import warnings from typing import TextIO, Optional def dump_parameters_text(PARAMETERS: dict, file: Optional[TextIO] = None): from .parameters import Parameter, SequenceParameter, PlaceholderParameter for path, param in PARAMETERS.items(): p...
import re from io import StringIO from pathlib import Path import warnings from typing import TextIO, Optional def dump_parameters_text(PARAMETERS: dict, file: Optional[TextIO] = None): from .parameters import Parameter, SequenceParameter, PlaceholderParameter for path, param in PARAMETERS.items(): p...
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 from neptune_load.sigv4_signer.sigv4_signer import SigV4Signer from neptune_load.bulk_loader.bulk_loader import BulkLoader import logging import os import sys logger = logging.getLogger("bulk_load") logger.setL...
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 from neptune_load.sigv4_signer.sigv4_signer import SigV4Signer from neptune_load.bulk_loader.bulk_loader import BulkLoader import logging import os import sys logger = logging.getLogger("bulk_load") logger.setL...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. '''Dá para fazer em 2 linhas... for i in range(0, len(prod), 2): print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')''' produtos = (...
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. '''Dá para fazer em 2 linhas... for i in range(0, len(prod), 2): print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')''' produtos = (...
# Inspired in # https://github.com/grizzlypeaksoftware/Flask-Stock-Widget # https://github.com/rubenafo/yfMongo import sys, os import re import csv import json from datetime import datetime, date, time, timedelta from itertools import zip_longest import numpy as np import pytz import yfinance as yf import ast import c...
# Inspired in # https://github.com/grizzlypeaksoftware/Flask-Stock-Widget # https://github.com/rubenafo/yfMongo import sys, os import re import csv import json from datetime import datetime, date, time, timedelta from itertools import zip_longest import numpy as np import pytz import yfinance as yf import ast import c...
import logging import os from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.sto...
import logging import os from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.sto...
#!/usr/bin/env python3 from contextlib import contextmanager from os import path as osp import joblib import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.svm import SVC DEMO_DIR = osp.abspath(osp.dirname(__file__)) DATA_DIR = osp.join(DEMO_DIR, "data") MODELS_DIR = osp.join(DEMO_DIR, "m...
#!/usr/bin/env python3 from contextlib import contextmanager from os import path as osp import joblib import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.svm import SVC DEMO_DIR = osp.abspath(osp.dirname(__file__)) DATA_DIR = osp.join(DEMO_DIR, "data") MODELS_DIR = osp.join(DEMO_DIR, "m...
import pandas as pd estados = ['acre|ac', 'alagoas|al', 'amapá|ap', 'amazonas|am', 'bahia|ba', 'ceará|ce', 'espírito santo|es', 'goiás|go', 'maranhão|ma', 'mato grosso|mt', 'mato grosso do sul|ms', 'goiás|go', 'maranhão|ma', 'minas gerais|mg', 'pará|pa', 'paraíba|pb', 'paraná|pr', 'pernambuco|pe', 'piauí...
import pandas as pd estados = ['acre|ac', 'alagoas|al', 'amapá|ap', 'amazonas|am', 'bahia|ba', 'ceará|ce', 'espírito santo|es', 'goiás|go', 'maranhão|ma', 'mato grosso|mt', 'mato grosso do sul|ms', 'goiás|go', 'maranhão|ma', 'minas gerais|mg', 'pará|pa', 'paraíba|pb', 'paraná|pr', 'pernambuco|pe', 'piauí...
from onelang_core import * import OneLang.Parsers.Common.Reader as read import OneLang.Parsers.Common.ExpressionParser as exprPars import OneLang.Parsers.Common.NodeManager as nodeMan import OneLang.Parsers.Common.IParser as iPars import OneLang.One.Ast.AstTypes as astTypes import OneLang.One.Ast.Expressions as exprs i...
from onelang_core import * import OneLang.Parsers.Common.Reader as read import OneLang.Parsers.Common.ExpressionParser as exprPars import OneLang.Parsers.Common.NodeManager as nodeMan import OneLang.Parsers.Common.IParser as iPars import OneLang.One.Ast.AstTypes as astTypes import OneLang.One.Ast.Expressions as exprs i...
#!/usr/bin/env python3 import json import logging import argparse from project.default import get_homedir def validate_generic_config_file(): sample_config = get_homedir() / 'config' / 'generic.json.sample' with sample_config.open() as f: generic_config_sample = json.load(f) # Check documentatio...
#!/usr/bin/env python3 import json import logging import argparse from project.default import get_homedir def validate_generic_config_file(): sample_config = get_homedir() / 'config' / 'generic.json.sample' with sample_config.open() as f: generic_config_sample = json.load(f) # Check documentatio...
import datetime import logging import tornado.escape import tornado.web from icubam.backoffice.handlers import base, home, icus, users from icubam.db import store from icubam.messaging import client class ListMessagesHandler(base.AdminHandler): ROUTE = "list_messages" def initialize(self): super().initiali...
import datetime import logging import tornado.escape import tornado.web from icubam.backoffice.handlers import base, home, icus, users from icubam.db import store from icubam.messaging import client class ListMessagesHandler(base.AdminHandler): ROUTE = "list_messages" def initialize(self): super().initiali...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module implements a friendly (well, friendlier) interface between the raw JSON responses from Jira and the Resource/dict abstractions provided by this library. Users will construct a JIRA object as described below. Full API documentation can be found at: https://jira.r...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module implements a friendly (well, friendlier) interface between the raw JSON responses from Jira and the Resource/dict abstractions provided by this library. Users will construct a JIRA object as described below. Full API documentation can be found at: https://jira.r...
# cmu_112_graphics.py # version 0.9.0 # Pre-release for CMU 15-112-s21 # Require Python 3.6 or later import sys if (sys.version_info[0] != 3) or (sys.version_info[1] < 6): raise Exception("cmu_112_graphics.py requires Python version 3.6 or later.") # Track version and file update timestamp import datetime MAJO...
# cmu_112_graphics.py # version 0.9.0 # Pre-release for CMU 15-112-s21 # Require Python 3.6 or later import sys if (sys.version_info[0] != 3) or (sys.version_info[1] < 6): raise Exception("cmu_112_graphics.py requires Python version 3.6 or later.") # Track version and file update timestamp import datetime MAJO...
from datetime import datetime from airflow.models import DAG from airflow.providers.apache.spark.operators.spark_jdbc import SparkJDBCOperator from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator im...
from datetime import datetime from airflow.models import DAG from airflow.providers.apache.spark.operators.spark_jdbc import SparkJDBCOperator from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator im...
import os import asyncio import logging import configparser from contextlib import suppress from eventkit import Event from ib_insync.objects import Object from ib_insync.contract import Forex from ib_insync.ib import IB import ib_insync.util as util __all__ = ['IBC', 'IBController', 'Watchdog'] class IBC(Object):...
import os import asyncio import logging import configparser from contextlib import suppress from eventkit import Event from ib_insync.objects import Object from ib_insync.contract import Forex from ib_insync.ib import IB import ib_insync.util as util __all__ = ['IBC', 'IBController', 'Watchdog'] class IBC(Object):...
"""Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ import datetime as dt import dateutil.parser as date_parser from dateutil.relativedelta import relativedelta from regolith.helpers.basehelper import DbHelpe...
"""Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ import datetime as dt import dateutil.parser as date_parser from dateutil.relativedelta import relativedelta from regolith.helpers.basehelper import DbHelpe...
from bilibili import bilibili from statistics import Statistics import printer from printer import Printer import rafflehandler from configloader import ConfigLoader import utils import asyncio import struct import json import sys import aiohttp class BaseDanmu(): __slots__ = ('ws', 'roomid', 'area_id', 'client'...
from bilibili import bilibili from statistics import Statistics import printer from printer import Printer import rafflehandler from configloader import ConfigLoader import utils import asyncio import struct import json import sys import aiohttp class BaseDanmu(): __slots__ = ('ws', 'roomid', 'area_id', 'client'...
import datetime import discord from discord.ext import commands from discord.ext.commands import Bot, Context from tortoise.functions import Sum import config from db.models.stats import Stats from db.models.user import User from db.redis import RedisDB from models.command import CommandInfo from rpc.client import RP...
import datetime import discord from discord.ext import commands from discord.ext.commands import Bot, Context from tortoise.functions import Sum import config from db.models.stats import Stats from db.models.user import User from db.redis import RedisDB from models.command import CommandInfo from rpc.client import RP...
def topla(a, b): return a + b print(topla(2, 3)) topla2 = lambda a, b: a + b print(topla2(2, 3)) def listeyiGoster(liste, gosteriFonksiyonu): for i in liste: print(gosteriFonksiyonu(i)) list = [ {"id": 1, "ad": "Alper", "soyad": "Konuralp" }, {"id": 2, "ad": "Burcu", "soyad": "K...
def topla(a, b): return a + b print(topla(2, 3)) topla2 = lambda a, b: a + b print(topla2(2, 3)) def listeyiGoster(liste, gosteriFonksiyonu): for i in liste: print(gosteriFonksiyonu(i)) list = [ {"id": 1, "ad": "Alper", "soyad": "Konuralp" }, {"id": 2, "ad": "Burcu", "soyad": "K...
from contextlib import closing import json import logging import boto3 from lambda_logs import JSONFormatter, custom_lambda_logs logger = logging.getLogger() logger.setLevel(logging.INFO) logger.handlers[0].setFormatter(JSONFormatter()) class QCFailed(Exception): def __init__(self, message: str): self....
from contextlib import closing import json import logging import boto3 from lambda_logs import JSONFormatter, custom_lambda_logs logger = logging.getLogger() logger.setLevel(logging.INFO) logger.handlers[0].setFormatter(JSONFormatter()) class QCFailed(Exception): def __init__(self, message: str): self....
#!/usr/bin/env python3 import copy import difflib import logging from pathlib import Path from typing import Dict, Optional, Union import click import requests import rich import toml from packaging.specifiers import Specifier from packaging.version import Version from rich.logging import RichHandler from rich.syntax...
#!/usr/bin/env python3 import copy import difflib import logging from pathlib import Path from typing import Dict, Optional, Union import click import requests import rich import toml from packaging.specifiers import Specifier from packaging.version import Version from rich.logging import RichHandler from rich.syntax...
import logging from binascii import hexlify from pprint import pformat from lntenna.bitcoin import AuthServiceProxy, SATOSHIS, make_service_url try: from lntenna.server.bitcoind_password import BITCOIND_PW except ModuleNotFoundError: pass from lntenna.database import ( mesh_add_verify_quote, orders_g...
import logging from binascii import hexlify from pprint import pformat from lntenna.bitcoin import AuthServiceProxy, SATOSHIS, make_service_url try: from lntenna.server.bitcoind_password import BITCOIND_PW except ModuleNotFoundError: pass from lntenna.database import ( mesh_add_verify_quote, orders_g...
#!/usr/bin/env python # Copyright 2022 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Creates a new branch that bumps the llvm-project commit. # Typical usage (from...
#!/usr/bin/env python # Copyright 2022 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Creates a new branch that bumps the llvm-project commit. # Typical usage (from...
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1156371286.47dzzz0': {'Type': 'Building Interior','Name': '','Instanced': False,'Objects': {'1165344228.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(2.145, 0.0, 0.0),'Pos': Point3(-1.873, -5.288, -0.154),...
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1156371286.47dzzz0': {'Type': 'Building Interior','Name': '','Instanced': False,'Objects': {'1165344228.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(2.145, 0.0, 0.0),'Pos': Point3(-1.873, -5.288, -0.154),...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
import logging import os from pathlib import Path from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shar...
import logging import os from pathlib import Path from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shar...
import base64 import pathlib import sys import threading def read(path: pathlib.Path, stdout_lock: threading.Lock): with path.open(mode='rb') as file, stdout_lock: sys.stdout.write( f'{{'contents':'{base64.b64encode(file.read()).decode('utf-8')}"}}\n', ) sys.stdout.flush()
import base64 import pathlib import sys import threading def read(path: pathlib.Path, stdout_lock: threading.Lock): with path.open(mode='rb') as file, stdout_lock: sys.stdout.write( f'{{"contents":"{base64.b64encode(file.read()).decode("utf-8")}"}}\n', ) sys.stdout.flush()
# coding: utf-8 """JupyterLab command handler""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import contextlib import errno import hashlib import itertools import json import logging import os import os.path as osp import re import shutil import stat import site...
# coding: utf-8 """JupyterLab command handler""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import contextlib import errno import hashlib import itertools import json import logging import os import os.path as osp import re import shutil import stat import site...
"""This script is used to measure output dispersion score of synthetic datasets """ import os import sys import numpy as np import torch import random import tqdm import time from pathlib import Path from os.path import join from model.model import EncoderDecoder sys.path.append(join(os.path.dirname(os.path.abspath(__f...
"""This script is used to measure output dispersion score of synthetic datasets """ import os import sys import numpy as np import torch import random import tqdm import time from pathlib import Path from os.path import join from model.model import EncoderDecoder sys.path.append(join(os.path.dirname(os.path.abspath(__f...
# 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. """ Train a network across multiple GPUs. """ import contextlib import logging import sys import time from argparse import Namespace from ite...
# 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. """ Train a network across multiple GPUs. """ import contextlib import logging import sys import time from argparse import Namespace from ite...
import argparse import time import csv import yaml import os import logging from pathlib import Path import numpy as np from tqdm import tqdm from tensorboardX import SummaryWriter import cv2 import matplotlib.pyplot as plt class plot_results(object): def __init__(self, frame_list=[100], mode='base'): #...
import argparse import time import csv import yaml import os import logging from pathlib import Path import numpy as np from tqdm import tqdm from tensorboardX import SummaryWriter import cv2 import matplotlib.pyplot as plt class plot_results(object): def __init__(self, frame_list=[100], mode='base'): #...
from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.errors import UserIsBlocked, PeerIdInvalid from LuciferMoringstar_Robot.database.autofilter_db import is_subscribed, get_file_details from LuciferMoringstar_Robot...
from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.errors import UserIsBlocked, PeerIdInvalid from LuciferMoringstar_Robot.database.autofilter_db import is_subscribed, get_file_details from LuciferMoringstar_Robot...
import speech_recognition as sr from pydub import AudioSegment import os from datetime import date import sounddevice as sd from scipy.io.wavfile import write from random import choice, randint import pyttsx3 import time import webbrowser from playsound import playsound # Commands hello = ["hi", "Hi", "hello", "Hello...
import speech_recognition as sr from pydub import AudioSegment import os from datetime import date import sounddevice as sd from scipy.io.wavfile import write from random import choice, randint import pyttsx3 import time import webbrowser from playsound import playsound # Commands hello = ["hi", "Hi", "hello", "Hello...
#! /usr/bin/env python3 """ Bishbot - https://github.com/ldgregory/bishbot Leif Gregory <leif@devtek.org> space.py v0.1 Tested to Python v3.7.3 Description: Bot commands for the Space channel Changelog: 20200603 - Initial code Copyright 2020 Leif Gregory Licensed under the Apache License, Version 2.0 (the "Licens...
#! /usr/bin/env python3 """ Bishbot - https://github.com/ldgregory/bishbot Leif Gregory <leif@devtek.org> space.py v0.1 Tested to Python v3.7.3 Description: Bot commands for the Space channel Changelog: 20200603 - Initial code Copyright 2020 Leif Gregory Licensed under the Apache License, Version 2.0 (the "Licens...
# Calcular o IMC de uma pessoa cores = { 'limpo':'\033[m', 'verde':'\033[32m', 'amarelo':'\033[33m', } linha = f'{cores['amarelo']}-=' * 26 + f'{cores['limpo']}' print(linha) print('Vamos calcular seu IMC!') print(linha) peso_kg = str(input('Preciso saber seu peso, em Quilogramas: ')).strip() alt_metros ...
# Calcular o IMC de uma pessoa cores = { 'limpo':'\033[m', 'verde':'\033[32m', 'amarelo':'\033[33m', } linha = f'{cores["amarelo"]}-=' * 26 + f'{cores["limpo"]}' print(linha) print('Vamos calcular seu IMC!') print(linha) peso_kg = str(input('Preciso saber seu peso, em Quilogramas: ')).strip() alt_metros ...
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ from utils.GlobalVars import * from recbole.config import Config, EvalSetting from r...
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ from utils.GlobalVars import * from recbole.config import Config, EvalSetting from r...
from typing import Iterable, Optional from app.integrations.mailchimp import exceptions from app.integrations.mailchimp.http import MailchimpHTTP from app.integrations.mailchimp.member import MailchimpMember from users.models import User class AppMailchimp: def __init__(self): self.http = MailchimpHTTP()...
from typing import Iterable, Optional from app.integrations.mailchimp import exceptions from app.integrations.mailchimp.http import MailchimpHTTP from app.integrations.mailchimp.member import MailchimpMember from users.models import User class AppMailchimp: def __init__(self): self.http = MailchimpHTTP()...
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, division, print_function import json import logging import math import os import random import warnings from multiprocessing import cpu_count import numpy as np from scipy.stats import mode, pearsonr from sklearn.metrics import ( conf...
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, division, print_function import json import logging import math import os import random import warnings from multiprocessing import cpu_count import numpy as np from scipy.stats import mode, pearsonr from sklearn.metrics import ( conf...
# Constellation Control Server # A centralized server for controlling museum exhibit components # Written by Morgan Rehnberg, Fort Worth Museum of Science and History # Released under the MIT license # Standard modules from http.server import HTTPServer, SimpleHTTPRequestHandler from socketserver import ThreadingMixIn...
# Constellation Control Server # A centralized server for controlling museum exhibit components # Written by Morgan Rehnberg, Fort Worth Museum of Science and History # Released under the MIT license # Standard modules from http.server import HTTPServer, SimpleHTTPRequestHandler from socketserver import ThreadingMixIn...
import json from flask import Flask, render_template , request from flask.wrappers import Response from get_ocr import get_ocr import os import datetime from werkzeug.utils import secure_filename import csv app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("/uplo...
import json from flask import Flask, render_template , request from flask.wrappers import Response from get_ocr import get_ocr import os import datetime from werkzeug.utils import secure_filename import csv app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("/uplo...
import pytest from r2d7.meta import Metawing import json list_printer_tests = ( ('{"position": 5, "id": 2085, "name": "DBS Swarm", "faction": "Separatist Alliance", "ships": [{"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.jso...
import pytest from r2d7.meta import Metawing import json list_printer_tests = ( ('{"position": 5, "id": 2085, "name": "DBS Swarm", "faction": "Separatist Alliance", "ships": [{"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.jso...
import json from landsatxplore.api import API from pprint import pprint # Initialize a new API instance and get an access key username = "batuhang" password = "SLCH6i5k9L.." api = API(username, password) # Search for Landsat TM scenes scenes = api.search( dataset='landsat_8_c1', latitude=28.85, longitude=4...
import json from landsatxplore.api import API from pprint import pprint # Initialize a new API instance and get an access key username = "batuhang" password = "SLCH6i5k9L.." api = API(username, password) # Search for Landsat TM scenes scenes = api.search( dataset='landsat_8_c1', latitude=28.85, longitude=4...
_E='replace' _D=False _C='\n' _B='\r\n' _A=None import contextlib,io,os,shlex,shutil,sys,tempfile from . import formatting,termui,utils from ._compat import _find_binary_reader class EchoingStdin: def __init__(A,input,output):A._input=input;A._output=output def __getattr__(A,x):return getattr(A._input,x) def _echo(...
_E='replace' _D=False _C='\n' _B='\r\n' _A=None import contextlib,io,os,shlex,shutil,sys,tempfile from . import formatting,termui,utils from ._compat import _find_binary_reader class EchoingStdin: def __init__(A,input,output):A._input=input;A._output=output def __getattr__(A,x):return getattr(A._input,x) def _echo(...
# Copyright 2019, The Emissions API Developers # https://emissions-api.org # This software is available under the terms of an MIT license. # See LICENSE fore more information. class RESTParamError(ValueError): """User-specific exception, used in :func:`~emissionsapi.utils.polygon_to_wkt`. """ pass def b...
# Copyright 2019, The Emissions API Developers # https://emissions-api.org # This software is available under the terms of an MIT license. # See LICENSE fore more information. class RESTParamError(ValueError): """User-specific exception, used in :func:`~emissionsapi.utils.polygon_to_wkt`. """ pass def b...
from falcon.testing import Result, TestClient from sustainerds.api.entities.user.model import UserDbModel ############################################################################### # model tests ############################################################################### def test_something(): d = UserDbM...
from falcon.testing import Result, TestClient from sustainerds.api.entities.user.model import UserDbModel ############################################################################### # model tests ############################################################################### def test_something(): d = UserDbM...
from inspect import trace from fastapi import APIRouter, Depends, status, Response from typing import Optional from pydantic import BaseModel from core.config import ( ALLOWED_HOSTS, PROJECT_NAME, PROJECT_VERSION, API_PORT, DATABASE_NAME, NER_LABEL_COLLECTION, Feedback_Template_Collection...
from inspect import trace from fastapi import APIRouter, Depends, status, Response from typing import Optional from pydantic import BaseModel from core.config import ( ALLOWED_HOSTS, PROJECT_NAME, PROJECT_VERSION, API_PORT, DATABASE_NAME, NER_LABEL_COLLECTION, Feedback_Template_Collection...
#!/usr/bin/env python3 import argparse import copy from datetime import datetime from distutils.util import strtobool from distutils.version import LooseVersion import functools import os import pathlib import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_e...
#!/usr/bin/env python3 import argparse import copy from datetime import datetime from distutils.util import strtobool from distutils.version import LooseVersion import functools import os import pathlib import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_e...
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by ...
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by ...
import torch import pandas as pd from io import BytesIO from subprocess import check_output from . import writing import time def memory(device=0): total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_m...
import torch import pandas as pd from io import BytesIO from subprocess import check_output from . import writing import time def memory(device=0): total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_m...