content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python import sys import time from ansible.module_utils.forward import * try: from fwd_api import fwd except: print('Error importing fwd from fwd_api. Check that you ran ' + 'setup (see README).') sys.exit(-1) # Module documentation for ansible-doc. DOCUMENTATION = ''' --- module:...
python
from django.db.models import ForeignKey from graphene.utils.str_converters import to_camel_case # https://github.com/graphql-python/graphene/issues/348#issuecomment-267717809 def get_selected_names(info): """ Parses a query info into a list of composite field names. For example the following query: ...
python
"""Constants for integration_blueprint tests.""" from custom_components.arpansa_uv.const import CONF_NAME, CONF_LOCATIONS, CONF_POLL_INTERVAL # Mock config data to be used across multiple tests MOCK_CONFIG = {CONF_NAME: "test_arpansa", CONF_LOCATIONS: ['Brisbane','Sydney','Melbourne','Canberra'], CONF_POLL_INTERVAL: 1...
python
import json from datetime import datetime, timedelta from email import utils as email_utils import pytest from flask.testing import FlaskClient from sqlalchemy.orm import Session from app.models.exceptions import NotFound from app.models.products import Brand, Category, Product, FEATURED_THRESHOLD def create_basic_...
python
print('domain.com'.endswith('com'))
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Batch-create ownCloud users """ __author__ = "Constantin Kraft <c@onstant.in>" import sys import argparse import owncloud from owncloud.owncloud import HTTPResponseError import csv API_URL = '' # User needs Admin permissions OC_USER = '' OC_PASS = '' oc = owncloud.C...
python
from chipclock.display import ModeDisplay from chipclock.modes.clock import ClockMode from chipclock.renderers.time import render_ascii, render_chip from chipclock.renderers.segment import setup_pins, render_segment seconds_pins = [ ['LCD-D5', 'LCD-D11'], ['LCD-D4', 'LCD-D10'], ['LCD-D3', 'LCD-D7'], ['LCD-D20'...
python
from typing import NoReturn, TypeVar, Type import six from .avrojson import AvroJsonConverter TC = TypeVar('TC', bound='DictWrapper') class DictWrapper(dict): __slots__ = ['_inner_dict'] def __init__(self, inner_dict=None): super(DictWrapper, self).__init__() self._inner_dict = {} if inner_...
python
"""Functions to simplify interacting with database.""" import datetime as dt from math import ceil from bson.objectid import ObjectId from bson import SON from motor.motor_asyncio import AsyncIOMotorClient from pymongo import WriteConcern, IndexModel, ASCENDING, ReturnDocument def init_db(config, loop): """Initi...
python
#! /usr/bin/env python # def timestamp ( ): #*****************************************************************************80 # ## TIMESTAMP prints the date as a timestamp. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 06 April 2013 # # Author: # # John Burkardt ...
python
""" Tests for the :module`regression_tests.parsers.c_parser.module` module. """ import io import re import sys from textwrap import dedent from unittest import mock from regression_tests.utils.list import NamedObjectList from tests.parsers.c_parser import WithModuleTests class ModuleTests(WithModuleTests): ...
python
import types from operator import add import sys from common.functions import permutations, pick_from COMMON_ENGLISH_WORDS = ['of', 'the', 'he', 'she', 'when', 'if', 'was'] ALPHABET = map(chr, range(ord('a'), ord('z') + 1) + range(ord('A'), ord('Z') + 1)) NUMBERS = set(map(str, range(0, 10))) SPECIAL_CHARACTERS = {'...
python
# File name: SIM_SolarSys.py # Author: Nawaf Abdullah # Creation Date: 9/October/2018 # Description: numerical simulation of the n-body problem of a solar system from classicalMech.planet import Planet import matplotlib.pyplot as plt # Constants PI = 3.14159 class System: def __init__(self, i_ms, i_pla...
python
# -*- coding: utf-8 -*- import json from jinja2.ext import Extension from jinja2 import nodes from watson.assets.webpack import exceptions from watson.common.decorators import cached_property __all__ = ['webpack'] class WebpackExtension(Extension): tags = set(['webpack']) cached_stats = None @cached_pr...
python
#:coding=utf8: import logging from django.test import TestCase as DjangoTestCase from django.conf import settings from jogging.models import Log, jogging_init class DatabaseHandlerTestCase(DjangoTestCase): def setUp(self): from jogging.handlers import DatabaseHandler, MockHandler import logging...
python
"""Defines preselections. Currently implements 'loose' and 'tight' strategies.""" from __future__ import annotations __all__ = ["preselection_mask", "cut_vars"] from functools import singledispatch import awkward as ak import numpy as np from uproot.behaviors.TTree import TTree def cut_vars(strength: str) -> list[...
python
from tutils import Any from tutils import Callable from tutils import List from tutils import Tuple from tutils import cast from tutils import concat from tutils import reduce from tutils import lmap from tutils import splitstriplines from tutils import load_and_process_input from tutils import run_tests """ END H...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import __future__ import sys print("===" * 30) print("SAMPLE INPUT:") print("===" * 30) print(open("./input14.txt", 'r').read()) sys.stdin = open("./input14.txt", 'r') #print(open("./challenge_sample_input", 'r').read()) #sys.stdin = open("./challenge_sample_input", 'r') ...
python
# -*- coding: utf-8 -*- import io import time import queue import socket import select import functools from quickgui.framework.quick_base import time_to_die class DisconnectedException(Exception): '''Socket was disconnected''' pass class QueueClient(): ''' TCP client for queue-based communication...
python
import xml4h import os import re import spacy #doc = xml4h.parse('tests/data/monty_python_films.xml') #https://xml4h.readthedocs.io/en/latest/ class getData: def __init__(self, name, path): self.name = name self.path = path self.files = [] # test self.testfile = None ...
python
import os import logging """ Provide a common interface for all our components to do logging """ def basic_logging_conf(): """Will set up a basic logging configuration using basicConfig()""" return basic_logging_conf_with_level( logging.DEBUG if "MDBRAIN_DEBUG" in os.environ else logging.INFO) def ...
python
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Implement a linked list with insert, append, find, delete, length, an...
python
#!/usr/bin/env python3 import json import os import random random.seed(27) from datetime import datetime import sqlalchemy.ext import traceback import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) import connexion impo...
python
#!/usr/bin/env python2 """Create GO-Dag plots.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" import sys sys.path.append("/dfs/scratch2/caruiz/code/goatools/") from goatools.cli.gosubdag_plot import PlotCli def run(): """Create GO-Dag ...
python
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: ...
python
import pytest from . import constants from pybible import pybible_load from pybible.classes.bible import Bible from pybible.classes.bible_without_apocrypha import BibleWithoutApocrypha from pybible.classes.book import Book from pybible.classes.chapter import Chapter from pybible.classes.verse import Verse @pytest.fix...
python
from django.shortcuts import render, redirect from django.template.loader import render_to_string from django.http import JsonResponse, HttpResponse from .models import User, Photo, Followers from .forms import * from django.contrib.auth import authenticate, login, logout as dlogout import json def ajaxsignup(request)...
python
import numpy from scipy.spatial import distance import matplotlib.pyplot as plt # wspolczynnik uczenia eta = 0.1 # momentum alfa = 0 class NeuralNetwork: def __repr__(self): return "Instance of NeuralNetwork" def __str__(self): # todo: zaktualizuj to_string() if self.is_bias: ...
python
import torch import matplotlib.pyplot as plt from torchsummary import summary import yaml from pprint import pprint import random import numpy as np import torch.nn as nn from torchvision import datasets, transforms from itertools import product def imshow(img): # functions to show an image fi...
python
from models.mlm_wrapper import MLMWrapper from transformers import BertForMaskedLM, BertTokenizer class BertWrapper(MLMWrapper): def __init__(self, tokenizer: BertTokenizer, model: BertForMaskedLM, device: int = None): super().__init__(tokenizer, model, device=device)
python
import csv import clueUtils import guess suspects = clueUtils.suspects weapons = clueUtils.weapons rooms = clueUtils.rooms allCards = clueUtils.allCards playerNames = clueUtils.playerNames numPlayers = clueUtils.numPlayers numSuspects = clueUtils.numSuspects numWeapons = clueUtils.numWeapons numRooms = clueUtils.nu...
python
# This file is part of the scanning-squid package. # # Copyright (c) 2018 Logan Bishop-Van Horn # # 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 limita...
python
""" Feb 23 Like net_feb23_1 but with faster affine transform and more filters and DNN (~15s faster) 363 | 0.678831 | 0.869813 | 0.780434 | 74.74% | 69.6s Early stopping. Best valid loss was 0.846821 at epoch 262. Finished training. Took 25459 seconds Accuracy test score is 0.7608 Multicla...
python
# cat train.info | grep "Test net output #0: accuracy =" | awk '{print $11}' import re import os import matplotlib.pyplot as plt import numpy as np import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--traininfo', type=str, required=True) args = parser.parse_...
python
''' Perform Object Classification (SGCLS only) Input is the pointcloud of the BOX, its location and heading is known Output the predicted class of the BOX ''' import torch from torch import nn from torch.nn import functional as F from model.modeling.detector.pointnet2.pointnet2_modules import PointnetSAModuleVotes, P...
python
# Copyright 2016 Intel # # 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, softwar...
python
#! /usr/bin/env nix-shell #! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy ps.psycopg2 ps.requests ps.websockets])" import sys import threading from tenmoTypes import * from tenmoGraph import universe_print_dot import select import time import datetime import pprint import traceback import io import jso...
python
from django.urls import path from django.contrib.auth import views as auth_views from account import views as account_views urlpatterns = [ path('login', auth_views.LoginView.as_view( template_name='account/login.html', extra_context={ 'title': 'Account login'})...
python
''' This is based on cnn35_64. This is after the first pilot. Changes: -don't filter out # in the tokenizer, tokenize both together. or save tokenizer https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring -use 'number' w2v as representation for any digit -shu...
python
#!/usr/bin/env python import os import sqlite3 import cherrypy from collections import namedtuple import tweepy import random import twitterkeys # setup twitter authentication and api twitter_auth = tweepy.OAuthHandler(twitterkeys.consumer_key, twitterkeys.consumer_secret) twitter_auth.set_access_token(twitterkeys.ac...
python
#!/usr/bin/env python3 import xml.etree.ElementTree as ET CSPROJ_FILE = 'Uri/Uri.csproj' ENV_VARIABLE_FILE = '.env' ENV_VARIABLE_NAME = 'URI_VERSION' csproj_tree = ET.parse(CSPROJ_FILE) version_tag = csproj_tree.getroot().find('PropertyGroup').find('Version') version_parts = version_tag.text.split('.', 2) version_p...
python
class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: dic = {} stack = [] for num in nums2: stack.append(num) while len(stack) >= 2: if stack[-1] > stack[-2]: dic[stack[-2]] = stack[-1] ...
python
# -*- coding: utf-8 -*- import torch import torch.nn as nn from torch.nn import BatchNorm1d from ncc.models import register_model from ncc.models.ncc_model import ( NccEncoder, NccEncoderModel, ) from ncc.modules.base.layers import ( Embedding, Linear, ) class DeepTuneEncoder(NccEncoder): def __...
python
# MAP WARMPUP # Given the two lists of numbers below, produce a new iterable of their element-wise sums # In this example, that'd be (21, 33, 3, 60...) # Hint: look for a `from operator import ...` one = [1, 2, 3, 40, 5, 66] two = [20, 31, 0, 20, 55, 10] # FILTER WARMPUP # Take the following iterable, and filter o...
python
""" This is templates for common data structures and algorithms. Frequently used in my leetcode practices. """ """ Binary search """ nums, target left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 # might need modification to fit the problem. if nums[mid] < target: ...
python
from __future__ import (absolute_import, division,print_function, unicode_literals) from builtins import * import numpy as np import cv2 import SimpleITK as sitk from builtins import * from scipy.spatial import distance from scipy import stats import sys import time ############### FUNCTIONS ##############...
python
import tempfile import pickle import os import sys import time import zipfile import inspect import binaryninja as binja from binaryninja.binaryview import BinaryViewType, BinaryView from binaryninja.filemetadata import FileMetadata, SaveSettings from binaryninja.datarender import DataRenderer from binaryninja.function...
python
#!/bin/python3 import math import os import random import re import sys # Complete the arrayManipulation function below. def arrayManipulation(n, queries): d=[0]*(n+1) max_val=0 for query in queries: d[query[0]-1]+=query[2] d[query[1]]+=query[2]*(-1) max_dif=0 for i in d: ...
python
from model.model.space.space import Space from model.model.space.space import Space from watchmen.auth.storage.user_group import get_user_group_list_by_ids, update_user_group_storage, USER_GROUPS from watchmen.auth.user_group import UserGroup from watchmen_boot.guid.snowflake import get_surrogate_key from watchmen.co...
python
from scipy.spatial.distance import pdist, squareform from causality.greedyBuilder.scores import mutual_info_pairwise import networkx as nx class TreeBuilder: def __init__(self, score=None): if score is None: self.score = mutual_info_pairwise else: self.score = score d...
python
"""Interval set abstract type""" import datetime import collections __version__ = "0.1.5" _InternalInterval = collections.namedtuple("Interval", ["begin", "end"]) class Interval(_InternalInterval): """Represent an immutable interval, with beginning and ending value. To create a new interval: ...
python
#!/usr/bin/env python3 from ctypes import cdll, c_char_p, c_int, create_string_buffer, c_long SO_PATH="/home/***************/libAdAuth/libAdAuth.so" username = create_string_buffer(b"********") password = create_string_buffer(b"********") host = create_string_buffer(b"*********.uk") domain = create_string_buffer(b"**...
python
# rearrange name of data in anat directories, # delete repeated task-name pattern, add missing pattern import os # change to main directory main_directory = '/mindhive/saxelab3/anzellotti/forrest/forrest_bids/' #main_directory = '/Users/chloe/Documents/test10/' os.chdir(main_directory) # get all subject folders in main...
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.ohio import ohio def test_ohio(): """Test module ohio.py by downloading ohio.csv and testing shape of extracted data has 2148 rows and 4 c...
python
class User: """ This class will contain all the details of the user """ def __init__(self,login,password): """ This will create the information of (Levert) the user """ self.login = login self.password = password # Levert def user_exists(self,password): """Levert Co ...
python
# 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...
python
import pytest import numpy as np class DataGenerator: def __init__(self, fs=100e3, n_iter=10, sample_duration=1): self.fs = fs self.n_iter = n_iter self.sample_duration = sample_duration self.n_samples = int(round(sample_duration * fs)) def _iter(self): self.generate...
python
# # Copyright (c) Sinergise, 2019 -- 2021. # # This file belongs to subproject "field-delineation" of project NIVA (www.niva4cap.eu). # All rights reserved. # # This source code is licensed under the MIT license found in the LICENSE # file in the root directory of this source tree. # import os import re from setuptool...
python
import time import base64 def normalize_scope(scope): return ' '.join(sorted(scope.split())) def is_token_expired(token, offset=60): return token['expires_at'] - int(time.time()) < offset def get_authorization_headers(client_id, client_secret): auth_header = base64.b64encode(f'{client_id}...
python
""" # 100daysCodingChallenge Level: Medium Kevin and Stuart want to play the 'The Minion Game'. Game Rules Both players are given the same string, S . Both players have to make substrings using the letters of the string S . Stuart has to make words starting with consonants. Kevin has to make words starting with vow...
python
''' Date: 2021-08-02 22:38:28 LastEditors: xgy LastEditTime: 2021-08-15 16:12:14 FilePath: \code\ctpn\src\CTPN\BoundingBoxDecode.py ''' import mindspore.nn as nn from mindspore.ops import operations as P class BoundingBoxDecode(nn.Cell): """ BoundintBox Decoder. Returns: pred_box(Tensor): decoder ...
python
'''In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary. Download this file and save it in the same directory as your Python code. This file is Peter Norvig’s compilation of the dictionary of words used in professional Scrabble tournaments. Each lin...
python
from django.db import models # Create your models here. class Post(models.Model): title = models.CharField('Titulo', max_length=150) description = models.TextField('Description') # author = models.ForeignKey(User, verbose_name = 'Autor') is_published = models.BooleanField('Publicado?', default = False...
python
# from os.path import dirname import os,sys,pytest sys.path.append(os.path.dirname(os.path.dirname(__file__))) from Page.login_page import Login_Page from Base.init_driver import get_driver from Base.read_data import Op_Data from time import sleep from loguru import logger # sys.path.append(os.getcwd()) def get_data...
python
from unittest import TestCase import pytest import pandas as pd import numpy as np from pipelines.wine_quality_preparers import WinesPreparerETL, WhiteWinesPreparer inputs = [7.0, 0.27, 0.36, 20.7, 0.045, 45.0, 170.0, 1.0010, 3.00, 0.45, 8.8, 6] np_inputs = np.array(inputs) class TestWinesPreparerETL(TestCase):...
python
from openfermion_dirac import MolecularData_Dirac, run_dirac from openfermion.transforms import jordan_wigner from openfermion.utils import eigenspectrum import os # Set molecule parameters. basis = 'STO-3G' bond_length = 0.5 charge = 1 data_directory=os.getcwd() delete_input = True delete_xyz = True delete_output = ...
python
# Copyright (c) 2021-present, Ethan Henderson # All rights reserved. # # 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 condit...
python
# -*- coding: utf-8 -*- # :Project: pglast -- DO NOT EDIT: automatically extracted from struct_defs.json @ 13-2.1.0-0-gd1d0186 # :Author: Lele Gaifax <lele@metapensiero.it> # :License: GNU General Public License version 3 or later # :Copyright: © 2021 Lele Gaifax # from collections import namedtuple from decima...
python
""" mqtt_base_client.py ==================================== Base MQTT Client """ import paho.mqtt.client as mqtt from helper import run_async import _thread import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def on_subscribe_callback(client, userdata, mid, granted_qos): ""...
python
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, DateField,IntegerField, FloatField, SelectField, SelectMultipleField, RadioField, TextAreaField, Form, FieldList, FormField from wtforms.fields.html5 import DateField from wtforms.widgets import ListWidget, CheckboxInput from wtforms.validato...
python
"""Thread function's arguments When target function you want to call to run in a thread has arguments. """ import threading, time def pause(seconds): i = 0 while i < seconds: print('Run thread: ' + threading.currentThread().name) i = i + 1 time.sleep(1) print('Start main') threading.T...
python
import logging import os import sys from constants.dbpedia import LINKS_FILE from extras.dbpedia.loader import start_crawling log = logging.getLogger( __name__ ) if __name__ == '__main__': if not os.path.isfile( LINKS_FILE ): log.error( 'File with links to DBpedia-related files not found. nothing to do'...
python
# -*- coding: utf-8 -*- """ site.py ~~~~~~~ Flask main app :copyright: (c) 2015 by Vivek R. :license: BSD, see LICENSE for more details. """ import os import datetime from urlparse import urljoin from collections import Counter, OrderedDict from flask import Flask from flask_frozen import Freezer from werkzeug...
python
from allennlp.predictors.predictor import Predictor from typing import List from allennlp.common.util import JsonDict, sanitize from allennlp.data import Instance @Predictor.register("rationale_predictor") class RationalePredictor(Predictor) : def _json_to_instance(self, json_dict): raise NotImplementedEr...
python
from setuptools import setup, find_packages with open("README.md", "r") as f: long_description = f.read() with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='alfrodull', version='0.1.0', author='Philip Laine', author_email='philip.laine@gmail.com', descri...
python
annoy_index_db_path = 'cache/index.db' already_img_response = 'there are not math image' success_response = 'success' dim_800x800 = (800,800)
python
#!/usr/bin/env python3 # (C) Copyright 2022 European Centre for Medium-Range Weather Forecasts. # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunit...
python
from typing import Any, Dict import pytest from nuplan.common.utils.testing.nuplan_test import NUPLAN_TEST_PLUGIN, nuplan_test from nuplan.planning.metrics.evaluation_metrics.common.ego_yaw_acceleration import EgoYawAccelerationStatistics from nuplan.planning.metrics.utils.testing_utils import metric_statistic_test ...
python
import pandas as pd import numpy as np from src.configs import * from src.features.transform import categorical_to_ordinal import collections class HousePriceData: ''' Load House Price data for Kaggle competition ''' def __init__(self, train_path, test_path): self.trainset = pd.read_csv(train_...
python
#!/usr/bin/env python # coding=utf-8 import os import shutil from src.core.setcore import * # Py2/3 compatibility # Python3 renamed raw_input to input try: input = raw_input except NameError: pass dest = ("src/html/") url = ("") debug_msg(mod_name(), "entering src.html.templates.template'", 1) # # used for pre-def...
python
from typing import Any, Optional from fastapi import HTTPException class NotFoundHTTPException(HTTPException): """Http 404 Not Found exception""" def __init__(self, headers: Optional[dict[str, Any]] = None) -> None: super().__init__(404, detail="Not Found", headers=headers) class BadRequestHTTPExce...
python
from setuptools import setup setup(name="spikerlib", version="0.8", description="Collection of tools for analysing spike trains", author="Achilleas Koutsou", author_email="achilleas.k@gmail.com", #package_dir={'': 'spikerlib'}, packages=["spikerlib", "spikerlib.metrics"] )
python
"""Parse CaffeModel. Helped by caffe2theano, MarcBS's Caffe2Keras module. Author: Yuhuang Hu Email : duguyue100@gmail.com """ from __future__ import print_function from collections import OrderedDict import numpy as np from scipy.io import loadmat from transcaffe import caffe_pb2, utils from google.protobuf.text_fo...
python
# # 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 the ...
python
import json from dejavu import Dejavu from dejavu.logic.recognizer.file_recognizer import FileRecognizer from dejavu.logic.recognizer.microphone_recognizer import MicrophoneRecognizer # load config from a JSON file (or anything outputting a python dictionary) config = { "database": { "host": "db", ...
python
#!/usr/bin/env python # coding: utf-8 # # Exercises 9: Functions # # There are some tricky questions in here - don't be afraid to ask for help. You might find it useful to work out a rough structure or process on paper before going to code. # # ## Task 1: Regular functions # # 1. Write a function to find the maximu...
python
# Copyright 2017 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 or a...
python
import pytorch_lightning as pl from pytorch_lightning import Trainer from pytorch_lightning.loggers import WandbLogger from deperceiver.models.debug_model import DebugModel if __name__ == '__main__': model = DebugModel() wandb_logger = WandbLogger( name='debug_cifar', project='DePerceiver', ...
python
def img_to_encoding(image_path, model): # loading the image with resizing the image img = load_img(image_path, target_size=(160, 160)) print('\nImage data :',img) print("\nImage Data :",img.shape) # converting the img data in the form of pixcel values img = np.around(np.array(img) / 255.0, dec...
python
from styx_msgs.msg import TrafficLight from keras.models import load_model import cv2 import numpy as np import tensorflow as tf import os import rospy from PIL import Image DIR_PATH = os.path.dirname(os.path.realpath(__file__)) class TLSimClassifier(object): def __init__(self): #TODO load classifier ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import galaxy.main.fields import galaxy.main.mixins class Migration(migrations.Migration): dependencies = [('main', '0049_auto_20161013_1744')] operations = [ migrations.CreateModel( ...
python
from __future__ import annotations import numpy as np from bqskitrs import Circuit as Circ from bqskit.ir.circuit import Circuit from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix def check_gradient(circ: Circuit, num_params: int) -> None: totaldiff = [0] * num_params eps = 1e-5 repeats = 100 ...
python
"""WMEL diagrams.""" # --- import -------------------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt # --- define -------------------------------------------------------------------------------------- # --- subplot --------------------------...
python
import torch.utils.data as data import cv2 import numpy as np import math from lib.utils import data_utils from pycocotools.coco import COCO import os from lib.utils.tless import tless_utils, visualize_utils, tless_config from PIL import Image import glob class Dataset(data.Dataset): def __init__(self, ann_file, ...
python
""" Proxy discovery operations """ import os import socket import logging import functools from contextlib import closing from dataclasses import dataclass from typing import Mapping, Tuple, List from urllib.parse import urlparse from nspawn import CONFIG logger = logging.getLogger(__name__) @dataclass class ProxyC...
python
""" Partition the numbers using a very simple round-robin algorithm. Programmer: Erel Segal-Halevi Since: 2022-02 """ from typing import Callable, List, Any from prtpy import outputtypes as out, objectives as obj, Bins def roundrobin( bins: Bins, items: List[any], valueof: Callable[[Any], float] = lambd...
python
import cv2 import dlib import threading import numpy as np from keras.models import load_model from scipy.spatial import distance as dist from imutils import face_utils import sys from tensorflow import Graph, Session import utils.logging_data as LOG ''' Blink frequence, This file predicts blinking Make sure models a...
python
import sys import argparse import os import re import yaml from . import workflow class Runner(object): tasks = [ ] out_and_cache_subfolder_with_sumatra_label = True def run(self): parser = argparse.ArgumentParser(description='Run workflow') parser.add_argument('config_path', type...
python
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2018 Nortxort Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,...
python
import json from dotenv import load_dotenv from os import getenv from plex_trakt_sync.path import config_file, env_file, default_config_file from os.path import exists class Config(dict): env_keys = [ "PLEX_BASEURL", "PLEX_FALLBACKURL", "PLEX_TOKEN", "PLEX_USERNAME", "TRAKT...
python