content
stringlengths
5
1.05M
""" This is the script for saving the hdf5 file containing the experiment data. """ import h5py from pyccapt.control_tools import loggi from pyccapt.control_tools import variables def hdf_creator_oxcart(time_counter, time_ex_s, time_ex_m, time_ex_h): # save hdf5 file logger_creator = loggi.logger_creator('h...
def run(): r.setpos(0,0,0) r.conf_set('enable_stuck', 1) r.speed(40) @_on('motion:stuck') def _(): _goto('after_stuck', ref='main') r.goto(-1000, 0, -1) _label('after_stuck') r.setpos(x=155/2-1500) r.goto(0,0)
def main(): N, S = input().split() N = int(N) result = 0 for i in range(N): a, b = 0, 0 for c in S[i:]: if c == 'A': a += 1 elif c == 'T': a -= 1 elif c == 'C': b += 1 elif c == 'G': ...
import datetime from pandas import Timestamp, DatetimeIndex, DataFrame from backtrader.tradingcal import TradingCalendarBase from backtrader.utils import tzparse from backtrader.utils.py3 import string_types class TradingCalendarsTradingCalendar(TradingCalendarBase): params = ( ('calendar', None), ...
import itertools import logging import os import time from urllib.parse import urlparse from urllib.request import quote import requests from bs4 import BeautifulSoup from requests.sessions import TooManyRedirects logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) class AccountHandler: ...
import requests as rs from .makerequest import makeRequest make = makeRequest("token") def checkAvailableUser(username): """This function will return whether the given username for registration is available for new registration""" resp = rs.get(make.API + "/register/search/?username={}".format(username)...
#!/usr/bin/env python # # Exploit Title: nginx heap corruption # Date: 08/26/2010 # Author: aaron conole <apconole@yahoo.com> # Software Link: http://nginx.org/download/nginx-0.6.38.tar.gz # Version: <= 0.6.38, <= 0.7.61 # Tested on: BT4R1 running nginx 0.6.38 locally # CVE: 2009-2629 # # note: this was written and tes...
from django.shortcuts import render, get_object_or_404,redirect from django.views.generic import TemplateView, ListView from cart.forms import CartAddProductForm from .models import Category, Product from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib.auth.form...
import boto3 from auditlog.writer.writer import kinesis_writer kinesis_writer.set_client(boto3.client('kinesis', endpoint_url='http://localhost:4566/'))
# code:utf-8 ''' @author: memect @date: 16/04/2018 @mail: liukun@memect.co @description: 获取上市公司:基本信息,利润表,资产负债表,现金流量表 python3示例代码 ''' import requests import json import config HEADERS = config.HEADERS#{'Authorization': APPCODE, } class CompanyInfoAPI: def __init__(self, field,eng_name): """field in ["资产...
with open('input2.txt', 'r') as file: data = file.read().split('\n') v = 0 iv = 0 for line in data: if line.count(' ') != 2: continue r, l, p = line.split(' ') min_, max_ = map(int, r.split('-')) min_ -= 1 max_ -= 1 l = l.replace(':', '') if (len(p) > max_ and ((p[min_] == l...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 def joe_say(text): template = r''' =-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-= // {message} \\ =-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-= \\ \\ ---------------- /...
import numpy as np from piece import Piece import time from scipy.ndimage import convolve class Board: def __init__(self, size = 20, player_colors = [1,2,3,4]): self.size = size self.board = np.zeros((size,size), dtype = int) self.start_squares = [[0,0], [0, size-1], [size-1, 0], [size-1, size-1]] self.playe...
""" Cartesian products of Posets AUTHORS: - Daniel Krenn (2015) """ #***************************************************************************** # Copyright (C) 2015 Daniel Krenn <dev@danielkrenn.at> # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foun...
#!/usr/bin/env python3 import warnings import pytest import rocks @pytest.mark.parametrize("id_", ["Fortuna", "doesnotexist", "Ceres"]) def test_get_ssoCard(id_): warnings.filterwarnings("ignore", "UserWarning") card = rocks.ssodnet.get_ssocard(id_) if id_ == "Ceres": assert isinstance(card, dic...
import logging from typing import Optional, Dict, Any from slack_sdk.web.internal_utils import ( _parse_web_class_objects, get_user_agent, convert_bool_to_0_or_1, ) from .webhook_response import WebhookResponse def _build_body(original_body: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: if o...
from unittest.mock import Mock import pytest from atst.domain.permission_sets import PermissionSets from atst.models import Permissions from atst.utils.context_processors import ( get_resources_from_context, user_can_view, portfolio as portfolio_context, ) from tests.factories import * def test_get_res...
#!/usr/bin/env python # Copyright (c) 2013-2015, Rethink Robotics # 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, # ...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\world\lot_tuning.py # Compiled at: 2020-04-27 21:48:35 # Size of source mod 2**32: 27675 bytes impor...
# -*- coding: utf-8 -*- import requests from pydeform.auth import ( get_session_http_auth_header, get_token_http_auth_header ) from pydeform.resources import ( CollectionListResource, CollectionOneResource, CurrentProjectInfoResource, DocumentListResource, DocumentOneResource, NonAuthUs...
from typing import List from .action_postprocessor import ActionPostprocessor from ..actions import Action class PostprocessorCombiner(ActionPostprocessor): """ Combines multiple other postprocessors """ def __init__(self, postprocessors: List[ActionPostprocessor]): self.postprocessors = pos...
# Minimum Height Triangle # Find the smallest height of a triangle preserving the given constraints. # # https://www.hackerrank.com/challenges/lowest-triangle/problem # base, area = map(int, input().split()) height = (2 * area - 1) // base + 1 print(height)
#!/usr/bin/env python # # This is the library for Grove Base Hat. # # Helper Classes # ''' ## License The MIT License (MIT) Grove Base Hat for the Raspberry Pi, used to connect grove sensors. Copyright (C) 2018 Seeed Technology Co.,Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy ...
#!/usr/bin/python from axis_fifo import AXIS_FIFO from devices import fifo_devices import struct def writeToDDS(dds_char_dev, address, data): data_bytes = struct.pack('<I', data) words = [] #instruction and D16-D31 words.append(data_bytes[2]) words.append(data_bytes[3]) words.append(struct.pack('<B', add...
import pandas import os from desafio_iafront.data.saving import save_partitioned def save_clustered_data(dataset:pandas.DataFrame, saida:str): date_first = os.path.join(saida, 'date_first') cluster_first = os.path.join(saida, 'cluster_first') save_partitioned(dataset, date_first, ['data', 'hora', 'clust...
import math import numpy as np # Converts URx's rotation vector into a rotation matrix # # I did not derive this nor do I fully understand the maths behind this :0 # I took it from: https://dof.robotiq.com/discussion/1648/around-which-axes-are-the-rotation-vector-angles-defined def convert_tool_pose_to_transformation...
""" Create a python file that collects the necessary information and prints json: ```python #! /usr/bin/env python from exdoc import doc import json from project import User print json.dumps({ 'user': doc(User), }) ``` And then use its output: ```console ./collect.py | j2 --format=json README.md.j2 ``` """ fr...
"""Wrap the sklearn.linear_model ridge classification model.""" from model_base import ClassificationModelBase from sklearn.linear_model import RidgeClassifier class RidgeClassifierModel(ClassificationModelBase): def __init__(self, model_conf): model = RidgeClassifier() super().__init__(model_con...
# Copyright 2015 Vladimir Rutsky <vladimir@rutsky.org> # # 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...
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class CopyDriveFileReq(object): file_token: str = attr.ib( default="", metadata={"...
from time import sleep import random from os import system, name import urllib.request import json item = [] money = 0 print(''' _____ ____ ____ __ ___ ______ ____ ____ ____ _ / ___/| \ / | / ] / _] | || \ / || || | ( \_ | o ) o | / / / [_ | ...
from unittest.mock import patch from pytest import mark @mark.parametrize('return_code, pretend, world', [(b'0', False, False), (b'0', True, False), (b'0', True, True), (b'1', False, False), (b'1', False, True), (b'1'...
from contextlib import contextmanager from inspect import currentframe, getargvalues import plyvel @contextmanager def open_leveldb(name, create_if_missing=False, error_if_exists=False, paranoid_checks=None, write_buffer_size=None, ...
# -*- coding: utf-8 -*- """ Microsoft-Windows-OneX GUID : ab0d8ef9-866d-4d39-b83f-453f3b8f6325 """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid from etl.parser...
import os import numpy as np import pandas as pd def find_emb_dim(ratio, max_emb, data): dim = round(np.unique(data).shape[0] * ratio) if dim > max_emb: return max_emb else: return dim def post_process(pred): # simple post processing if pred > 1: return 1 elif pred < 0:...
from torch import Tensor import torch from src.schema import Metric def get_metric(query_set: Tensor, support_set: Tensor, metric: Metric) -> Tensor: """ run metrics with name Args: query_set: the train/input feature space from encoder support_set: the support set feature space from encod...
import unittest from pympcam.coralManager import CoralManager class TestCoralManagerMethods(unittest.TestCase): def setUp(self) -> None: self.coral = CoralManager() return super().setUp() def test_on(self): self.assertTrue(self.coral.turnOn()) def test_off(self): self.cor...
import pytest import yaml import launch import launch.cli import launch.config import launch.util import test_util.aws def test_aws_cf_simple(check_cli_success, aws_cf_config_path): """Test that required parameters are consumed and appropriate output is generated """ info, desc = check_cli_success(aws_cf...
""" This package contains utilities and extensions for the Astropy sphinx documentation. In particular, the `astropy.sphinx.conf` should be imported by the sphinx ``conf.py`` file for affiliated packages that wish to make use of the Astropy documentation format. Note that some sphinx extensions which are bundled as-is...
# -*- coding: utf-8 -*- from scrapy.spiders import Spider from scrapy.selector import Selector from gorden_crawler.items import BaseItem, ImageItem, SkuItem, Color from scrapy import Request from scrapy_redis.spiders import RedisSpider from gorden_crawler.spiders.shiji_base import BaseSpider import logging import re ...
"""This defines a quick I/O framework for importing from Mathematica """ from __future__ import print_function import os mathematica_type_importers = {} def mathematica_default_import(i_dict): return i_dict["ImportValue"] def mathematica_register_type_importer(t, f): mathematica_type_importers[t] = f mathemat...
from flask import Flask, request, render_template import mysql.connector app = Flask(__name__) connection = mysql.connector.connect(host='database-maui.ct7yl5rjhgtx.us-east-1.rds.amazonaws.com', database='mauidb', user='admin', ...
''' Implementation of the nDCG metric for ranking evaluation. Balazs Kovacs, 2017 ''' import numpy as np def dcg(rel_scores, k=None, use_exp=False): ''' Computes the DCG metric as defined in https://en.wikipedia.org/wiki/Discounted_cumulative_gain :param rel_scores: List of relevance scores. :param...
import math import numpy as np from sklearn.metrics import pairwise_distances from scipy.spatial import distance from scripts.ssc.persistence_pairings_visualization.Pseudo_AlphaBetaWitnessComplex import \ count_pairings from scripts.ssc.persistence_pairings_visualization.utils_definitions import make_plot from sr...
#!/usr/bin/env python3 # Copyright (C) Alibaba Group Holding Limited. """ S3D/S3DG branch. """ import torch import torch.nn as nn from models.base.base_blocks import ( BRANCH_REGISTRY, InceptionBaseConv3D ) class InceptionBlock3D(nn.Module): """ Element constructing the S3D/S3DG. See models/base/b...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. #...
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, val): self.items.append(val) def pop(self): if self.is_empty(): return None return self.items.pop() def peek(self): ...
#coding=utf8 from asdl.sql.parser.parser_base import Parser from asdl.asdl import ASDLGrammar from asdl.asdl_ast import RealizedField, AbstractSyntaxTree class ParserV0(Parser): """ In this version, we eliminate all cardinality ? and restrict that * must have at least one item """ def parse_select(self, se...
from __future__ import unicode_literals from django.test import override_settings from mayan.apps.rest_api.tests.base import BaseAPITestCase from ..classes import Template TEST_TEMPLATE_RESULT = '<div' class CommonAPITestCase(BaseAPITestCase): auto_login_user = False def _request_content_type_list_api_vi...
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: May 18, 2015 # Question: 054-Spiral-Matrix # Link: https://leetcode.com/problems/spiral-matrix/ # =======================================================================...
#!/usr/bin/env python3 """ Normalize """ import numpy as np def normalization_constants(X): """ normalizing """ m = X.shape[0] mean = np.sum(X / m, axis=0) std = np.sqrt(np.sum(((X - mean) ** 2), axis=0) / m) return mean, std
from marshmallow import Schema, fields, validate class AuthSchema(Schema): firstname = fields.Str( required=True, error_messages={"required": "Firstname is required."}, validate=validate.Length(min=2, max=32), ) lastname = fields.Str( required=True, error_messages={...
import nthmc, ftr import tensorflow as tf import tensorflow.keras as tk import math, os, unittest import sys sys.path.append("../lib") import field, group class TestGenericStoutSmear(unittest.TestCase): """ Examples: def setUp(self): print('setUp') def tearDown(self): print('tearDown') ...
import json def build_payload(intent, params={}, contexts=[], action='test_action', query='test query'): return json.dumps({ "id": "8ea2d357-10c0-40d1-b1dc-e109cd714f67", "timestamp": "2017-06-26T22:43:14.935Z", "lang": "en", "result": { "action": action, "a...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import recurrent, workspace from caffe2.python.model_helper import ModelHelper from hypothesis import given import caffe2.python.hypothesis_test_util a...
# import packages import pandas as pd import numpy as np # to plot within notebook import matplotlib matplotlib.use('GTK3Agg') import matplotlib.pyplot as plt # importing required libraries from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, Dropout, LST...
import os import argparse import pandas as pd import numpy as np def getStats(x): """ Takes an input numpy array and calcualtes the mean, standard deviation, median, min and max values of the array Input: x: numpy array Output: Reutnrs the mean, std.dev., median, min and max ...
# # django-audiofield License # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initial Developer of the Original C...
start_time = time.time() # Training Set cd '/mnt/data/shamir/Annotation data set/Original Images/Good Images/Positive Counts/Training Set' ## Decode JSON file and store all the corner coordinates of ground truth in an array json_data = open('T4_r3p6') # list[z][:-4] data = json.load(json_data) brx, tlx...
from setuptools import find_packages, setup with open('README.md', 'r') as f: long_description = f.read() setup( name='wids-datathon-2020', version='0.1.5', license='MIT', author='Iain Wong', author_email='iainwong@outlook.com', description='The challenge is to create a model that uses dat...
# !/usr/bin/env python # -*- coding: utf-8 -*- """ @Reference : https://github.com/JusperLee/UtterancePIT-Speech-Separation/blob/master/model.py """ import warnings warnings.filterwarnings('ignore') import torch import torch.nn as nn import numpy as np from torch.nn.utils.rnn import pad_packed_sequence class PITNet...
__author__ = 'Todd.Hay' # ------------------------------------------------------------------------------- # Name: HaulSelection.py # Purpose: # # Author: Todd.Hay # Email: Todd.Hay@noaa.gov # # Created: Jan 11, 2016 # License: MIT #------------------------------------------------------------...
default_app_config = 'healthz.apps.HealthzConfig'
# use consecutive time steps, excluding actions as the input # sample trajs as a semi-circle to the goal import gym from stable_baselines.gail import ExpertDataset, generate_expert_traj from stable_baselines.gail.dataset.dataset import ExpertDatasetConsecutive, ExpertDatasetConsecutiveManual import numpy as np from ...
""" File to contain constants """ PACKAGE_LOGGER_NAME = 'service_framework'
""" This program encodes/decodes text given to it as an input. It takes three arguments as an input: 1. Action: Encode/Decode 1. Text to be encoded/decoded 2. Shift value (The value by which the alphabets will be shifted) """ from caesar_art import logo from time import perf_counter from time import process_time # Ti...
# REF: https://github.com/hubutui/DiceLoss-PyTorch/blob/master/loss.py import torch import torch.nn as nn import torch.nn.functional as F from .utils import weight_reduce_loss from ..builder import LOSSES def _make_one_hot(gt, num_classes, ignore=0): """ :param label: [N, *], values in [0,num_classes) :...
from collections import OrderedDict def suggestion_list(inp, options): """ Given an invalid input string and a list of valid options, returns a filtered list of valid options sorted based on their similarity with the input. """ options_by_distance = OrderedDict() input_threshold = len(inp) /...
import re import io import json import asyncio from urllib import request from functools import partial from datetime import datetime from collections import OrderedDict import discord from discord.ext import commands import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter from .utils import ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/protobuf/internal/file_options_test.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf ...
print("Enter the number of rows: ") rows = int(input()) i = rows count=0 flag = 1 while i >= 1: j = rows while j > i: # display space print(' ', end=' ') j -= 1 k = 1 while k <= i: print(flag, end=' ') k += 1 flag+=1 count+=1 print() i -=...
# Program for Trie Insert and Search # Trie node class TrieNode: def __init__(self): self.children = [None]*26 self.isEndOfWord = False # Trie Class class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def toIndex(self, ch): return ord(ch)-ord('a') # Functi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Command line script to make a simple PDF plot of gcc vs datetime using the roistats file for a particular site and ROI. """ from __future__ import absolute_import from __future__ import print_function import argparse import os import pandas as pd from matplotlib im...
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set >>> fruit set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False
from nltk.corpus import wordnet as wn class WordnetHandler(): def get_synonyms(self, word): #print('in syns', word) s = wn.synsets(word) syns = [str(syn)[8:-7] for syn in s] unique_syns = list(set(syns)) return unique_syns def get_hypernyms(self, word): """ ...
import numpy as np class Conv1dObservation(object): def __init__(self, non_lidar_obs, lidar_obs): """ :type non_lidar_obs: np.ndarray :type lidar_obs: np.ndarray """ assert len(non_lidar_obs.shape) == 1 assert len(lidar_obs.shape) == 2 self._non_lidar_obs =...
#!/usr/bin/env python3 import collections import datetime import itertools import operator import sys records = [(datetime.datetime.strptime(r[0], '[%Y-%m-%d %H:%M'), r[1]) for r in map(lambda line: line.rstrip().split(sep='] '), sys.stdin)] # Sort by time to assign each event to a guard. records.sort(key...
""" This file contains the implementation of the class Player. Author: Alejandro Mujica (aledrums@gmail.com) Date: 07/21/20 """ from src.states.entities import player as player_states from src.entity import Entity import settings class Player(Entity): def __init__(self, x, y, game_level): super(Player, ...
''' Package definition for 'soane.items'. ''' from soane.items.book import Book from soane.items.note import Note
"""Example ox_herd plugins used by our app """ import requests # Import base class so we can create plugins from ox_herd.core.plugins import base class CheckWeb(base.OxPlugTask): """Class to check on a web site. This is meanly meant to serve as an example of a minimal plugin. All we do is implement th...
import habitat from habitat.sims.habitat_simulator.actions import HabitatSimActions import cv2 import envs.spring_env import numpy as np from PIL import Image from habitat_sim.utils.common import d3_40_colors_rgb import os, glob import json import argparse import quaternion from scipy.spatial.transform import Rotation...
import numpy as np import cv2 def eval_poly(vec, poly): """ Evaluates value of a polynomial at a given point :param vec: The given point :float :param poly: The polynomial :ndarray[3,] :return: value of polynomial at given point :float """ return vec ** 2 * poly[0] + vec * poly[1] + poly[2...
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # x''(t) + x(t)) = 0 # convert second order ode to first order system # y'(t) = x(t) # dydt(t) = -y'(t) def func(y_vec, t): y, ydot = y_vec dydt = [ydot, -y] return dydt y0 = [1, 0.0] t = np.linspace(0, 10, 101) s...
"""Imports for Python API. This file is MACHINE GENERATED! Do not edit. Generated by: tensorflow/tools/api/generator/create_python_api.py script. """ from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.framework.summary_pb2 import SummaryDescription from tensorflow.core.util.event_pb2 import...
class Tree: def __init__(self) -> None: self.root:Node = None self.nodes = {} @classmethod def build(cls, edges, root_value, m): tree = Tree() for key, (i, j) in enumerate(edges): if key == m: break if not tree.nodes.get(i): ...
from pynput import keyboard def on_press(key): print("INPUT:", key) with keyboard.Listener(on_press=on_press) as listener: listener.join()
import os import cv2 import glob import numpy as np import pandas as pd def create_video_summary(model, frames, video_as_features, time_length): scores = model.predict(video_as_features) scores_median = np.median(scores) impt_frames = np.argwhere(scores, scores > scores_median) return create_video_from_frames(...
from elizabeth.core.interdata import ROMANIZATION_ALPHABETS def romanize(func): """Cyrillic letter to latin converter. Romanization of the Russian alphabet is the process of transliterating the Russian language from the Cyrillic script into the Latin alphabet. .. note:: At this moment it's work only ...
import argparse import sys import os import numpy as np import pandas as pd import glob import pdb parser = argparse.ArgumentParser(description = '''Fuse the MSAs for interacting chains by writing gaps where the other chain should be.''') parser.add_argument('--a3m1', nargs=1, type= str, default=sys.stdin, help = 'Pa...
from Employee import * e1 = Employee("seasonfif", 27) e2 = Employee("season", 20) e1.name = "qqq" setattr(e1, "sex", "female") getattr(e1, "sex") e1.displayEmployee() print Employee.empCount
import matplotlib.pyplot as plt import numpy as np import random as r import math from sim.plot import plot, print_particle_error AUTORUN = False robot_start = 7 num_particles = 20 distance = 40 poles = [10, 15, 17, 19, 30, 39] ### START STUDENT CODE class Robot: def __init__(self, pos): self.pos = pos ...
# coding=utf-8 # Copyright 2020 The Real-World RL Suite 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...
# shop/models.py # Django modules from django.db import models # Create your models here. # Model: Slider class Slider(models.Model): slider_title = models.CharField(max_length=100) slider_sub_title = models.CharField(max_length=150) slider_description = models.TextField() slider_image = models.ImageField(upload...
from app.core.db import db from models import * from flask import Blueprint, request, session, render_template hotel_views = Blueprint('hotel', __name__, template_folder='../../templates', static_folder='../../static') @hotel_views.route('/hotel') def hotel(): hotel = Hotel.query....
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-08-04 15:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion def populate_channels_and_boards(apps, schema_editor): from django.db.models import OuterRef, Subquery, F Organization = a...
""" Service Lookup ============== Use DNS SRV records to discover services by name and protocol. """ import collections import logging import socket from dns import rdatatype, resolver __version__ = '2.0.0' LOGGER = logging.getLogger(__name__) SRV = collections.namedtuple( 'SRV', ['host', 'port', 'priority', ...
from django.shortcuts import render, redirect, HttpResponse from django.http import JsonResponse from django.contrib import messages import datetime import json from django.core import serializers from django.contrib.auth import login, authenticate, logout from django.contrib.auth.models import User, Group from django...
import os, random, time from jennie.ubuntu.nginxfiles import * from jennie.ubuntu.uwsgifiles import * def deploy_django(port, domain): dir_arr = os.getcwd().split("/") main_dir = "" for i in range(0, len(dir_arr)-1): main_dir += dir_arr[i] + "/" main_dir = main_dir[:-1] project_dir = dir_ar...
# coding=utf-8 import os import filecmp import itertools class fdups: def __init__(self, list_of_dirs = []): self.exclude = {'Thumbs.db'} self.set(list_of_dirs) def set(self, list_of_dirs): self.list_of_dirs = list_of_dirs self.files = [] self.filecount...
from unittest import mock import pytest from indieweb.models import TToken @pytest.mark.django_db class TestIndieAuthExchangeToken: @pytest.fixture def target(self): return "/a/indieauth/token" @pytest.fixture def post_data(self, auth_token, client_id): return { "grant_ty...