content
stringlengths
0
894k
type
stringclasses
2 values
class BadMoves(object): def bad_move(self, move, gs): if move is None: return True coord = gs.me.head + move if gs.me.neck == coord: return True if not gs.is_empty(coord) and coord not in gs.all_tails: return True if coord in gs.possible...
python
''' Created on Jan 3, 2016 @author: graysonelias ''' seeding = False import wallaby as w # Time startTime = -1 # Motor ports LMOTOR = 0 RMOTOR = 3 COWMOTOR = 1 # analog ports LTOPHAT = 0 RTOPHAT = 1 # Digital ports LEFT_BUTTON = 0 RIGHT_BUTTON = 1 CLONE_SWITCH = 9 RIGHT_BUTTON = 13 isClone = w.digital(CLONE_SWIT...
python
# O(n) time complexity # O(n) space complexity def reverse1(a): i = 0 j = len(a) b = a[:] while j > 0: #b.append(a[j - 1]) -> not efficient b[i] = a[j - 1] i += 1 j -= 1 return b # O(n) time complexity # O(1) space complexity def reverse2(a...
python
import sys import time from sdk import * addr_list = addresses() _pid = 20036 _proposer = addr_list[0] _initial_funding = (int("2") * 10 ** 9) _each_funding = (int("3") * 10 ** 9) _big_funding = (int("8") * 10 ** 9) _funding_goal_general = (int("10") * 10 ** 9) def gen_prop(): global _pid prop = Proposal(str...
python
text_3 = '3' print(text_3.isalnum())
python
import subprocess import time import unittest from game.client.controller.network import Network class TestServer(unittest.TestCase): def setUp(self) -> None: self.server = subprocess.Popen(["python3", "-m", "game", "--server"]) time.sleep(2) def test_game_creation(self): network = ...
python
from unittest.mock import ANY, mock_open, patch import pytest import rumps from src.app_functions.exceptions.credentials_failed import CredentialInputFailed from src.duo.login.input_credentials import input_credentials def test_succesful_entry_of_credentials(mocker): """Check if prompt correctly returns when to ...
python
import torch from ..bayesian.models.models import create_model import numpy as np from xopt.vocs import VOCS class TestModelCreation: vocs = VOCS(variables = {'x1': [0, 1], 'x2': [0, 1], 'x3': [0, 1]} ) def test_create_model(self): train_x = torch.r...
python
#64 # Given a m x n grid filled with non-negative numbers, # find a path from top left to bottom right # which minimizes the sum of all numbers along its path. # # Note: You can only move either down or right at any point in time. class DynamicProgrammingSol(): # Time: O(m * n) # Space: O(m + n) def...
python
from flask import Flask,jsonify from flask_restplus import Resource, Api from faker import Faker app = Flask(__name__) api = Api(app, version='0.1.0', title='Faker', description="""## Faker API **λ‹Ήμ‹ μ˜ μƒˆλ‘œμš΄ μ˜μ›…μ„ μ†Œν™˜ν•˜μ„Έμš”.** """) ns = api.namespace('Hero', description='μ˜μ›…μ΄ μ—¬κΈ° μž λ“€λ‹€.') fake = Faker("ko-KR") @ns.route('/new_her...
python
import cv2 img = cv2.imread("example_images/brain_noise.jpeg") # Structuring element se = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # also called kernel # Basic morphology img_erosion = cv2.erode(img, se, iterations=1) img_dilation = cv2.dilate(img, se, iterations=1) img_opening = cv2.morphologyEx(img, cv2....
python
from django.contrib.auth.models import User from rest_framework import serializers from blog.models import Like, Post class UserInfoSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="api:user-detail") class Meta: model = User fields = ("url", "id",...
python
def merge_the_tools(string, k): # your code goes here s = int(len(string)/k) l=[] for i in range(0,len(string),k): l.append(string[i:i+k]) aux = [] aux_2 = [] for j in l: for k in j: if k not in aux: aux.append(k) st = ''.join(aux) ...
python
import numpy as np import random import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerLine2D from matplotlib import ticker import torch import math k = 20 # num of selected clients in each round K = 100 # num of total activated clients T = 2500 # num of total rounds def classA(size...
python
import Formatter import Config import Logger import Arguments from Utils import * args = Arguments.Parse() cfg = Config.Get() @Formatter.Register("csv") def csv_formatter(components): """ Formats components as a CSV """ columns = cfg['columns'] nl = cfg['outputLineSeparator'] result = denormalizeStr(columns...
python
import collections class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: # freq = collections.Counter(words) # return [item[0] for item in heapq.nsmallest(k, (freq.items()), key=lambda x: (x[1] * -1, x[0]))] # sorted_freq = [item[0] for item in sorted(freq.items(),...
python
############################################################### # Autogenerated module. Please don't modify. # # Edit according file in protocol_generator/templates instead # ############################################################### from typing import Dict from ...structs.api.list_offsets_reque...
python
from septentrion import core def test_initialize(db): settings_kwargs = { # database connection settings "host": db["host"], "port": db["port"], "username": db["user"], "dbname": db["dbname"], # migrate settings "target_version": "1.1", "migrations_...
python
from .motion_dataloader import * from .spatial_dataloader import *
python
import pytest from pathlib import Path from app.database import db from app.main import create_app TEST_DB = 'test.db' class TestMainCase: @pytest.fixture def client(self): BASE_DIR = Path(__file__).resolve().parent.parent self.app = create_app() self.app.app_context().push() ...
python
import json import falcon import smtplib from smtplib import SMTPException from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart corp_email_server = 'mail.example.com' corp_email_port = 587 corp_email_name = "My Company" corp_email_sentfrom = 'donotreply@example.com' corp_email...
python
import pyctrl.bbb as pyctrl class Controller(pyctrl.Controller): def __init__(self, *vargs, **kwargs): # Initialize controller super().__init__(*vargs, **kwargs) def __reset(self): # call super super().__reset() # add source: encoder1 self.add_device('encode...
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier. All rights reserved. # Distributed under the terms of the new BSD License. # ----------------------------------------------------------------------------- import unittest imp...
python
''' A recursive approach to implementing the fibonacci series This is a BAD approach since it takes a very long time to execute takes a ridiculously long time ''' def fib_recurr(n): if n <= 1: return n else: return fib_recurr(n-1) + fib_recurr(n -2)
python
def create_mapping_with_unk(dico): sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0])) id_to_word = {index + 1: w[0] for (index, w) in enumerate(sorted_items)} word_to_id = {v: k for k, v in id_to_word.items()} id_to_word[0] = "<unk>" word_to_id["<unk>"] = 0 return word_t...
python
""" Scenario: 1 speaker, 2 listeners (one of which is an adversary). Good agents rewarded for proximity to goal, and distance from adversary to goal. Adversary is rewarded for its distance to the goal. """ import numpy as np from multiagent.core import World, Agent, Landmark from multiagent.scenario import BaseScenar...
python
# -*- coding: utf-8 -*- """ Created on Fri Jan 26 12:11:02 2018 @author: User """ def forever15(n): final = (((n*3) + 45)*2)//6 - n print( final) forever15(1550) def findmin(a, b, c): first = a - b second = b - c third = c - a
python
from typing import Generator, Generic, Optional, TypeVar _T = TypeVar("_T") class Ring(Generic[_T]): def __init__(self, value: _T, next_: "Ring[_T]"): self.value = value self.next = next_ def copy(self) -> "Ring[_T]": result = None run = self first = True whil...
python
# Generated by Django 3.2.3 on 2021-05-31 04:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0005_alter_studentprofile_student'), ] operations = [ migrations.AddField( model_name='studentprofile', ...
python
class Solution: def maxProduct(self, nums: List[int]) -> int: ans = nums[0] prevMin = nums[0] prevMax = nums[0] for i in range(1, len(nums)): mini = prevMin * nums[i] maxi = prevMax * nums[i] prevMin = min(nums[i], mini, maxi) prevMax = max(nums[i], mini, maxi) ans = max...
python
from __future__ import print_function import os.path import time import sys import six import platform from openpype.api import Logger from openpype.api import get_system_settings from .abstract_provider import AbstractProvider from ..utils import time_function, ResumableError log = Logger().get_logger("SyncServer") ...
python
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class CroatianDefaults(La...
python
""" Data related functions and objects. This module contains several parts: - `data_loader` defines a DataLoader objects that behave similar to pandas DataFrame and are used to load data. In addition it provides DataLoader wrappers that implement various transformations on the loaded dataset. - `da...
python
from .ner_labels import NERLabels from .ner_dataset import NERDataset from .label_mapper import LabelMapper from .dataset_tokenizer import DatasetTokenizer __all__=["NERLabels", "NERDataset", "LabelMapper", "DatasetTokenizer"]
python
from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.shortcuts import get_object_or_404 from .models import * from .forms import * from datetime import datetime, timedelta from django.contrib.auth.decorators import login_required...
python
from .accuracy import Accuracy, accuracy __all__ = ['Accuracy', 'accuracy']
python
import sys """ File name: scenario_modifier Date created: 03/03/2019 Feature: # Feature to enable the user to overwrite the scenario file. """ __author__ = "Alexander Kell" __copyright__ = "Copyright 2018, Alexander Kell" __license__ = "MIT" __email__ = "alexander@kell.es" def overwrite_scenario_file(scenario_file):...
python
class User: """Represents a MangaDex User.""" __slots__ = ("id", "username", "roles", "client") def __init__(self, data, client): self.id = data.get("id") _attrs = data.get("attributes") self.username = _attrs.get("username") self.roles = _attrs.get("roles", []) self...
python
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com> # Ibrahim Merad <imerad7@gmail.com> # License: BSD 3 clause """ This module implement the ``GMOM`` class for the geometric median-of-means robust estimator. ``StateGMOM`` is a place-holder for the GMOM estimator containing: gradient: numpy.ndarra...
python
#!/usr/bin/python3 # -*- coding:utf-8 -*- from os import listdir from os.path import splitext, join import markdown import yaml import json def read(uri): with open(uri, 'r') as f: return f.read() def text_to_yml_md(tex): tex = tex.strip('-') sep = '---' if sep in tex: return tex.split(sep) else: return ...
python
#!/usr/bin/env python3 # Copyright (c) 2016 Fabian Schuiki # # This script generates GDS layout data for a memory macro. import sys, os, argparse from potstill.macro import Macro from potstill.layout import Layout from potstill.output.gds import make_gds, make_phalanx_input # Parse the command line arguments. parser...
python
# 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 ...
python
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
python
from . import base_api_core class Backup(base_api_core.Core): def __init__(self, ip_address, port, username, password, secure=False, cert_verify=False, dsm_version=2, debug=True): super(Backup, self).__init__(ip_address, port, username, password, secure, cert_verify, dsm_version, debug) def backup_re...
python
""" Copyright (C) 2019 NetApp Inc. All rights reserved. A test module for the recline.repl.shell module """ import asyncio import builtins import pytest import recline from recline.repl import shell @pytest.mark.parametrize("user_input, expected_marker, expected_output", [ ("ut command -arg 2", 2, ""), ("...
python
#!/usr/bin/env python #-*- coding:utf-8 -*- ## ## setup.py ## ## Created on: Jan 23, 2018 ## Author: Alexey S. Ignatiev ## E-mail: aignatiev@ciencias.ulisboa.pt ## # #============================================================================== import os import os.path import contextlib import glob try: ...
python
# pylint: disable=missing-module-docstring # -*- coding: utf-8 -*- __short_version__ = '1.6' __release__ = '1.6.0' __description__ = 'Framework for Quart to add swagger generation to routes and restful resources'
python
""" This module contains common code shared by utils/rule_dir_stats.py and utils/rule_dir_diff.py. This code includes functions for walking the output of the utils/rule_dir_json.py script, and filtering functions used in both scripts. """ from __future__ import absolute_import from __future__ import print_function im...
python
class Database(Exception): pass class Serialize(Database): def __init__(self, cls, msg="Serialization Failed"): self.cls = cls self.msg = msg def __str__(self) -> str: return f"'{self.cls}' {self.msg}"
python
from sqlalchemy import Column, Integer, String, Sequence, SmallInteger from sgs_schema.declarative_base import Base from sqlalchemy.orm import relationship from sqlalchemy.sql.schema import ForeignKey from sqlalchemy.sql.sqltypes import Float class Produto(Base): __tablename__ = "PRODUTO" id = Column(Intege...
python
# SPDX-FileCopyrightText: 2019 Scott Shawcroft for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_il91874` ================================================================================ CircuitPython `displayio` driver for IL91874-based ePaper displays * Author(s): Scott Shawcroft Implementat...
python
# pylint: disable=C0111,R0903 """Print the branch and git status for the currently focused window. Requires: * xcwd * Python module 'pygit2' """ import os import pygit2 import core.module import util.cli class Module(core.module.Module): def __init__(self, config, theme): super().__init__(con...
python
from pathlib import Path import typer from spacy.tokens import DocBin import spacy ASSETS_DIR = Path(__file__).parent.parent / "assets" CORPUS_DIR = Path(__file__).parent.parent / "corpus" def read_categories(path: Path): return path.open().read().strip().split("\n") def read_tsv(file_): for line in file_...
python
# -*- coding: utf-8 -*- from httoop.exceptions import InvalidURI from httoop.messages import Request, Response from httoop.parser import NOT_RECEIVED_YET, StateMachine from httoop.status import ( BAD_REQUEST, HTTP_VERSION_NOT_SUPPORTED, LENGTH_REQUIRED, MOVED_PERMANENTLY, SWITCHING_PROTOCOLS, URI_TOO_LONG, ) from htt...
python
""" Test passing exceptions to logs """ import inspect import pytest from .util import check_finished_spans, logger, tracer @pytest.mark.parametrize('stmt,exception', [ ('1 / 0', ZeroDivisionError('division by zero')), ('y = non_existent_variable', NameError("name 'non_existent_variable' is not defined")),...
python
from fastapi import HTTPException from datetime import datetime from .router import Router import models from secrets import token_hex class SessionsRouter(Router): def __init__(self, config, database): super().__init__('/sessions', config, database) def methods(self): @self.router.get('/a...
python
# Copyright (c) 2020 elParaguayo # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
python
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license """ Public API surface is re-exported here. This API is exported for users building angular from source in downstream projects. The rules fr...
python
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.template import Context, loader from haystack import connections, connection_router, con...
python
# Generated by Django 3.2.9 on 2021-12-12 10:34 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("customers", "0005_auto_20211205_0953"), ] operations = [ migrations.AlterF...
python
#tree # β”œβ”€β”€ data # β”‚Β Β  β”œβ”€β”€ SRR388226_1.fastq # β”‚Β Β  β”œβ”€β”€ SRR388226_2.fastq # β”‚Β Β  β”œβ”€β”€ SRR388227_1.fastq # β”‚Β Β  β”œβ”€β”€ SRR388227_2.fastq # β”‚Β Β  β”œβ”€β”€ SRR388228_1.fastq # β”‚Β Β  β”œβ”€β”€ SRR388228_2.fastq # β”‚Β Β  β”œβ”€β”€ SRR388229_1.fastq # β”‚Β Β  β”œβ”€β”€ SRR388229_2.fastq # β”‚Β Β  └── SRR.file # β”œβ”€β”€ fastqc_res # β”œβ”€β”€ RSEM_res # └── STAR_res #write for pa...
python
# -*- coding: utf-8 -*- import urllib.request, urllib.parse, urllib.error print("\xe7\xbb\xb4\xe5\x9f\xba\xe6\x96\xb0\xe9\x97\xbb\xef\xbc\x8c\xe8\x87\xaa\xe7\x94\xb1\xe7\x9a\x84\xe6\x96\xb0\xe9\x97\xbb\xe6\xba\x90") print(urllib.parse.unquote_plus("http%3A%2F%2Fzh.wikinews.org%2Fwiki%2FWikinews%3A%25E9%25A6%2596%25E9...
python
""" Copyright (c) 2017, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on Aug 3, 2017 @author: jrm """ from atom.api import Typed from enamlnative.widgets.scroll_view import ProxyScrollView from .bridge import ObjcMet...
python
# --------------------------------------------------------- # Tensorflow Utils Implementation # Licensed under The MIT License [see LICENSE for details] # Written by Cheng-Bin Jin # Email: sbkim0407@gmail.com # --------------------------------------------------------- import os import logging import functools import te...
python
import pathlib from django.utils.safestring import mark_safe CSS_PATH = (pathlib.Path(__file__).resolve().parent / 'static' / 'frontend' / 'built' / 'style' / 'email.min.css') def get(): return mark_safe(CSS_PATH.read_text(encoding='utf-8')) # nosec
python
import os print("if you want use the service Install : ") print(":django") print(":vsftpd") Select_usr = input("Do You Want Install django and vsftpd?:") print("[Y]or[N] if Select_usr == 'Y': os.system("pip3 install django") os.system("sudo apt install vsftpd") print("[*]Services has been Installed") print("Start FTP...
python
""" The proper way to create an uncertain array is by calling :func:`.uarray` """ # Adding numpy arrays to GTC is not an easy exercise. # Our need is to provide convenient containers for uncertain numbers. # We do not try to integrate uncertain numbers in numpy's design. from __future__ import division import warnings...
python
''' The default translation file removes all the attributes with empty values ''' def filterTags(attrs): if not attrs: return tags = {} for k,v in attrs.iteritems(): if v: tags.update({k: v}) return tags
python
import os import unittest def resolve_runfile(path): if os.getenv('RUNFILES_MANIFEST_ONLY') != "1": return os.path.join(os.environ['TEST_SRCDIR'], path) manifest = os.getenv('RUNFILES_MANIFEST_FILE') with open(manifest) as f: for line in f.readlines(): if line.split()[0] == path: return li...
python
import tensorflow as tf import sys sys.path.append('./ext/voxelmorph/') sys.path.append('./ext/neurite-master/') sys.path.append('./ext/pynd-lib/') sys.path.append('./ext/pytools-lib/') from voxelmorph.tf.losses import Grad, NCC, NonSquareNCC loss_object = tf.keras.losses.MeanSquaredError() # used for GAN + def. re...
python
import time import datetime import shutil import os import sys sys.path.insert( 0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) import emdee print(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) # In this case we want to LOAD the results of a previous emdee run...
python
############################################################################### # # file: typing.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #########################################...
python
from .runners import Noun # ?
python
class Value: def __get__(self, instance, instance_type): return self.amount def __set__(self, instance, value): self.amount = value - instance.commission * value class Account: amount = Value() def __init__(self, commission): self.commission = commission """ new_account = Acco...
python
""" 395. Longest Substring with At Least K Repeating Characters This question is listed as a medium question under sliding window category. But sliding window approach is too complex and maybe a hard problem for that case, simple approach is doing a dfs. But it is expensive. The following solution is not optimal bu...
python
from sys import argv from pathlib import Path from datetime import date from time import strftime import json # Logging (console) def print_log(message): """Simple logging function: Adds timestamp before message""" print(strftime("%H:%M:%S") + ": " + message) # Basic structures def set_date(date_=None):...
python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2012 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
python
""" Copyright (c) 2020 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WI...
python
#!/usr/bin/env python from setuptools import setup, find_packages import os import shutil from subprocess import check_output setup( name="array_neutron_lbaas", description="Array vADC OpenStack Neutron LBaaS Device Driver", long_description=open("README.md").read(), version="1.0.0", url="https://...
python
# from typing import Optional # from discord import Embed # from discord.utils import get # from discord.ext.menus import MenuPages, ListPageSource # from discord.ext.commands import Cog, command # def syntax(command): # cmd_and_aliases = "|".join([str(command), *command.aliases]) # params = [] # for ke...
python
## heap # Time: O(NlogK) class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return heapq.nlargest(k, nums)[-1] ## sort # Time: O(NlogN) class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: nums.sort() return nums[-k]
python
from typing import Any from .metaf_base import DataDescriptor class Direction(DataDescriptor): def __init__(self, name: str): super().__init__(name) def _handler(self, value): return float(value) class Speed(DataDescriptor): def __init__(self, name: str): super().__init__(name)...
python
import csv import numpy as np from scipy import signal import copy def getCsv(txtFileName='seventeenth.txt'): with open(txtFileName) as csv_file: csv_reader = csv.reader(csv_file, delimiter=' ') return list(csv_reader) def parseCharacter(character): value = 1 if character == '#' else 0 r...
python
from gi.repository import Gtk import asyncio import threading class ThreadLoop(threading.Thread): def __init__(self, loop): threading.Thread.__init__(self) self.loop = loop def run(self): print("starting Thread") self.loop.run_forever() print("Ending Thread") class C...
python
#coding: utf-8 if __name__ == '__main__': st = "data/mult/result" print st t = open("data/resultX.csv","w") t.write("Id,Tags\n") a = 0 for i in range(21): print i f = open(st+str(i)+".csv") h = f.readlines() temp = 0 print len(h) for line in h: ...
python
"""Sweep tests""" import pytest import wandb def test_create_sweep(live_mock_server, test_settings): live_mock_server.set_ctx({"resume": True}) sweep_config = { "name": "My Sweep", "method": "grid", "parameters": {"parameter1": {"values": [1, 2, 3]}}, } sweep_id = wandb.sweep(s...
python
import os import signal from abc import ABCMeta, abstractmethod from multiprocessing import Pool from django.conf import settings import pymei import solr DEFAULT_MIN_GRAM = 2 DEFAULT_MAX_GRAM = 10 class AbstractMEIConverter: __metaclass__ = ABCMeta TYPE = "cantusdata_music_notation" def __init__(self...
python
import sys import atlednolispe_settings # private_password from .base import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': atlednolispe_settings.DATABASE_NAME, 'USER': atlednolispe_settings.USER, 'PASSWORD': atlednolispe_settings.PASSWO...
python
from xml.dom.minidom import Document, parseString from xml.parsers.expat import ExpatError import pytest from sunpy.util import xml def test_xml_to_dict1(): """ should return dict of xml string. """ source_xml = "<outer>\ <inner1>one</inner1>\ <inner2>two</inner2>\ </oute...
python
"""Interface of RLAlgorithm.""" import abc class RLAlgorithm(abc.ABC): """Base class for all the algorithms. Note: If the field sampler_cls exists, it will be by Trainer.setup to initialize a sampler. """ # pylint: disable=too-few-public-methods @abc.abstractmethod def trai...
python
import data import copy, logging import numpy as np def minimize_states_and_actions_to_iterate(): logging.info("Minimizing states and actions to iterate for each engine type...") for engine_subtype in data.engine_subtypes: num_working_engines = data.engines_info[engine_subtype]['NUM_WORKING_ENGINES'] current_sta...
python
import csv, sys if (len(sys.argv) != 6): print("format: python3 join_csv.py OUT-FILE FILE-1 KEY-INDEX-1 FILE-2 KEY-INDEX-2") exit() with open(sys.argv[2], 'rb') as file: reader = csv.reader(file, delimiter=",", quotechar='"') with open(sys.argv[4]) as file2: reader2 = csv.reader(file2, delimiter=",", quot...
python
#!/usr/local/bin/python3 import boto3 from botocore.client import Config from botocore.vendored.requests.exceptions import ReadTimeout import traceback import json import sys from run_cumulus_task import run_cumulus_task import requests, zipfile, io client = boto3.client('stepfunctions', region_name = 'us-east-1') lam...
python
##################################################################### # # # SkillsFuture IBM Cloud Function Example 2 # # This example is used to show how to get data from Discovery # # and return it to Watson Assistan...
python
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
python
import requests import shutil import csv import os def writeToFile(directory, filename, filecontent): if directory: try: os.mkdir(directory) except: pass else: directory = "" with open(os.path.join(directory, filename), 'wb') as f: filecontent.raw.decode_content = True ...
python
NAMES = ["cmd_insensetive"] ANSWER = "You used `cmd_insensetive` command!"
python
# # PySNMP MIB module AC-LAG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-LAG-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:09:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
python
import torch import torch.optim as optim device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(device) import sys sys.path.append("PATH") from Models.MATCH.MATCH import MATCH from Models.MATCH.functions import (get_tensors, augment, format_output, CE_loss) from Models.metrics import (AUC...
python
# coding=utf-8 import ctypes import json import time import jsonpath import requests import progressbar import requests.packages.urllib3 headers1 = { 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0' } headers2 = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWe...
python