content
stringlengths
5
1.05M
# Generated by Django 3.0.1 on 2020-01-08 09:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WebAXEL', '0047_auto_20200107_1358'), ] operations = [ migrations.CreateModel( name='RobotCategory', fields=[ ...
from __future__ import absolute_import import functools import black_magic.decorator from test.benchmark import _common class StandardPartial(_common.Base): def __init__(self): self.func = functools.partial(_common.func, 0) class BlackMagicPartial(_common.Base): def __init__(self): self.fu...
class ERROR_CODE(object): NOT_FOUND_ERROR = 404
# -*- coding: utf-8 -*- """ link ~~~~~~~~~~~~ The link module helps you connect to all of the data sources you need through a simple configuration Sample Config to connect to mysql:: { "dbs":{ "my_db": { "wrapper": "MysqlDB", "host": "mysql-master.123fakestre...
#!/usr/bin/env python3 """ 9.xxx 2 Octet Floating Point Number """ import struct def encode(value): s = 0 e = 0 if value < 0: s = 0x8000 m = int(value * 100) while (m > 2047) or (m < -2048): e = e + 1 m = m >> 1 num = s | (e << 11) | (int(m) & 0x07ff) ret = bytea...
import os import sys import argparse def prompt_sudo(): try: os.mkdir('/test') os.rmdir('/test') except PermissionError: print('You need root permission to generate the service!') sys.exit(1) prompt_sudo() parser = argparse.ArgumentParser() parser.add_argument...
import os from itertools import combinations file_path = os.path.join(os.path.dirname(__file__), "input.txt") with open(file_path, 'r') as input: all_lines = input.readlines() for i in range(len(all_lines)): all_lines[i] = all_lines[i].strip('\n') all_lines[i] = int(all_lines[i]) preamble = [] for i in...
# -*- coding: utf-8 -*- """ @author: Yi Zhang @contact: zhangyi_aero@hotmail.com @time: 2022/05/07 3:46 PM """ import sys if './' not in sys.path: sys.path.append('./') from screws.freeze.base import FrozenOnly class FrameSegments(FrozenOnly): """""" def __init__(self, cell, edge_name, segments): "...
import random #to print out the board def drawBoard (board): print (' | |') print (' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print (' | |') print ('------------') print (' | |') print (' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print (' | |') prin...
# Keeps the rates.csv file updated from pandas import * from pyvalet import ValetInterpreter # Fetch the data using Valet API vi = ValetInterpreter() # Step 1: Get all foreign exchange rates # CAD to INR _, cad_inr = vi.get_series_observations('FXCADINR') dates = cad_inr.loc[3:]['id'] cad_inr = cad_inr.loc[3:]['label...
import sys import csv import StringIO import json from threading import Thread from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer clients = [] class SockClient(WebSocket): def handleMessage(self): if self.data is None: self.data = '' try: self.sendM...
# coding=utf-8 # Copyright 2021 The Google Research 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 applicab...
import boto3 import fire if __name__ == '__main__': fire.Fire(boto3)
import re from string import punctuation from string import digits import pymorphy2 import codecs def prepr(input: str): input = input.lower() input = re.sub(':', '', input) input = re.sub("#", '', input) delreg = "(\S+(\.|\/)+\S+)+" input = re.sub(delreg, '', input) stop = punctuation + digits...
import os import sys ''' Since tweetme.py is now present in parent directory we need to add appropriate path in order to access it as a module. Path is added with respect to the location user is running the tests from. ''' parent_directory_path = os.getcwd().split('/') if 'tests' in parent_directory_path: parent_d...
from typing import List from odm2_postgres_api.schemas.schemas import ( SamplingFeaturesCreate, VariablesCreate, EquipmentModelCreate, LoggersTimeSeriesCreate, DataQualityCreate, ControlledVocabularyCreate, ) def loggers_controlled_vocabularies() -> List[ControlledVocabularyCreate]: logge...
''' Module for reading Cosmo Skymed HDF5 imagery. This is more or less a line-for-line port of the reader from NGA's MATLAB SAR Toolbox. ''' # SarPy imports from .sicd import MetaNode from . import Reader as ReaderSuper # Reader superclass from . import sicd from ...geometry import geocoords as gc from ...geometry im...
import re from typing import Dict, List, Tuple, Type from graia.amnesia.message import Element, MessageChain from avilla.commander.utilles import gen_subclass from avilla.core.elements import Text ELEMENT_MAPPING: Dict[str, Type[Element]] = {i.__name__: i for i in gen_subclass(Element)} def chain_from_mapping_stri...
#!/usr/bin/env python3 """ Copyright (C) 2018 Christian Thomas Jacobs Pynea facilitates the reproducibility of LaTeX documents by embedding the scripts and data files required to regenerate the figures within the document itself. Pynea is released under the MIT license. See the file LICENSE.md for more details. """ ...
# Generated by Django 2.2.3 on 2020-06-02 21:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cers', '0003_auto_20200602_2111'), ] operations = [ migrations.RenameField( model_name='attendance', old_name='is_entry', ...
# -*- coding: utf-8 -*- from django.contrib.auth.backends import ModelBackend from .models import EmailAddress from .utils import get_most_qualified_user_for_email_and_password class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): """ tries verified email address...
import os import re from shift_oelint_parser.parser import get_items from shift_oelint_parser.cls_item import Variable, Item from shift_oelint_parser.helper_files import expand_term, guess_recipe_name, guess_recipe_version, guess_base_recipe_name from shift_oelint_parser.constants import CONSTANTS class Stash(object...
from matplotlib import pyplot as plt from epyseg.deeplearning.augmentation.generators.data import DataGenerator from epyseg.deeplearning.augmentation.generators.meta import MetaGenerator import numpy as np # logging from epyseg.tools.logger import TA_logger logger = TA_logger() # MINIMAL_AUGMENTATIONS = [{'type': N...
import anachronos from e2e_test.runner import http from e2e_test.testing_messages import SIMPLE_GET, SIMPLE_POST_DTO, DIFFERENT_POST_DTO, GET_WITH_PARAMETERS, \ GET_WITH_PATH_PARAMETER class SimpleResourceTest(anachronos.TestCase): def test_simple_get(self): http.get("/") self.assertThat(SI...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np data_connect = pd.read_csv('C:/Users/sch/PycharmProjects/pythonProject3/csv/connect.csv') connect = data_connect['connect'] connect_ad = data_connect['connect_ad'] connect_k8s = data_connect['connect_k8s'] connect_hyscal = data_connect['connect_hys...
""" Hamilitonian Monte Carlo implementation. Adapted from https://github.com/franrruiz/vcd_divergence/blob/master/mcmc/hmc_vae.m """ import torch import utils def hmc_vae(current_q, model, img, epsilon=None, Burn=3, T=10, adapt=0, L=5): """ Hamilitonian Monte Carlo sampler. :param current_q: initial sa...
# Copyright (c) 2017 Sony Corporation. 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 applicabl...
from .user import CustomUserAdmin from ... import forms class StudentAdmin(CustomUserAdmin): form = forms.StudentChangeForm add_form = forms.StudentCreationForm list_filter = CustomUserAdmin.list_filter + ('supervisor', ) list_display = CustomUserAdmin.list_display + ('supervisor',) fieldsets = C...
import numpy as np class Node: def __init__(self, name_initial, id): self.id = id self.nextNodes = [] self.name_initial = name_initial if name_initial == 'transition': self.listExpectedType = Place elif name_initial == 'places': self.listExpectedType ...
class DateException(Exception): pass class UnknownModeException(Exception): pass
import json import pandas as pd; import matplotlib.pyplot as plt; import seaborn as sns; import folium as fol; from config.settings import DATA_DIRS, STATICFILES_DIRS, TEMPLATES # 인구이동 df = pd.read_excel(DATA_DIRS[0]+'//data1.xlsx',engine='openpyxl' ,header=0); # 전력량 df2 = pd.read_excel(DATA_DIRS[0...
""" Implementations of the subnetworks: - Encoder - Generator (Decoder) - D_real - D_prior - D_em """ import tensorflow as tf import numpy as np from PK_Utils.PK_layers import dense, conv2d, deconv2d, batch_norm from PK_Utils.PK_config import size_batch, num_z_channels # --HELPERS ----------------------------------...
https://leetcode.com/problems/count-sorted-vowel-strings/ class Solution: def countVowelStrings(self, n: int) -> int: # The formula is (n+5-1)C(n)=(n+4)C(n) return (n+4)*(n+3)*(n+2)*(n+1)//24
from PIL import Image from PIL import ImageFont from PIL import ImageDraw def img_add_number(image_path,sign="46"): im=Image.open(image_path) width,height=im.size draw=ImageDraw.Draw(im) font=ImageFont.truetype("Arial.ttf",min(width//6,height//6)) draw.text((width*0.75,height*0.075),sign,font=font,fill=(255,33,33...
import os import sys import pickle import warnings from typing import Dict import numpy as np import pandas as pd from autosklearn.estimators import AutoSklearnClassifier from sklearn.exceptions import DataConversionWarning from surfboard.sound import Waveform from surfboard.feature_extraction import extract_features ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-10-18 09:30 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependenc...
""" Plugin to create a quick panel lookup that lets you jump between comment titles """ import os import imp import time import sys import sublime import sublime_plugin import re # # > Plugin command # class table_of_comments_command(sublime_plugin.TextCommand): def run(self, edit, move=None, fold=None, unfold=...
# coding=utf-8 import numpy as np import scipy.stats from .cobsampler import ChangeOfBasisSampler class Test(object): """ Super class implementing tests for CoBSampler. Sub-classes should specify target distribution. """ def __init__(self, ndim, target, nsteps, cobparams={}): self.ndim = ...
#!/usr/bin/env python # # MIT License # # Copyright (c) 2018-2019 Groupe Allo-Media # # 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 rig...
# pylint: disable-msg=no-name-in-module,import-error from distutils.cmd import Command from os import getcwd from subprocess import check_call from setuptools import setup class ComputePerformingFundsCommand(Command): description = 'calculate performing funds' user_options = [] def initialize_options(self...
"""User Expression module ============================= Contains the definition of user defined expressions. It has the class UserExpression that evaluates an expression defined in an string. Example: Creating an expression:: true_value = UserExpression("1==1").evaluate() false_expression = UserEx...
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 19:33:17 2019 @author: Mysia """ import numpy as np def nnloss(x,t,dzdy): instanceWeights=np.ones(len(x)) res=x-t if(dzdy==0): y = (1/2) * instanceWeights * np.power(res,2) else: y = res return y
import time, DAN, requests, random, datetime import sys from threading import Thread import re import json import traceback name = "" light = 0 interval = 50 changeinterval = 10 #s ledmesseges = {} ledindex = 0 skip = 0 def sendMessegeToLEDMatrix(msg): DAN.push('LEDCommandSender', json.dumps({'model':'LEDMatrix',...
import argparse import sys from subprocess import call import numpy as np def parseVals(fname): f = open(fname) line = f.readline() rtvals = [] schemes = [] while line: if (line == '' or line == '\n'): break tmp = line.split() if (tmp[0] == 'matrix'): ...
from setuptools import setup setup( name='deepgp_approxep', version='1.0', description='Approximate Expectation Propagation for Deep GPs', author='Thang Bui et al (2016)', author_email='thang.buivn@gmail.com', packages=['deepgp_approxep'], #same as name install_requires=['numpy'], #external packa...
# The rand7() API is already defined for you. # def rand7(): # @return a random integer in the range 1 to 7 class Solution: def rand10(self): """ :rtype: int """ a = rand7() while a > 5: a = rand7() b = rand7() while b == 4: b = rand7(...
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ config.py ] # Synopsis [ configuration settings ] # Author [ Ting-Wei Liu (Andi611) ] # Copyright [ Copyleft(c), NTUEE, NTU, Taiwan ] """*******************...
import time import twitter import twitter_tokens api = twitter.Api( consumer_key=twitter_tokens.api_key, consumer_secret=twitter_tokens.api_secret, access_token_key=twitter_tokens.access_token, access_token_secret=twitter_tokens.access_token_secret ) # api.PostUpdate("This is the...
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import os from PIL import Image from jina import Flow from ...pdf_segmenter import PDFSegmenter def test_flow(test_dir, doc_generator_img_text, expected_text): flow = Flow().add(uses=PDFSegmenter) doc_...
from setuptools import setup setup( name='pypythia', packages=['pypythia'], license='MIT', version='0.0.3', author='Christian Schulze', author_email='chris@andinfinity.de', url='https://github.com/ChristianSch/PyPythia' )
import asyncio import audioop import functools import ipaddress import threading import traceback import urllib.parse from typing import Coroutine, Union import av from ..config import Config from ..natives import AudioFifo, AudioFilter from ..utils.threadLock import withLock AVOption = { "err_detect": "ignore_e...
#!/usr/bin/env python #____________________________________________________________ # # # A very simple way to make plots with ROOT via an XML file # # Francisco Yumiceva # yumiceva@fnal.gov # # Fermilab, 2010 # #____________________________________________________________ """ ntuplemaker A very simple script t...
"""A package (for Nevow) for defining the schema, validation and rendering of HTML forms. """ version_info = (0, 9, 3) version = '.'.join([str(i) for i in version_info]) from nevow import static from formal.types import * from formal.validation import * from formal.widget import * from formal.widgets.restwidget imp...
# !/usr/bin/env python3 # Copyright (c) 2022 PaddlePaddle Authors. 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 # ...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class ColorgradingGetGlobalNode(Node, ArmLogicTreeNode): '''Colorgrading Get Global node''' bl_idname = 'LNColorgradingGetGlobalNode' bl_label = 'Colorgrading Get Global' bl_icon = 'QUESTION'...
import base64 import random import re from random import randint import discord from discord.ext.commands import Cog, Context, command, group, cooldown, BucketType, CommandError import missile from dimsecret import debug max_pp_size = 69 guild_id = 675477913411518485 spam_ch_id = 723153902454964224 bot...
# -*- coding: utf-8 -*- from .expr import * def_Topic( Title("Landau's function"), Section("Definitions"), Entries( "32e430", ), Section("Tables"), Entries( "177218", ), Section("Arithmetic representations"), Entries( "7932c3", ), Section("Asymptotic...
# -*- coding: utf-8 -*- """ @author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/ """ #This is a graphical display tool for candlestick charts + indicators #It has a trading model inside. #Import modules from YahooGrabber import YahooGrabber from YahooSourceDailyGrabber import Ya...
import tensorflow as tf tf.logging.set_verbosity(tf.logging.FATAL) import sys sys.path.append('../') import tensorflow as tf import numpy as np import gpflow from dgps_with_iwvi.layers import LatentVariableLayer, GPLayer from dgps_with_iwvi.models import DGP_VI, DGP_IWVI # class DirectlyParameterizedEncoder(gpflow...
""" Loading a pretrained model and using it for superresolution and denoising purposes on the test-set. Denoising_in_superresolution/src @author: Angel Villar-Corrales """ import os import json from tqdm import tqdm import torch import lib.utils as utils import lib.metrics as metrics import lib.arguments as argument...
from django.http import HttpResponseRedirect from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.views.generic import TemplateView from .forms import PostForm, CommentForm from .models import Post, Comment from django.contrib.auth.models import User from dja...
# GET import os db_login = os.environ['db_login'] db_password = os.environ['db_password'] # # MONGO STUFF from pymongo import MongoClient # from pymongo import MongoClient # from bson.json_util import dumps # from bson.objectid import ObjectId client = MongoClient( f"mongodb+srv://{db_login}:{db_password}@clu...
# -*- coding: utf-8 -*- # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import doctest import nodepy import unittest import os import subprocess import tempfile import sys import nbformat if sys.version_info >= (3,0): kernel = 'python3' else: kernel = 'python2' def _notebook_run(path): """Execute a notebook via nb...
import sys import time import argparse import requests import bs4 # Douban house renting groups MAIN_URLS = { 'hangzhou': 'https://www.douban.com/group/145219/', 'beijing' : 'https://www.douban.com/group/fangzi/', 'shanghai': 'https://www.douban.com/group/shanghaizufang/' } # Open URL, return HTML data de...
import requests from bs4 import BeautifulSoup import pandas as pd import time from PostgreSQLConnector import PostgresConnector import json # Program that connects to Urban Dictionary.com & oxford dictionary.com # to search for words and determine if each word is sexist or not class UrbanDictCrawler: def __init...
from ds_discovery import Controller import os import warnings warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=DeprecationWarning) __author__ = 'Darryl Oatridge' def domain_controller(): # Controller uri_pm_repo = os.environ.get('HADRON_PM_REPO',...
from tensorflow.keras.models import Sequential from tensorflow.keras.callbacks import Callback, ModelCheckpoint from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from tensorflow.keras.datasets import mnist from tensorflow.keras.models import save_model import tensorflow as tf import tem...
import inspect # from collections import OrderedDict as odict import numpy as np from galry import Manager, TextVisual, get_color, NavigationEventProcessor, \ DefaultEventProcessor, EventProcessor, GridEventProcessor, ordict, \ log_debug, log_info, log_warn __all__ = ['InteractionManager'] class Interaction...
#!/usr/bin/env python3 import os import sys thispath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(thispath),"helper")) from MiscFxns import * from StandardModules import * def CompareEgy(EgyIn): return EgyIn+224.912529687124<0.00001 def CompareGrad(GradIn): Cor...
from .wide_resnet import wide_resnet_28_2
# -*- coding: utf-8 -*- # date: 2018-12-02 15:47 from torch.autograd import Variable from .functional import subsequent_mask class Batch(object): """ Object for holding a batch of data with mask during training. """ def __init__(self, src, trg=None, pad=0): self.src = src self.src_ma...
from django.shortcuts import render from .models import language # Create your views here. def Serach(req): Input = req.GET key = Input.get('key') result = language.objects.filter(name__contains=key) return render(req,'Serach.html',{'data':result,'title':'方言搜索'}) def Test(req): return render(req,'Te...
from math import e, exp, log print(pow(e, 1) == exp(log(e))) print(pow(2, 2) == exp(2 * log(2))) print(log(e, e) == exp(0))
"""removed user_x_branch Revision ID: 182718a0a9ae Revises: f7f61b0fadff Create Date: 2020-11-26 02:10:39.739942 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '182718a0a9ae' down_revision = 'f7f61b0fadff' branch_labels = None depends_on = None def upgrade()...
""" Test the bss module. MIT License (C) Copyright [2020] Hewlett Packard Enterprise Development LP 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 limitat...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure from ansible.module_utils._text import to_bytes, to_text class TerminalModule(TerminalBase): termin...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import sys import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from utils import padding_idx from ask_agent import AskAg...
def check_fibonacci(n): """Returns the nth Fibonacci number for n up to 40""" fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 390...
from Commands.Base import LitsQuestionsCommand from WareHouse import wareHouse import webbrowser import PythonSheep.IOSheep.PrintFormat class HelpDocument(LitsQuestionsCommand): def run(self, userNowUsingLanguage:str, mainWareHouse:wareHouse): mainPrintControler = PythonSheep.IOSheep.PrintFormat.PrintFo...
import bs4 import jinja2 import codecs from collections import defaultdict import argparse parser = argparse.ArgumentParser() parser.add_argument("--all", action="store_true", dest="convert_all") parser.add_argument("--target", action="store", default="chosakukenhou.xml") args = parser.parse_args() templateLoader = j...
from recon.core.module import BaseModule from urlparse import urlparse class Module(BaseModule): meta = { 'name': 'Google CSE Hostname Enumerator', 'author': 'Tim Tomes (@LaNMaSteR53)', 'description': 'Leverages the Google Custom Search Engine API to harvest hosts using the \'site\' search...
from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance, stations_within_radius, rivers_with_station, stations_by_river from floodsystem.geo import rivers_by_station_number def test_stationsbydistance(): stations = build_station_list() p = (52.2053, 0.1218) a...
from os import system, name system('cls' if name == 'nt' else 'clear') dsc = ('''DESAFIO 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou...
def main(): chk_lst = range(1, 21) skip = max(chk_lst) current = skip while not chk_divisible(current, chk_lst): current += skip print(current) def chk_divisible(n, lst): chk = all(map(lambda x: n % x == 0, lst)) return chk if __name__=="__main__": main(...
#!/usr/bin/env python # # getopt_tests.py: testing the svn command line processing # # Subversion is a tool for revision control. # See http://subversion.apache.org for more information. # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) un...
import aos_sw_api from .user_pass_ip import username, password, switch_ip, api_version def test_auth_client(): with aos_sw_api.Client(switch_ip, api_version, username, password) as client: print(client._session.headers) def main(): test_auth_client() if __name__ == "__main__": main()
from tornado.gen import Task from . import cached from . validate import validate from . import internal from . import singleton import logging import ujson class AppNotFound(Exception): pass class ApplicationInfoAdapter(object): def __init__(self, data): self.id = data.get("id") self.name...
from fireo import models as mdl class User(mdl.Model): id = mdl.IDField() name = mdl.TextField() class Student(mdl.Model): id = mdl.IDField() address = mdl.TextField() def test_parent_key_with_id_field(): u = User() u.id = 'test_parent_key_with_id_field' u.name = 'testing parent key wi...
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolButton, QLineEdit, QMessageBox from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtCore import QUrl, QSize from PyQt5.QtGui import QIcon, QPixmap #Variaveis home_url = "https://www.google.com" facebook_url = "https://www.facebook.com" twitter...
# 读取人物名称 f = open('name.txt') data = f.read() data0 = data.split('|') # 读取兵器名称 f2 = open('weapon.txt') # data2 = f2.read() i = 1 for line in f2.readlines(): if i % 2 == 1: print(line.strip('\n')) i += 1 f3 = open('sanguo.txt',encoding='GB18030') print(f3.read().replace('\n','')) # # # def func(filen...
thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red)
import grpc import time import drivers.xarm.wrapper.xarm_api as xai from concurrent import futures import robot_con.xarm_shuidi_grpc.xarm.xarm_pb2 as xarm_msg import robot_con.xarm_shuidi_grpc.xarm.xarm_pb2_grpc as xarm_rpc import numpy as np class XArmServer(xarm_rpc.XArmServicer): def __init__(self, arm_ip): ...
from django.db import models # Create your models here. from django.forms import Textarea from django.db import models from django.contrib import admin from django.utils.encoding import python_2_unicode_compatible from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFit # Create your mo...
# coding: utf-8 import os import sys import logging from importlib import import_module def pytest_sessionstart(session): logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s", ) proj_dir = os.path.abspath(o...
# Generated by Django 3.1.4 on 2020-12-02 13:33 import datetime import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Lexer", fields...
#!/usr/bin/python3 """ Script language: Python3 Talks to: - Vega node (REST) - Vega wallet (REST) Apps/Libraries: - REST: requests (https://pypi.org/project/requests/) """ # Note: this file uses smart-tags in comments to section parts of the code to # show them as snippets in our documentation. They are not necessa...
# type: ignore[attr-defined] ''' :created: 2019-07-29 :author: Leandro (Cerberus1746) Benedet Garcia''' from dataclasses import _FIELDS, _get_field from typing import Optional, Any, Type from keyword import iskeyword def add_field(dataclass_instance: object, field_name: str, field_type: Type[Any], fiel...
import pickle import json import os OUTPUT_DIR='json/' os.makedirs(OUTPUT_DIR, exist_ok=True) # ------------------------------------- # SheetProperties # ------------------------------------- with open("dict_SheetProperties.pickle", mode='rb') as f: data = pickle.load(f) sd = json.dumps(data, sort_key...
import re #replace charset notation in text def repalce_charset_notation(content, new_notation): #try: charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*...