text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/python -tt
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distrib... |
import itertools
import json
import logging
import threading
import typing
import boto3
import boto3.resources.base
import boto3.resources.model
from taskhawk.conf import settings
from taskhawk.exceptions import RetryException, LoggingException, ValidationError, IgnoreException
from taskhawk.models import Message
fro... |
import sys; sys.path.append('/work/awilf/utils/'); from alex_utils import *
import torch.nn as nn
import torchvision.transforms as transforms
from PIL import Image
from transformers import BeitFeatureExtractor, BeitModel
import transformers
import torch
import torchvision
import cv2
np.cat = np.concatenate
def vid... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#! /usr/bin/env python
"""
Copyright 2018 Duo Security
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disc... |
import csv
import json
import numpy as np
import pdb
from tqdm import tqdm
def check_k(queries):
return len(queries[0]['mentions'][0]['candidates'])
def evaluate_topk_acc(data):
"""
evaluate acc@1~acc@k
"""
queries = data['queries']
k = check_k(queries)
errors = [] #['truth', 'prediction'... |
import pyclbr
import pkgutil
import importlib
import inspect
from itertools import chain
from functools import reduce
from tornado_json.constants import HTTP_METHODS
from tornado_json.utils import extract_method, is_method, is_handler_subclass
def get_routes(package):
"""
This will walk ``package`` and gener... |
from sklearn.base import BaseEstimator, TransformerMixin
from keras.models import Model, Input
from keras.layers import Dense, LSTM, Dropout, Embedding, SpatialDropout1D, Bidirectional, concatenate, InputSpec
from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D
from keras.optimizers import Adam, RMSprop
... |
from six import iteritems
from drf_auto_endpoint.utils import reverse
from rest_framework import status
from .factories import get_admin
class BaseAPITestCase(object):
model_factory_class = None
model = None
factory_default_kwargs = {}
factory_delete_kwargs = {}
api_base_name = None
api_bas... |
"""Services for sending notifications to community members."""
import logging
import datetime
from itertools import chain
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import translation
import django_rq
from co... |
"""
Description:
- Includes all function to manage the data
"""
""" import packages """
import os
from importlib import import_module
import logging
import shutil
import csv
import zipfile as zf
import pathlib as pl
from zipimport import zipimporter as zim
import pandas as pd
""" import configurations """
import con... |
import os
try:
from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
from SocketServer import TCPServer as HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import json
from six.moves import range
import numpy as np
from tqdm import tqdm
from cloudvolume.lib import Vec, Bb... |
import subprocess
import signal
import os
from collections import OrderedDict
from time import sleep
write_file = "/tmp/bt_out.txt"
default_bt_freqs = [2.40e9, 2.42e9, 2.44e9, 2.46e9, 2.48e9, 2.410e9, 2.412e9, 2.414e9, 2.416e9, 2.418e9, 2.420e9, 2.40e9, 2.42e9, 2.44e9, 2.46e9, 2.48e9, 2.410e9, 2.412e9, 2.414e9, 2.416e... |
"""Helpers for release automation.
These are written according to the order they are called in.
"""
import contextlib
import os
import pathlib
import subprocess
import tempfile
from typing import Iterator, List, Optional, Set
from nox.sessions import Session
def get_version_from_arguments(session: Session) -> Opti... |
import json
import logging
import shutil
import subprocess
from pathlib import Path
from typing import Generator, List
from django.core import checks, exceptions
from django.db import models
from django.db.models.fields.files import FieldFile
from django.db.models.signals import post_init, pre_save
from jsonfield impo... |
"""The Module will open a terminal window for you to work with.
The terminal window will take in your age and then a planet and,
return your age on that planet.
"""
import sys
import time
class Planet:
"""Class for the planet objects."""
def __init__(self, planet_name, days_percent, years_percent):
... |
#!/usr/bin/python3
import sys
import argparse
import os
class BNilai:
nilai = ''
def __init__(self, nilai='{}>[]'):
nilai = '('+nilai+')'
self.nilai = nilai
def operasi(self, op, other):
if isinstance(other, str):
if eval(other) == 0:
h = self.nilai
... |
import contextlib
import functools
import logging
import os
import click
import torch
from tqdm import tqdm
from transformers import WEIGHTS_NAME, AdamW, get_constant_schedule_with_warmup, get_linear_schedule_with_warmup
logger = logging.getLogger(__name__)
def trainer_args(func):
@click.option("--learning-rate... |
# -*- coding: utf-8 -*-
import numpy as np
from tqdm import tqdm
import os
import re
import nltk
# nltk.download('punkt', 'stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import TweetTokenizer
tweet_tokenizer = TweetTokenizer()
from nltk.stem.lancaster import L... |
# -*- coding: utf-8 -*-
import threading
import time
from BulkHelper import BulkHelper
from IOHelper import IOHelper
from AzureHelper import AzureHelper
from config import Config
class ChunkJobHelper:
__instance = None
chunk_job_mainbatch_list = []
chunk_job_object_dict = {}
@staticmethod
def getInstance():
... |
import os
import random
from concurrent.futures import ProcessPoolExecutor
import flask
import dash
import dash_core_components
import dash_html_components
import plotly
import plotly.io
from dash.dependencies import Input, Output
server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)
nodes = {}
DE... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import strip_html
from frappe.website.utils import get_full_index
from frappe import _
from jinja2.utils import concat
from jinja2 import meta
imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Worker reading messages from the ``files`` queue, splitting the Crypt4GH header from the remainder of the file.
The header is stored in the database and the remainder is sent to the staging area.
It is possible to start several workers.
Upon completion, a message is... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 <NAME>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
... |
import os, signal, sys
import logging, logging.handlers
import re, time
import boto3
from threading import Timer
def exit_handler(sig, frame):
logging.info('Exit handler invoked, preparing to exit gracefully.')
logging.shutdown()
print('Goodbye!')
sys.exit(0)
def loadParams(defaults):
if not defaults:
... |
import asyncio
import logging
import functools
from aiohttp import web
from aiohttp_cors import CorsViewMixin, ResourceOptions, setup as cors_setup
from ..dispatcher import Dispatcher
from ..utils import json, generate_json_payload
from ..types import AliceRequest, AliceResponse, Response
log = logging.getLogger(__na... |
# -*- coding: utf-8 -*-
"""
author: zengbin93
email: <EMAIL>
create_dt: 2021/11/21 12:18
describe: 信号计算的工具函数
"""
import numpy as np
import pandas as pd
import traceback
from datetime import datetime
from typing import List, Union
from ..utils.ta import KDJ
from ..objects import RawBar, BI, Direction, ZS
def return_t... |
#!/usr/bin/env python3
# Copyright 2021 The Kubernetes 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 appl... |
import re
import math
num_moons = 4
class Moon:
_scan_regexp = "^\<x\=(\-?\d+)\,\sy\=(\-?\d+),\sz\=(\-?\d+)\>$"
def __init__(self, str):
self._x, self._y, self._z = self._parse_scan(str)
self._vx = 0
self._vy = 0
self._vz = 0
def _parse_scan(self,... |
# display image with masks and bounding boxes
from os import listdir
from xml.etree import ElementTree
from numpy import zeros
from numpy import asarray
from mrcnn.utils import Dataset
from mrcnn.visualize import display_instances
from mrcnn.utils import extract_bboxes
from mrcnn.config import Config
from mrcn... |
import itertools
import re
import sys
import operator
from collections import defaultdict, namedtuple
from dataclasses import dataclass
from itertools import product
from math import prod
from typing import List, Dict, Any, Tuple
import aocd
from . import aoc_year
from loguru import logger
aoc_day = 21
try:
if __n... |
from __future__ import print_function, division, absolute_import
import os, sys, subprocess
import itertools
import numpy as np
from numba import unittest_support as unittest
from numba.compiler import compile_isolated
from numba import types, typeinfer, typing, jit
class TestArgRetCasting(unittest.TestCase):
def... |
import argparse
import open3d as o3d
import numpy as np
import pyvista as pv
import time
def run_triangulation(in_filename, out_filename, verbose, display):
if verbose:
print("Perfoming screened poisson triangulation")
o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Debug)
pcd = o... |
import argparse
import os
import numpy as np
import torch
from utility.nturgbd.pairs import Pairs
from utility.nturgbd.read_skeleton import *
from torch_geometric.data import Data
from tqdm import tqdm
edge_index = torch.tensor([(1, 2), (2, 21), (3, 21), (4, 3), (5, 21), (6, 5), (7, 6),
(8,... |
# Copyright 2016 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 required by applicable law ... |
from __future__ import unicode_literals
import traceback
from django.conf import settings
from django.core.cache import cache
from django.utils import six
from jinja2.ext import Extension
from jinja2 import nodes
from jinja2 import Markup
from jinja2 import TemplateSyntaxError
try:
from django.utils.encoding im... |
import glob
import codecs
import string, re, pickle, math
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize,sent_tokenize
import collections
#data preprocessing
def data_comine(folder_name,file_name):
files = [f for f in glob.glob(f'F:/MTECH1/NLP/20_newsgroups/{folder_name}' + "**/*", recur... |
from typing import List, Dict
import os
import igraph as ig
import json
import common.igraph as ig_utils
from shapely.geometry import LineString
from common.igraph import Edge as E
def __get_total_noises_len(noises: Dict[int, float]) -> float:
"""Returns a total length of exposures to all noise levels.
"""
... |
from __future__ import absolute_import, division, print_function
import cv2
import numpy as np
import torch
from torch.utils.data import DataLoader
from datasets.mc_dataset import relpath_split
from networks.encoders import getEncoder
from networks.depth_decoder import getDepthDecoder
from networks.layers import di... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The Project U-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import os.path
import numpy as ... |
import glob
import random
import tqdm
PROGRESS_BAR_FORMAT = "{desc} - {percentage:3.0f}% |{bar:40}| {n_fmt}/{total_fmt} \
[{elapsed}<{remaining},{rate_fmt}{postfix}]"
def format_num(num, digit=4):
"""Formatting the float values as string."""
rounding = f".{digit}g"
num_str = f"{num:{rounding}}".rep... |
""" Main sript to run image capture screenshots for state data pages. """
import io
import os
import sys
from loguru import logger
import pandas as pd
import requests
import yaml
from args import parser as screenshots_parser
from screenshots import Screenshotter, S3Backup, SlackNotifier
def load_state_urls(args):
... |
import base64
import json
import re
import shutil
import tempfile
from pathlib import Path
from unittest.mock import patch
import pytest
import requests_mock
from ci_credentials.main import ENV_GCP_GSM_CREDENTIALS
from ci_credentials.main import main
from ci_credentials import SecretsLoader
HERE = Path(__file__).res... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -*- mode: python; python-indent-offset: 4 -*-
#
# ./create-assignment-with-textual-submission.py course_id [name_of_assignment]
# Purpose:
# Create an assignment with a textual submission
#
# with the option "-v" or "--verbose" you get lots of output - showing in detail the ... |
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Underworld geophysics modelling application. ##
## ... |
__author__ = 'maartenbreddels'
import collections
import logging
import pyarrow as pa
import pyarrow.dataset
import vaex.dataset
from ..itertools import buffer
from vaex.multithreading import get_main_io_pool
logger = logging.getLogger("vaex.multithreading")
class DatasetArrow(vaex.dataset.Dataset):
def __ini... |
import operator
import PySimpleGUI as psg
from nation_gui.logger import ISL
__MODULE_NAME__ = 'NationGUI.gui.issues'
__MOD_LOG__ = ISL.device.add_child(__MODULE_NAME__)
class ToggleObj(object):
"""
An object that functions as a toggle switch that keeps track of number of state changes and binary cycles.
... |
#!/usr/local/bin/python3
"""
Simulates sensors
The MIT License (MIT)
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation t... |
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
main = None
from api import *
from analyse_images import *
import time
import web
import json
from PIL import Image
import requests
from StringIO import StringIO
urls = (
'/', 'Welcome',
'/moodboard', 'Main_Interface',
'/update', 'Update',
'/search', 'Se... |
import os
import os.path
import json
from os import walk, makedirs, remove
from multiprocessing import Pool
import re
from codecs import open
from os.path import join, dirname, exists, relpath, abspath, basename
from sys import platform
from json_tools import prepare, field_by_path, list_field_paths
from utils import g... |
import os
from pathlib import Path
import re
import subprocess
import sys
import traffic
ICON_PATH = Path(traffic.__file__).parent.parent / "icons"
class LinuxApp:
linux_desktop = """#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Name=traffic
Comment=A GUI for manipulating and analysing air traffic data
E... |
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
import torch
UCI_datafolder = "../data/UCI/"
def dummy_encode(df):
"""
Auto encodes any dataframe column of type category or object.
"""
columnsToEncode = list(df.select_dtypes(include=['category', 'object']))
le ... |
from abc import ABC, abstractmethod
from collections import Counter
from functools import reduce
from typing import List, Tuple
import numpy as np
from sklearn.utils.linear_assignment_ import linear_assignment
class Scorer(ABC):
precision: float
recall: float
def get_scores(self, predicted_chains: List[... |
# ===============================================================================
# Copyright 2012 <NAME>
#
# 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/... |
"""
These tests were written to check that FormDictPayloadGenerator behaved
like FormRepeaterJsonPayloadGenerator, but they also show automatic type
casting by `jsonobject`_ when using the Couch backend.
The takeaway here is that when configuring integrations for domains on
Couch, it's important to remember that not a... |
import numpy as np
from ..assignment.linear_assignment import LinearAssignment
from pyuwds3.bbox_metrics import overlap, centroid
from pyuwds3.types.temporal_relation import TemporalRelation, Event
OCCLUSION_TRESHOLD = 0.2
class ActionStates(object):
PLACED = 0
HELD = 1
RELEASED = 2
def centroid_cost(t... |
#!/usr/bin/env python
import os
import sys
import time
import datetime
import requests
import argparse
from argparse import ArgumentParser
from bs4 import BeautifulSoup
import pandas as pd
__author__ = '<NAME>'
__version__ = '0.01'
# v0.01 : 2020-08-01 : original version
def get_parser():
"""
Creates a new argume... |
import schema, re
from experta import *
from experta.utils import freeze
class Faza(Fact):
pass
class Osoba(Fact):
ime = Field(str)
pol = Field(schema.Or("m", "z"))
ime_supruznika = Field(str)
ime_oca = Field(str)
ime_majke = Field(str)
class StatusInputa(Fact):
pass
class TipUpita(Fa... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
#... |
import logging
from enum import Enum
from bitstring import BitArray
from scapy.layers.ntp import NTPHeader, NTP
class RawNTP:
"""
A pure bit representation of NTP packages. Provides methods to access the bit masks of the different NTP fields.
"""
def __init__(self, ntp_pck: NTP = NTPHeader()):
... |
import FreeCAD, Part, Mesh, math
DOC = FreeCAD.activeDocument()
DOC_NAME = "assembly"
def clear_doc():
# Clear the active document deleting all the objects
for obj in DOC.Objects:
DOC.removeObject(obj.Name)
def setview():
# Rearrange View
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
Free... |
import matplotlib
matplotlib.use('Agg')
import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import models
models_path = './checkpoints/AdvGAN/'
losses_path = './results/losses/'
def init_weights(m):
'''
C... |
# Copyright 2020 Roboception GmbH
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaim... |
from lxml import etree
import logging
from netconf import NSMAP, error, qmap, util
def remove_state(data):
for state in data.iter("{*}state"):
state.getparent().remove(state)
def process_changes(data_to_insert_xml, current_config_xml):
config_tree = etree.ElementTree(current_config_xml)
data_t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from .utils import *
from .explorer import *
from .manager import *
#*****************************************************
# QfLocListExplorer
#*****************************************************
class QfLocListExplorer(Explorer):
def __init__(self):
... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
def plot2d(ca, timestep=None, title=''):
cmap = plt.get_cmap('Greys')
plt.title(title)
if timestep is not None:
data = ca[timestep]
else:
data = ca[-1]
... |
#!/usr/bin/python3
from sys import argv
from getpass import getuser
import pickle
from pdb import set_trace
from ceRNA import Networks, RateTests
import ceRNA.Estimators
def main():
if argv[1] == "averages":
get_averages()
exit(0)
x = int(argv[2])
y = int(argv[3])
if argv[1] == "ru... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import random
import datetime
import uuid
import json
import numpy as np
import gzip
import codecs
import bisect
from faker import Faker
from faker.providers import internet
from faker.providers import user_agent
from... |
"All about scraping PSE website for usage"
import logging
import os
import asyncio
from datetime import date, datetime, time, timedelta
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import AsyncGenerator, Dict, Iterable, List, Optional, Sequence
from zipfile import ZipFile
from contextli... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
from livelossplot import PlotLosses
from apex import amp
def load_csv_data(path, index_col):
df = pd.read_csv(path, index_col=index_col)
... |
# Copyright 2016, 2017, 2018 IBM Corp.
#
# 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 ... |
# How to run: python newsroom_data_maker.py $HOME/data/newsroom/
# The directory must contain the following files: [train,dev,test].data
# This code will tokenize and detect Named-Entities and concat them with "_".
# Therefore, given the following sentence:
# --President Trump said he based his decision on "open hosti... |
from util import network_strong_connectivity, network_import_postprocessing, link_travel_time
def TNTP_import(network_filepath, demand_filepaths, defaultDemandMultiplier, numClasses, classToll=None):
if not classToll:
classToll = {}
numZones = None
numNodes = None
numLinks = None
defaultTol... |
# -*- coding: utf-8 -*-
import re
import requests
from time import sleep
from fake_useragent import UserAgent
from .cache import cache
from .singleton import Singleton
@cache()
def get_user_agent():
""" Return user-agent
Returns
-------
str
user-agent
"""
ua = UserAgent()
agent = u... |
import click
import json
import inspect
from auth0_client.Auth0Client import Auth0Client
from auth0_client.cli_util import (pretty, get_config_dict, group, highlight)
def lineno():
"""Returns the current line number in our program."""
return str(' - commands/administration.py - line number: '+str(inspect.curre... |
"""
개발환경 : PyQt5 x64, Python 3.4.3 x64, Windows 8.1 x64
파일 : CryptoVigenereKasiskiHackExtra.py
내용 : Kasiski 검사를 위한 모듈, 참조 내용에서 GUI환경을 위해 약간의 수정을 가함.
참조 : http://inventwithpython.com/hacking (BSD Licensed)
"""
# Vigenere Cipher Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
import re
import CryptoVigenere... |
from ppadb.client import Client as AdbClient
from pathlib import Path
import os, shutil
MIN_NO_FOR_FILE_TRANSFER = 10 #the criteria used to determine if a folder should be transfered
#absolute path seemed to keep getting a permission denied error from ppadb when transfering hence the reason for the relative os ... |
#<NAME> et <NAME>
#Bugnon 3M4
#5 Février 2019
#Jeu du morpion avec SenseHat
"""
Morpion is a game played by 2 players on a 3x3 board.
The goal is to align 3 symbols in a line, column or diagonal.
"""
from sense_hat import SenseHat
from time import sleep, time
from gamelib import *
sense = SenseHat()
X = WHITE
O = BLA... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 19:00:56 2020
@author: byron
"""
import numpy as np
import matplotlib.pyplot as plt
import math
import itertools
from __main__ import *
class Line:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c... |
from types import CodeType
import flask,core.plugins.MusicPlayer.music_apis,core.api,core.xmcp,core.plugins.MusicPlayer.counter,pymediainfo
from werkzeug.utils import redirect
from flask.globals import g
from flask.templating import render_template
import json
name = 'MusicPlayer'
requestCPR = None
def cross_plugin_... |
import json
import os
import subprocess
import sys
from optparse import OptionParser
def export_file_to_bloop(filename):
# get the name of the file according to bazel
command = [BAZEL_CMD, "query", filename]
bazel_name = run_command(command)
for i in iter(bazel_name.splitlines()):
targets = ... |
import os
import argparse
import random
import torch
import torch.optim as optim
import broadface.loss as loss
import broadface.backbone as backbone
import broadface.embedding as embedding
from tqdm import tqdm
from torch.utils.data import DataLoader
from utils.dataset import StanfordOnlineProductsMetric
from utils... |
from flask import Flask, render_template, jsonify, request
from celery import Celery
from celery.result import AsyncResult
import time
import copy
import datetime
from pytz import timezone
from pathlib import Path
import statistics
import game_env.hidenseek_gym
from game_env.hidenseek_gym.config import config as defa... |
import argparse
import torch
import numpy as np
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
from PIL import Image
import json
#python predict.py flowers/test/28/image_05253.jpg checkpoints/checkpo... |
d=[[3,5,7,18],[17,15,16,11,13]]
t=[[1,2,6,7],[16,15,17,12,18]]
z=[[6,7,14,19],[8,9,10,15,17]]
l=[[1,5,7,18],[13,17,10,12,15]]
m=[[7,10,18,19],[5,4,8,9,15]]
f=[[10,12,13,19],[7,6,2,3,11]]
ma=[[4,5,9,10],[1,6,8,15,18]]
b=[[3,4,5,18],[8,9,10,11,13,15]]
p=[[4,5,6,18],[3,9,14,16,17]]
lo=[[3,7,19],[1,4,5,10,13,18]]
... |
import hashlib
# for gravatar URLs and user's profile image and its unique name
import urllib
import django
# for time related tasks, incl. timezone
import pytz
from django.conf import settings
from django.contrib.auth.models import AbstractUser, UserManager
from django.core.validators import MaxValueValidator, MinV... |
#!/usr/bin/env python
import argparse
import json
import requests
ENDPOINT = 'http://127.0.0.1:9000'
def add_check(args):
data = {
'date': args.date,
'description': args.description,
}
return requests.post('%s/check' % (ENDPOINT), json=data)
def get_check(args):
return requests.ge... |
#!/usr/bin/python3
import urllib.request
import json
import subprocess
import os
import sys
import shutil
import argparse
from urllib.parse import urlparse
from urllib.parse import urljoin
from urllib.parse import urlsplit
# Hardcoded map of storage account to azure region endpoint
storage_account_to_endpoint_map = {
... |
#!/usr/bin/python
import sys
import json
from ansible.module_utils import ntap_util
try:
from NaServer import *
NASERVER_AVAILABLE = True
except ImportError:
NASERVER_AVAILABLE = False
if not NASERVER_AVAILABLE:
module.fail_json(msg="The NetApp Manageability SDK library is not installed")
DOCUMENTA... |
#! /usr/bin/env python
#
# Copyright (C) 2017 Sony Interactive Entertainment Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, th... |
#!/usr/bin/env pytest -vs
"""Tests for pws-api-wrapper."""
# Standard Python Libraries
from datetime import datetime
# Third-Party Libraries
import pytest
import vcr
# Custom Libraries
from pws_api_wrapper import AbstractEndpoint, APIKeyMissingError, Engagement
from pws_api_wrapper.session import get_api_key
class... |
"""Converter"""
from pathlib import Path
from random import sample
from string import digits
from typing import List
from telethon import events, Button
from telethon.tl.custom import Message, MessageButton
from ebook_converter_bot.bot import BOT
from ebook_converter_bot.db.curd import get_lang
from ebook_converter_b... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from open_spiel.python.games.optimal_stopping_game_config import OptimalStoppingGameConfig
from open_spiel.python.games.optimal_stopping_game_observation_type import OptimalStoppingGameObserv... |
from flask import Flask, render_template, request
from flask_cors import CORS
from pymemcache.client import base
from tensorflow.keras.models import model_from_json
import json
import numpy as np
import category_encoders
import pickle
import os
from keras import backend as K
from keras.models import load_model
#initai... |
"""Settings dialog advanced example.
This example shows the an advanced approach to using a QSettings class for
persisting user preferences and tool settings between sessions. It uses
descriptors and partials to eliminate most of the boilerplate.
"""
import collections
import sys
import functools
fro... |
"""Abode cloud push events."""
import collections
import logging
from abodepy.devices import AbodeDevice
from abodepy.exceptions import AbodeException
import abodepy.helpers.constants as CONST
import abodepy.helpers.errors as ERROR
import abodepy.helpers.timeline as TIMELINE
import abodepy.socketio as sio
_LOGGER = l... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import argparse
import errno
import json
import os
import os.path
import shutil
import tempfile
import traceback
import zipfile
import win32con
import win32ui
BLOCKED_TABS = ["PETRefinement.R", "SurrogateModeling.R"]
def copy_files(origi... |
#!/usr/bin/env python3
"""problem_096.py
Problem 96: Su Doku
Su Doku (Japanese meaning number place) is the name given to a popular puzzle
concept. Its origin is unclear, but credit must be attributed to <NAME>
who invented a similar, and much more difficult, puzzle idea called Latin
Squares. The objective of Su Dok... |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# Mellin_NegTempStable_European_Price.m
@function
def Mellin_NegTempStable_European_Price(S_0=None,W=None,T=None,r=None... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Mapping, MutableMapping, Any, Optional
_PREFIX_NODE = '_copy' # for copy node content command (must be dict)
_PREFIX_PATH = '_copy:' # for copy node value command (must be scaler)
def resolve_all(root_d:MutableM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.