text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/python2.7
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
def parse_wiki_rest ():
rest_vars = attr_dict ()
rest_vars.wiki_mode = request.function
if request.args (1):
rest_vars.page_slug = request.args (0)
rest_vars.page_op = request.args (1)
else:
rest_vars.page_slug = None
rest_vars.page_op = request.args (0)
if request.ar... |
__all__ = [
'ComponentStore',
]
from pathlib import Path
import copy
import hashlib
import json
import logging
import requests
import tempfile
from typing import Callable, Iterable
from . import _components as comp
from .structures import ComponentReference
from ._key_value_store import KeyValueStore
_COMPONENT_... |
__author__ = '<EMAIL>'
"""
Given an input fasta/fastq and alignment SAM (from minimap2, GMAP, STAR, etc),
Output two report files.
Report #1. For each alignment:
(1) sequence id
(2) alignment coverage (just for this alignment)
(3) alignmen identity
(4) number of mismmatches
(5) number of insertions
(6) nu... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
from nipy.core.api import (AffineTransform, Image,
ArrayCoordMap, compose)
from nipy.core.reference import slices
from nipy.algorithms.resample import resam... |
import array
import functools
import numpy as np
import deap.algorithms
import deap.base
import deap.creator
import deap.tools
import random
from addnn.controller.proto.controller_pb2 import Node
from addnn.profile.layer_profile import LayerProfile
from addnn.serve.placement.placement import NodeIndex, Placement, estim... |
#!/usr/bin/env python
# coding: utf-8
# In[12]:
'''
This script contains two classes.
1: JobPostingsCollector: for crawling job postings
2: HardSkillsCollector: for scraping the hard skills
'''
__author__ = '<NAME>'
__email__ = '<EMAIL>'
import pandas as pd
from urllib.request import Request, urlopen
import reques... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tools to run compression experiments
"""
__author__ = "<NAME> <<EMAIL>>"
__date__ = "19/09/2019"
import os
import collections
import itertools
import inspect
from enb import atable
from enb import sets
from enb.config import get_options
options = get_options()
clas... |
from collections import OrderedDict as od
def makeOrderedDicts(next_states):
case_state_case_entries = od()
#print(next_states)
for cases_ in next_states[1:][0]:
state_case_entries = od()
#print(cases_)
for case_ in cases_[1:]:
#print(case_)
for state_case in case_:
state = state_case[0]
case__... |
#!/usr/bin/python
import os, sys
import json
import numpy as np
import re
### YOUR CODE HERE: write at least three functions which solve
### specific tasks by transforming the input x and returning the
### result. Name them according to the task ID as in the three
### examples below. Delete the three examples. The ta... |
import aiopg
from functools import wraps
from psycopg2.extras import DictCursor
class TableName(object):
def __init__(self, table_name, alias=None):
self.table_name = table_name
self.alias_name = alias
def alias(self, alias):
return TableName(self.table_name, alias)
def __str__(... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012, <NAME>
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
""" Module wavefront
This module produces functionality to read and write wavefront (.OBJ) files.
http://en.wikipedia.org/wiki/Wavefront_.obj_file... |
"""
Hardware Wallet Client Interface
********************************
The :class:`SpecterClient` is the class to communicate with Specter-DIY hardware wallet.
"""
import serial
import serial.tools.list_ports
import socket, time
from hwilib.hwwclient import *
from hwilib.errors import (
ActionCanceledError,
Ba... |
# Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
#!/usr/bin/python
# Copyright: (c) 2019, DellEMC
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils import dellemc_ansible_utils as utils
import logging
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'suppo... |
import textwrap
from conans.test.assets.genconanfile import GenConanfile
from conans.test.utils.tools import TestClient
def test_cpp_info_editable():
client = TestClient()
conan_hello = str(GenConanfile())
conan_hello += """
def layout(self):
self.folders.source = "my_sources"
self.... |
# Copyright 2018 Iguazio
#
# 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, softwa... |
#!/usr/bin/env python
u"""
tools.py
Written by <NAME> (12/2021)
Plotting tools and utilities
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python
https://numpy.org
https://numpy.org/doc/stable/user/numpy-for-matlab-users.html
matplotlib: Python 2D plotting library
http://ma... |
from __future__ import annotations
import functools
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Optional, List, ClassVar, Dict, Union
from fauxcaml.lir import gen_ctx
class ToTgt(ABC):
@abstractmethod
def to_nasm(self, ctx: gen_ctx.NasmGenCtx) -> List[str... |
import os
import xml.dom.minidom
from xml.dom.minidom import Document
import pymel.core as pm
import lct.src.core.lcPath as lcPath
import lct.src.core.lcUtility as lcUtility
class Texture(object):
def __init__(self, *args, **kwargs):
""" Initialize class and variables """
self.settingsPath = lc... |
import asyncio
import logging
from typing import TYPE_CHECKING, Any, Optional, Set, TypeVar, Union
import aiohttp
from .constants import STREAMING
from .schemas import (
CandleResolution,
CandleStreamingResponse,
CandleSubscription,
ErrorStreamingResponse,
Event,
HashableModel,
InstrumentI... |
import datetime
import pytest
import io
import pandas as pd
import random
from datetime import timedelta
from tqdm import tqdm
from pathlib import Path
from tempfile import NamedTemporaryFile
from unittest import mock
from hashlib import sha1
from furl import furl
from ketl.db import models
from ketl.extractor.Extra... |
__doc__="""
Parses original McStas instrument definition files.
"""
__author__="<NAME>"
from .pyparsing.pyparsing import *
# numbers: 1, 30.0, 1e-5, -99, for parsing parameter values
number = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) + \
Optional( '.' + Word(nums) ) + \
... |
import os
import time
import math
from PIL import Image
import numpy as np
import requests
import urllib.parse
from io import BytesIO
import IPython
import moviepy.editor as mpe
from .utils import downloads
Image.MAX_IMAGE_PIXELS = 1e9
sample_images = {
'escher_sphere.jpg': '1pXYUSTfVDhJSOES0L0LEhf8A1lB28S4t',
... |
"""A utility class that handles database operations related to covidcast.
See src/ddl/covidcast.sql for an explanation of each field.
"""
# third party
import json
import mysql.connector
import numpy as np
from math import ceil
# first party
import delphi.operations.secrets as secrets
class CovidcastRow():
"""A... |
import pysam
from collections import Counter
def message(case, variables):
if case=="cstring_error":
message="""
unrecognized cigar tuple value : %i
accepted intergers: 4 = soft_clip
0 = match
1 = insertion
2 = deletion\n\n""" %(variables)
... |
import hashlib
from unittest import mock
from django.conf import settings
from django.utils import timezone
from options.options import SysOptions
from utils.api.tests import APITestCase
from .models import JudgeServer
class SMTPConfigTest(APITestCase):
def setUp(self):
self.user = self.create_super_adm... |
"""
Sample script for running parallel inference on a video with two different models (Depth Estimation + Object Detection)
Navie implementation:
0. Spawn ModelProcessor instances
1. Thread grabs frame - store to queue for callback afterwards, and send frame to 2 models
2. Once inference is done, send signal to dequeu... |
#!/usr/bin/env python3
"""
CLI to process multiple molecules with shared optimization.
"""
import os
from deeperwin.available_gpus import get_free_GPU_id
os.environ['CUDA_VISIBLE_DEVICES'] = get_free_GPU_id()
import argparse
import copy
import logging
import os
import time
from dataclasses import dataclass
from typing... |
import gc
import logging
import os
import random
import sys
import time
import numpy as np
import pandas as pd
import src.config.constants as constants
import src.viz as viz
__all__ = [
"set_seed",
"trigger_gc",
"set_timezone",
"get_logger",
"update_tracking",
"save_file",
"save_artifacts... |
from dataclasses import dataclass, field
from html import escape as html_escape
from typing import Iterable
from elementary_flask.typing import OptionalSet, Union, List, Optional
REDUCE_INCLUDES_MAX_DEPTH = 5
@dataclass()
class DependencyLink:
link: str
include_type: str
include_position: Optional[str] ... |
from abc import ABC
from itertools import combinations
try:
import EasyWebdriver
except ImportError:
print("Missing EasyWebdriver. Please get it at: https://github.com/xjdeng/EasyWebdriver")
raise ImportError
import time
import pandas as pd
import tempfile
import sys
from path import Path as path
SAVEFILE... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 19 10:09:38 2017
@author: tih
"""
import os
import gdal
import osr
import scipy
import numpy as np
import pandas as pd
Startdate ="2017-01-01"
Enddate ="2017-21-21"
Temp_folder = r"K:\Weather_Data\Model\GLDAS\three_hourly\tair_f_inst\Tair_GLDAS-NOAH_C_3hour_{yyyy}.{mm:0... |
import math
from utils.data.collates import NormalizePAD, ResizeNormalize
from PIL import ImageFont, ImageDraw, Image
from pathlib import Path
from utils.utility import initial_logger
logger = initial_logger()
import numpy as np
import cv2
import uuid
class AlignCollate(object):
def __init__(self, img... |
from abc import abstractmethod
from parso.tree import search_ancestor
from jedi._compatibility import Parameter
from jedi.evaluate.base_context import ContextSet
from jedi.cache import memoize_method
class AbstractNameDefinition(object):
start_pos = None
string_name = None
parent_context = None
tree... |
#!usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'yanqiong'
import random
import secrets
from bisect import bisect_right
from sgqlc.operation import Operation
from pandas.core.internals import BlockManager
from tqsdk.ins_schema import ins_schema, _add_all_frags
RD = random.Random(secrets.randbits(128)) #... |
# coding: utf-8
import warnings
import numpy as np
import pandas as pd
from packaging import version
from sklearn.metrics import pairwise_distances_chunked
from sklearn.utils import check_X_y,check_random_state
from sklearn.preprocessing import LabelEncoder
import functools
from pyclustering.cluster.clarans import cla... |
#! /usr/bin/python
"""
Monitoring functions for xrootd cache server, producing classads
that can be handed to condor
"""
import os
import math
import time
import errno
import struct
import collections
import six
from six.moves import urllib
import classad
import XRootD.client
__all__ = ['collect_cache_stats']
# th... |
import os
import pandas as pd
import numpy as np
import tensorflow as tf
import keras
from keras.layers import *
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras import backend as K
#os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ["CUDA_DEVICE_ORDER... |
def encryption(text, keys):
text_IP = apply_table(IP_table, text)
#print(text_IP)
round_values = {}
round_values["L0"] = text_IP[:32]
round_values["R0"] = text_IP[32:]
#print("L0 :", round_values["L0"])
#print("R0 :", round_values["R0"])
for i in range(1, 17):
roun... |
"""This module supports puzzles that place fixed shape regions into the grid."""
from collections import defaultdict
import sys
from typing import Dict, List
from z3 import ArithRef, Int, IntVal, Or, Solver, PbEq
from .fastz3 import fast_and, fast_eq, fast_ne
from .geometry import Lattice, Point, Vector
from .quadtre... |
import numpy
from matplotlib import pyplot
import gdal
from skimage import io,exposure
from skimage.segmentation import slic,mark_boundaries
import os
from PIL import Image
import shelve
import sys
sys.path.append('..')
from Config import config
def seg(path,n_segments=500, compactness=20):
i=io.imread(path)[:,... |
import struct
import time
import six
from six import iteritems
from .batch import Batch
def _check_table_existence(method):
def wrap(table, *args, **kwargs):
if not table._exists():
raise IOError('TableNotFoundException: %s' % table.name)
return method(table, *args, **kwargs)
retu... |
import importlib
import pkgutil
import signal
import string
import sys
import traceback
from contextlib import contextmanager
from datetime import datetime, tzinfo
from pathlib import Path
from typing import Iterable, Optional, Set, Tuple, Union
import pytz
from .aliases import PathOrStr
from .exceptions import SigTe... |
# coding=utf-8
# Copyleft 2019 project LXRT.
import os
import collections
import torch
import torch.nn as nn
import logging
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from param import args
from lxrt.qa_answer_table import load_lxmert_qa
from tasks.vqa_model import VQAModel
from tasks.v... |
from people.models import Village, Mother, Driver, HealthCenter, MotherDriverConnection
from django.http import JsonResponse, Http404
from django.core import serializers
from decouple import config
from .geokdbush.geokdbush import around, distance
import requests
import json
import time
FRONTLINE_KEY = config('FRONTLI... |
import unittest
import struct
import sys
import os
import pywintypes
import win32event, win32api
import os
from pywin32_testutil import TestSkipped
import win32com.directsound.directsound as ds
import pythoncom
# next two lines are for for debugging:
# import win32com
# import directsound as ds
WAV_FORMAT_PCM = 1
WAV... |
import datetime as dt
from abc import abstractmethod
from django.db import models
from tacticalrmm.middleware import get_debug_info, get_username
ACTION_TYPE_CHOICES = [
("schedreboot", "Scheduled Reboot"),
("taskaction", "Scheduled Task Action"),
("agentupdate", "Agent Update"),
("chocoinstall", "Ch... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
from collections import defaultdict
from typing import Union, List, Any, Callable, Dict
import numpy as np
from continual_learning.datasets.base import AbstractDataset, DatasetSplitsContainer
from continual_learning.scenarios.base import TasksGenerator
from continual_learning.scenarios.classification.new_classes imp... |
from __future__ import absolute_import, print_function
# --- System ---
import os
import sys
import time
import warnings
# --- Utility ---
import pandas as pd
import numpy as np
import math
import random
import logging
import pickle
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import... |
import re
import time
from collections import defaultdict
from contextlib import contextmanager
from urllib.parse import urlencode
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.db import transaction
from django.db.models import Q, Prefetch
from django.http import H... |
import gc, macpath, pickle, pickletools, errno, traceback, gzip, io, copy, random, bisect, os, time
from autograd.numpy.numpy_extra import ArrayNode
import numpy as np
from functools import reduce
def safe_mkdir(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != e... |
# Copyright 2019 Alorium Technology, LLC.
#
# This utility is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This utilit... |
"""Core classes and interfaces.
This defines a couple of standard feed types and scopes. Currently
feed types are strings and scopes are integers, but you should use the
symbolic names wherever possible (everywhere except for adding a new
feed type) since this might change in the future. Scopes are integers,
but do no... |
""" Usage:
qa_to_oie --in=INPUT_FILE --out=OUTPUT_FILE [--dist=DIST_FILE] [--oieinput=OIE_INPUT]
"""
from docopt import docopt
import re
import itertools
from oie_readers.extraction import Extraction, escape_special_chars, normalize_element
from collections import defaultdict
import logging
import operator
impor... |
# -*- coding: utf-8 -*-
import os
import numpy as np
import pytest
import sys
from qa4sm_reader.img import QA4SMImg
from qa4sm_reader import globals
# if sys.platform.startswith("win"):
# pytestmark = pytest.mark.skip(
# "Failing on Windows."
# )
@pytest.fixture
def testfile_path():
testfile =... |
import os
import tempfile
import unittest
import shutil
import time
import matplotlib
from trixi.util.metrics import get_roc_curve, get_pr_curve, get_classification_metrics
matplotlib.use("Agg")
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from trixi.logger.experiment import... |
#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for launching application within the sel_ldr.
"""
import argparse
import os
import subprocess
import sys
import cre... |
"""
A simple xml file generator from python dictionary.
load the dictionary (or yaml) generated by the scene_gen code, which includes the object label names
"""
def dict_to_xml(problem, path):
"""
================================================================
- problem
- objects
- obj... |
import json
import logging
import os
class XPParams:
useModuloReduction = True
usePMICalc = False
sumAllComponents = None
vectorOfSumAllVectors = None
numberModuloReduction = 499
twoD_feats = False
new_y_number = None #73
dropout = 0.025 #0.025
useBatchGenerator = False
use_ext... |
#!/usr/bin/env python3
import sys
import os
import argparse
import subprocess
import pandas as pd
from random import randint
from math import log
from select_samples import filter_fasta, read_metadata
def main():
parser = argparse.ArgumentParser(description="Create wastewater benchmarks.")
parser.add_argume... |
import copy
import inspect
import pprint
import re
from typing import Any, Dict, Optional
import qcelemental as qcel
import qcengine as qcng
from qcelemental.models import AtomicInput, AtomicResult, FailedOperation
from qcengine.exceptions import InputError
from qcengine.programs.nwchem import NWChemHarness
from qceng... |
# Copyright 2019, The TensorFlow Federated 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 o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Wrapper for different types of Ideal Observers:
- The hidden markov model for coupled change points, with known volatility
- The hidden markov model for coupled change points and unknown volatility
- he hidden markov model for uncoupled change points, with ... |
import mdl
from display import *
from matrix import *
from draw import *
from equation import parse
"""======== first_pass( commands ) ==========
Checks the commands array for any animation commands
(frames, basename, vary)
Should set num_frames and basename if the frames
or basename commands are present
... |
'''
wopiclient.py
A set of WOPI client functions for the WOPI bridge service.
Main author: <EMAIL>, CERN/IT-ST
'''
import os
import json
import http.client
import requests
from flask import Response
class InvalidLock(Exception):
'''A custom exception to represent an invalid or missing WOPI lock'''
# initializ... |
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
def set_constants():
confThreshold = 0.5 # Confidence threshold
nmsThreshold = 0.4 # Non-maximum suppression threshold
inpWidth = 416 # Width of network's input image
inpHeight = 416
return confThreshold, nmsThreshold... |
import sys, os
sys.path.append('../')
from main import WordEmbedding
from numpy.linalg import norm
from numpy import unravel_index, argmax, isnan, delete, arange
import random as rand
import argparse
import json
from main import to_utf8
# CONSTANTS
BOLD = '\033[1m' # add this string to start printing in bold
END ... |
import inspect
import io
import os
import subprocess as sp
import sys
import textwrap
import time
import traceback
from contextlib import redirect_stdout
from pathlib import Path
import discord
from discord.ext import commands
from ...lib import *
class Developer(commands.Cog):
def __init__(self, bot):
... |
'''
Calculate and save bins, beta and/or bispectrum.
'''
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import argparse
import cProfile, pstats
import sys
import os
import numpy as np
from scipy.special import spherical_jn
sys.path.insert(0,'./../')
from ss... |
# Author: <NAME>
import sys
from datetime import datetime # to print the date & time in the output log whenever this script is run OR for time related checks
from decouple import config
import pymongo
import tweepy # Twitter API helper package
from decouple import config
from tweepy import OAuthHandler
sys.path.ins... |
import time
from collections import OrderedDict
import convpoint.knn.lib.python.nearest_neighbors as knn
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from modules.functional.backend import _backend
from modules.functional.sampling import gather, furthest_point_sam... |
#!/usr/bin/python3
# Welcome to PiLaps deamon
# You need only this package on Raspbian Jessie:
# sudo apt-get install libav-tools
# Git: DaveCalaway: https://goo.gl/9r6bwz
import os
import subprocess
import sys
import json
import time
import datetime
import threading
import shutil
from time import sleep
from picame... |
from tkinter import *
from contextlib import suppress
import mysql
import runtime
import spreadsheets
import setup
import os
separator = "/"
if os.name == 'nt':
separator = "\\"
class Exec_Helper:
'''
Exec_Helper is a static class that connects the UI to the runtime module
'''
process = None
d... |
from typing import Tuple, List
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch import Tensor
from torch.nn import Sequential
from .utils import image_loader
class ContentLoss(nn.Module):
"""
Content loss layer
"""
def __init__(self, target: ... |
import subprocess
from pathlib import Path
from typing import Optional, List
from fire import Fire
class PrepDrNMTData:
def __init__(self, data_dir: str,
beam_sizes: Optional[List[int]] = None,
num_shards: Optional[List[int]] = None):
self.data_dir = Path(data_dir)
... |
import math
import random
import time
def basic_print(*zones, **kwargs):
"""Simulates the PRINT command from BASIC to some degree.
Supports `printing zones` if given multiple arguments."""
line = ""
if len(zones) == 1:
line = str(zones[0])
else:
line = "".join([f"{str(zone):<14}" ... |
import numpy as np
import torch
import math
import random
from data import augmentation
# ============================ R is 3x3 matrix for point clouds ===================================================
def generate_rotation_group(axis_number=3, right_angle_rotation_number=3, negative_reflection=False, include_ident... |
import os
import mimetypes
import warnings
from io import StringIO
from django.conf import settings
from django.core.files.base import File
from django.core.files.storage import Storage
from django.core.exceptions import ImproperlyConfigured
try:
from ..utils.S3 import AWSAuthConnection, QueryStringAuthGenerator... |
import random
print("module top(input [3:0] clk, ce, rst, input [7:0] d, output [7:0] q);")
data = ["d[{}]".format(i) for i in range(8)]
def data_bits(N):
return "{{{}}}".format(", ".join([random.choice(data) for i in range(N)]))
def clock_port(name):
print(" .{}(clk[{}]),".format(name, random.randint(... |
import h5py
import numpy as np
import os
import pandas as pd
import shutil
import sys
import tarfile
from collections import Counter
from tqdm import tqdm
from urllib import request
from utils import io
############
# DOWNLOAD #
############
def download_and_extract(data_dir):
filename = os.path.join(data_di... |
#!/usr/bin/env python3
"""spark application"""
import argparse
from datetime import datetime
import csv
# create parser and set its arguments
from pyspark.sql import SparkSession
# the second dataset needs double-quotes ("") escaping to parse correctly
def parse_line(row):
csv_reader = csv.reader([row], delimite... |
import requests
import json
import argparse
import psutil
import sys
import multiprocessing
import subprocess
from datetime import datetime, timedelta
from os.path import expanduser, getsize
from hashlib import md5
from .version import __version__
class NodeMonitor:
def __init__(self, args):
self.defi_pat... |
# yacon.views.user.py
# blame ctrudeau chr(64) arsensa.com
import logging, urllib
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.forms.utils import ErrorList
from django.http import Http404, JsonResponse, HttpResponseRedirect
from django.shortcuts imp... |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pt... |
#
# 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
# distributed under ... |
"""Define the player module."""
import asyncio
from datetime import datetime
from typing import Dict, Optional, Sequence
from . import const
from .response import HeosResponse
from .source import HeosSource, InputSource
def parse_player_id(data: dict) -> int:
"""Parse the player ID from the data payload."""
... |
import sys
import os
import os.path
import logging
libpath = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
if os.path.isdir(libpath):
sys.path.insert(0, libpath)
# Intrapackage imports
import sift_pyx12.error_handler
import sift_pyx12.errors
import sift_pyx12.map_index
import sift_pyx12.map_if... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
ResNet50 models base on Keras.
This procedure is suitable for the situation that you need to quickly train
a ResNet50 network as a classification.
The program will do fine turning on the weights pretrained by imageNet.
If you want to start training from scratch on t... |
import osmipy.tokens
from osmipy.smiles_ast import Chain, BranchedAtom, Branch, RingBond, Atom, Bond
from osmipy.tokens import *
class ParserException(Exception):
def __init__(self, token, msg):
super().__init__('parser error at position {} [{}]: {}'.format(token.position, repr(token), msg))
self.... |
"""Tools to manage the properties of a feature
Classes
-------
Property
The class `Property`, which represents the values of a property of a feature.
A Property be:
* A constant (initialization with, e.g., a number, a tuple)
* A sequence of variables (initialization with, e.g., an iterator)
* A ran... |
try: from utils import smartsplit
except: from .utils import smartsplit
import ssl
import gzip
import json
import os
import os.path
import re
import sys
import time
try:
import urllib.parse as urllibparse
import urllib.request as urllibrequest
import urllib.error as urlliberror
except ImportError:
import urllib as ... |
from __future__ import print_function
from flask import Flask, request
from structs import *
from copy import deepcopy
import json
import numpy as np
import astar
app = Flask(__name__)
niv = 0
costs = [0, 15000, 50000, 100000, 250000, 500000]
def create_action(action_type, target):
actionContent = ActionContent(... |
import datetime
import pandas as pd
from dateutil import parser
from emannotationschemas.models import make_annotation_model, make_dataset_models
from flask import (
Blueprint,
abort,
redirect,
render_template,
request,
url_for,
current_app,
)
from sqlalchemy import and_, func, or_
from ma... |
from __future__ import unicode_literals
import logging
import os
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.utils import six
from django.utils.six.moves.urllib.error im... |
# -*- coding: utf-8 -*-
"""
Local target implementations.
"""
__all__ = ["LocalFileSystem", "LocalTarget", "LocalFileTarget", "LocalDirectoryTarget"]
import os
import fnmatch
import shutil
import glob
import random
import logging
from contextlib import contextmanager
import luigi
import six
from law.target.base ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os.path as osp
import sys
import re
import json
import argparse
from selenium import webdriver
from pykakasi import kakasi
# Logging
from logging import getLogger, StreamHandler, WARNING, INFO
from selenium.webdriver.remote import remote_connection
logger... |
# This script shows the netlist database for the VCO-ADC Database Using the new version of spectreIOlib
# It demands Mentor Graphics: Analog Fast Spice to run netlists
import sys
sys.path.insert(0,'/GlobalLibrary')
import os
from spectreIOlib import TestSpice, Netlists
home_address = os.getcwd()
import numpy as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.