edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
#!/opt/anaconda3/bin/python
from bs4 import BeautifulSoup
import requests
import ftfy
import glob
import argparse
import os
import jsonlines
def main(args):
# Create the new file. Overwrite if it exits
f = open(args.output_file, "w+")
f.close()
# Get a list of documents in the folder
filelist = ... | #!/opt/anaconda3/bin/python
from bs4 import BeautifulSoup
import requests
import ftfy
import glob
import argparse
import os
import jsonlines
def main(args):
# Create the new file. Overwrite if it exits
f = open(args.output_file, "w+")
f.close()
# Get a list of documents in the folder
filelist = ... |
from gql import gql
from dds import client as dds_client
link_service_mutation = gql(
"""
mutation {
linkService(
serviceType: REDIS,
serviceName: "test-service",
appname: "test-app"
) {
ok
error
}
}
"""
)
result = dds... | from gql import gql
from dds import client as dds_client
link_service_mutation = gql(
"""
mutation {
linkService(
serviceType: REDIS,
serviceName: "test-service",
appname: "test-app"
) {
ok
error
}
}
"""
)
result = dds... |
import discord
from discord.ext import commands
from Globals import Globals
def return_category(guild: discord.Guild, category_id_to_check: int):
category_dict = {i.id: i for i in guild.categories}
if category_id_to_check in category_dict:
return category_dict[category_id_to_check]
return None
... | import discord
from discord.ext import commands
from Globals import Globals
def return_category(guild: discord.Guild, category_id_to_check: int):
category_dict = {i.id: i for i in guild.categories}
if category_id_to_check in category_dict:
return category_dict[category_id_to_check]
return None
... |
from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient
from stix_shifter_utils.utils import logger
from stix_shifter_utils.utils.error_response import ErrorResponder
from .response_mapper import ResponseMapper
from datetime import datetime, timezone
import secrets
import string
import hashli... | from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient
from stix_shifter_utils.utils import logger
from stix_shifter_utils.utils.error_response import ErrorResponder
from .response_mapper import ResponseMapper
from datetime import datetime, timezone
import secrets
import string
import hashli... |
import math
import Levenshtein as Lev # see https://pypi.python.org/pypi/python-Levenshtein
#see https://stackoverflow.com/q/29233888/2583476
keyboard_cartesian = {'q': {'x':0, 'y':0}, 'w': {'x':1, 'y':0}, 'e': {'x':2, 'y':0}, 'r': {'x':3, 'y':0}, 't': {'x':4, 'y':0}, 'y': {'x':5, 'y':0}, 'u': {'x':6, 'y':0}, 'i':... | import math
import Levenshtein as Lev # see https://pypi.python.org/pypi/python-Levenshtein
#see https://stackoverflow.com/q/29233888/2583476
keyboard_cartesian = {'q': {'x':0, 'y':0}, 'w': {'x':1, 'y':0}, 'e': {'x':2, 'y':0}, 'r': {'x':3, 'y':0}, 't': {'x':4, 'y':0}, 'y': {'x':5, 'y':0}, 'u': {'x':6, 'y':0}, 'i':... |
#!/usr/bin/env python3
import requests
import json
from pprint import pprint
from jnpr.healthbot import HealthBotClient
from jnpr.healthbot import DeviceSchema
from jnpr.healthbot import DeviceGroupSchema
import argparse
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = argpa... | #!/usr/bin/env python3
import requests
import json
from pprint import pprint
from jnpr.healthbot import HealthBotClient
from jnpr.healthbot import DeviceSchema
from jnpr.healthbot import DeviceGroupSchema
import argparse
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = argpa... |
#!python
# Copyright 2018 Datawire. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | #!python
# Copyright 2018 Datawire. 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 json
import logging
import os
from typing import List, Tuple, Dict
from antlr4 import *
from qualitymeter.gen.javaLabeled.JavaLexer import JavaLexer
from qualitymeter.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled
from .pullup_field_identification_utils import InfoExtractorListener, get_list_of_fil... | import json
import logging
import os
from typing import List, Tuple, Dict
from antlr4 import *
from qualitymeter.gen.javaLabeled.JavaLexer import JavaLexer
from qualitymeter.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled
from .pullup_field_identification_utils import InfoExtractorListener, get_list_of_fil... |
import torch
from apex import amp
from math import ceil
import random
import PIL
from tqdm import tqdm
#torch.multiprocessing.set_start_method('spawn', force=True)
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
urbangan_dir = os.path.dirname(curr... | import torch
from apex import amp
from math import ceil
import random
import PIL
from tqdm import tqdm
#torch.multiprocessing.set_start_method('spawn', force=True)
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
urbangan_dir = os.path.dirname(curr... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
import warnings
from dataclasses import dataclass, field
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Union
from omegaconf import DictConfig, OmegaConf
from hydra import MissingC... | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
import warnings
from dataclasses import dataclass, field
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Union
from omegaconf import DictConfig, OmegaConf
from hydra import MissingC... |
import asyncio
import os
import random
import re
import string
import discord
from discord.ext import commands
from utils.functions import read_file
class MadLibs(commands.Cog):
"""The classic [madlibs game](https://en.wikipedia.org/wiki/Mad_Libs)"""
def __init__(self, bot):
self.bot = bot
... | import asyncio
import os
import random
import re
import string
import discord
from discord.ext import commands
from utils.functions import read_file
class MadLibs(commands.Cog):
"""The classic [madlibs game](https://en.wikipedia.org/wiki/Mad_Libs)"""
def __init__(self, bot):
self.bot = bot
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy.table import Table
from gammapy.maps import MapAxes, MapAxis
from gammapy.utils.integrate import trapz_loglog
from gammapy.utils.nddata import NDDataArray
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy.table import Table
from gammapy.maps import MapAxes, MapAxis
from gammapy.utils.integrate import trapz_loglog
from gammapy.utils.nddata import NDDataArray
... |
import netCDF4
import defopt
import sys
import datetime
def main(*, tfile: str='',
ufile: str='',
vfile: str='',
outputdir: str='./', jmin: int, jmax: int, imin: int, imax: int):
"""
subset nemo data
:param tfile: name of the netCDF file containing T cell grid data
:param u... | import netCDF4
import defopt
import sys
import datetime
def main(*, tfile: str='',
ufile: str='',
vfile: str='',
outputdir: str='./', jmin: int, jmax: int, imin: int, imax: int):
"""
subset nemo data
:param tfile: name of the netCDF file containing T cell grid data
:param u... |
from typing import Dict, List, Optional
import os
from glob import glob
from yaml.parser import ParserError, ScannerError
from bs4 import BeautifulSoup
from app_settings.app_settings import AppSettings
from general_tools import file_utils
from general_tools.file_utils import write_file
from resource_container.Resourc... | from typing import Dict, List, Optional
import os
from glob import glob
from yaml.parser import ParserError, ScannerError
from bs4 import BeautifulSoup
from app_settings.app_settings import AppSettings
from general_tools import file_utils
from general_tools.file_utils import write_file
from resource_container.Resourc... |
#from bottom_up import maximumScore
from memo_recursion import maximumScore
if __name__ == "__main__":
print("TestCase-1")
nums = [1,2,3]
multipliers = [3,2,1]
ans = maximumScore(nums, multipliers)
expected = 14
#print(f"{"Correct" if ans == expected else "Incorrect"}")
print(f"{"Correct" ... | #from bottom_up import maximumScore
from memo_recursion import maximumScore
if __name__ == "__main__":
print("TestCase-1")
nums = [1,2,3]
multipliers = [3,2,1]
ans = maximumScore(nums, multipliers)
expected = 14
#print(f"{'Correct' if ans == expected else 'Incorrect'}")
print(f"{'Correct' ... |
#!/usr/bin/env python3
#
# Copyright 2017-2020 GridGain Systems.
#
# 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 applicab... | #!/usr/bin/env python3
#
# Copyright 2017-2020 GridGain Systems.
#
# 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 applicab... |
# Copyright 2018 Jian Wu
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from collections import defaultdict
from typing import Optional, NoReturn, Tuple
from kaldi_python_io import Reader as BaseReader
class MetricReporter(object):
"""
Metric reporter (WER, SiSNR, SDR ...)
"""
de... | # Copyright 2018 Jian Wu
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from collections import defaultdict
from typing import Optional, NoReturn, Tuple
from kaldi_python_io import Reader as BaseReader
class MetricReporter(object):
"""
Metric reporter (WER, SiSNR, SDR ...)
"""
de... |
import sys
import importlib
import glob
from pathlib import Path
from panda3d.core import NodePath
from ursina.vec3 import Vec3
from panda3d.core import Vec4, Vec2
from panda3d.core import TransparencyAttrib
from panda3d.core import Shader
from panda3d.core import TextureStage, TexGenAttrib
from ursina.texture import ... | import sys
import importlib
import glob
from pathlib import Path
from panda3d.core import NodePath
from ursina.vec3 import Vec3
from panda3d.core import Vec4, Vec2
from panda3d.core import TransparencyAttrib
from panda3d.core import Shader
from panda3d.core import TextureStage, TexGenAttrib
from ursina.texture import ... |
'''
Copyright (C) 2021 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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... | '''
Copyright (C) 2021 CG Cookie
http://cgcookie.com
hello@cgcookie.com
Created by Jonathan Denning, Jonathan Williamson, and Patrick Moore
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... |
# -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 15/05/2021
"""
from py_dss_interface.models.Example.ExampleBase import ExampleBase
dss = ExampleBase("13").dss
# Integer methods
print(45 * '=' + ' Integer Methods' + 45 * '=')
print(f'dss.dssprogress_pct_progress(): {dss.dssprogress_pct_progress(12.5)}')
print(... | # -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 15/05/2021
"""
from py_dss_interface.models.Example.ExampleBase import ExampleBase
dss = ExampleBase("13").dss
# Integer methods
print(45 * '=' + ' Integer Methods' + 45 * '=')
print(f'dss.dssprogress_pct_progress(): {dss.dssprogress_pct_progress(12.5)}')
print(... |
import re
from nonebot import on_command, export, logger
from nonebot.typing import T_State
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import MessageEvent, GroupMessageEvent, PrivateMessageEvent
from nonebot.adapters.cqhttp.permission import GROUP, PRIVATE_FRIEND
from nonebot.adapter... | import re
from nonebot import on_command, export, logger
from nonebot.typing import T_State
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import MessageEvent, GroupMessageEvent, PrivateMessageEvent
from nonebot.adapters.cqhttp.permission import GROUP, PRIVATE_FRIEND
from nonebot.adapter... |
# document_grid.py
#
# MIT License
#
# Copyright (c) 2020-2021 Andrey Maksimov <meamka@ya.ru>
#
# 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 limitati... | # document_grid.py
#
# MIT License
#
# Copyright (c) 2020-2021 Andrey Maksimov <meamka@ya.ru>
#
# 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 limitati... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/9/12
# @Author : MashiroF
# @File : DailyCash.py
# @Software: PyCharm
'''
cron: 30 5,12 * * * DailyCash.py
new Env('欢太每日现金');
'''
import os
import re
import sys
import time
import random
import logging
# 日志模块
logger = logging.... | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/9/12
# @Author : MashiroF
# @File : DailyCash.py
# @Software: PyCharm
'''
cron: 30 5,12 * * * DailyCash.py
new Env('欢太每日现金');
'''
import os
import re
import sys
import time
import random
import logging
# 日志模块
logger = logging.... |
# SPDX-License-Identifier: Apache-2.0
# Copyright © 2021 Intel Corporation
"""Helpers for strict type checking."""
import typing as T
from .. import compilers
from ..build import EnvironmentVariables, CustomTarget, BuildTarget, CustomTargetIndex, ExtractedObjects, GeneratedList
from ..coredata import UserFeatureOpti... | # SPDX-License-Identifier: Apache-2.0
# Copyright © 2021 Intel Corporation
"""Helpers for strict type checking."""
import typing as T
from .. import compilers
from ..build import EnvironmentVariables, CustomTarget, BuildTarget, CustomTargetIndex, ExtractedObjects, GeneratedList
from ..coredata import UserFeatureOpti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import platform
import sympy
import mpmath
import numpy
from mathics.version import __version__
version_info = {
"mathics": __version__,
"sympy": sympy.__version__,
"mpmath": mpmath.__version__,
"numpy": numpy.__version__,
"python": platfo... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import platform
import sympy
import mpmath
import numpy
from mathics.version import __version__
version_info = {
"mathics": __version__,
"sympy": sympy.__version__,
"mpmath": mpmath.__version__,
"numpy": numpy.__version__,
"python": platfo... |
from pprint import pprint
from ttp import ttp
import json
import time
from netmiko import ConnectHandler
ssh = {
'device_type': 'alcatel_sros',
'ip': '135.243.92.119',
'username': 'admin',
'password': 'admin',
'port': '22'
}
print ('Connection successful')
net_connect = ConnectHandler(**ssh)
outp... | from pprint import pprint
from ttp import ttp
import json
import time
from netmiko import ConnectHandler
ssh = {
'device_type': 'alcatel_sros',
'ip': '135.243.92.119',
'username': 'admin',
'password': 'admin',
'port': '22'
}
print ('Connection successful')
net_connect = ConnectHandler(**ssh)
outp... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
""" Financial Modeling Prep Controller """
__docformat__ = "numpy"
import argparse
import os
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import fmp_view
from gamestonk_terminal import feature_flags as gtff
from game... | """ Financial Modeling Prep Controller """
__docformat__ = "numpy"
import argparse
import os
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import fmp_view
from gamestonk_terminal import feature_flags as gtff
from game... |
from generallibrary import match, replace, deco_cache
from urllib.parse import quote
class Path_Strings:
""" String operations for Path. """
def __getitem__(self, item):
""" Get character from path string.
:param generalfile.Path self: """
return self.Path(self.path.__getitem__(... |
from generallibrary import match, replace, deco_cache
from urllib.parse import quote
class Path_Strings:
""" String operations for Path. """
def __getitem__(self, item):
""" Get character from path string.
:param generalfile.Path self: """
return self.Path(self.path.__getitem__(... |
"""
Defines the base class for optimizations as well as a certain
amount of useful generic optimization tools.
"""
import abc
import contextlib
import copy
import inspect
import logging
import pdb
import sys
import time
import traceback
import warnings
from collections import OrderedDict, UserList, defaultdict, deque
... | """
Defines the base class for optimizations as well as a certain
amount of useful generic optimization tools.
"""
import abc
import contextlib
import copy
import inspect
import logging
import pdb
import sys
import time
import traceback
import warnings
from collections import OrderedDict, UserList, defaultdict, deque
... |
#!/usr/bin/env python3
import boto3
import json
import os
import os
import pprint
from sys import version_info
import sys
AWS_REGION = "us-west-1"
EC2_CLIENT = boto3.client('ec2', region_name=AWS_REGION)
INSTANCE_ID = 'i-06a2ac220369ddb08'
# Stopping the instance using stop_instances.
instances = EC2_CLIENT.stop_i... | #!/usr/bin/env python3
import boto3
import json
import os
import os
import pprint
from sys import version_info
import sys
AWS_REGION = "us-west-1"
EC2_CLIENT = boto3.client('ec2', region_name=AWS_REGION)
INSTANCE_ID = 'i-06a2ac220369ddb08'
# Stopping the instance using stop_instances.
instances = EC2_CLIENT.stop_i... |
import pandas as pd
import psycopg2 as pg2
import yaml
import io
import ohio.ext.pandas
from sqlalchemy import create_engine
def open_db_connection(secrets_file="secrets.yaml", verbose=True):
"""
Opens connection to psql db
:return:
connection object
"""
try:
with open(secrets_... | import pandas as pd
import psycopg2 as pg2
import yaml
import io
import ohio.ext.pandas
from sqlalchemy import create_engine
def open_db_connection(secrets_file="secrets.yaml", verbose=True):
"""
Opens connection to psql db
:return:
connection object
"""
try:
with open(secrets_... |
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as dt
import matplotlib.ticker as ticker
import datetime
import pickle
import copy
import snake_case
YAXPARAMS = {
'cases': {
'total': {
'ymax': 90,
'yinterval':10... | import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as dt
import matplotlib.ticker as ticker
import datetime
import pickle
import copy
import snake_case
YAXPARAMS = {
'cases': {
'total': {
'ymax': 90,
'yinterval':10... |
#!/usr/bin/env python
"""
1a. As you have done in previous classes,
create a Python file named "my_devices.py".
In this file, define the connection information for:
'cisco3', 'arista1', 'arista2', and 'srx2'.
This file should contain all the necessary information
to create a Netmiko connection. Use getpass() for ... | #!/usr/bin/env python
"""
1a. As you have done in previous classes,
create a Python file named "my_devices.py".
In this file, define the connection information for:
'cisco3', 'arista1', 'arista2', and 'srx2'.
This file should contain all the necessary information
to create a Netmiko connection. Use getpass() for ... |
import base64
import fnmatch
import glob
import json
import os
import re
import shutil
import stat
import subprocess
import urllib.parse
import warnings
from datetime import datetime, timedelta
from distutils.util import strtobool
from packaging.version import Version
from pathlib import Path
from typing import Tuple,... | import base64
import fnmatch
import glob
import json
import os
import re
import shutil
import stat
import subprocess
import urllib.parse
import warnings
from datetime import datetime, timedelta
from distutils.util import strtobool
from packaging.version import Version
from pathlib import Path
from typing import Tuple,... |
#!/usr/bin/env python3
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import sys
import requests
import json
import time
import datetime
if __name__ == "__main__":
# state_name = str(input("Enter the state name: "))
# district_name = str(input("Enter the district name:... | #!/usr/bin/env python3
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import sys
import requests
import json
import time
import datetime
if __name__ == "__main__":
# state_name = str(input("Enter the state name: "))
# district_name = str(input("Enter the district name:... |
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.commit()
... | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.commit()
... |
from flask import Flask, request, jsonify
from cloudevents.http import from_http
import logging, json
from vcenter import Session
from datetime import date
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
app = Flask(__name__)
@app.route('/', methods=['... | from flask import Flask, request, jsonify
from cloudevents.http import from_http
import logging, json
from vcenter import Session
from datetime import date
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
app = Flask(__name__)
@app.route('/', methods=['... |
import logging
import os
from abc import ABC, abstractmethod
from typing import Optional
from checkov.terraform.module_loading.content import ModuleContent
from checkov.terraform.module_loading.registry import module_loader_registry
# ModuleContent allows access to a directory containing module file via the `path()`... | import logging
import os
from abc import ABC, abstractmethod
from typing import Optional
from checkov.terraform.module_loading.content import ModuleContent
from checkov.terraform.module_loading.registry import module_loader_registry
# ModuleContent allows access to a directory containing module file via the `path()`... |
#!/usr/bin/env python3
import os
# os.path() features a lot of functionalities.
# 1. os.path.basename() prints the end leaf name
print(os.path.basename("/tmp/test.txt"))
# 2. os.path.dirname() prints the directory part
print(os.path.dirname("/tmp/test.txt"))
# 3. os.path.exists() check for the existence of paths
p... | #!/usr/bin/env python3
import os
# os.path() features a lot of functionalities.
# 1. os.path.basename() prints the end leaf name
print(os.path.basename("/tmp/test.txt"))
# 2. os.path.dirname() prints the directory part
print(os.path.dirname("/tmp/test.txt"))
# 3. os.path.exists() check for the existence of paths
p... |
"""
Probabilistic Detectron Inference Script
"""
import json
import os
import sys
from shutil import copyfile
import torch
import tqdm
import core
# This is very ugly. Essential for now but should be fixed.
sys.path.append(os.path.join(core.top_dir(), "src", "detr"))
from detectron2.data import MetadataCatalog, bui... | """
Probabilistic Detectron Inference Script
"""
import json
import os
import sys
from shutil import copyfile
import torch
import tqdm
import core
# This is very ugly. Essential for now but should be fixed.
sys.path.append(os.path.join(core.top_dir(), "src", "detr"))
from detectron2.data import MetadataCatalog, bui... |
import scrapy
import logging
from scrapy.loader import ItemLoader
from scrapy.http import FormRequest
from scrapy.exceptions import CloseSpider
from datetime import datetime
from fbposts.items import FbPostItem, parse_date
class FacebookSpider(scrapy.Spider):
"""
Parse FB pages (needs credentials)
"""
... | import scrapy
import logging
from scrapy.loader import ItemLoader
from scrapy.http import FormRequest
from scrapy.exceptions import CloseSpider
from datetime import datetime
from fbposts.items import FbPostItem, parse_date
class FacebookSpider(scrapy.Spider):
"""
Parse FB pages (needs credentials)
"""
... |
import os
import shutil
from io import StringIO
from types import SimpleNamespace
import pkg_resources
#
from colt import Colt
#
from .qm.qm import QM, implemented_qm_software
from .molecule.terms import Terms
from .dihedral_scan import DihedralScan
from .misc import LOGO
class Initialize(Colt):
_user_input = """... | import os
import shutil
from io import StringIO
from types import SimpleNamespace
import pkg_resources
#
from colt import Colt
#
from .qm.qm import QM, implemented_qm_software
from .molecule.terms import Terms
from .dihedral_scan import DihedralScan
from .misc import LOGO
class Initialize(Colt):
_user_input = """... |
import os
import re
import sys
# Read arguments
if len(sys.argv) != 2:
raise ValueError('Please provide a filename input')
filename = sys.argv[1]
# Read file
file_data = open(os.getcwd() + '/' + filename, 'r')
# Parse file
tiles = []
for line in file_data.readlines():
line = line.replace('\n', '')
line... | import os
import re
import sys
# Read arguments
if len(sys.argv) != 2:
raise ValueError('Please provide a filename input')
filename = sys.argv[1]
# Read file
file_data = open(os.getcwd() + '/' + filename, 'r')
# Parse file
tiles = []
for line in file_data.readlines():
line = line.replace('\n', '')
line... |
#!/usr/bin/env python
# Notes on formulas
# -----------------
#
# There are four output types of formulas:
#
# 1. string
# 2. number
# 3. date — never a date range, unlike date properties
# 4. boolean
# Notes on rollups
# ----------------
#
# There are four signatures of rollup functions:
#
# 1. any -> array[any]
# ... | #!/usr/bin/env python
# Notes on formulas
# -----------------
#
# There are four output types of formulas:
#
# 1. string
# 2. number
# 3. date — never a date range, unlike date properties
# 4. boolean
# Notes on rollups
# ----------------
#
# There are four signatures of rollup functions:
#
# 1. any -> array[any]
# ... |
#!/usr/bin/env python
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Implementation for `pmg config` CLI.
"""
import glob
import os
import shutil
import subprocess
import sys
from urllib.request import urlretrieve
from monty.serialization import dumpfn, loadfn
from... | #!/usr/bin/env python
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Implementation for `pmg config` CLI.
"""
import glob
import os
import shutil
import subprocess
import sys
from urllib.request import urlretrieve
from monty.serialization import dumpfn, loadfn
from... |
"""
Driver of graph construction, optimization, and linking.
"""
import copy
import copyreg
import logging
import os
import pickle
import time
import warnings
from itertools import chain
from typing import List
import numpy as np
import aesara
import aesara.compile.profiling
from aesara.compile.compilelock import l... | """
Driver of graph construction, optimization, and linking.
"""
import copy
import copyreg
import logging
import os
import pickle
import time
import warnings
from itertools import chain
from typing import List
import numpy as np
import aesara
import aesara.compile.profiling
from aesara.compile.compilelock import l... |
#!/usr/bin/env python3
'''This is a copy of the python script that bashtop starts in a coprocess when using psutil for data collection'''
import os, sys, subprocess, re, time, psutil
from datetime import timedelta
from collections import defaultdict
from typing import List, Set, Dict, Tuple, Optional, Union
system: ... | #!/usr/bin/env python3
'''This is a copy of the python script that bashtop starts in a coprocess when using psutil for data collection'''
import os, sys, subprocess, re, time, psutil
from datetime import timedelta
from collections import defaultdict
from typing import List, Set, Dict, Tuple, Optional, Union
system: ... |
# Copyright (c) 2018-2020, NVIDIA CORPORATION.
from __future__ import division
import inspect
import itertools
import numbers
import pickle
import sys
import warnings
from collections import OrderedDict, defaultdict
from collections.abc import Iterable, Mapping, Sequence
import cupy
import numpy as np
import pandas a... | # Copyright (c) 2018-2020, NVIDIA CORPORATION.
from __future__ import division
import inspect
import itertools
import numbers
import pickle
import sys
import warnings
from collections import OrderedDict, defaultdict
from collections.abc import Iterable, Mapping, Sequence
import cupy
import numpy as np
import pandas a... |
import asyncio
import json
import os
import string
from statistics import mean
from typing import Any
from packaging import version as pyver
import pytz
from alerts.models import SEVERITY_CHOICES
from core.models import CoreSettings
from django.conf import settings
from django.contrib.postgres.fields import ArrayField... | import asyncio
import json
import os
import string
from statistics import mean
from typing import Any
from packaging import version as pyver
import pytz
from alerts.models import SEVERITY_CHOICES
from core.models import CoreSettings
from django.conf import settings
from django.contrib.postgres.fields import ArrayField... |
"""'Git type Path Source."""
import logging
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
from .source import Source
LOGGER = logging.getLogger(__name__)
class Git(Source):
"""Git Path Source.
The Git path source can be tasked with cloning a... | """'Git type Path Source."""
import logging
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
from .source import Source
LOGGER = logging.getLogger(__name__)
class Git(Source):
"""Git Path Source.
The Git path source can be tasked with cloning a... |
from django.utils import timezone
from calendar import HTMLCalendar
import logging
logger = logging.getLogger(__name__)
class Calendar(HTMLCalendar):
def __init__(self, year=None, month=None, dark=False):
self.year = year
self.month = month
self.events = None
self.dark = dark
... | from django.utils import timezone
from calendar import HTMLCalendar
import logging
logger = logging.getLogger(__name__)
class Calendar(HTMLCalendar):
def __init__(self, year=None, month=None, dark=False):
self.year = year
self.month = month
self.events = None
self.dark = dark
... |
# SPDX-License-Identifier: BSD-3-Clause
"""
Utility to create a SoftFab results file from PyLint's JSON output.
For SoftFab, 'error' means the test results are incomplete, while 'warning'
means the results are complete but the content has problems. So if PyLint
ran successfully but finds errors in the code it examine... | # SPDX-License-Identifier: BSD-3-Clause
"""
Utility to create a SoftFab results file from PyLint's JSON output.
For SoftFab, 'error' means the test results are incomplete, while 'warning'
means the results are complete but the content has problems. So if PyLint
ran successfully but finds errors in the code it examine... |
"""
This is a sample on how to define custom components.
You can make a repo out of this file, having one custom component per file
"""
import os
import shutil
import pytest
import pp
from pp.add_padding import add_padding_to_grid
from pp.add_termination import add_gratings_and_loop_back
from pp.autoplacer.yaml_place... | """
This is a sample on how to define custom components.
You can make a repo out of this file, having one custom component per file
"""
import os
import shutil
import pytest
import pp
from pp.add_padding import add_padding_to_grid
from pp.add_termination import add_gratings_and_loop_back
from pp.autoplacer.yaml_place... |
import csv
import io
import json
import logging
import uuid
from abc import ABCMeta, abstractmethod
from collections import defaultdict, namedtuple
from contextlib import closing
from itertools import chain
from typing import Set
import psycopg2
from botocore.exceptions import ClientError
from csp.decorators import cs... | import csv
import io
import json
import logging
import uuid
from abc import ABCMeta, abstractmethod
from collections import defaultdict, namedtuple
from contextlib import closing
from itertools import chain
from typing import Set
import psycopg2
from botocore.exceptions import ClientError
from csp.decorators import cs... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and re... | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and re... |
""" Crie um programa que leia nome e duas notas de vários alunos e guarte tudo em uma lista composta.
No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas
de cada aluno individualmente."""
lista_main = []
while True:
nome = str(input('Nome: '))
nota1 = float(inp... | """ Crie um programa que leia nome e duas notas de vários alunos e guarte tudo em uma lista composta.
No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas
de cada aluno individualmente."""
lista_main = []
while True:
nome = str(input('Nome: '))
nota1 = float(inp... |
# -*- coding=utf-8 -*-
import datetime
import pathlib
import os
import re
import sys
import invoke
from parver import Version
from towncrier._builder import (
find_fragments, render_fragments, split_fragments
)
from towncrier._settings import load_config
from pipenv.__version__ import __version__
from pipenv.ven... | # -*- coding=utf-8 -*-
import datetime
import pathlib
import os
import re
import sys
import invoke
from parver import Version
from towncrier._builder import (
find_fragments, render_fragments, split_fragments
)
from towncrier._settings import load_config
from pipenv.__version__ import __version__
from pipenv.ven... |
from aioify import aioify
from discord.ext import commands, tasks
import aiohttp
import aiosqlite
import asyncio
import discord
import json
import os
import shutil
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.os = aioify(os, name='os')
self.shutil = aioify(shuti... | from aioify import aioify
from discord.ext import commands, tasks
import aiohttp
import aiosqlite
import asyncio
import discord
import json
import os
import shutil
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.os = aioify(os, name='os')
self.shutil = aioify(shuti... |
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
agent basic tests
"""
import json
from pathlib import Path
from uuid import uuid4
from flask import url_for
from sner.agent.core import main as agent_main
from sner.lib import file_from_zip
from sner.server.scheduler.models i... | # This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
agent basic tests
"""
import json
from pathlib import Path
from uuid import uuid4
from flask import url_for
from sner.agent.core import main as agent_main
from sner.lib import file_from_zip
from sner.server.scheduler.models i... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import requests
import base64
import email
import hashlib
from typing import List
from dateutil.parser import parse
from typing import Dict, Tuple, Any, Optional, Union
from threading import ... | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import requests
import base64
import email
import hashlib
from typing import List
from dateutil.parser import parse
from typing import Dict, Tuple, Any, Optional, Union
from threading import ... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... |
#!/usr/bin/python3
import time
from web3 import Web3, KeepAliveRPCProvider, IPCProvider
web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545'))
# Global Declarations
global true
global false
global myst_account_0_a
global myst_account_1_a
global myst_account_2_a
global myst_account_3_a
global myst_... | #!/usr/bin/python3
import time
from web3 import Web3, KeepAliveRPCProvider, IPCProvider
web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545'))
# Global Declarations
global true
global false
global myst_account_0_a
global myst_account_1_a
global myst_account_2_a
global myst_account_3_a
global myst_... |
import copy
import json
import math
import os
import random
import re
import socket
import string
import time
import traceback
import sys
from functools import cmp_to_key
from http.client import IncompleteRead
from multiprocessing import Process, Manager, Semaphore
from threading import Thread
import crc32
import logg... | import copy
import json
import math
import os
import random
import re
import socket
import string
import time
import traceback
import sys
from functools import cmp_to_key
from http.client import IncompleteRead
from multiprocessing import Process, Manager, Semaphore
from threading import Thread
import crc32
import logg... |
"""
This is a very first draft idea of a module system.
The general idea is to NOT use Djangos ``django.setup()`` which inherently uses the ENV Variable to find the path
to a settings.py and loads it.
Instead we use the ``settings.configure()`` method INSTEAD of ``django.setup()`` where you can pass in arbitrary sett... | """
This is a very first draft idea of a module system.
The general idea is to NOT use Djangos ``django.setup()`` which inherently uses the ENV Variable to find the path
to a settings.py and loads it.
Instead we use the ``settings.configure()`` method INSTEAD of ``django.setup()`` where you can pass in arbitrary sett... |
import json
import aiohttp
import discord
from aiocache.decorators import cached
from utils.context import BlooContext, PromptData
from utils.permissions.permissions import permissions
from utils.views.menu import Menu
class TweakMenu(Menu):
def __init__(self, *args, **kwargs):
super().__init__(*args, *... | import json
import aiohttp
import discord
from aiocache.decorators import cached
from utils.context import BlooContext, PromptData
from utils.permissions.permissions import permissions
from utils.views.menu import Menu
class TweakMenu(Menu):
def __init__(self, *args, **kwargs):
super().__init__(*args, *... |
#!/usr/bin/env python3
# Need to run this from the directory containing this script and make_rules.py
# Run this script, then check output in the generated file, then run make_rules.py
import argparse
import json
import requests
import sys
import os
import boto3
from slugify import slugify
import common.common_lib ... | #!/usr/bin/env python3
# Need to run this from the directory containing this script and make_rules.py
# Run this script, then check output in the generated file, then run make_rules.py
import argparse
import json
import requests
import sys
import os
import boto3
from slugify import slugify
import common.common_lib ... |
#!/usr/bin/env python3
# This file is a part of toml++ and is subject to the the terms of the MIT license.
# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
# SPDX-License-Identifier: MIT
import sys
import utils
import... | #!/usr/bin/env python3
# This file is a part of toml++ and is subject to the the terms of the MIT license.
# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
# SPDX-License-Identifier: MIT
import sys
import utils
import... |
# -*- coding: utf-8 -*-
from ThymeBoost.trend_models.trend_base_class import TrendBaseModel
import numpy as np
import pandas as pd
class EwmModel(TrendBaseModel):
model = 'ewm'
def __init__(self):
self.model_params = None
self.fitted = None
def __str__(self):
return f'{self.mo... | # -*- coding: utf-8 -*-
from ThymeBoost.trend_models.trend_base_class import TrendBaseModel
import numpy as np
import pandas as pd
class EwmModel(TrendBaseModel):
model = 'ewm'
def __init__(self):
self.model_params = None
self.fitted = None
def __str__(self):
return f'{self.mo... |
# 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 u... | # 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 u... |
import peewee as pw
import pytest
from muffin_peewee import Plugin as Peewee, JSONField
@pytest.fixture(scope='module')
def aiolib():
return 'asyncio', {'use_uvloop': False}
@pytest.fixture(scope='session', autouse=True)
def setup_logging():
import logging
logger = logging.getLogger('peewee')
logge... | import peewee as pw
import pytest
from muffin_peewee import Plugin as Peewee, JSONField
@pytest.fixture(scope='module')
def aiolib():
return 'asyncio', {'use_uvloop': False}
@pytest.fixture(scope='session', autouse=True)
def setup_logging():
import logging
logger = logging.getLogger('peewee')
logge... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB 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... | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB 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... |
#!/usr/bin/env python3
import time
import re
import os
import logging
import glob
import argparse
import change_dir
import abunpack
import acb2wav
__version__ = "2.2.8"
def main():
# argparse 설정
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-o", "--output_dir", help="Master output di... | #!/usr/bin/env python3
import time
import re
import os
import logging
import glob
import argparse
import change_dir
import abunpack
import acb2wav
__version__ = "2.2.8"
def main():
# argparse 설정
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-o", "--output_dir", help="Master output di... |
from __future__ import annotations
import asyncio
import datetime
import gzip
import itertools
import json
import string
from pathlib import Path
from typing import Counter, Iterable, Sequence, TypeVar
import platformdirs
import pyperclip
from rich.align import Align
from rich.bar import Bar
from rich.console import ... | from __future__ import annotations
import asyncio
import datetime
import gzip
import itertools
import json
import string
from pathlib import Path
from typing import Counter, Iterable, Sequence, TypeVar
import platformdirs
import pyperclip
from rich.align import Align
from rich.bar import Bar
from rich.console import ... |
""" serverextension for starters
"""
from .handlers import add_handlers
from .manager import StarterManager
def load_jupyter_server_extension(nbapp):
"""create a StarterManager and add handlers"""
manager = StarterManager(parent=nbapp)
add_handlers(nbapp, manager)
nbapp.log.info(f"""💡 starters: {", "... | """ serverextension for starters
"""
from .handlers import add_handlers
from .manager import StarterManager
def load_jupyter_server_extension(nbapp):
"""create a StarterManager and add handlers"""
manager = StarterManager(parent=nbapp)
add_handlers(nbapp, manager)
nbapp.log.info(f"""💡 starters: {", "... |
#!/usr/bin/env python3
"""
Rules for building C/API module with f2py2e.
Here is a skeleton of a new wrapper function (13Dec2001):
wrapper_function(args)
declarations
get_python_arguments, say, `a' and `b'
get_a_from_python
if (successful) {
get_b_from_python
if (successful) {
callfortran
... | #!/usr/bin/env python3
"""
Rules for building C/API module with f2py2e.
Here is a skeleton of a new wrapper function (13Dec2001):
wrapper_function(args)
declarations
get_python_arguments, say, `a' and `b'
get_a_from_python
if (successful) {
get_b_from_python
if (successful) {
callfortran
... |
# Copyright 2020 The TensorTrade 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... | # Copyright 2020 The TensorTrade 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... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.core.goals.package import OutputPathField
from pants.engine.target import (
COMMON_TARGET_FIELDS,
DictStringToStringField,
Sources,
SpecialCasedDependencies,
... | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.core.goals.package import OutputPathField
from pants.engine.target import (
COMMON_TARGET_FIELDS,
DictStringToStringField,
Sources,
SpecialCasedDependencies,
... |
import asyncio
import dataclasses
import logging
import random
import time
import traceback
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from blspy import AugSchemeMPL
import staidelta.server.ws_connection as ws # lg... | import asyncio
import dataclasses
import logging
import random
import time
import traceback
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from blspy import AugSchemeMPL
import staidelta.server.ws_connection as ws # lg... |
#!/usr/bin/python3
"""
Primary module
"""
# pylint: disable=wildcard-import
import logging
import signal
from time import time, sleep
from threading import Thread, Event
from yaml import load, FullLoader
import typing as tp
import humanfriendly
import argparse
from pymeterreader.device_lib import BaseReader, Sample, st... | #!/usr/bin/python3
"""
Primary module
"""
# pylint: disable=wildcard-import
import logging
import signal
from time import time, sleep
from threading import Thread, Event
from yaml import load, FullLoader
import typing as tp
import humanfriendly
import argparse
from pymeterreader.device_lib import BaseReader, Sample, st... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from functools import singledispatch
from .array import is_numeric_array
from .op import trace_ops
from .program import OpProgram
def _debug(x):
return f"{type(x).__module__.split(".")[0]}.{ty... | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from functools import singledispatch
from .array import is_numeric_array
from .op import trace_ops
from .program import OpProgram
def _debug(x):
return f"{type(x).__module__.split('.')[0]}.{ty... |
# -*- coding: utf8 -*-
import json
import random
import socket
from collections import OrderedDict
from time import sleep
import requests
from fake_useragent import UserAgent
import TickerConfig
from agency.agency_tools import proxy
from config import logger
def _set_header_default():
header_dict = OrderedDict()
... | # -*- coding: utf8 -*-
import json
import random
import socket
from collections import OrderedDict
from time import sleep
import requests
from fake_useragent import UserAgent
import TickerConfig
from agency.agency_tools import proxy
from config import logger
def _set_header_default():
header_dict = OrderedDict()
... |
import logging
from PyQt5.QtWidgets import QPlainTextEdit, QGroupBox, QVBoxLayout
from ..python_core.appdirs import get_app_log_dir
import pathlib as pl
import time
import sys
# solution copied from https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt
class QPlainTextEditLogger(QPlainTextEdit... | import logging
from PyQt5.QtWidgets import QPlainTextEdit, QGroupBox, QVBoxLayout
from ..python_core.appdirs import get_app_log_dir
import pathlib as pl
import time
import sys
# solution copied from https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt
class QPlainTextEditLogger(QPlainTextEdit... |
# -*- coding: utf-8 -*-
'''The file contains functions for working with the database'''
import base64
import time
from os.path import isfile
import sqlalchemy as sa
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from envparse import env
# Reading settings file
if isfile('.env'):
e... | # -*- coding: utf-8 -*-
'''The file contains functions for working with the database'''
import base64
import time
from os.path import isfile
import sqlalchemy as sa
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from envparse import env
# Reading settings file
if isfile('.env'):
e... |
# -*- coding: utf-8 -*-
"""
Instructor Demo: Dicts.
This script showcases basic operations of Python Dicts.
"""
# Initialize a dictionary containing top traders for each month in 2019
top_traders_2019 = {
"january" : "Karen",
"february" : "Harold",
"march" : "Sam"
}
print()
print(f"Dictionary: {top_trad... | # -*- coding: utf-8 -*-
"""
Instructor Demo: Dicts.
This script showcases basic operations of Python Dicts.
"""
# Initialize a dictionary containing top traders for each month in 2019
top_traders_2019 = {
"january" : "Karen",
"february" : "Harold",
"march" : "Sam"
}
print()
print(f"Dictionary: {top_trad... |
import io
from types import NoneType
import utils
from pprint import pprint
def typeMapFromFlatDict():
union: dict[str, set] = {}
for doc in utils.docs(progress_bar=True):
for key, val in doc.items():
union.setdefault(key, set())
union[key].add(type(val))
return union
de... | import io
from types import NoneType
import utils
from pprint import pprint
def typeMapFromFlatDict():
union: dict[str, set] = {}
for doc in utils.docs(progress_bar=True):
for key, val in doc.items():
union.setdefault(key, set())
union[key].add(type(val))
return union
de... |
# Lint as: python3
import json
import logging
import os
import datasets
from layoutlmft.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox
from transformers import AutoTokenizer
_URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/"
_LANG = ["zh", "de", "es", "fr", "en", "it", "... | # Lint as: python3
import json
import logging
import os
import datasets
from layoutlmft.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox
from transformers import AutoTokenizer
_URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/"
_LANG = ["zh", "de", "es", "fr", "en", "it", "... |
from unittest import TestCase
from tests import abspath
from pytezos.repl.interpreter import Interpreter
from pytezos.michelson.converter import michelson_to_micheline
from pytezos.repl.parser import parse_expression
class OpcodeTestnot_binary_61(TestCase):
def setUp(self):
self.maxDiff = None
... | from unittest import TestCase
from tests import abspath
from pytezos.repl.interpreter import Interpreter
from pytezos.michelson.converter import michelson_to_micheline
from pytezos.repl.parser import parse_expression
class OpcodeTestnot_binary_61(TestCase):
def setUp(self):
self.maxDiff = None
... |
#
# Copyright (c) 2019-2021, ETH Zurich. All rights reserved.
#
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause
#
import logging
import os
import jwt
import stat
import datetime
import hashlib
import tempfile
import json
import functools
from flask import request, j... | #
# Copyright (c) 2019-2021, ETH Zurich. All rights reserved.
#
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause
#
import logging
import os
import jwt
import stat
import datetime
import hashlib
import tempfile
import json
import functools
from flask import request, j... |
# -*- coding: utf-8 -*-
"""Tools for working with epoched data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
# Denis Engemann <denis.engemann@gmail.com>
# Mainak Jas... | # -*- coding: utf-8 -*-
"""Tools for working with epoched data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
# Denis Engemann <denis.engemann@gmail.com>
# Mainak Jas... |
import collections.abc
import warnings
from abc import abstractmethod
from collections import defaultdict
from datetime import datetime
from enum import Enum, EnumMeta
from textwrap import dedent
from typing import Any, Callable, Dict, Mapping, Optional, Set, Tuple, Union
from urllib.parse import urlencode
import ciso... | import collections.abc
import warnings
from abc import abstractmethod
from collections import defaultdict
from datetime import datetime
from enum import Enum, EnumMeta
from textwrap import dedent
from typing import Any, Callable, Dict, Mapping, Optional, Set, Tuple, Union
from urllib.parse import urlencode
import ciso... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import json
import logging
from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When
from django.conf import settings
from ... | """This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import json
import logging
from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When
from django.conf import settings
from ... |
# Copyright (c) 2018-2021 Patricio Cubillos.
# bibmanager is open-source software under the MIT license (see LICENSE).
__all__ = [
'browse',
]
import re
import os
from asyncio import Future, ensure_future
import io
from contextlib import redirect_stdout
import textwrap
import webbrowser
from prompt_toolkit impo... | # Copyright (c) 2018-2021 Patricio Cubillos.
# bibmanager is open-source software under the MIT license (see LICENSE).
__all__ = [
'browse',
]
import re
import os
from asyncio import Future, ensure_future
import io
from contextlib import redirect_stdout
import textwrap
import webbrowser
from prompt_toolkit impo... |
import requests
import zipfile
import shutil
import csv
import pandas as pd
from datetime import date
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
class BhavCopy(object):
"""description of class"""
def __init__(self, date: date):
self.date = date
self... | import requests
import zipfile
import shutil
import csv
import pandas as pd
from datetime import date
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
class BhavCopy(object):
"""description of class"""
def __init__(self, date: date):
self.date = date
self... |
"""Stock Context Controller"""
__docformat__ = "numpy"
import argparse
import logging
import os
from datetime import datetime, timedelta
from typing import List
import financedatabase
import yfinance as yf
from prompt_toolkit.completion import NestedCompleter
from openbb_terminal import feature_flags as obbff
from o... | """Stock Context Controller"""
__docformat__ = "numpy"
import argparse
import logging
import os
from datetime import datetime, timedelta
from typing import List
import financedatabase
import yfinance as yf
from prompt_toolkit.completion import NestedCompleter
from openbb_terminal import feature_flags as obbff
from o... |
#!/usr/bin/env python3
import argparse
import copy
from datetime import datetime
import json
import modulefinder
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import torch
from torch.utils import cpp_extension
from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell,... | #!/usr/bin/env python3
import argparse
import copy
from datetime import datetime
import json
import modulefinder
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import torch
from torch.utils import cpp_extension
from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell,... |
"""
#
# 26/08/2018
# Oladotun Rominiyi - Copyright © 2018. all rights reserved.
"""
__author__ = 'dotun rominiyi'
# IMPORTS
import ujson
import ssl
import websockets
from base64 import b64decode
from zlib import decompress, MAX_WBITS
from signalr_aio.transports import Transport as SignalRTransport
from signalr_aio i... | """
#
# 26/08/2018
# Oladotun Rominiyi - Copyright © 2018. all rights reserved.
"""
__author__ = 'dotun rominiyi'
# IMPORTS
import ujson
import ssl
import websockets
from base64 import b64decode
from zlib import decompress, MAX_WBITS
from signalr_aio.transports import Transport as SignalRTransport
from signalr_aio i... |
# Copyright (C) 2021 Dino Bollinger, ETH Zürich, Information Security Group
# Released under the MIT License
"""
Using a database of collected cookie + label data, determine potential GDPR violations by checking whether
Google Analytics cookie variants (or another known cookie, can be specified) were misclassified.
---... | # Copyright (C) 2021 Dino Bollinger, ETH Zürich, Information Security Group
# Released under the MIT License
"""
Using a database of collected cookie + label data, determine potential GDPR violations by checking whether
Google Analytics cookie variants (or another known cookie, can be specified) were misclassified.
---... |
from datetime import (
date,
datetime,
timedelta,
)
from functools import partial
from io import BytesIO
import os
import re
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
get_option,
se... | from datetime import (
date,
datetime,
timedelta,
)
from functools import partial
from io import BytesIO
import os
import re
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
get_option,
se... |
from typing import Tuple
import pygame
from pygame_gui import UIManager
import pygame_gui
from pygame_gui.elements.ui_window import UIWindow
from pygame_gui.elements.ui_text_box import UITextBox
from talktown.person.person import Person
from talktown.place import Building
class CharacterInfoWindow(UIWindow):
"""
... | from typing import Tuple
import pygame
from pygame_gui import UIManager
import pygame_gui
from pygame_gui.elements.ui_window import UIWindow
from pygame_gui.elements.ui_text_box import UITextBox
from talktown.person.person import Person
from talktown.place import Building
class CharacterInfoWindow(UIWindow):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.