content
stringlengths
5
1.05M
# # Copyright (C) 2019 Guillaume Bernard <guillaume.bernard@koala-lms.org> # Copyright (C) 2020 Louis Barbier <louis.barbier41@outlook.fr> # # This file is part of Koala LMS (Learning Management system) # Koala LMS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public L...
from operator import concat import numpy as np import torch import torch.nn as nn from torch.nn import init from torch.autograd import Variable from scipy.special import factorial2 from torch.nn import functional as F from typing import Optional, Any from torch import Tensor # from torch import linalg as LA import math...
# pylint: disable=unused-variable,expression-not-assigned import pytest from expecter import expect from tests.utils import fail_msg def describe_expect(): def it_can_expect_startswith(): expect("fooBar").startswith("foo") def _fails(): expect("fooBar").startswith("Foo") wi...
import vcr import pytest import pytest_asyncio import urllib.parse as urlparse from urllib.parse import parse_qs from tap_zenefits.client import ZenefitsClient import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv("API_KEY") company_id = os.getenv("COMPANY_ID") @pytest.mark.asyncio async def t...
def unproxy(trusted_proxies): """ Decorates a WSGI application function, rewriting HTTP_X_FORWARDED_FOR and REMOTE_ADDR in the WSGI environment to present the true remote IP address to the wrapped WSGI application. trusted_proxies is a list or set of proxy IP addresses that are trusted...
r"""The script to generate submission file, please use fake_test_annotations.json file. Test submission: python generate_submission.py --data_path </data/DelftBikes/> \ --test_json <fake_test_annotations.json> --resume <checkpoint> Val submission: python generate_submission.py --data_path </data/DelftBikes/> \ --eva...
import unittest import amorf.metrics as metrics import numpy as np import torch as torch class TestError(unittest.TestCase): def test_average_correlation_coefficient(self): labels = np.array([[2, -6], [3, 5], [4, 4], [5, 3], [-6, 2]]) predicted_labels = np.array([[3, 7], [2, -5], [4, 4], [-5, 2],...
import pandas as pd #specify values for each column df = pd.DataFrame( {"a": [4,5,6], "b": [7,8,9], "c": [10,11,12]}, index= [1,2,3]) #specify values for each row df = pd.DataFrame( [[4,7,10], [5,8,11], [6,9,12]], index=[1,2,3], columns=['a','b','c']) #create dataframe with a multiIndex df ...
from django.db import models from django.utils.translation import ugettext_lazy as _ from habitat._common.models import HabitatModel from habitat._common.models import MissionDateTime from habitat._common.models import ReporterAstronaut class Intoxication(HabitatModel, MissionDateTime, ReporterAstronaut): """ ...
# -*- coding: utf-8 -*- import sys import re def extractNums(filename): textFile = str(open(filename).read()) pattern = r"(?:\+7|8)[0-9\s\-\(\)]{10,16}" phone_re = re.compile(pattern) numbers = phone_re.findall(textFile) return numbers def printExtractedNums(filename): numbers = extractNums(filename...
from django.urls import path, include from rest_framework.routers import DefaultRouter from bills import views from django.conf.urls import url router = DefaultRouter() router.register('headbill', views.HeadBillViewSet) router.register('relationshipTaxProduct', views.RelationshipTaxProductViewSet) router.register('b...
class OperationEngineException(Exception): def __init__(self, message): Exception.__init__(self, message)
# Software License Agreement (BSD License) # # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # 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 ...
import os import unittest import csv import java_sk.main import java_sk.util import re from . import TestCommon pwd = os.path.dirname(__file__) tests = os.path.join(pwd, "axioms/benchmarks") numTests = 1 class TestJava(TestCommon): def __test(self, fs, inline, unroll, adp_conc=False, arr=32): _fs = map(...
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~...
from django.urls import path from . import views app_name ='blog' urlpatterns = [ path('',views.all_blogs, name='all_blogs' ), path('about',views.about, name='about'), path('<int:blog_id>', views.detail, name='detail') ]
import redis import socket import logging import threading import multiprocessing import time import cPickle as pickle import logger as logger from ryu.lib.packet import * import consts #Process class BufferManager(multiprocessing.Process): def __init__(self,name,conn): # class BufferManager(threading.Thread): # ...
import csv r = csv.reader(open('akb48.csv')) fields = r.next() for _row in r: row = dict((k, unicode(_row[i], 'utf-8')) for i, k in enumerate(fields)) birth_year, birth_month, birth_day = [int(c) for c in row['birthday'].split('-')] file = u'''# encoding: utf-8 import datetime __all__ = [ 'info', ]...
# -*- coding:utf-8 -*- """ Automated testing of the Tracking interface, including POST requests and GET requests """ import unittest import json from base64 import b64encode from werkzeug.security import generate_password_hash from patch_tracking.app import app from patch_tracking.database import reset_db from patch_tr...
from flask import Blueprint, render_template, request from flask_login import current_user, login_required from dinamit import PANEL_TEMPLATE_DIR from dinamit.panel.helpers import redirect_with_flash from dinamit.core.models import db from pony.orm import desc from uuid import uuid4 from dinamit.panel.forms.asset impor...
n=int(input()) c=0 a=input() b=input() for i in range(n): if a[i] == b[i] == 'C': c+=1 print(c)
from . import FixtureTest class DontMergeZ16Roads(FixtureTest): def test_roads_not_merged(self): # if we're merging, then only one of these will be in tiles. if # both exist then it's more likely that no merging is happening. self.load_fixtures(['http://www.openstreetmap.org/way/89912879',...
import os, datetime, json, mock, unittest from django.conf.urls import patterns, url from django.test.utils import override_settings from rest_framework import status from rest_framework.test import APITestCase class FineSignedUrlViewTest(APITestCase): urls = 'drf_to_s3.urls' def setUp(self): from .uti...
#============================================================================= # FILE: file_include.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # MODIFIED: LittleBird # License: MIT license #============================================================================= import jedi import os import re im...
# read_dataset.py # Author : Hiroki # Modified: 2018-1-10 import cPickle import matplotlib.pyplot as pl import numpy as np def unpickle(file): with open(file, 'rb') as fo: dict = cPickle.load(fo) return dict def load_dataset(): data = unpickle('cifar-10/data_batch_1') images = [data['data'][i]...
import random import requests from lxml import html from cloudbot import hook from cloudbot.util import formatting, filesize, colors API_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Composite" # filters for SafeSearch # DEFAULT_FILTER is used unless a user appends " nsfw" to a search term, then the NSFW_...
#!/usr/bin/env python __author__ = 'machiry' """Interface or Facade for computing scripts to run. This hides the internal details of fetching the scripts, number of scripts to run etc and exposes a standard interface which can be used to fetch/update scripts to run for each tick. """ from collections import defaultdic...
from sphinx_gallery.sorting import ExampleTitleSortKey class CustomSortKey(ExampleTitleSortKey): def __call__(self, filename): return ("" if filename == "basic.py" # goes first else super().__call__(filename))
#! /usr/bin/env python3 ''' This tool reads NVD JSON feed and transcribe it to local sqlite3 database. (Will update description later.) ''' import os import sys import sqlite3 import getopt import json from distutils.version import LooseVersion DEFAULT_CVEDB_FILE = "/var/db/cvedb" EXIT_ERROR = 1 EX...
#!/usr/bin/env python3 import sys import random def gen_grid(rows=4, cols=4): ''' Generate a Schulte Grid with given cols and rows The result is a 2D array (list of rows) ''' nums = list(range(1, cols * rows + 1)) random.shuffle(nums) grid = [None] * rows for r in range(0, len(grid)):...
from .slurm_ops import * # noqa
#!/usr/bin/env python """ Copyright 2019 Jesus Villalba (Johns Hopkins University) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import sys import os from jsonargparse import ( ArgumentParser, ActionConfigFile, ActionParser, namespace_to_dict, ) import time import logging import nump...
import logging import math import numpy as np logging.basicConfig(filename='output.log', filemode='a', format='%(asctime)s - %(levelname)-4s [%(filename)s:%(lineno)d] %(message)s', level=logging.INFO) class BackTester(): def __init__(self, data, initial_period, window_size): self.data = data self._rts =...
# Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
# Code generated by `typeddictgen`. DO NOT EDIT. """V2beta1CrossVersionObjectReferenceDict generated type.""" from typing import TypedDict V2beta1CrossVersionObjectReferenceDict = TypedDict( "V2beta1CrossVersionObjectReferenceDict", { "apiVersion": str, "kind": str, "name": str, }, ...
from math import cos, sin ps2_radians = 0.559347 x2 = -0.03884 + 0.5 * cos(ps2_radians) + 0.5 * sin(ps2_radians) y2 = 4.08117 + 0.5 * sin(ps2_radians) - 0.5 * cos(ps2_radians) ps3_radians = 0.5759972 x3 = 2.5153 + 0.5 * cos(ps3_radians) - 0.5 * sin(ps3_radians) y3 = -0.448662 + 0.5 * sin(ps3_radians) + 0.5 * cos(ps3_ra...
''' 06 - Scaling fish data for clustering You are given an array samples giving measurements of fish. Each row represents an individual fish. The measurements, such as weight in grams, length in centimeters, and the percentage ratio of height to length, have very different scales. In order to cluster this data eff...
#!/usr/bin/env python3 # Imports {{{ # builtins import inspect from typing import Optional, Literal import pathlib # 3rd party import requests import aiohttp # local modules from notifeed.feeds import RemotePost from notifeed.utils import import_subclasses # }}} class NotificationChannel(object): def __init__...
from django.db import models from ace.constants import COMPANY_STATUS # Create your models here. class Company(models.Model): name = models.CharField(max_length = 100, default= "") address = models.CharField(max_length = 100, default= "") website = models.CharField(max_length = 100, default= "") profil...
import time from random import randrange import displayio from adafruit_gizmo import tft_gizmo # Create the TFT Gizmo display display = tft_gizmo.TFT_Gizmo() # You can now use the display to do whatever you want # Here we show how to draw random pixels # Create a bitmap with two colors bitmap = displayio...
from Agents.SystemAgent import SystemAgent from Domain.DTO import RecognitionResultDTO from Persistance.RecognitionBlackboard import RecognitionBlackboard from PIL import Image, UnidentifiedImageError from Services.ModelManager import ModelManager from concurrent.futures.thread import ThreadPoolExecutor from spade.beha...
#!/usr/bin/env pypy # flask imports from flask import abort from flask import flash from flask import Flask from flask import g from flask import Markup from flask import redirect from flask import render_template from flask import request from flask import session from flask import url_for # markdown imports import ...
"""empty message Revision ID: 1d09e9261d5 Revises: 40d93619b7d Create Date: 2016-12-16 11:38:41.336859 """ # revision identifiers, used by Alembic. revision = '1d09e9261d5' down_revision = '40d93619b7d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - plea...
from django.db import models import datetime import feedparser from dateutil import parser from time import mktime from django.db import transaction from dateutil.tz import * from math import * from topia.termextract import extract from constants.app_constants import * from common.stemming import * # Create your model...
import sys sys.path.append('../..') import codestudio z = codestudio.load('s1level107') def draw_circle(step): saved_speed = z.speed z.speed = 'fastest' for count in range(60): z.move_forward(step) z.turn_right(6) z.speed = saved_speed for counter in range(4,9,4): for count in rang...
foo = 1 bar = 2 baz = 3 quux = 4
from __future__ import print_function, division, absolute_import from collections import deque, namedtuple from itertools import chain from tornado.concurrent import Future import zmq from zmq import POLLOUT, POLLIN from zmq.eventloop.future import Poller from zmq.eventloop.ioloop import IOLoop # mixins for tornad...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import signal import threading from torch import nn logger = logging.getLogger(__name__) class DistributedTimeou...
from .moderation_command_base import ModerationCommandBase from .responses import WarnDecayToggledResponse from ..managers import IWarnManager from holobot.discord.sdk.actions import ReplyAction from holobot.discord.sdk.commands import CommandInterface from holobot.discord.sdk.commands.models import CommandResponse, Op...
''' File [ ctc_asr.py ] Author [ Heng-Jui Chang (NTUEE) ] Synopsis [ CTC ASR model. ] ''' import logging from re import A import numpy as np import torch from torch import nn from miniasr.model.base_asr import BaseASR from miniasr.module import RNNEncoder import torch import torch.nn as nn import...
from wa.framework.configuration.core import MetaConfiguration, RunConfiguration from wa.framework.configuration.plugin_cache import PluginCache from wa.utils.serializer import yaml from wa.utils.doc import strip_inlined_text DEFAULT_AUGMENTATIONS = ['execution_time', 'interrupts', ...
# Some of this code is taken from FITBert and removed from its class and converted to functions # There is also original code here import numpy import numpy as np from functional import seq import torch import tensorflow as tf MODEL_TYPE = "int64" def softmax(x): return x.exp() / (x.exp().sum(-1)).unsqueeze(-1)...
# 随机产生10个整数存入列表,对其进行由大到小的排序 from random import randint def sort_nums(m, n): # 随机返回一个有10个从大到小排列的元素的列表 # 参数要求:m>n且均为整数 list_nums = list() for i in range(10): list_nums.append(randint(m, n)) list_nums.sort(reverse=True) return list_nums print(sort_nums(-50, 50))
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Protection Monitoring"), "items": [ { "type": "doctype", "name": "Focus Group Discussion", }, { "type": "doctype", "name": "Key Information Interview", }, { "type": ...
print("...CITIES...") print("1-Add an element to the llist.") print("2-Remove an element from the list.") print("3-Find an element in the list.") print("4-Exit the program") list_variable = [] i = 0 chosen_option = int(input("Choose an option: ")) while (chosen_option != 4): if (chosen_option == 1): element = i...
# Apply STG on PRAD dataset import time import tensorflow as tf import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.model_selection import train_test_split ...
# Copyright (c) 2021, Djaodjin Inc. # 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 conditions and t...
"""Utils module.""" import inspect import time from datetime import datetime from multiprocessing.managers import SyncManager, NamespaceProxy import psutil def shallow_sleep(sleep_time=0.1): time.sleep(sleep_time) def format_ts(ts, time_format='%a %b %d %H:%M:%S %Y'): return datetime.fromtimestamp(ts).str...
#!/usr/bin/python3 import webbrowser from nlp.universal_dependencies import ParsedUniversalDependencies from user_interface.user_interaction_service_base import UserInteractionServiceBase from .skill import SkillInput, Skill class SendEmailSkill(Skill): """Lets the assistant send emails for the user.""" def...
from django.conf.urls.defaults import * #from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() #from datetime import datetime urlpatterns = patterns('', # Example: # (r'^m2m/', include('m2m.foo.urls')), #(r'^api/v1/', in...
# -*- coding: utf-8 -*- """ Editor: Zhao Xinlu School: BUPT Date: 2018-03-27 算法思想:最小路径和--动态规划 """ class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ rows = len(grid) cols = len(grid[0]) dp = [[0] * cols for i in...
# Channel specifications #=============================================================================== import numpy as np #------------------------------------------------------------------------------- # Fast Na current # From Traub et al. 1991 J Neurophys #---------------------------------------------------------...
import os import boto3 import pytest from moto import mock_s3 from code.handle import lambda_handler @pytest.fixture(scope='function') def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ['AWS_ACCESS_KEY_ID'] = 'testing' os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing' os.environ[...
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Chao Yang) # Copyright (c) 2021 Jinsong Pan # # 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/LIC...
import asyncio import json import discord import datetime import utils.utils as utils import utils.commands as cmds import utils.request_manager as requests import utils.file_manager as files empty = discord.Embed.Empty all_control_emoji = ["⏮", "⬅️", "➡️", "⏭"] confirm_control_emoji = ["✅","❌"] async def help(ctx, p...
import torch from torch.utils import data import sys from sklearn.utils import shuffle import numpy as np import argparse import matplotlib.pyplot as plt class UserSet(data.Dataset): def __init__(self, path, tsplit, idim=100, seed=0, Nsongs=180198, pc_split=0.1, tag2vector_path=""): """ path : str path + fn...
# author: Lesley Miller # date: 2020/02/08 # # takes in a file path to the dataset and # peforms train_test_split to make train, validation and test sets # # '''This script takes in a file path to a dataset and performs train_test_split to obtain train, validation and test sets. It then writes those datasets to c...
#!/usr/bin/env python # # demultiplex_undetermined_fastq.py: demultiplex undetermined Illumina reads # Copyright (C) University of Manchester 2013-2019 Peter Briggs # ######################################################################## # # demultiplex_undetermined_fastq.py # ################################...
from rich._palettes import STANDARD_PALETTE from rich.table import Table def test_rich_cast(): table = STANDARD_PALETTE.__rich__() assert isinstance(table, Table) assert table.row_count == 16
import unittest from bottle import HTTPResponse, request from datetime import timedelta from mock import Mock from biicode.server.rest.bottle_plugins.dos_blocker_bottle_plugin import DOSBlockerBottlePlugin import time from biicode.test.fake_mem_store import FakeMemStore from biicode.common.utils.bii_logging import logg...
#import time import datetime from bs4 import BeautifulSoup import pandas as pd #import selenium from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By #from selenium.common.except...
"""#### Record Module collecting functions necessary to validate data from application form. Each of them raises `ValueError` when set value is not correct. Values are supposed to be stored in class `Record` which extends dictionary and maps proper validation function with expected database key. All database fields ar...
from itertools import count __all__ = ['get_packer'] from rb2py.error import * import rb2py PACKERS = {} def get_packer(format_char): return PACKERS[format_char]() class Packer: def __init__(self, format_char, byte_size): self.format_char = format_char self.byte_size = byte_size se...
import numpy as np from mpi4py import MPI from ngsolve import H1, InnerProduct, dx, grad, ngsglobals from .lanczos import Lanczos from .mesh import construct_2d_square_mesh, construct_3d_cube_mesh from .mpi_kron import as_matrix from .multigrid import MeshHierarchy, MultiGrid, Smoother from .ngsolve_helper import BilF...
import bluelet def echoer(conn): while True: data = yield conn.recv(1024) if not data: break print "CLIENT:", data yield conn.sendall(data) bluelet.run( bluelet.server('127.0.0.1', 4915, echoer) )
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import mock from dashboard.common import namespaced_stored_object from dashboard.common import testing_common from dashboard.pinpoint.models.change import c...
import cv2 as cv import numpy as np def find_slope(region,ker): # reg = np.array(region, dtype=np.float64) kern = np.array(ker, dtype=np.float64) divs = kern.shape[0] reg = np.ndarray([divs,region.shape[0],region.shape[1]], dtype=np.float64) reg[:] = np.array(region, dtype=np.float64) slope_ma...
from os.path import join # data_set_folder = "/media/riot/5127cd94-5f74-45d1-b6e9-d7aeb19bb1d9/versions_of_projects/scriptRepo_DataSets/" data_set_folder = "/Users/rohuntripathi/temp/Indic-Script-Recognition-RnnLib/DataSets/" offline_word_ban_data_set = join(data_set_folder, "OfflineWordLevelStrokesRetrieved/strokesB...
import re from basic_http.data_structures.header import HttpHeader def parse_response_line(response_line: str): tokens = re.findall('[^ ]+', response_line) http_protocol, status_code, status = tokens[: 2] + [' '.join(tokens[2:])] return { 'http_protocol': http_protocol, 'status_code': int...
""" Instruction to use meshed_memory_transformer (https://arxiv.org/abs/1912.08226) pip install git+https://github.com/ruotianluo/meshed-memory-transformer.git Note: Currently m2transformer is not performing as well as original transformer. Not sure why? Still investigating. """ from __future__ import absolute_impor...
#!/usr/bin/env python """Setup script for the package.""" import logging import os import sys from typing import Optional import setuptools PACKAGE_NAME = "realtime" MINIMUM_PYTHON_VERSION = "3.7" def check_python_version() -> None: """Exit when the Python version is too low.""" if sys.version < MINIMUM_P...
# Copyright 2022 Token Flow Insights # # 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 i...
import pygame, re class InputBox(): def __init__(self, x, y): self.font = pygame.font.Font(None, 24) self.inputBox = pygame.Rect(x, y, 75, 25) self.colourInactive = pygame.Color('lightskyblue3') self.colourActive = pygame.Color('dodgerblue2') self.colour = self.colou...
import unittest from pyalink.alink import * from pyalink.alink.udf.user_defined_function import UserDefinedFunction class TestPyAlinkUdfUdtf(unittest.TestCase): def setUp(self) -> None: class PlusOne(UserDefinedFunction): def eval(self, x): return x + 10 pass ...
''' optuna LightGBM integration https://github.com/optuna/optuna/blob/8ef763023e5ad858284566b3de2fa5eca7fd19b2/optuna/integration/_lightgbm_tuner/optimize.py Modified ''' import abc import copy import json import os import pickle import time from typing import Any from typing import Callable from typing import Dict f...
# This an autogenerated file # Represents a key/value entry # Generated with Attribute from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.attribute import AttributeBlueprint from typing import Dict class Attribute(Entity): """ Represents a k...
import cv2 import imutils import numpy as np from frigate.config import MotionConfig class MotionDetector: def __init__(self, frame_shape, config: MotionConfig): self.config = config self.frame_shape = frame_shape self.resize_factor = frame_shape[0] / config.frame_height self.motio...
# https://open.kattis.com/problems/integerlists from collections import deque def process(p, n, l): if sum(1 for c in p if c == 'D') > n: return 'error' d = deque(l) is_rev = False for c in p: if c == 'R': is_rev = not is_rev elif is_rev: d.pop() ...
account_age_checker = lambda x: x < (now - discord_creation_date).days join_age_checker = lambda ctx, x: x < (now - ctx.guild.created_at).days import datetime now = datetime.datetime.now() discord_creation_date = datetime.datetime(2015, 5, 13)
#!/usr/bin/env python3 import os import re import sys import time import shutil from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler, DirCreatedEvent def main(): if len(sys.argv) != 4: print("Usage: python3 {} <BASEPATH> <SOURCE_SUBDIRECTORY> <DESTINATION_SUBDIRECTORY...
import turtle import math # table of specific heat capacities [in Joules per kilogram Kelvin] materials = { "iron": "440", "aluminium": "887", "copper": "385", "steel": "452", "gold": "129", "mercury": "140", "copper": "385", "aluminum": "902", "water": "4197", "air": "1000", ...
from config import WIDTH, HEIGHT from snake import Snake from apple import Apple from curses import KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT from astar import find_path class Game(object): def __init__(self, window): self.snake = Snake() self.apple = Apple() self.window = window self.g...
#Creates new dictionary with mapped chess symbols def _symbols_dict(symbols): return dict(zip(symbols, range(len(symbols)))) #Creates 5 new "symbols dicts" for different piece combinations _COLOR_PIECE_SYMBOLS = _symbols_dict(['p', 'n', 'b', 'r', 'q', 'k', 'P', 'N', 'B', 'R', 'Q', 'K', None]) _COLOR_PIECE_SYMBOLS_...
import json # create dic from dispatch-entry string def get_user_dic(hpc_infos, partitions_path, unicore_path): dic = {} with open(unicore_path) as f: unicore = json.load(f) for i in hpc_infos: infos = i.lower().split(',') # infos: [account, system[_partition], project, email] ...
""" Copyright 2017 NREL 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 un...
from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "codemirror/index.html" def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['curren...
#!python3.6 # # Kingdom Come Deliverance - inventory sorting generator v1.1 # # Copyright 2018 OVNI # 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 limitati...
import logging import time import typing from io import BytesIO from usb import USBError from pymobiledevice3.irecv import IRecv, Mode from pymobiledevice3.lockdown import LockdownClient from pymobiledevice3.restore.device import Device from pymobiledevice3.restore.ipsw.ipsw import IPSW from pymobiledevice3.restore.t...
from django.contrib.auth.models import User from main import models def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.META.get("REMOTE_ADDR") return ip def log_analytic(req...
from __future__ import absolute_import, division, unicode_literals import numpy as np from matplotlib.collections import LineCollection, PatchCollection from matplotlib.patches import Rectangle from ...core.options import abbreviated_exception from ..mixins import GeomMixin from .element import ColorbarPlot from .pa...