content
stringlengths
5
1.05M
# Copyright 2020 Google LLC. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
""" Hooks for customizing login with social providers https://django-allauth.readthedocs.io/en/latest/advanced.html """ from allauth.account.signals import user_logged_in from common.helpers.front_end import section_url from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.account.adapter i...
#!/usr/bin/env python # coding: latin-1 """ CUBA example with delays. """ import sys, time, os from brian2 import * standalone = int(sys.argv[-2]) n_threads = int(sys.argv[-1]) path = 'data_cuba_%d' %n_threads if standalone == 1: set_device('cpp_standalone') brian_prefs.codegen.cpp_standalone.openmp_t...
from typing import Tuple, cast import reapy_boost from reapy_boost import reascript_api as RPR from reapy_boost.core import ReapyObject class Source(ReapyObject): def __init__(self, id: str) -> None: self.id = id def __eq__(self, other: object) -> bool: return isinstance(other, Source) and s...
from django.shortcuts import get_object_or_404 from mayan.apps.documents.models.document_models import Document from mayan.apps.rest_api.api_view_mixins import ExternalObjectAPIViewMixin from mayan.apps.rest_api import generics from ..permissions import ( permission_workflow_instance_transition, permission_wo...
#!/usr/bin/python ############################################################################### # # remote.py # # <tbd>. # # Resources: # <list> # # January 12, 2019 # ############################################################################### import time ###########################################...
#!/usr/bin/python # -*- coding:utf-8 -*- from CNN_Datasets.R_A.datasets.CWRU import CWRU from CNN_Datasets.R_A.datasets.CWRUFFT import CWRUFFT from CNN_Datasets.R_A.datasets.CWRUCWT import CWRUCWT from CNN_Datasets.R_A.datasets.CWRUSTFT import CWRUSTFT from CNN_Datasets.R_A.datasets.CWRUSlice import CWRUSlice from CNN...
# -*- coding: utf-8 -*- # Copyright (C) 2020 Ross Scroggs All Rights Reserved. # # 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...
# -*- coding: utf-8 -*- """056 - Maior e Menor da Sequência Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1-RmYLOW85mV31Tpi2dQ285vIwO3wR3tL """ pesos = [ ] for p in range(0,5): peso = float(input('Digite o peso: ')) pesos.append(peso) print('...
import sys sys.path.append('..') import json import os from datetime import datetime from typing import Dict, List import platform import warnings warnings.filterwarnings("ignore") import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Optimizer import numpy as np import fire from ...
from libs import engineLib as engine ##Done with the includes class Zone(object):##this is all rooms and areas the player will be in. It has add/remove item functions and search/examine functions def __init__(self, name, references, description, contents, exits, bLocked, keyItem, blockedText, unlockText, bDe...
from setuptools import setup setup( name = 'evohomeclient', version = '0.2.8', description = 'Python client for connecting to the Evohome webservice', url = 'https://github.com/watchforstock/evohome-client/', download_url = 'https://github.com/watchforstock/evohome-client/tarball/0.2.8', author = 'Andrew Stock',...
import numpy as np def get_sorted_top_k(array, top_k=1, axis=-1, reverse=False): """ 多维数组排序 Args: array: 多维数组 top_k: 取数 axis: 轴维度 reverse: 是否倒序 Returns: top_sorted_scores: 值 top_sorted_indexes: 位置 """ if reverse: # argpartition分区排序,在给定轴上找...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and Contributors # See license.txt import frappe, unittest from frappe.contacts.doctype.address.address import get_address_display class TestAddress(unittest.TestCase): def test_template_works(self): if not frappe.db.exists('Address Template', 'India...
from fabric.api import run from fabric.context_managers import cd def deploy(): with cd("~/classwhole"): run("./deploy.sh")
import requests, os, json, time import pandas as pd """ TODO: add features to df: eg. javascripts, widgets, language, frameworks, analytics """ #domains_file = '../Datasets/features_extractions/base_(all).csv' domains_file = './new_mal_urls.csv' #path = os.path.dirname(os.path.abspath(__file__)) ...
#!/usr/bin/env python3 ############################################################################### # # # RMG - Reaction Mechanism Generator # # ...
# -*- coding: utf-8 -*- import pygame from graphic.graphics import Background, Graphics class Game: def __init__(self): self._graphics = Graphics() self._playing = False def start(self): background = Background(self._graphics) background.draw() self._playing = True ...
from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from django.shortcuts import redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.mixin...
def ObjectType(properties, on_dressed=None): def decorate(base): ''' Decorate a base class with a new method and a classmethod ''' def info(cls, frm): args = [frm[p] for p in properties if p is not None] instance = cls(*args) if on_dress...
from client import client from datetime import datetime import discord import os import socket import threading import time try: import psutil except ModuleNotFoundError: has_psutil = False else: has_psutil = True cmd_name = "stats" client.basic_help(title=cmd_name, desc=f"shows various running statistics of {c...
#!/usr/bin/python # # Copyright 2018 Kaggle 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 ag...
class Bandwidth: months = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'} hosts = {} storeId = {} def add(self, host, bytes, date): newDate = self.parseDate(date) if (self.host...
from ....utils.code_utils import deprecate_module deprecate_module("ediFilesUtils", "edi_files_utils", "0.15.0") from .edi_files_utils import *
#!/usr/bin/env python3 """ Contains the interactions for GitHub webhooks """ import secrets from fastapi import FastAPI, Depends, Request, Response, HTTPException, status from fastapi.responses import FileResponse, HTMLResponse from fastapi.security import HTTPBasic, HTTPBasicCredentials import uvicorn from ubiquiti_...
from .router import Router from .parser import Parser
import os import tempfile def format_dict(d): return ', '.join(['%s=%s' % (k, v) for k, v in d.items()]) def change_ext(filename, ext): return os.path.splitext(filename)[0] + ('' if ext == '' else '.' + ext) def url_basename(url, *, _d={}): import re from urllib.parse import urlparse if _d.get...
# import from sklearn.metrics import f1_score import numpy as np import matplotlib.pyplot as plt import json import pandas as pd import torch import os from tqdm import tqdm from data_generator import Dataset_train, Dataset_test from metrics import Metric from postprocessing import PostProcessing def seed_everything(...
import requests from build_assets import arg_getters, api_handler, util import re def main(): try: print("Please wait a few seconds...") args = arg_getters.get_release_message_args() # fetch first page by default data = api_handler.get_merged_pull_reqs_since_last_release(args.token...
#!/usr/bin/env python # -*- coding: utf-8 -*- ###################################################################### # # Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved # # @file source/decoders/state.py # ###################################################################### class DecoderState(object): "...
import logging from os import path import operator import time import traceback from ast import literal_eval from flask import request # import mysql.connector # from mysql.connector import errorcode # @added 20180720 - Feature #2464: luminosity_remote_data # Added redis and msgpack from redis import StrictRedis fr...
from .BaseRelationship import BaseRelationship class MorphTo(BaseRelationship): _morph_map = {} def __init__(self, fn, morph_key="record_type", morph_id="record_id"): if isinstance(fn, str): self.fn = fn = None self.morph_key = fn self.morph_id = morph_key ...
""" The tsnet.utils.valve_curve contains function to define valve characteristics curve, gate valve by default. """ import numpy as np def valve_curve(s, coeff=None): """Define valve curve Parameters ---------- s : float open percentage valve : str, optional [description], by defa...
import xml.etree.ElementTree as ET import requests COUNTS_URL = "http://ligand-expo.rcsb.org/dictionaries/cc-counts.tdd" RESIDUES_URL = "http://ligand-expo.rcsb.org/reports/{0}/{1}/{1}.xml" MIN_COUNT = 500 PDB_ORDERS = {"sing": 1, "doub": 2, "trip": 3, "quad": 4} response = requests.get(COUNTS_URL) assert response...
from pathlib import Path import textwrap import numpy as np import random import matplotlib.pyplot as plt from typing import List, AnyStr, Tuple plt.style.use('seaborn') medium_font = {'family': 'serif', 'name': 'Helvetica', 'size': 16} large_font = {'family': 'serif', 'nam...
def main(): age = int(input('How old are you? ')) is_citizen = (input('Are you a citizen? Y or N ').lower() == 'y') if age >= 21 and is_citizen: print('You can vote and drink.') elif age >= 21: print('You can drink, but can\'t vote.') elif age >= 18 and is_citizen: print('Y...
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: target = 1 i = 0 while i < len(arr): if arr[i] == target: i += 1 else: k -= 1 if k == 0: return targ...
import configparser import argparse import sys import os sys.path.append(os.path.dirname(__file__)) import modules.deamon as daemon def main(): # Argument parser parser = argparse.ArgumentParser() parser.add_argument("command", help="command, given to daemon. Possible options: start|stop|restart", type=...
cities = [ 'Accord', 'Acra', 'Adams', 'Adams Basin', 'Adams Center', 'Addison', 'Adirondack', 'Afton', 'Akron', 'Alabama', 'Albany', 'Albertson', 'Albion', 'Alcove', 'Alden', 'Alder Creek', 'Alexander', 'Alexandria Bay', 'Alfred', 'Alfred S...
from datetime import datetime, timedelta import pandas as pd import numpy as np from scipy.interpolate import interp1d from pyseir.load_data import load_public_implementations_data from pyseir.inference import fit_results # Fig 4 of Imperial college. # https://www.imperial.ac.uk/media/imperial-college/medicine/sph/id...
# encoding=utf8 # This is temporary fix to import module from parent folder # It will be removed when package is published on PyPI import sys sys.path.append('../') # End of fix from NiaPy.algorithms.basic import ParticleSwarmAlgorithm from NiaPy.task.task import StoppingTask, OptimizationType from NiaPy.benchmarks im...
# -*- coding: utf-8 -*- from .base import BaseThumbnailEngine class WandEngine(BaseThumbnailEngine): """ Image engine for wand. """ def __init__(self): super(WandEngine, self).__init__() from wand.image import Image self._Image = Image def engine_image_size(self, image): ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import logging import numpy as np from astropy.units import Quantity from astropy.io import fits __all__ = ["Energy", "EnergyBounds"] log = logging.getLogger(__name__) class Energy(Quantity): """Energy quantity scalar or array. This is a `~ast...
import pytest from src.teamwork.client import Teamwork from src.teamwork.exceptions import CREDENTIALS_MESSAGE, CredentialsError def test_credential_raises(): """Test for credentials, if not provided raise the Error""" with pytest.raises(CredentialsError) as error: Teamwork() assert str(error.val...
# ทำ Chat Bot ง่าย ๆ ในภาษา Python # เขียนโดย นาย วรรณพงษ์ ภัททิยไพบูลย์ # https://python3.wannaphong.com/2015/07/ทำ-chat-bot-ง่าย-ๆ-ในภาษา-python.html import random while True: text = input("> ") a = ['HI','Hello'] b = ['Hello :D','Hi',':D'] if text in a: print(random.choice(b)) else: print("?")
# -*- coding: utf-8 -*- # Copyright (c) 2019 Dave Kruger. # 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 copyright notice, this # list...
import os from sqlalchemy.ext.declarative import declarative_base from fns.db.session import create_db_session from fns.util.resutils import get_database_paths database_path = os.environ.get("DATABASE_URL") if os.environ.get("DATABASE_URL") else get_database_paths()["LOCAL"] engine, db_session = create_db_session(dat...
# -*- coding: utf-8 -*- import os import logging from ProxyGeoDetector import Detector from proxy_validator import config from proxy_validator.chain import Handler, RChain from proxy_validator.client import Client Connection_Detect_Targets = config['CONNECTION_DETECT_TARGETS'] Proxy_Types = config['PROXY_TYPES'] Prox...
#!/usr/bin/env python from collections import Counter from itertools import repeat, chain from functools import partial import random from optparse import OptionParser import sys import numpy as np from scipy import stats from scipy.stats import wilcoxon from db import PerfDB import util # verbosity verbose = False...
from typing import ( Callable, ) from htdfsdk.web3._utils.rpc_abi import ( RPC, ) from htdfsdk.web3.method import ( Method, ) from htdfsdk.web3.types import ( TxPoolContent, TxPoolInspect, TxPoolStatus, ) content: Method[Callable[[], TxPoolContent]] = Method( RPC.txpool_content, munger...
import sys import time import datetime import logging from docopt import docopt import numpy as np from pysilcam import __version__ from pysilcam.acquisition import Acquire from pysilcam.background import backgrounder from pysilcam.process import processImage, statextract import pysilcam.oilgas as scog from pysilcam.co...
import unittest from django.test import Client from django.test import TestCase from django.urls import reverse from accounts.models import AccountDetails from categories.models import Category from django.contrib.auth.models import User from events.models import Event from tasks.models import Task class Events...
import functools import cachetools import numpy as np import pandas as pd def async_ttl_cache(ttl: int = 3600, maxsize: int = 1): cache = cachetools.TTLCache(ttl=ttl, maxsize=maxsize) def decorator(fn): @functools.wraps(fn) async def memoize(*args, **kwargs): key = str((args, kwa...
# -*- coding: utf-8 -*- """pybooru.api_danbooru This module contains all API calls of Gelbooru. Classes: GelbooruApi_Mixin -- Contains all API endspoints. """ # __future__ imports from __future__ import absolute_import class GelbooruApi_Mixin(object): """Contains all Gelbooru API calls. * API Version c...
n1 = float(input("digite o 1º numero ")) n2 = float(input("digite o 2º numero ")) n3 = float(input("digite o 3º numero ")) n4 = float(input("digite o 4º numero ")) n5 = float(input("digite o 5º numero ")) soma = n1 + n2 + n3 + n4 + n5 media = (soma/5) print("A soma foi {}".format(soma)) print("A média foi {}".format(me...
import pp from pp import components as pc @pp.autoname def test_comb( pad_size=(200, 200), wire_width=1, wire_gap=3, comb_layer=0, overlap_zigzag_layer=1, comb_pad_layer=None, comb_gnd_layer=None, overlap_pad_layer=None, ): """ Superconducting heater device from phidl.geometry ...
from os import *
# Copyright (c) 2015 Uber Technologies, Inc. # # 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, publ...
import random from BaseAI import BaseAI from helper_functions import * class ComputerAI(BaseAI): def __init__(self, initial_position=None) -> None: super().__init__() self.pos = initial_position self.player_num = None def setPosition(self, new_pos: tuple): self.pos = new_pos...
import numpy as np class CONST_SYNAPSE(): ''' This synapse can be represented by a single non changing weight ''' def __init__(self, w, I0, tau, tau_s, tau_d): self.w = w self.I0 = I0 self.tau = tau self.tau_s = tau_s self.tau_d = tau_d def getI(self...
# Generated by Django 2.2.24 on 2021-12-21 10:18 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FeedBack', fields=[ ('key', mo...
from .twitter import TwitterHandler from .pixiv import PixivHandler
from typing import List, Generator, Tuple from .window import Window, Trackbar from ..app import Application, Config from ..backend import cv from ..frame import AnyFrame class WindowManager: """Manages windows.""" def __init__(self, windows: List[Window] = None, app: Application = None): """ ...
def somar(n, n2): return n + n2
import socket TCP_IP = 'http://www.sapo.pt' TCP_PORT = 80 BUFFER_SIZE = 1024 MESSAGE = "Hello, World!" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE) data = s.recv(BUFFER_SIZE) s.close() print "received data:", data
import re from day import Day from utils.grid import Grid from utils.point import UniquePoint from utils.timer import Timer rx_collapsible = re.compile(r'(?P<start>[(|^])(?P<prefix>[NESW]+)\((?P<contents>[NESW|]+)\)') class DoorGrid(Grid): fallback = '#' directions = { 'N': UniquePoint.Y_MINUS, ...
import os import pexpect import rootfs_boot from lib.installers import install_jmeter from devices import board, lan, prompt from devices.common import scp_from class JMeter(rootfs_boot.RootFSBootTest): '''Runs JMeter jmx file from LAN device''' jmx = "https://jmeter.apache.org/demos/ForEachTest2.jmx" s...
#!/usr/bin/python3 from __future__ import print_function import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging import tensorflow as tf tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2) # Enable GPU dynamic memory allocation gpus = tf.config.experimental.list_ph...
import usb.core import usb.util import threading def is_usb_printer(dev): if dev.bDeviceClass == 7: return True for cfg in dev: if usb.util.find_descriptor(cfg, bInterfaceClass=7) is not None: return True class PyUSBBackend(): def __init__(self, dev): self.dev = dev ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v2/proto/services/change_status_service.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobu...
""" """ import os from django.urls import reverse_lazy # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BASE_URL = '/' HOST = 'http://127.0.0.1' # This is for links in emails, must not end with a slash # ...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem engine= create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind= engine DBSession= sessionmaker(bind= engine) session= DBSession() #how to use a session: #newEntry= ClassName(pro...
# -*- coding: utf-8 -*- import dash_core_components as dcc import dash_daq as daq import dash_html_components as html from dash import dash from dash.dependencies import Input, Output, State from zvt.contract import Mixin from zvt.contract import zvt_context, IntervalLevel from zvt.contract.api import get_entities, g...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # 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 # # Unle...
from coalib.bearlib.aspects import Root, Taste @Root.subaspect class Metadata: """ This describes any aspect that is related to metadata that is not inside your source code. """ @Metadata.subaspect class CommitMessage: """ Your commit message is important documentation associated with your ...
# Copyright 2021 Zilliz. 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 agree...
import argparse def parse_arg(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--subtitle", help="subtitle path") parser.add_argument("-t", "--tracks", help="track list") parser.add_argument("-p", "--prefix", help=...
import sys, operator, math sys.path.append('..') import ZynqScope.ArmwaveRenderEngine as awre # configure logger import LoggingHandler, logging log = logging.getLogger() LoggingHandler.set_console_logger(log, logging.DEBUG) # create armwave object aobj = awre.ArmwaveRenderEngine() def main(): print("aobj set_c...
from ms_mint.tools import generate_grid_peaklist def test__generate_peaklist(): peaklist = generate_grid_peaklist([115], .1, intensity_threshold=10000) assert peaklist is not None
# Copyright 2018 Open Source Foundries Limited. # # SPDX-License-Identifier: Apache-2.0 '''West's bootstrap/wrapper script. ''' import argparse import configparser import os import platform import subprocess import sys import west._bootstrap.version as version if sys.version_info < (3,): sys.exit('fatal error: ...
import pandas as pd import numpy as np from ldetect2.src.m2v import mat2vec from sys import argv partitions = argv[1] theta2 = argv[2] covariances = argv[3:] theta2 = float(open(theta2).readline().strip()) import sys # print(partitions, file=sys.stderr) # print(covariances, file=sys.stderr) # partitions = snakem...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name="home"), url(_(r'^signatures-(?P<slug>[\w-]+)$'), views.SignatureListVi...
import base64 import multiprocessing import sys from concurrent import futures import cv2 import grpc import numpy as np import work_object_detection_pb2 import work_object_detection_pb2_grpc from work_object_detection_model import const from work_object_detection_model.model import Model # SERVER_PORT = 50051 SERVE...
import sys import torch import torch.nn.functional as F #from warp_rnnt import rnnt_loss as loss1 #from warprnnt_pytorch import rnnt_loss as loss2 from transducer.functions.transducer import Transducer from timeit import default_timer as timer def run_loss1(xs, ys, xn, yn): xs = F.log_softmax(xs, -1) retur...
""" Sthis adds 'created_at', 'updated_at' and 'delete_at' fields like a rail apps in django, also added soft delete method. Copyright (c) 2018, Carlos Ganoza Plasencia url: http://carlosganoza.com """ from django.contrib import admin class ParanoidAdmin(admin.ModelAdmin): readonly_fields = ('created_at','d...
import subprocess import sys import os import os.path def cd(path): os.chdir(path) def cdToScript(): cd(os.path.dirname(os.path.abspath(__file__))) def conv(path): print('Convert {}'.format(path)) temp = open(path,mode='rb') byte = temp.read(1) temp.close() if b'\xef' == byte: return data = None if dat...
#!/usr/local/bin/python3 import serial #SERIAL_DEVICE = "/dev/tty.SLAB_USBtoUART" SERIAL_DEVICE = "/dev/tty.usbserial-1420" DISABLE_MOSFETS_COMMAND = 0 ENABLE_MOSFETS_COMMAND = 1 SET_POSITION_AND_MOVE_COMMAND = 2 SET_VELOCITY_COMMAND = 3 SET_POSITION_AND_FINISH_TIME_COMMAND = 4 SET_ACCELERATION_COMMAND = 5 START_CAL...
import setuptools from numpy.distutils.core import setup, Extension import os import sys import io import re def read(*names, **kwargs): with io.open( os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8") ) as fp: return fp.read() def find_version(*f...
#!/bin/python import numpy import scipy.ndimage from pyami import mrc if __name__ == "__main__": ## using scipy.ndimage to find blobs labelstruct = numpy.ones((3,3,3)) def scipyblobs(im,mask): labels,n = scipy.ndimage.label(mask, labelstruct) ## too bad ndimage module is inconsistent with what is returned from...
old_file = open('../one/one_1.cfg', mode='r') lines = old_file.readlines() for index in range(1,21): new_file = open('two_{}.cfg'.format(index), mode='w') for line in lines: if 'doom_scenario_path' in line: line = "doom_scenario_path = two_{}.wad".format(index) new_file.write(line) ...
from . import api from flask import jsonify from ..models import Comment @api.route('/comments/') def get_comments(): comments = Comment.query.all() return jsonify({'comments':[comment.to_json() for comment in comments]}) @api.route('/comments/<int:id>') def get_comment(id): comment = Comment.query.get_or...
# 本脚本是针对中国新冠病毒各省市历史发病数据的清洗工具 # 作者 https://github.com/Avens666 mail: cz_666@qq.com # 源数据来自 https://github.com/BlankerL/DXY-COVID-19-Data/blob/master/csv/DXYArea.csv # 本脚本将各省市每天的数据进行去重处理,每个省市只保留最新的一条数据 (也可选择保留当天最大数值) # 因为省市的“疑似数据 suspectedCount”参考意义不大,没有进行处理和导出 # 用户通过修改 inputfile 和 outputfile 定义源数据文件和输出文件 import pand...
import copy from Harmony import Chord class ChordProg: prog_delim = ',' def __init__(self, chordString: str = "") -> None: self.chords: list = [] self.parse_prog(chordString) def add(self, chord: Chord): self.chords.append(chord) def parse_prog(self, string: str): ...
def application(env, start_response): start_response("200 OK", [("Content-Type", "text/html")]) return [ b"Hello World from a default Nginx uWSGI Python 3.6 app in a\ Docker container (default)" ]
import pandas as pd from .well_data import WellInterface from nl_project.input_layer.get_data import GetProjectData from PIL import Image import matplotlib.pyplot as plt import numpy as np from skimage.filters import sobel class CorePhotoInterface(WellInterface): """Interface to work with core photo data""" ...
import numpy as np import pandas as pd from pandas.api.types import is_numeric_dtype from pandas.api.types import is_datetime64_any_dtype from pmdarima.arima import auto_arima, ARIMA def convert_float(rawdata): result = rawdata.copy() # converting all columns to float64 if numeric for col in result.column...
from FreeTAKServer.model.FTSModel.fts_protocol_object import FTSProtocolObject class ChecklistTasks(FTSProtocolObject): @staticmethod def Checklist(): checklistTasks = ChecklistTasks() return checklistTasks
import turtle import math import weakref import threading import sys from pylogo.common import * from ide import add_command, get_canvas class Turtle: _all_turtles = [] _turtle_count = 1 def __init__(self): self.pen = turtle.RawPen(get_canvas()) self.pen.degrees() self._all_turtl...
import os import torch from torchvision.datasets import Kinetics400 def getkinetics(datafolder,tempfolder,categorylist,frames_per_instance,reallabel,frame_skip=1,centercrop=None): # TODO # for category in categorylist: # os.system("mv "+datafolder+"/"+category+" "+tempfolder) a = Kinetics400(temp...
## import requests, time, smtplib, logging, datetime ## CONFIGURE YOUR GEO-LOCATION FOR BETTER AND ACCURATE RESULTS # find your coordinates at "latlong.net" # enter your email and passord to get an email notification (optional) # DONT FORGET TO ENTER YOUR COORDINATES...THOSE ENTERED ARE AN EXAMPLE !!...