text
stringlengths 3
1.05M
|
---|
const mongoose = require('mongoose');
const trackSchema = new mongoose.Schema({
userId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
trackNum : {
type : Number
},
status : {
type : String
},
lastUpdate : {
type : String
},
nextDeadline : {
type : String
},
img : {
type : String
}
});
mongoose.model('Track', trackSchema);
|
import numpy as np
from .hamiltonian import SpinHamiltonian, read_spin_ham_from_file
#from minimulti.spin.mover import SpinMover
class SpinModel():
def __init__(self, fname=None, sc_matrix=None):
if fname is not None:
self.read_from_file(fname)
else:
self._ham = SpinHamiltonian()
if sc_matrix is not None:
self.make_supercell(sc_matrix)
#self.mover = SpinMover(self._ham)
@property
def ham(self):
return self._ham
def add_term(self, term, name=None):
self._ham.add_Hamiltonian_term(term, name=name)
@ham.setter
def ham(self, ham):
self._ham = ham
#@property
#def S(self):
# return self.mover.s
@property
def nspin(self):
return self._ham.nspin
def read_from_file(self, fname):
self._ham = read_spin_ham_from_file(fname)
def set(self, **kwargs):
self.params.set(**kwargs)
# self.mover.set(
# time_step=self.params.time_step,
# temperature=self.params.temperature,
# total_time=self.params.total_time,
# )
def set_ham(self, **kwargs):
self._ham.set(**kwargs)
def make_supercell(self, sc_matrix=None, supercell_maker=None):
self._ham = self._ham.make_supercell(
sc_matrix=sc_matrix, supercell_maker=supercell_maker)
#self.mover = SpinMover(self._ham)
return self
# def run_one_step(self):
# self.mover.run_one_step()
# def run_time(self):
# self.mover.run()
def plot_magnon_band(
self,
kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],
[0, 0, 0], [.5, .5, .5]]),
knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
supercell_matrix=None,
npoints=100,
color='red',
ax=None,
kpath_fname=None,
Jq=False,
):
self._ham.plot_magnon_band(
kvectors=kvectors,
knames=knames,
supercell_matrix=supercell_matrix,
npoints=npoints,
color=color,
ax=ax,
Jq=Jq,
kpath_fname=kpath_fname)
|
const chalk = require("chalk")
const clear = require("clear")
const connection = require("../database/connection")
const foreignQ = {
resetServer: async function () {
clear();
await connection.query("DROP DATABASE IF EXISTS foreign_toolboxDB", function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.red("DATA BASE DROPPED"));
});
await connection.query("create database foreign_toolboxDB;", function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("foreign_toolboxDB database created"));
});
await connection.query("use foreign_toolboxDB;", function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.white("foreign_toolboxDB database created"));
});
const tableD = `create table department (
id INT NOT NULL AUTO_INCREMENT,
sector VARCHAR(30),
PRIMARY KEY (id)
)`;
await connection.query(tableD, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.red("DEPARTMENT") + chalk.bold.white(" table created!"));
});
const tableR = `create table role (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(30),
salary Decimal(8,2),
departmentID INT,
PRIMARY KEY (id),
FOREIGN KEY (departmentID) references department(id)
)`;
await connection.query(tableR, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.red("ROLE") + chalk.bold.white(" table created!"));
});
const tableE = `create table employee (
id INT NOT NULL AUTO_INCREMENT,
firstName varchar(30),
lastName varchar(30),
roleID INT,
managerID INT,
PRIMARY KEY(id),
FOREIGN KEY (roleID)references role(id),
FOREIGN KEY (managerID) references role(id)
)`;
await connection.query(tableE, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.red("EMPLOYEE") + chalk.bold.white(" table created!"));
});
await connection.query(`INSERT INTO department(sector) VALUES("CEO")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("CEO") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Marketing")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("MARKETING") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Legal")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("LEGAL") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Research and Development")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("RESEARCH AND DEVELOPMENT") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Information Technology")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("INFORMATION TECHNOLOGY") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Enquiries")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("ENQUIRIES") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO department(sector) VALUES("Security")`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.blue("SECURITY") + chalk.bold.white(" department added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Director", 520000.00, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("DIRECTOR") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Marketing Manager", 165000.50, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("MARKETING MANAGER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Sales", 122322.00, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SALES") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Public Relations", 118009.28, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("PUBLIC RELATIONS") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Graphic Design", 92000, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("GRAPHIC DESIGN") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Analyst", 102890.19, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("ANALYST") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Law Office Manager", 135000.50, 3)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("LAW OFFICE MANAGER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Consultant", 102105.00, 3)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("CONSULTANT") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Accountant", 100371.93, 3)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("ACCOUNTANT") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Corperate Lawyer", 120220.99, 3)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("CORPERATE LAWYER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Paralegal", 108013.50, 3)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("PARALEGAL") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Research Manager", 205000.50, 4)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("PARALEGAL") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Robotics Engineer", 322070.35, 4)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("ROBOTICS ENGINEER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Mechanical Engineer", 272108.33, 4)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("MECHANICAL ENGINEER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Physicist", 302040.22, 4)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("PHYSICIST") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Electronics Engineer", 199222.22, 4)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("ELECTRONIC ENGINEER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("IT Manager", 105000.50, 5)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("IT MANAGER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Software Engineer", 87000.20, 5)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SOFTWARE ENGINEER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Network Engineer", 92021.87, 5)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("NETWORK ENGINEER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Adminstration", 102001.01, 5)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("ADMINSTRATION") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Network Architect", 87333.19, 5)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("NETWORK ARCHITECT") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("CC Manager", 165000.50, 6)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("CC MANAGER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Feedback administration", 51081.22, 6)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("FEEDBACK ADMINISTRATION") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Systems specialist", 42992.17, 6)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SYSTEMS SPECIALIST") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Customer Service Representive", 39988.78, 6)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("CUSTOMER SERVICE REPRESENTIVE") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Security Manager", 75200.50, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SECURITY MANAGER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Security Officer", 64118.21, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SECURITY OFFICER") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Surveillance", 58128.92, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SURVEILLANCE") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Security Guard", 62118.21, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("SECURITY GUARD") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO role(title, salary, departmentID) VALUES("Unknown", 420871.22, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.yellow("UNKNOWN") + chalk.bold.white(" position added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Joshua K", "Bader", 1, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Jarrad", "Vennett", 2, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Michael", "Burry", 5, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Mark", "Baum", 3, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Cynthia", "Baum", 3, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Ben", "Rickert", 4, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Lewis", "Ranieri", 6, 2)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Mitch", "McDeere", 7, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Abby", "McDeere", 8, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Avery", "Tolar", 9, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Oliver", "Lambert", 9, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Lamar", "Quinn", 10, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("William", "Devasher", 11, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Tammy", "Hemphill", 11, 7)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Neil", "Armstrong", 12, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Ed", "White", 14, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Deke", "Slayton", 13, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Buzz", "Aldrin", 14, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Janet", "Armstrong", 16, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Elliot", "See", 15, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Patrick", "White", 13, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Robert", "Gilruth", 16, 12)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Douglas", "Rayholm", 17, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Roy", "Trenneman", 19, 17)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Jennifer", "Barber", 20, 17)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Maurice", "Moss", 18, 17)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Denholm", "Reyholm", 20, 17)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Richmond", "Dracula", 21, 17)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Michael", "Scott", 22, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Dwight", "Schrute", 23, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Jim", "Halpert", 25, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Pam", "Beesly", 25, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Kelly", "Kapoor", 24, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Stanley", "Hudson", 25, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Angela", "Martin", 23, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Kevin", "Malone", 23, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Phyllis", "Vance", 24, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Creed", "Bratton", 23, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Meredith", "Palmer", 25, 22)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Nick", "Fury", 26, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Tony", "Stark", 29, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Bruce", "Banner", 29, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Thor", "OdinSon", 29, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Steve", "Rogers", 27, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Natasha", "Romanoff", 28, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Clint", "Barton", 28, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Clint", "Barton", 28, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Phil", "Coulson", 28, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Maria", "Hill", 28, 26)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added"));
});
await connection.query(`INSERT INTO employee(firstName, lastName, roleID, managerID) VALUES("Kokomi", "Bader", 30, 1)`, function (err, res) {
if (err) throw err;
if (res) console.log(chalk.bold.green("Employee added. \n\n") + chalk.bold.yellow("DATABASE HAS BEEN RESET. LEAVING DATABASE"));
});
await connection.end(function(err,res){
if (err) throw err;
if (res) return console.log("Thank you")
})
},
}
module.exports = foreignQ |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-2-13.js
* @description Array.prototype.filter applied to the Array-like object that 'length' is inherited accessor property without a get function
*/
function testcase() {
var accessed = false;
function callbackfn(val, idx, obj) {
accessed = true;
return true;
}
var proto = {};
Object.defineProperty(proto, "length", {
set: function () { },
configurable: true
});
var Con = function () { };
Con.prototype = proto;
var child = new Con();
child[0] = 11;
child[1] = 12;
var newArr = Array.prototype.filter.call(child, callbackfn);
return newArr.length === 0 && !accessed;
}
runTestCase(testcase);
|
# library functions for handling job data
import re
import datetime
CAUSE_ACTION_CLASS = {
'timer': 'hudson.triggers.TimerTrigger$TimerTriggerCause',
'user': 'hudson.model.Cause$UserIdCause',
'upstream': 'hudson.model.Cause$UpstreamCause'
}
def get_stage_failure(build_stages):
''' takes in build stages dict
returns string with the name of failed stage or 'N/A' if there is no failed stage
'''
for stage in build_stages['stages']:
if stage['status'] == 'FAILED':
return stage.get('name', 'N/A')
return 'N/A'
def generate_failure_stage_log_urls(config, err_stage, job_url, lcb_num):
''' generates list of urls for failed build stages
'''
stage_urls = []
if 'stage_logs' in config and err_stage in config['stage_logs']:
for path in config['stage_logs'][err_stage]:
stage_urls.append("{}/{}/artifact/{}".format(job_url, lcb_num, path))
if not stage_urls:
stage_urls = None
return stage_urls
def get_jenkins_job_info(server, job_name, filter_param_name=None, filter_param_value=None, cause_action_class=None):
''' takes in jenkins server object and job name
optionally takes name and value of jenkins param to filter builds by
returns dict of API info for given job if success
returns False if failure
'''
# set default value for job_info for cased exception handling
job_info = {}
try:
job_info = server.get_job_info(job_name)
job_url = job_info['url']
lcb_num = job_info['lastCompletedBuild']['number']
tempest_tests_failed = None
stage_failure = 'N/A'
build_info = server.get_build_info(job_name, lcb_num)
build_actions = build_info['actions']
for action in build_actions:
if action.get('_class') in ['com.tikal.jenkins.plugins.multijob.MultiJobParametersAction', 'hudson.model.ParametersAction']:
build_parameters = action['parameters']
elif action.get('_class') in ['hudson.model.CauseAction']:
build_cause = action['causes'][0].get('_class', '')
elif action.get('_class') == 'hudson.tasks.junit.TestResultAction':
tempest_tests_failed = action['failCount']
# if desired, get last completed build with custom parameter and value or desired cause action class
if ((filter_param_name is not None and filter_param_value is not None) or cause_action_class is not None):
while True:
if cause_action_class is not None:
if CAUSE_ACTION_CLASS[cause_action_class] == build_cause:
break
if filter_param_name is not None:
api_param_value = [param['value'] for param in build_parameters if filter_param_name == param.get('name', '')][0]
if api_param_value == filter_param_value:
break
if build_info['previousBuild'] is None:
raise Exception("No filter match")
lcb_num = build_info['previousBuild']['number']
build_info = server.get_build_info(job_name, lcb_num)
build_actions = build_info['actions']
for action in build_actions:
if action.get('_class') in ['com.tikal.jenkins.plugins.multijob.MultiJobParametersAction', 'hudson.model.ParametersAction']:
build_parameters = action['parameters']
elif action.get('_class') in ['hudson.model.CauseAction']:
build_cause = action['causes'][0].get('_class', '')
elif action.get('_class') == 'hudson.tasks.junit.TestResultAction':
tempest_tests_failed = action['failCount']
build_time = build_info.get('timestamp')
build_days_ago = (datetime.datetime.now() - datetime.datetime.fromtimestamp(build_time / 1000)).days
lcb_url = build_info['url']
lcb_result = build_info['result']
composes = [str(action['html']).split('core_puddle:')[1].split('<')[0].strip() for action in build_actions if 'core_puddle' in action.get('html', '')]
if lcb_result == 'FAILURE':
build_stages = server.get_build_stages(job_name, lcb_num)
stage_failure = get_stage_failure(build_stages)
# No composes could be found; likely a failed job where the 'core_puddle' var was never calculated
if composes == []:
compose = "Could not find compose"
second_compose = None
# Two composes found - job is likely Update or Upgrade
elif len(composes) == 2:
compose = composes[0]
second_compose = composes[1]
# One compose found
else:
compose = composes[0]
second_compose = None
except Exception as e:
# No "Last Completed Build" found
# Checks for len <= 1 as running builds are included in the below query
# or check for filter exclusion
if len(job_info.get('builds')) <= 1 or str(e) == "No filter match":
lcb_num = None
lcb_url = None
compose = "N/A"
second_compose = None
build_days_ago = "N/A"
lcb_result = "NO_KNOWN_BUILDS"
stage_failure = 'N/A'
tempest_tests_failed = None
# Unknown error, skip job
else:
print("Jenkins API call error on job {}: {} - skipping...".format(job_name, e))
return False
jenkins_api_info = {
'job_url': job_url,
'lcb_num': lcb_num,
'lcb_url': lcb_url,
'compose': compose,
'second_compose': second_compose,
'lcb_result': lcb_result,
'build_days_ago': build_days_ago,
'tempest_tests_failed': tempest_tests_failed,
'stage_failure': stage_failure
}
return jenkins_api_info
def get_jenkins_jobs(server, job_search_fields, supported_versions):
''' takes in a Jenkins server object, job_search_fields string, and supported_versions list
returns list of jobs with given search field as part of their name
'''
# parse list of search fields
fields = job_search_fields.split(',')
fields_length = len(fields)
# remove spacing from strings
for i in range(fields_length):
fields[i] = fields[i].strip(' ')
# check for fields that contain valid regex
relevant_jobs = []
for field in fields:
try:
# fetch all jobs from server that match the given regex or search
all_jobs = server.get_job_info_regex(field)
# parse out all jobs that do not contain any search field and/or are not a supported version
for job in all_jobs:
job_name = job['name']
if any(supported_version in job_name for supported_version in supported_versions):
relevant_jobs.append(job)
except Exception as e:
print("Error compiling regex: {} - skipping this search field...".format(e))
return relevant_jobs
def get_osp_version(job_name, filter_version=None):
''' gets osp version from job name via regex
if multiple versions detected, the highest number is considered osp version
returns osp version as a string or None if no version is found
'''
if not filter_version or filter_version is None:
filter_version = r'1{1}[0,3,6]{1}\.{1}\d{1}|1{1}[0,3,6]{1}(?=\D+)'
versions = re.findall(
r'{filter_version}'.format(filter_version=filter_version),
job_name
)
if not versions:
return None
versions_f = map(float, versions)
max_value = max(versions_f)
return '{:g}'.format(max_value)
|
'use strict'
const Page = require('./page')
class ReviewPage extends Page {
get url () {
return '/review'
}
clickCancel () {
const clickCancel = browser.element('#return-summary')
clickCancel.click()
}
}
module.exports = new ReviewPage()
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[1618],{3030:function(t,e,r){"use strict";r.r(e);var a=r(19),o=Object(a.a)({},(function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[r("h1",{attrs:{id:"中间件"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#中间件"}},[t._v("#")]),t._v(" 中间件")]),t._v(" "),r("p",[t._v("本节包含有关 PX4 中间件,包括 PX4 内部通信机制("),r("RouterLink",{attrs:{to:"/zh/middleware/uorb.html"}},[t._v("uORB")]),t._v(")、 以及 PX4 与伴随计算机和 QCS(例如 "),r("RouterLink",{attrs:{to:"/zh/middleware/mavlink.html"}},[t._v("MAVLink")]),t._v(", "),r("RouterLink",{attrs:{to:"/zh/middleware/micrortps.html"}},[t._v("RTPS")]),t._v(")的离板系统之间的主题。")],1),t._v(" "),r("div",{staticClass:"custom-block tip"},[r("p",{staticClass:"custom-block-title"},[t._v("提示")]),t._v(" "),r("p",[t._v("For a detailed overview of the platform architecture see the "),r("RouterLink",{attrs:{to:"/zh/concept/architecture.html"}},[t._v("Architectural Overview")]),t._v(".")],1)])])}),[],!1,null,null,null);e.default=o.exports}}]); |
from matplotlib import pyplot as plt
from matplotlib import image as pltImg
import numpy as np
import pprint as pp
refCodes = { # Barcode language(for reading from right end to center)
'0' : [0, 0, 0, 1, 1, 0, 1],
'1' : [0, 0, 1, 1, 0, 0, 1],
'2' : [0, 0, 1, 0, 0, 1, 1],
'3' : [0, 1, 1, 1, 1, 0, 1],
'4' : [0, 1, 0, 0, 0, 1, 1],
'5' : [0, 1, 1, 0, 0, 0, 1],
'6' : [0, 1, 0, 1, 1, 1, 1],
'7' : [0, 1, 1, 1, 0, 1, 1],
'8' : [0, 1, 1, 0, 1, 1, 1],
'9' : [0, 0, 0, 1, 0, 1, 1]
}
B = [0, 0, 0] # Black
W = [255, 255, 255] # White
def toBinaryImage(data, h, w):
for i in range(h):
for j in range(w):
pix = data[i][j]
if (pix[0]/3 + pix[1]/3 + pix[2]/3 >= 127.5):
data[i][j] = [255, 255, 255]
else:
data[i][j] = [0, 0, 0]
return data
def getWidthOfStripes(lineInfo):
for i in range(len(lineInfo) - 1):
lineInfo[i][1] = lineInfo[i + 1][1] - lineInfo[i][1]
lineInfo.pop()
print("\nData with length of each stripe")
pp.pprint(lineInfo)
def printNoOfStripes(lineInfo):
sum = 0
for line in lineInfo:
sum += line[1]
unitLineLength = lineInfo[0][1]
totalStripes = sum/unitLineLength
print("\nWidth of scan area: " + str(sum) + "\n", "\bTotal Stripes: " + str(totalStripes))
def getLineInfo(imgPath, rowToScan):
# SETUP
ORIGINAL = pltImg.imread(imgPath)
height, width, mode = ORIGINAL.shape
OurCopy = ORIGINAL.copy()
lineInfo = []
# Create plot for image
plt.subplot(1, 2, 1)
plt.title("Working Image")
if (mode == 3):
# Change our image into B and W
Data = toBinaryImage(OurCopy, height, width)
underScan = W
# Record the indices of change in colour(stripes) and put it inside the array lineInfo
for i in range(width):
BorW = Data[rowToScan][i]
if (BorW[0] != underScan[0]):
if (BorW[0] == B[0]):
lineInfo.append(['B', i])
if (BorW[0] == W[0]):
lineInfo.append(['W', i])
plt.plot([i, i], [0, height], linewidth = 1)
underScan = BorW
print("Data with index(coloumns)"); pp.pprint(lineInfo)
# Few function calls
getWidthOfStripes(lineInfo)
printNoOfStripes(lineInfo)
# Plotting
plt.imshow(Data)
plt.subplot(1, 2, 2)
plt.title("Original")
plt.imshow(ORIGINAL)
else:
print("Image mode incompatible")
return lineInfo
def getBinaryCode(Stripes):
unitLength = Stripes[0][1]
binaryCode = []
for i, line in enumerate(Stripes):
for count in range(int(line[1]/unitLength)):
if (line[0] == 'B'):
binaryCode.append(0)
if (line[0] == 'W'):
binaryCode.append(1)
del binaryCode[0:3]; del binaryCode[42:47]; del binaryCode[-3:]
print("Stripes under scan: " + str(len(binaryCode)))
print("Binary Code of our barcode: " + str(binaryCode))
binaryCode = np.array_split(binaryCode, 2)
return binaryCode
def invertBits(arrayOfOnesAndZeroes):
def complement(n):
if (n == 0):
return 1
else:
return 0
return list(map(complement, arrayOfOnesAndZeroes))
def getCode(Stripes):
binaryCode = getBinaryCode(Stripes)
leftParity = np.array_split(binaryCode[0], 6);
rightParity = np.array_split(binaryCode[1], 6)
CodeArray = []
for refCode in leftParity:
for key, value in refCodes.items():
if (np.array_equal(refCode, invertBits(value))):
CodeArray.append(key)
break
for refCode in rightParity:
for key, value in refCodes.items():
if (np.array_equal(refCode, value)):
CodeArray.append(key)
break
print("Code Array: " + str(CodeArray))
lineInfo = getLineInfo('barImgs/bar6.jpg', 75)
getCode(lineInfo)
plt.show() |
MobData = {
33: [{ id: "0",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:51.56,posy:13.56, lv_min:0, lv_max:0, is_npc: false },
{ id: "1",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:42.13,posy:17.56, lv_min:0, lv_max:0, is_npc: false },
{ id: "2",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:53.00,posy:20.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "3",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:85.25,posy:13.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "4",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:82.63,posy:21.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "5",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:72.69,posy:23.44, lv_min:0, lv_max:0, is_npc: false },
{ id: "6",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:89.13,posy:19.44, lv_min:0, lv_max:0, is_npc: false },
{ id: "7",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:82.81,posy:33.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "8",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:69.19,posy:33.56, lv_min:0, lv_max:0, is_npc: false },
{ id: "9",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:68.63,posy:41.50, lv_min:0, lv_max:0, is_npc: false },
{ id: "10",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:81.19,posy:42.88, lv_min:0, lv_max:0, is_npc: false },
{ id: "11",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:101.13,posy:29.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "12",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:97.00,posy:32.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "13",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:95.75,posy:54.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "14",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:97.38,posy:74.19, lv_min:0, lv_max:0, is_npc: false },
{ id: "15",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:106.56,posy:66.13, lv_min:0, lv_max:0, is_npc: false },
{ id: "16",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:113.63,posy:75.06, lv_min:0, lv_max:0, is_npc: false },
{ id: "17",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:122.56,posy:64.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "18",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:114.44,posy:55.75, lv_min:0, lv_max:0, is_npc: false },
{ id: "19",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:136.31,posy:58.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "20",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:126.06,posy:45.69, lv_min:0, lv_max:0, is_npc: false },
{ id: "21",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:125.31,posy:52.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "22",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:148.44,posy:53.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "23",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:141.75,posy:44.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "24",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:137.44,posy:35.69, lv_min:0, lv_max:0, is_npc: false },
{ id: "25",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:151.53,posy:33.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "26",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:155.13,posy:15.31, lv_min:0, lv_max:0, is_npc: false },
{ id: "27",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:152.06,posy:19.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "28",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:143.69,posy:14.88, lv_min:0, lv_max:0, is_npc: false },
{ id: "29",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:135.13,posy:21.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "30",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:131.00,posy:15.50, lv_min:0, lv_max:0, is_npc: false },
{ id: "31",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:141.06,posy:17.69, lv_min:0, lv_max:0, is_npc: false },
{ id: "32",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:64.19,posy:59.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "33",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:48.31,posy:51.69, lv_min:0, lv_max:0, is_npc: false },
{ id: "34",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:46.56,posy:56.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "35",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:56.81,posy:59.94, lv_min:0, lv_max:0, is_npc: false },
{ id: "36",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:58.50,posy:73.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "37",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:51.75,posy:79.50, lv_min:0, lv_max:0, is_npc: false },
{ id: "38",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:61.31,posy:77.38, lv_min:0, lv_max:0, is_npc: false },
{ id: "39",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:28.31,posy:70.06, lv_min:0, lv_max:0, is_npc: false },
{ id: "40",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:21.13,posy:79.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "41",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:26.69,posy:80.44, lv_min:0, lv_max:0, is_npc: false },
{ id: "42",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:32.00,posy:75.06, lv_min:0, lv_max:0, is_npc: false },
{ id: "43",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:15.69,posy:59.44, lv_min:0, lv_max:0, is_npc: false },
{ id: "44",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:17.69,posy:45.50, lv_min:0, lv_max:0, is_npc: false },
{ id: "45",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:14.44,posy:50.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "46",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:20.81,posy:48.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "47",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:22.81,posy:60.31, lv_min:0, lv_max:0, is_npc: false },
{ id: "48",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:24.31,posy:73.75, lv_min:0, lv_max:0, is_npc: false },
{ id: "49",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:55.75,posy:76.06, lv_min:0, lv_max:0, is_npc: false },
{ id: "50",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:69.56,posy:82.13, lv_min:0, lv_max:0, is_npc: false },
{ id: "51",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:50.13,posy:63.88, lv_min:0, lv_max:0, is_npc: false },
{ id: "52",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:42.81,posy:53.44, lv_min:0, lv_max:0, is_npc: false },
{ id: "53",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:69.31,posy:54.56, lv_min:0, lv_max:0, is_npc: false },
{ id: "54",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:67.25,posy:37.31, lv_min:0, lv_max:0, is_npc: false },
{ id: "55",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:85.00,posy:37.13, lv_min:0, lv_max:0, is_npc: false },
{ id: "56",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:94.50,posy:28.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "57",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:80.13,posy:18.31, lv_min:0, lv_max:0, is_npc: false },
{ id: "58",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:50.06,posy:16.94, lv_min:0, lv_max:0, is_npc: false },
{ id: "59",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:127.31,posy:19.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "60",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:158.44,posy:18.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "61",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:152.09,posy:29.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "62",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:142.69,posy:38.13, lv_min:0, lv_max:0, is_npc: false },
{ id: "63",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:137.38,posy:46.31, lv_min:0, lv_max:0, is_npc: false },
{ id: "64",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:141.63,posy:55.88, lv_min:0, lv_max:0, is_npc: false },
{ id: "65",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:122.00,posy:58.56, lv_min:0, lv_max:0, is_npc: false },
{ id: "66",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:115.38,posy:66.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "67",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:103.50,posy:59.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "68",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:101.19,posy:70.50, lv_min:0, lv_max:0, is_npc: false },
{ id: "69",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:65.06,posy:80.81, lv_min:0, lv_max:0, is_npc: false },
{ id: "70",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:33.69,posy:78.94, lv_min:0, lv_max:0, is_npc: false },
{ id: "71",name:"ゾンビド",type:2,inid:2,repop:30,isptboss:0,posx:54.06,posy:55.19, lv_min:0, lv_max:0, is_npc: false },
{ id: "72",name:"ゾンビド",type:2,inid:2,repop:30,isptboss:0,posx:122.75,posy:56.25, lv_min:0, lv_max:0, is_npc: false },
{ id: "73",name:"ゾンビド",type:2,inid:2,repop:30,isptboss:0,posx:149.63,posy:13.69, lv_min:0, lv_max:0, is_npc: false },
{ id: "74",name:"ゾンビド",type:2,inid:2,repop:30,isptboss:0,posx:19.81,posy:76.63, lv_min:0, lv_max:0, is_npc: false },
{ id: "75",name:"堕落魔法師",type:2,inid:1,repop:30,isptboss:0,posx:158.94,posy:72.72, lv_min:0, lv_max:0, is_npc: false },
{ id: "76",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:165.22,posy:73.00, lv_min:0, lv_max:0, is_npc: false },
{ id: "77",name:"ゾンビ",type:2,inid:0,repop:30,isptboss:0,posx:161.56,posy:77.25, lv_min:0, lv_max:0, is_npc: false },
]};
AreaData = {
33: [{ id: "0",name:"none",area_name:"_필드 전체",type:0,posx:0.00,posx2:0.00,access_map:"none",posy:0.00,posy2:0.00,is_secret:0},
{ id: "1",name:"none",area_name:"_화면",type:0,posx:0.00,posx2:0.00,access_map:"none",posy:0.00,posy2:0.00,is_secret:0},
{ id: "2",name:"路上強盗団アジト B2",area_name:"B2로..3",type:3,posx:19.25,posx2:22.81,access_map:"[034]G15_D01_B02.rmd",posy:33.69,posy2:35.44,is_secret:0},
{ id: "3",name:"路上強盗団アジト 1F",area_name:"1F로 2",type:3,posx:21.97,posx2:25.53,access_map:"[032]G15_D01_F01.rmd",posy:16.50,posy2:18.22,is_secret:0},
{ id: "4",name:"none",area_name:"Area 3",type:4,posx:39.38,posx2:59.25,access_map:"none",posy:6.63,posy2:23.63,is_secret:0},
{ id: "5",name:"none",area_name:"Area 4",type:4,posx:63.00,posx2:93.50,access_map:"none",posy:8.25,posy2:27.13,is_secret:0},
{ id: "6",name:"none",area_name:"Area 5",type:4,posx:61.13,posx2:88.00,access_map:"none",posy:29.88,posy2:44.50,is_secret:0},
{ id: "7",name:"none",area_name:"Area 6",type:4,posx:91.00,posx2:110.13,access_map:"none",posy:25.25,posy2:35.25,is_secret:0},
{ id: "8",name:"none",area_name:"Area 7",type:4,posx:122.50,posx2:164.00,access_map:"none",posy:9.75,posy2:24.63,is_secret:0},
{ id: "9",name:"none",area_name:"Area 8",type:4,posx:131.38,posx2:153.19,access_map:"none",posy:27.75,posy2:44.88,is_secret:0},
{ id: "10",name:"none",area_name:"Area 9",type:4,posx:116.38,posx2:154.00,access_map:"none",posy:40.63,posy2:60.88,is_secret:0},
{ id: "11",name:"none",area_name:"Area 10",type:4,posx:89.25,posx2:127.50,access_map:"none",posy:49.00,posy2:80.38,is_secret:0},
{ id: "12",name:"none",area_name:"Area 11",type:4,posx:11.00,posx2:40.50,access_map:"none",posy:67.25,posy2:84.00,is_secret:0},
{ id: "13",name:"none",area_name:"Area 12",type:4,posx:37.63,posx2:70.88,access_map:"none",posy:46.63,posy2:65.75,is_secret:0},
{ id: "14",name:"none",area_name:"Area 13",type:4,posx:7.63,posx2:31.63,access_map:"none",posy:42.25,posy2:61.75,is_secret:0},
{ id: "15",name:"none",area_name:"Area 14",type:4,posx:44.88,posx2:71.13,access_map:"none",posy:69.88,posy2:86.00,is_secret:0},
{ id: "16",name:"路上強盗団アジト B2",area_name:"B2로 2",type:3,posx:16.66,posx2:20.06,access_map:"[034]G15_D01_B02.rmd",posy:76.13,posy2:77.97,is_secret:0},
{ id: "17",name:"路上強盗団アジト B2",area_name:"B2로 1",type:3,posx:162.97,posx2:165.88,access_map:"[034]G15_D01_B02.rmd",posy:26.06,posy2:27.75,is_secret:0},
{ id: "18",name:"none",area_name:"Area 17",type:4,posx:154.03,posx2:171.50,access_map:"none",posy:68.84,posy2:82.06,is_secret:0},
{ id: "19",name:"路上強盗団アジト 1F",area_name:"1F로 1",type:3,posx:47.13,posx2:50.56,access_map:"[032]G15_D01_F01.rmd",posy:42.28,posy2:44.44,is_secret:0},
{ id: "20",name:"none",area_name:"보물상자00",type:13,posx:151.97,posx2:153.97,access_map:"none",posy:77.06,posy2:77.97,is_secret:0},
{ id: "21",name:"none",area_name:"보물상자01",type:13,posx:130.09,posx2:131.94,access_map:"none",posy:65.09,posy2:65.97,is_secret:0},
{ id: "22",name:"none",area_name:"보물상자02",type:13,posx:105.81,posx2:107.81,access_map:"none",posy:58.03,posy2:58.97,is_secret:0},
{ id: "23",name:"none",area_name:"보물상자03",type:13,posx:146.03,posx2:147.94,access_map:"none",posy:8.03,posy2:8.81,is_secret:0},
{ id: "24",name:"none",area_name:"보물상자04",type:13,posx:98.06,posx2:99.94,access_map:"none",posy:25.03,posy2:25.94,is_secret:0},
{ id: "25",name:"none",area_name:"보물상자05",type:13,posx:52.13,posx2:54.25,access_map:"none",posy:61.06,posy2:61.91,is_secret:0},
]};
|
import argparse
from datetime import datetime
from decimal import Decimal
import json
import logging
import math
import os
import pathlib
from perfsize.perfsize import (
lt,
gte,
Condition,
Plan,
Workflow,
)
from perfsize.reporter.mock import MockReporter
from perfsize.result.gatling import GatlingResultManager, Metric
from perfsizesagemaker.cost import CostEstimator
from perfsizesagemaker.environment.sagemaker import SageMakerEnvironmentManager
from perfsizesagemaker.load.sagemaker import SageMakerLoadManager
from perfsizesagemaker.reporter.html import HTMLReporter
from perfsizesagemaker.step.sagemaker import FirstSuccessStepManager
from perfsizesagemaker.constants import Parameter, SageMaker
from pprint import pformat
import sys
from typing import Dict, Optional
import yaml
log = logging.getLogger(__name__)
def get_timestamp_utc() -> str:
"""Return current time as a formatted string."""
return datetime.utcnow().strftime("%Y-%m-%d-%H%M%S")
def validate_scenario_requests(input: str) -> None:
"""Confirm request payload files are valid and weights sum to 100."""
# TODO: See how to handle different file encoding types.
items = json.loads(input)
if not items:
raise RuntimeError("ERROR: scenario must contain at least one element")
sum_of_weights = 0
for item in items:
path = item["path"]
if not pathlib.Path(path).exists():
raise RuntimeError(f"ERROR: file {path} does not exist")
weight = item["weight"]
if weight < 0:
raise RuntimeError(f"ERROR: file {path} had negative weight: {weight}")
sum_of_weights = sum_of_weights + weight
if sum_of_weights != 100:
raise RuntimeError(f"ERROR: expected sum_of_weights=100, got: {sum_of_weights}")
class Main:
def __init__(self) -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--iam_role_arn",
help="role to assume to get credentials, otherwise will get credentials from environment",
required=False,
)
parser.add_argument(
"--host", help="SageMaker runtime host", required=True,
)
parser.add_argument(
"--region", help="region name for boto3 and cost lookup", required=True,
)
parser.add_argument(
"--endpoint_name", help="name of SageMaker Endpoint", required=True
)
parser.add_argument(
"--endpoint_config_name",
help="name of SageMaker EndpointConfig",
required=True,
)
parser.add_argument(
"--model_name", help="name of SageMaker Model", required=True
)
parser.add_argument(
"--scenario_requests",
help="json array of request file paths and weights",
required=True,
)
parser.add_argument("--peak_tps", help="required highest TPS", required=True)
parser.add_argument(
"--latency_success_p99", help="allowed p99 latency", required=True
)
parser.add_argument(
"--percent_fail", help="allowed failure percentage", required=True
)
parser.add_argument(
"--type_walk", help="comma separated instance types to test", required=True,
)
parser.add_argument(
"--count_walk", help="comma separated counts to test", required=True
)
parser.add_argument(
"--tps_walk", help="comma separated TPS values to test", required=True
)
parser.add_argument(
"--duration_minutes", help="duration in minutes for type tests", default=3
)
parser.add_argument(
"--endurance_ramp_start_tps",
help="TPS at start of endurance test ramp",
default=0,
)
parser.add_argument(
"--endurance_ramp_minutes",
help="duration in minutes for endurance test ramp",
default=0,
)
parser.add_argument(
"--endurance_steady_state_minutes",
help="duration in minutes for endurance steady state",
default=30,
)
parser.add_argument(
"--endurance_retries",
help="number of times to retry endurance test",
default=3,
)
parser.add_argument(
"--perfsize_results_dir",
help="directory for saving test results",
default="perfsize-results-dir",
)
parser.add_argument(
"--cost_file",
help="path to file mapping instance type to hourly rate",
default="resources/configs/cost/us-west-2.json",
)
parser.add_argument(
"--jar_file",
help="path to sagmaker-gatling.jar file",
default="sagemaker-gatling.jar",
)
parser.add_argument(
"--logging_config",
help="path to logging.yml file",
default="resources/configs/logging/logging.yml",
)
args = parser.parse_args()
# Tried setting type checking directly in add_argument but the error message
# result was not specific enough and only showed a stacktrace on parse_args.
# Do additional validation.
self.iam_role_arn = args.iam_role_arn
self.host = args.host
self.region = args.region
self.endpoint_name = args.endpoint_name
self.endpoint_config_name = args.endpoint_config_name
self.model_name = args.model_name
self.scenario_requests = args.scenario_requests
try:
json.loads(self.scenario_requests)
validate_scenario_requests(self.scenario_requests)
except:
error = sys.exc_info()[0]
description = sys.exc_info()[1]
parser.error(
f"argument --scenario_requests: got error {error}: {description}"
)
try:
self.peak_tps = Decimal(args.peak_tps)
except:
parser.error(
f"argument --peak_tps: expected a number but got: {args.peak_tps}"
)
try:
self.latency_success_p99 = Decimal(args.latency_success_p99)
except:
parser.error(
f"argument --latency_success_p99: expected a number but got: {args.latency_success_p99}"
)
try:
self.percent_fail = Decimal(args.percent_fail)
except:
parser.error(
f"argument --percent_fail: expected a number but got: {args.percent_fail}"
)
try:
self.type_walk = args.type_walk.split(",")
except:
parser.error(
f"argument --type_walk: expected a comma separated list of strings but got: {args.type_walk}"
)
try:
self.count_walk = list(map(int, args.count_walk.split(",")))
except:
parser.error(
f"argument --count_walk: expected a comma separated list of integers but got: {args.count_walk}"
)
try:
self.tps_walk = list(map(Decimal, args.tps_walk.split(",")))
except:
parser.error(
f"argument --tps_walk: expected a comma separated list of numbers but got: {args.tps_walk}"
)
try:
self.duration_minutes = Decimal(args.duration_minutes)
except:
parser.error(
f"argument --duration_minutes: expected a number but got: {args.duration_minutes}"
)
try:
self.endurance_ramp_start_tps = Decimal(args.endurance_ramp_start_tps)
except:
parser.error(
f"argument --endurance_ramp_start_tps: expected a number but got: {args.endurance_ramp_start_tps}"
)
try:
self.endurance_ramp_minutes = Decimal(args.endurance_ramp_minutes)
except:
parser.error(
f"argument --endurance_ramp_minutes: expected a number but got: {args.endurance_ramp_minutes}"
)
try:
self.endurance_steady_state_minutes = Decimal(
args.endurance_steady_state_minutes
)
except:
parser.error(
f"argument --endurance_steady_state_minutes: expected a number but got: {args.endurance_steady_state_minutes}"
)
try:
self.endurance_retries = int(args.endurance_retries)
except:
parser.error(
f"argument --endurance_retries: expected an integer but got: {args.endurance_retries}"
)
self.perfsize_results_dir = args.perfsize_results_dir
if not os.path.isdir(self.perfsize_results_dir):
os.mkdir(self.perfsize_results_dir)
job_id = f"job-{get_timestamp_utc()}-{self.model_name}"
self.job_id_dir = self.perfsize_results_dir + os.sep + job_id
if not os.path.isdir(self.job_id_dir):
os.mkdir(self.job_id_dir)
try:
self.cost_file = args.cost_file
self.cost = CostEstimator(self.cost_file)
except:
parser.error(f"argument --cost_file: error loading {args.cost_file}")
self.jar_file = args.jar_file
if not pathlib.Path(self.jar_file).exists():
parser.error(f"argument --jar_file not found: {self.jar_file}")
self.logging_config = args.logging_config
if not pathlib.Path(self.logging_config).exists():
parser.error(f"argument --logging_config not found: {self.logging_config}")
# Initialize logger if config file exists
with open(self.logging_config, "r") as stream:
config = yaml.safe_load(stream)
logging.config.dictConfig(config)
for name in logging.root.manager.loggerDict: # type: ignore
if name.startswith("perfsize"):
logging.getLogger(name).setLevel(logging.DEBUG)
# TODO: Make arg parsing more generic. For now, only handling latency_success_p99 and percent_fail.
self.requirements = {
Metric.latency_success_p99: [
Condition(
lt(self.latency_success_p99),
f"latency_success_p99 < {self.latency_success_p99}",
),
Condition(gte(Decimal("0")), "latency_success_p99 >= 0"),
],
Metric.percent_fail: [
Condition(lt(self.percent_fail), f"percent_fail < {self.percent_fail}"),
Condition(gte(Decimal("0")), "percent_fail >= 0"),
],
}
log.info(f"Starting perfsize with requirements: {self.requirements}")
# Track findings for each testing phase
self.type_plan: Optional[Plan] = None
self.max_count_plan: Optional[Plan] = None
self.min_count_plan: Optional[Plan] = None
self.recommend_type: Optional[Dict[str, str]] = None
self.recommend_max: Optional[Dict[str, str]] = None
self.recommend_min: Optional[Dict[str, str]] = None
def test_type(self) -> Optional[Dict[str, str]]:
# Phase 1: Find working instance type.
# The goal is to find the first instance type that works and how much
# load it can handle.
# The count should default to 1, but user might override with a list of
# higher counts. Final TPS per instance would just need to be calculated
# accordingly.
self.type_plan = Plan(
parameter_lists={
Parameter.host: [self.host],
Parameter.region: [self.region],
Parameter.endpoint_name: [self.endpoint_name],
Parameter.endpoint_config_name: [self.endpoint_config_name],
Parameter.model_name: [self.model_name],
Parameter.instance_type: self.type_walk,
Parameter.initial_instance_count: list(map(str, self.count_walk)),
Parameter.ramp_start_tps: ["0"],
Parameter.ramp_minutes: ["0"],
Parameter.steady_state_tps: list(map(str, self.tps_walk)),
Parameter.steady_state_minutes: [f"{self.duration_minutes}"],
},
requirements=self.requirements,
)
log.info(f"Testing instance type with plan: {self.type_plan}")
type_workflow = Workflow(
plan=self.type_plan,
step_manager=FirstSuccessStepManager(self.type_plan),
environment_manager=SageMakerEnvironmentManager(
self.iam_role_arn, self.region
),
load_manager=SageMakerLoadManager(
scenario_requests=self.scenario_requests,
gatling_jar_path=self.jar_file,
gatling_scenario="GenericSageMakerScenario",
gatling_results_path=self.job_id_dir,
iam_role_arn=self.iam_role_arn,
region=self.region,
),
result_managers=[GatlingResultManager(results_path=self.job_id_dir)],
reporters=[MockReporter()],
teardown_between_steps=False,
teardown_at_end=True,
)
type_recommendation = type_workflow.run()
log.debug(
f"Test for instance type got recommendation: {pformat(type_recommendation)}"
)
if not type_recommendation:
log.error(f"Test failed to find a working instance type from given list.")
return None
instance_type = type_recommendation[Parameter.instance_type]
initial_instance_count = Decimal(
type_recommendation[Parameter.initial_instance_count]
)
steady_state_tps = Decimal(type_recommendation[Parameter.steady_state_tps])
tps_per_instance = steady_state_tps / initial_instance_count
instance_count_needed = math.ceil(self.peak_tps / tps_per_instance)
recommend_type: Dict[str, str] = {}
recommend_type[Parameter.instance_type] = instance_type
recommend_type[Parameter.initial_instance_count] = f"{initial_instance_count}"
recommend_type[Parameter.steady_state_tps] = f"{steady_state_tps}"
recommend_type["tps_per_instance"] = f"{tps_per_instance}"
recommend_type["instance_count_needed"] = f"{instance_count_needed}"
recommend_type["explanation"] = (
f"Last green run was {steady_state_tps} TPS supported by {initial_instance_count} instances of {instance_type}.\n"
f"{steady_state_tps} / {initial_instance_count} = {tps_per_instance} TPS per instance.\n"
f"To support {self.peak_tps} TPS, we need ceiling({self.peak_tps} / {tps_per_instance}) = {instance_count_needed} instances."
)
log.info(f"recommend_type: {pformat(recommend_type)}")
return recommend_type
def test_max(
self, instance_type: str, instance_count_needed: int
) -> Optional[Dict[str, str]]:
# Phase 2: Find instance count needed for max TPS.
# Second set limits instance type to the one found above.
# The goal is to find the number of instances needed to support given
# peak load. This number is calculated as instance_count_needed,
# assuming linear extrapolation. But just in case it fails,
# the test plan includes some endurance_retries.
self.max_count_plan = Plan(
parameter_lists={
Parameter.host: [self.host],
Parameter.region: [self.region],
Parameter.endpoint_name: [self.endpoint_name],
Parameter.endpoint_config_name: [self.endpoint_config_name],
Parameter.model_name: [self.model_name],
Parameter.instance_type: [instance_type],
Parameter.initial_instance_count: list(
map(
str,
range(
instance_count_needed,
instance_count_needed + self.endurance_retries + 1,
),
)
),
Parameter.ramp_start_tps: ["0"],
Parameter.ramp_minutes: ["0"],
Parameter.steady_state_tps: [f"{self.peak_tps}"],
Parameter.steady_state_minutes: [
f"{self.endurance_steady_state_minutes}"
],
},
requirements=self.requirements,
)
log.info(f"Testing instance count with plan: {self.max_count_plan}")
max_count_workflow = Workflow(
plan=self.max_count_plan,
step_manager=FirstSuccessStepManager(self.max_count_plan),
environment_manager=SageMakerEnvironmentManager(
self.iam_role_arn, self.region
),
load_manager=SageMakerLoadManager(
scenario_requests=self.scenario_requests,
gatling_jar_path=self.jar_file,
gatling_scenario="GenericSageMakerScenario",
gatling_results_path=self.job_id_dir,
iam_role_arn=self.iam_role_arn,
region=self.region,
),
result_managers=[GatlingResultManager(results_path=self.job_id_dir)],
reporters=[MockReporter()],
teardown_between_steps=True,
teardown_at_end=True,
)
max_count_recommendation = max_count_workflow.run()
log.debug(
f"Test for instance count got recommendation: {pformat(max_count_recommendation)}"
)
if not max_count_recommendation:
log.error(f"Test failed to find a working instance count for peak TPS.")
return None
max_instance_count = int(
max_count_recommendation[Parameter.initial_instance_count]
)
max_steady_state_tps = Decimal(
max_count_recommendation[Parameter.steady_state_tps]
)
max_tps_per_instance = max_steady_state_tps / max_instance_count
invocations_target = int(
self.peak_tps / max_instance_count * 60 * SageMaker.SAFETY_FACTOR
)
recommend_max: Dict[str, str] = {}
recommend_max["max_instance_count"] = f"{max_instance_count}"
recommend_max["max_steady_state_tps"] = f"{max_steady_state_tps}"
recommend_max["max_tps_per_instance"] = f"{max_tps_per_instance}"
recommend_max["max_cost"] = self.cost.explain(instance_type, max_instance_count)
recommend_max["invocations_target"] = f"{invocations_target}"
recommend_max["explanation"] = (
f"Last green run was {max_steady_state_tps} TPS supported by {max_instance_count} instances of {instance_type}.\n"
f"max_tps_per_instance = {max_steady_state_tps} / {max_instance_count} = {max_tps_per_instance} TPS per instance.\n"
f"Autoscaling metric (SageMakerVariantInvocationsPerInstance):\n"
f"= int(max_tps_per_instance * 60 seconds/minute * safety_factor)\n"
f"= int({max_tps_per_instance} * 60 * {SageMaker.SAFETY_FACTOR})\n"
f"= {invocations_target} invocations / instance / minute"
)
log.info(f"recommend_max: {pformat(recommend_max)}")
return recommend_max
def test_min(
self, instance_type: str, max_instance_count: int, invocations_target: int
) -> Optional[Dict[str, str]]:
# Phase 3: Find min instance count that can still support given ramp time.
# Third set limits instance type and max count to values found above.
# The goal is to find the number of instances needed to support given
# ramp from starting TPS to peak TPS over ramp minutes.
# TODO: Implement...
self.min_count_plan = None
log.info(f"Testing min instance count with plan: {self.min_count_plan}")
min_count_workflow = None
min_count_recommendation = None
recommend_min: Dict[str, str] = {}
recommend_min["min_instance_count"] = "-" # TODO: implement
recommend_min["min_cost"] = "-" # TODO: implement
log.info(f"recommend_min: {pformat(recommend_min)}")
return recommend_min
def main(self) -> None:
inputs: Dict[str, str] = {}
inputs["iam_role_arn"] = f"{self.iam_role_arn}"
inputs["host"] = f"{self.host}"
inputs["region"] = f"{self.region}"
inputs["endpoint_name"] = f"{self.endpoint_name}"
inputs["endpoint_config_name"] = f"{self.endpoint_config_name}"
inputs["model_name"] = f"{self.model_name}"
inputs["scenario_requests"] = f"{self.scenario_requests}"
inputs["peak_tps"] = f"{self.peak_tps}"
inputs["latency_success_p99"] = f"{self.latency_success_p99}"
inputs["percent_fail"] = f"{self.percent_fail}"
inputs["type_walk"] = f"{self.type_walk}"
inputs["count_walk"] = f"{self.count_walk}"
inputs["tps_walk"] = f"{self.tps_walk}"
inputs["duration_minutes"] = f"{self.duration_minutes}"
inputs["endurance_ramp_start_tps"] = f"{self.endurance_ramp_start_tps}"
inputs["endurance_ramp_minutes"] = f"{self.endurance_ramp_minutes}"
inputs[
"endurance_steady_state_minutes"
] = f"{self.endurance_steady_state_minutes}"
inputs["endurance_retries"] = f"{self.endurance_retries}"
inputs["perfsize_results_dir"] = f"{self.perfsize_results_dir}"
inputs["job_id_dir"] = f"{self.job_id_dir}"
inputs["cost_file"] = f"{self.cost_file}"
inputs["jar_file"] = f"{self.jar_file}"
inputs["logging_config"] = f"{self.logging_config}"
log.debug(f"inputs: {pformat(inputs)}")
self.recommend_type = self.test_type()
if self.recommend_type:
instance_type = self.recommend_type[Parameter.instance_type]
instance_count_needed = int(self.recommend_type["instance_count_needed"])
self.recommend_max = self.test_max(
instance_type=instance_type, instance_count_needed=instance_count_needed
)
if self.recommend_max:
max_instance_count = int(self.recommend_max["max_instance_count"])
invocations_target = int(self.recommend_max["invocations_target"])
self.recommend_min = self.test_min(
instance_type=instance_type,
max_instance_count=max_instance_count,
invocations_target=invocations_target,
)
# Generate final report...
reporter = HTMLReporter(
inputs=inputs,
type_plan=self.type_plan,
max_count_plan=self.max_count_plan,
min_count_plan=self.min_count_plan,
recommend_type=self.recommend_type,
recommend_max=self.recommend_max,
recommend_min=self.recommend_min,
)
content = reporter.render()
report_file = f"{self.job_id_dir}/Final_Job_Report.html"
with open(report_file, "w") as file:
file.write(content)
# TODO: Add flag to save files to S3...
log.info(f"See report at {report_file}")
if __name__ == "__main__":
m = Main()
m.main()
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var METADATA_KEY = require("../constants/metadata_keys");
var MetadataReader = (function () {
function MetadataReader() {
}
MetadataReader.prototype.getConstructorMetadata = function (constructorFunc) {
var compilerGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.PARAM_TYPES, constructorFunc);
var userGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.TAGGED, constructorFunc);
return {
compilerGeneratedMetadata: compilerGeneratedMetadata,
userGeneratedMetadata: userGeneratedMetadata || {}
};
};
MetadataReader.prototype.getPropertiesMetadata = function (constructorFunc) {
var userGeneratedMetadata = Reflect.getMetadata(METADATA_KEY.TAGGED_PROP, constructorFunc) || [];
return userGeneratedMetadata;
};
return MetadataReader;
}());
exports.MetadataReader = MetadataReader;
|
"""
Medium puzzle
Algorithm to find scores while climbing the leaderboard
Given 2 sorted lists:
- Scoreboard: [100, 100, 80, 60]
- Alice: [50, 60, 75, 105]
Find the scores of alice
Ans: [3, 2, 2, 1]
"""
def countRankings(arr):
# Gets initial rankings
count = 1
if len(arr) == 1:
return count
for i in range(1, len(arr), 1):
if arr[i] != arr[i - 1]:
count += 1
return count
# Complete the climbingLeaderboard function below.
# Overall algo: time complexity O(nm)
def climbingLeaderboard(scores, alice):
current = countRankings(scores) + 1
ptr = len(scores) - 1
arr = []
prev = 0
# iterate through alice's scores
for alice_score in alice:
# while condition to move pointer
while (ptr >= 0):
if scores[ptr] == prev:
ptr -= 1
continue
# check if larger than score
if scores[ptr] > alice_score:
break
current -= 1
prev = scores[ptr]
ptr -= 1
# once stop moving pointer, append to array
arr.append(current)
return arr
|
import React from "react"
import useActiveMenu from "../hooks/ActiveMenu"
const MenuCancelIcon = () => {
const { setMenuOpen, giftOpen, setGiftOpen } = useActiveMenu()
const handleClick = () => {
if (giftOpen) {
setGiftOpen(false)
} else {
setMenuOpen(false)
}
}
return (
<svg
xmlns="http://www.w3.org/2000/svg"
onClick={() => handleClick()}
viewBox="0 0 39.914 39.914"
height="2rem"
>
<path
id="LaTrobe_Icon_Library-20"
data-name="LaTrobe Icon Library-20"
d="M39.914,1.414,38.5,0,19.957,18.543,1.414,0,0,1.414,18.543,19.957,0,38.5l1.414,1.414L19.957,21.371,38.5,39.914,39.914,38.5,21.371,19.957Z"
fill="#fff"
/>
</svg>
)
}
export default MenuCancelIcon
|
import pytest
import pandas as pd
from laptimize.curve_approximation import CurveApproximator
problem = pd.DataFrame({'objective': {'x1': lambda x: 12*x if x > 0 else 2, 'x2':lambda x: 7*x - x**2},
'constraints_1': {'x1': lambda x: -2*(x**4), 'x2': lambda x: -x, 'value': -2},
'constraints_2': {'x1': lambda x: 2*x, 'x2': lambda x: x, 'value': 3},
'capacity': {'x1': [0, 2], 'x2': [0, 3]}})
x_array = [0, 1, 2, 3, 4, 5, 6]
@pytest.fixture
def curve_approximation():
return CurveApproximator()
def test_curve_piecewise_approximation(curve_approximation):
constraint = problem.iloc[1, :-1]
result = curve_approximation.get_curve_approximation(constraint, x_array)
assert len(result) == 3
assert len(result['objective']) == len(x_array)
def test_curve_piecewise_exception(curve_approximation):
constraint = problem.iloc[0, :-1]
result = curve_approximation.get_curve_approximation(constraint, x_array)
assert len(result) == 3
assert result['objective'][0] == 2
|
'use strict';
var SwaggerParser = require('swagger-parser'),
InputValidationError = require('./inputValidationError'),
schemaPreprocessor = require('./utils/schema-preprocessor'),
swagger3 = require('./swagger3/open-api3'),
swagger2 = require('./swagger2'),
ajvUtils = require('./utils/ajv-utils'),
Ajv = require('ajv'),
sourceResolver = require('./utils/sourceResolver');
var schemas = {};
var middlewareOptions;
var framework;
/**
* Initialize the input validation middleware
* @param {string} swaggerPath - the path for the swagger file
* @param {Object} options - options.formats to add formats to ajv, options.beautifyErrors, options.firstError, options.expectFormFieldsInBody, options.fileNameField (default is 'fieldname' - multer package), options.ajvConfigBody and options.ajvConfigParams for config object that will be passed for creation of Ajv instance used for validation of body and parameters appropriately
*/
function init(swaggerPath, options) {
middlewareOptions = options || {};
framework = middlewareOptions.framework ? require(`./frameworks/${middlewareOptions.framework}`) : require('./frameworks/express');
const makeOptionalAttributesNullable = middlewareOptions.makeOptionalAttributesNullable || false;
return Promise.all([
SwaggerParser.dereference(swaggerPath),
SwaggerParser.parse(swaggerPath)
]).then(function (swaggers) {
const dereferenced = swaggers[0];
Object.keys(dereferenced.paths).forEach(function (currentPath) {
let pathParameters = dereferenced.paths[currentPath].parameters || [];
let parsedPath = dereferenced.basePath && dereferenced.basePath !== '/' ? dereferenced.basePath.concat(currentPath.replace(/{/g, ':').replace(/}/g, '')) : currentPath.replace(/{/g, ':').replace(/}/g, '');
schemas[parsedPath] = {};
Object.keys(dereferenced.paths[currentPath]).filter(function (parameter) { return parameter !== 'parameters' })
.forEach(function (currentMethod) {
schemas[parsedPath][currentMethod.toLowerCase()] = {};
const isOpenApi3 = dereferenced.openapi === '3.0.0';
const parameters = dereferenced.paths[currentPath][currentMethod].parameters || [];
if (isOpenApi3){
schemas[parsedPath][currentMethod].body = swagger3.buildBodyValidation(dereferenced, swaggers[1], currentPath, currentMethod, middlewareOptions);
} else {
let bodySchema = middlewareOptions.expectFormFieldsInBody
? parameters.filter(function (parameter) { return (parameter.in === 'body' || (parameter.in === 'formData' && parameter.type !== 'file')) })
: parameters.filter(function (parameter) { return parameter.in === 'body' });
if (makeOptionalAttributesNullable) {
schemaPreprocessor.makeOptionalAttributesNullable(bodySchema);
}
if (bodySchema.length > 0) {
const validatedBodySchema = swagger2.getValidatedBodySchema(bodySchema);
schemas[parsedPath][currentMethod].body = swagger2.buildBodyValidation(validatedBodySchema, dereferenced.definitions, swaggers[1], currentPath, currentMethod, parsedPath, middlewareOptions);
}
}
let localParameters = parameters.filter(function (parameter) {
return parameter.in !== 'body';
}).concat(pathParameters);
if (localParameters.length > 0 || middlewareOptions.contentTypeValidation) {
schemas[parsedPath][currentMethod].parameters = buildParametersValidation(localParameters,
dereferenced.paths[currentPath][currentMethod].consumes || dereferenced.paths[currentPath].consumes || dereferenced.consumes, middlewareOptions);
}
});
});
})
.catch(function (error) {
return Promise.reject(error);
});
}
/**
* The middleware - should be called for each express route
* @param {any} req
* @param {any} res
* @param {any} next
* @returns In case of an error will call `next` with `InputValidationError`
*/
function validate(...args) {
return framework.validate(_validateRequest, ...args);
}
function _validateRequest(requestOptions) {
return Promise.all([
_validateParams(requestOptions.headers, requestOptions.params, requestOptions.query, requestOptions.files, requestOptions.path, requestOptions.method.toLowerCase()).catch(e => e),
_validateBody(requestOptions.body, requestOptions.path, requestOptions.method.toLowerCase()).catch(e => e)
]).then(function (errors) {
if (errors[0] || errors[1]) {
return errors[0] && errors[1] ? Promise.reject(errors[0].concat(errors[1])) : errors[0] ? Promise.reject(errors[0]) : Promise.reject(errors[1]);
}
}).catch(function (errors) {
const error = new InputValidationError(errors, requestOptions.path, requestOptions.method.toLowerCase(),
{ beautifyErrors: middlewareOptions.beautifyErrors,
firstError: middlewareOptions.firstError });
return Promise.resolve(error);
});
}
function _validateBody(body, path, method) {
return new Promise(function (resolve, reject) {
if (schemas[path] && schemas[path][method] && schemas[path][method].body && !schemas[path][method].body.validate(body)) {
return reject(schemas[path][method].body.errors);
}
return resolve();
});
}
function _validateParams(headers, pathParams, query, files, path, method) {
return new Promise(function (resolve, reject) {
if (schemas[path] && schemas[path][method] && schemas[path][method].parameters && !schemas[path][method].parameters({ query: query, headers: headers, path: pathParams, files: files })) {
return reject(schemas[path][method].parameters.errors);
}
return resolve();
});
}
function createContentTypeHeaders(validate, contentTypes) {
if (!validate || !contentTypes) return;
return {
types: contentTypes
};
}
function buildParametersValidation(parameters, contentTypes, middlewareOptions) {
const defaultAjvOptions = {
allErrors: true,
coerceTypes: 'array'
// unknownFormats: 'ignore'
};
const options = Object.assign({}, defaultAjvOptions, middlewareOptions.ajvConfigParams);
let ajv = new Ajv(options);
ajvUtils.addCustomKeyword(ajv, middlewareOptions.formats);
var ajvParametersSchema = {
title: 'HTTP parameters',
type: 'object',
additionalProperties: false,
properties: {
headers: {
title: 'HTTP headers',
type: 'object',
properties: {},
additionalProperties: true
// plural: 'headers'
},
path: {
title: 'HTTP path',
type: 'object',
properties: {},
additionalProperties: false
},
query: {
title: 'HTTP query',
type: 'object',
properties: {},
additionalProperties: false
},
files: {
title: 'HTTP form files',
files: {
required: [],
optional: []
}
}
}
};
parameters.forEach(parameter => {
var data = Object.assign({}, parameter);
const required = parameter.required;
const source = sourceResolver.resolveParameterSource(parameter);
const key = parameter.in === 'header' ? parameter.name.toLowerCase() : parameter.name;
var destination = ajvParametersSchema.properties[source];
delete data.name;
delete data.in;
delete data.required;
if (data.type === 'file') {
required ? destination.files.required.push(key) : destination.files.optional.push(key);
} else if (source !== 'fields') {
if (required) {
destination.required = destination.required || [];
destination.required.push(key);
}
destination.properties[key] = data;
}
}, this);
ajvParametersSchema.properties.headers.content = createContentTypeHeaders(middlewareOptions.contentTypeValidation, contentTypes);
return ajv.compile(ajvParametersSchema);
}
module.exports = {
init: init,
validate: validate,
InputValidationError: InputValidationError
};
|
function hasAnyoneSeenImportBabelPolyfill() { return false };
|
import './SpeechToText.css'
import { getTokenOrRefresh } from './token_util';
import { ResultReason } from 'microsoft-cognitiveservices-speech-sdk';
import symObjSpeechToText from './symObjSpeechToText.js'
const speechsdk = require('microsoft-cognitiveservices-speech-sdk')
export default function SpeechToText({ setCurrentWord, originalLanguage }) {
// async function - function will now complete everything simultaneously, HOWEVER one of the benefits of this is the await.
async function speechToTalk(event) {
var symbol = symObjSpeechToText[originalLanguage]
// await - waits for a promise - if the certain promise is fulfilled, assign to tokenObject, and continue with the async function.
// Meaning the function after this await can proceed ONCE the promise return by getTokenOrRefresh has been fulfilled.
// tokenObject - checks your key BY server side index.js and creates a json for src/token_util.js to obtain that object
const tokenObject = await getTokenOrRefresh();
const speechConfig = speechsdk.SpeechConfig.fromAuthorizationToken(tokenObject.authToken, tokenObject.region);
speechConfig.speechRecognitionLanguage = symbol;
const audioConfig = speechsdk.AudioConfig.fromDefaultMicrophoneInput();
const recognizer = new speechsdk.SpeechRecognizer(speechConfig, audioConfig);
recognizer.recognizeOnceAsync(result => {
if (result.reason === ResultReason.RecognizedSpeech) {
setCurrentWord(result.privText.slice(0, -1))
} else {
console.error('no')
}
});
}
return (
<div className='footer-element'>
<button className="mic-image" onClick={() => speechToTalk()}></button>
</div>
)
} |
#!/usr/bin/env node
var Workshopper = require('workshopper');
var path = require('path');
var credits = require('./credits');
var name = 'kick-off-koa';
function fpath (f) {
return path.join(__dirname, f);
}
Workshopper({
name : name,
appDir : __dirname,
languages : ['en', 'fr'],
helpFile : fpath('./i18n/help/{lang}.txt'),
menuItems : [{
name : 'credits',
handler : credits
}]
});
|
import React from 'react'
import * as PropTypes from 'prop-types'
import * as generalUtils from 'common/utils/general.utils'
import { BiChair } from 'react-icons/bi'
import Button from 'common/components/button'
import './OfficeCard.scss'
const OfficeCard = ({ time, seat, onBook, translate }) => {
const timeFormatted = generalUtils.formattedRoundHour(time)
return (
<div className="office-card animate__animated animate__fadeIn" role="listitem">
<div className="office-card__content">
<div
className="office-card__time"
aria-label={translate('Time: {time}', { time: timeFormatted })}
>
{timeFormatted}
</div>
<div className="office-card__seats">
<div className="office-card__seats--icon" role="presentation" aria-hidden="true">
<BiChair />
</div>
<div
className="office-card__seats--text"
aria-label={translate('Seats available: {seat}', { seat })}
>
{seat}
</div>
</div>
</div>
<div className="office-card__footer">
<Button onClick={() => onBook({ seat, time })}>{translate('Book')}</Button>
</div>
</div>
)
}
OfficeCard.defaultProps = {
translate: (value) => value,
}
OfficeCard.propTypes = {
translate: PropTypes.func,
time: PropTypes.number,
seat: PropTypes.number,
onBook: PropTypes.func,
}
export default OfficeCard
|
window.EVENTDATA = {};
newModel('GlobalEvent', function(trigger, options) {
var self = getSelf(this, 'GlobalEvent');
self.inherit(BaseModel);
self.queue = [];
self.init = () => {
if ( trigger.constructor == Array ) {
trigger.forEach(t=>new GlobalEvent(t, options));
return false;
}
self.trigger = trigger;
self.options = mergeObjects({
initiator: document,
worker: ()=>{},
init_with: null
}, options);
GLOBALEVENT[trigger] = self;
self.start();
}
self.start = () => {
self.options.initiator.addEventListener(self.trigger, self._worker);
}
self._worker = (ev) => {
self.options.worker(ev, EVENTDATA, self);
self.queue.forEach((todo)=>{
todo(ev, EVENTDATA, self);
});
}
self.add = todo => { self.queue.push(todo); }
self.init();
});
|
import React from 'react';
import { toast } from 'react-toastify'
import axio from 'commons/axios';
import axios from 'commons/axios';
class EditInventory extends React.Component{
state={
id:'',
name: '',
price: '',
tags: '',
image: '',
status: 'available'
}
componentDidMount(){
const{}
}
handleChange = e =>{
const value = e.target.value;
const name = e.target.name;
this.setState({
[name]: value
})
}
submit=event=>{
event.preventDefault();
const product={...this.state};
axios.post('http://localhost:3003/products', product).then(res=>{
this.props.close(res.data);
toast.success('Add Success');
})
}
render(){
return(
<div className="inventory">
<p className="title has-text-centered">Add Product</p>
<form onSubmit={this.submit}>
<div className="field">
<div className="control">
<label className="label">Name</label>
<textarea className="textarea" name="name" value={this.state.name} onChange={this.handleChange} placeholder="e.g. Nike Air Max 97" />
</div>
</div>
<div className="field">
<div className="control">
<label className="label">Price</label>
<input type="text" className="input" name="price" value={this.state.price} onChange={this.handleChange} placeholder="e.g. 140" />
</div>
</div>
<div className="field">
<div className="control">
<label className="label">Tags</label>
<input type="text" className="input" name="tags" value={this.state.tags} onChange={this.handleChange} placeholder="e.g. 5 colors" />
</div>
</div>
<div className="field">
<div className="control">
<label className="label">Image</label>
<input type="text" className="input" name="image" value={this.state.image} onChange={this.handleChange} />
</div>
</div>
<div className="field">
<div className="control">
<label className="label">Status</label>
<div className="select is-fullwidth">
<select name="status" value={this.state.status} onChange={this.handleChange}>
<option>available</option>
<option>unavailable</option>
</select>
</div>
</div>
</div>
<div className="field is-grouped is-grouped-centered">
<div className="control">
<button className="button is-link">Submit</button>
</div>
<div className="control">
<button className="button" type="button" onClick={()=>{this.props.close()}}>Cancel</button>
</div>
</div>
</form>
</div>
);
}
}
export default EditInventory; |
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: [email protected]
//
// See http://js.arcgis.com/4.6/esri/copyright.txt for details.
define({stretchTitle:"Etirer",stretchDescription:"Etire les valeurs dans un dégradé de couleurs.",rgbTitle:"RVB",noneTitle:"Aucune",rgbDescription:"Combine des canaux sous la forme de compositions en rouge, vert et bleu.",vectorFieldTitle:"Champ vectoriel",vectorFieldDescription:"Affiche les images sous forme de symboles vectoriels",discreteTitle:"Discrète",discreteDescription:"Regroupe les données en fonction d’un nombre sélectionné de couleurs et applique une combinaison de couleurs.",classifyTitle:"Classer",classifyDescription:"Attribue une couleur à chaque groupe de valeurs",uniqueValueTitle:"Valeur unique",uniqueValueDescription:"Attribue une couleur à chaque valeur.",bandPrefix:"Canal",bandCombinationTitle:"Combinaison de canaux",bandCombinationPresetLabel:"Combinaison",bandComboNameCustom:"Personnalisé",bandComboNameNaturalColor:"Couleur naturelle",bandComboDescNaturalColor:"Ce rendu se rapproche le plus de ce que perçoit l’œil humain.",bandComboNameColorInfrared:"Couleur infrarouge",bandComboDescColorInfrared:"Fait la distinction entre la végétation, l’urbanisation et l’eau. Présente plus de contraste dans la végétation qu’Utilisation du sol.",bandComboNameLanduse:"Utilisation du sol",bandComboDescLanduse:"Fait la distinction entre l’urbanisation, la végétation et l’eau. Présente plus de contraste dans le paysage urbain que Couleur infrarouge.",bandComboNameLandWater:"Interface terre/eau",bandComboDescLandWater:"Crée une délimitation nette entre le sol et l’eau et peut tenir compte de la brume.",bandComboNameVegetation:"Analyse de la végétation",bandComboDescVegetation:"Met en surbrillance la végétation en fonction de son contenu hydraulique et de la structure des cellules.",bandComboNameShallowBathymetric:"Bathymétrie en eaux peu profondes",bandComboDescShallowBathymetric:"Met en surbrillance les entités sous-marines en eau claire.",redBandTitle:"Rouge",greenBandTitle:"Verte",blueBandTitle:"Bleu",alphaBandTitle:"Alpha",backgroundTitle:"Arrière-plan",displayBackgroundCheckboxTitle:"Afficher la valeur d’arrière-plan",noDataLabel:"Nodata",noneStretchTitle:"Aucune",noneStretchTypeDescription:"Affiche les valeurs situées entre les valeurs minimum et maximum potentielles.",percentClipStretchTitle:"Pourcentage de découpe",percentClipStretchTypeDescription:"Réduisez les pourcentages des valeurs les plus élevées et les plus faibles.",minMaxStretchTitle:"Minimum Maximum",minMaxStretchTypeDescription:"Affiche les valeurs situées entre les valeurs minimum et maximum réelles.",standardDeviationStretchTitle:"Ecart type",standardDeviationTypeDescription:"Affiche les valeurs situées entre un nombre spécifié d'écarts types.",stretchTypeLabel:"Type d’étirement",gammaLabel:"Gamma",statisticsLabel:"Statistiques",minLabel:"Min",maxLabel:"Max.",nStdDeviationsLabel:"Nombre d’écarts types",draStatisticsTitle:"DRA",datasetStatisticsTitle:"Jeu de données",fieldLabel:"Champ",normalizationLabel:"Normalisation",methodLabel:"Méthode",methodNaturalBreaksTitle:"Seuils naturels",methodQuantileTitle:"Quantile",methodEqualIntervalTitle:"Intervalle égal",methodDefinedIntervalTitle:"Intervalle défini",methodManualIntervalTitle:"Intervalle manuel",methodGeometricIntervalTitle:"Intervalle géométrique",methodStandardDeviationTitle:"StandardDeviation",classesLabel:"Classes",colorSchemeLabel:"Combinaison de couleurs",colorRampTitle:"Dégradé de couleurs",bandSelectionLabel:"Canal",noneBandKeyword:"Aucune",valueFieldTitle:"Champ de valeur",valuesTableTitle:"Valeurs",uniqueValueFieldTitle:"Champ",uniqueValuesColorRampTitle:"Valeurs uniques",valueLabel:"Valeur",symbolLabel:"Symbole",numberOfColors:"Nombre de couleurs"}); |
#!/usr/bin/python
#
# Copyright (c) 2011 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class BitcoinRPC:
OBJID = 1
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
self.conn = httplib.HTTPConnection(host, port, False, 30)
def rpc(self, method, params=None):
self.OBJID += 1
obj = { 'version' : '1.1',
'method' : method,
'id' : self.OBJID }
if params is None:
obj['params'] = []
else:
obj['params'] = params
self.conn.request('POST', '/', json.dumps(obj),
{ 'Authorization' : self.authhdr,
'Content-type' : 'application/json' })
resp = self.conn.getresponse()
if resp is None:
print "JSON-RPC: no response"
return None
body = resp.read()
resp_obj = json.loads(body)
if resp_obj is None:
print "JSON-RPC: cannot JSON-decode body"
return None
if 'error' in resp_obj and resp_obj['error'] != None:
return resp_obj['error']
if 'result' not in resp_obj:
print "JSON-RPC: no result in object"
return None
return resp_obj['result']
def getblockcount(self):
return self.rpc('getblockcount')
def getwork(self, data=None):
return self.rpc('getwork', data)
def uint32(x):
return x & 0xffffffffL
def bytereverse(x):
return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
(((x) >> 8) & 0x0000ff00) | ((x) >> 24) ))
def bufreverse(in_buf):
out_words = []
for i in range(0, len(in_buf), 4):
word = struct.unpack('@I', in_buf[i:i+4])[0]
out_words.append(struct.pack('@I', bytereverse(word)))
return ''.join(out_words)
def wordreverse(in_buf):
out_words = []
for i in range(0, len(in_buf), 4):
out_words.append(in_buf[i:i+4])
out_words.reverse()
return ''.join(out_words)
class Miner:
def __init__(self, id):
self.id = id
self.max_nonce = MAX_NONCE
def work(self, datastr, targetstr):
# decode work data hex string to binary
static_data = datastr.decode('hex')
static_data = bufreverse(static_data)
# the first 76b of 80b do not change
blk_hdr = static_data[:76]
# decode 256-bit target value
targetbin = targetstr.decode('hex')
targetbin = targetbin[::-1] # byte-swap and dword-swap
targetbin_str = targetbin.encode('hex')
target = long(targetbin_str, 16)
# pre-hash first 76b of block header
static_hash = hashlib.sha256()
static_hash.update(blk_hdr)
for nonce in xrange(self.max_nonce):
# encode 32-bit nonce value
nonce_bin = struct.pack("<I", nonce)
# hash final 4b, the nonce value
hash1_o = static_hash.copy()
hash1_o.update(nonce_bin)
hash1 = hash1_o.digest()
# sha256 hash of sha256 hash
hash_o = hashlib.sha256()
hash_o.update(hash1)
hash = hash_o.digest()
# quick test for winning solution: high 32 bits zero?
if hash[-4:] != '\0\0\0\0':
continue
# convert binary hash to 256-bit Python long
hash = bufreverse(hash)
hash = wordreverse(hash)
hash_str = hash.encode('hex')
l = long(hash_str, 16)
# proof-of-work test: hash < target
if l < target:
print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,)
return (nonce + 1, nonce_bin)
else:
print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,)
# return (nonce + 1, nonce_bin)
return (nonce + 1, None)
def submit_work(self, rpc, original_data, nonce_bin):
nonce_bin = bufreverse(nonce_bin)
nonce = nonce_bin.encode('hex')
solution = original_data[:152] + nonce + original_data[160:256]
param_arr = [ solution ]
result = rpc.getwork(param_arr)
print time.asctime(), "--> Upstream RPC result:", result
def iterate(self, rpc):
work = rpc.getwork()
if work is None:
time.sleep(ERR_SLEEP)
return
if 'data' not in work or 'target' not in work:
time.sleep(ERR_SLEEP)
return
time_start = time.time()
(hashes_done, nonce_bin) = self.work(work['data'],
work['target'])
time_end = time.time()
time_diff = time_end - time_start
self.max_nonce = long(
(hashes_done * settings['scantime']) / time_diff)
if self.max_nonce > 0xfffffffaL:
self.max_nonce = 0xfffffffaL
if settings['hashmeter']:
print "HashMeter(%d): %d hashes, %.2f Khash/sec" % (
self.id, hashes_done,
(hashes_done / 1000.0) / time_diff)
if nonce_bin is not None:
self.submit_work(rpc, work['data'], nonce_bin)
def loop(self):
rpc = BitcoinRPC(settings['host'], settings['port'],
settings['rpcuser'], settings['rpcpass'])
if rpc is None:
return
while True:
self.iterate(rpc)
def miner_thread(id):
miner = Miner(id)
miner.loop()
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: pyminer.py CONFIG-FILE"
sys.exit(1)
f = open(sys.argv[1])
for line in f:
# skip comment lines
m = re.search('^\s*#', line)
if m:
continue
# parse key=value lines
m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
if m is None:
continue
settings[m.group(1)] = m.group(2)
f.close()
if 'host' not in settings:
settings['host'] = '127.0.0.1'
if 'port' not in settings:
settings['port'] = 2532
if 'threads' not in settings:
settings['threads'] = 1
if 'hashmeter' not in settings:
settings['hashmeter'] = 0
if 'scantime' not in settings:
settings['scantime'] = 30L
if 'rpcuser' not in settings or 'rpcpass' not in settings:
print "Missing username and/or password in cfg file"
sys.exit(1)
settings['port'] = int(settings['port'])
settings['threads'] = int(settings['threads'])
settings['hashmeter'] = int(settings['hashmeter'])
settings['scantime'] = long(settings['scantime'])
thr_list = []
for thr_id in range(settings['threads']):
p = Process(target=miner_thread, args=(thr_id,))
p.start()
thr_list.append(p)
time.sleep(1) # stagger threads
print settings['threads'], "mining threads started"
print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port'])
try:
for thr_proc in thr_list:
thr_proc.join()
except KeyboardInterrupt:
pass
print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
|
import dayjs from "dayjs";
/**
* Return date in form of "15 September 2021 17:09"
*
* @param {number} timestamp
* @returns {string}
*/
export default function getFormattedDate(timestamp) {
return dayjs(timestamp).format("DD MMMM YYYY HH:MM");
} |
import { area } from 'd3-shape';
import { dArea, dLine, dSpline } from '../plugins/series/computeds';
import {
createAreaHitTester, createLineHitTester, createSplineHitTester,
createBarHitTester, createScatterHitTester, createPieHitTester,
changeSeriesState,
} from './series';
jest.mock('d3-shape', () => ({
area: jest.fn(),
}));
jest.mock('../plugins/series/computeds', () => ({
dArea: { x: jest.fn(), y0: jest.fn(), y1: jest.fn() },
dLine: { x: jest.fn(), y: jest.fn() },
dSpline: { x: jest.fn(), y: jest.fn(), curve: jest.fn() },
}));
const getContext = jest.fn();
// eslint-disable-next-line no-undef
document.createElement = () => ({ getContext });
describe('Series', () => {
const matchFloat = expected => ({
$$typeof: Symbol.for('jest.asymmetricMatcher'),
asymmetricMatch: actual => Math.abs(actual - expected) < 0.01,
toAsymmetricMatcher: () => `~${expected}`,
});
// Mocks are intentionally reset rather then cleared.
afterEach(jest.resetAllMocks);
const checkContinuousHitTester = (createHitTester) => {
const isPointInPath = jest.fn();
getContext.mockReturnValue({ isPointInPath });
const hitTest = createHitTester([
{ x: 115, y: 35, index: 'p1' },
{ x: 165, y: 65, index: 'p2' },
{ x: 195, y: 60, index: 'p3' },
]);
isPointInPath.mockReturnValueOnce(false);
expect(hitTest([90, 30])).toEqual(null);
expect(hitTest([110, 40])).toEqual({
points: [{ index: 'p1', distance: matchFloat(7.07) }],
});
expect(hitTest([115, 35])).toEqual({
points: [{ index: 'p1', distance: matchFloat(0) }],
});
expect(hitTest([185, 65])).toEqual({
points: [{ index: 'p2', distance: matchFloat(20) }, { index: 'p3', distance: matchFloat(11.18) }],
});
expect(hitTest([190, 60])).toEqual({
points: [{ index: 'p3', distance: matchFloat(5) }],
});
isPointInPath.mockReturnValueOnce(true);
expect(hitTest([140, 40])).toEqual({
points: [{ index: 'p1', distance: matchFloat(25.5) }],
});
isPointInPath.mockReturnValueOnce(true);
expect(hitTest([140, 60])).toEqual({
points: [{ index: 'p2', distance: matchFloat(25.5) }],
});
expect(isPointInPath.mock.calls).toEqual([
[90, 30],
[140, 40],
[140, 60],
]);
};
describe('#createAreaHitTester', () => {
const mockPath = jest.fn();
mockPath.x = jest.fn();
mockPath.y0 = jest.fn();
mockPath.y1 = jest.fn();
mockPath.context = jest.fn();
beforeEach(() => {
dArea.x.mockReturnValue('#x');
dArea.y0.mockReturnValue('#y0');
dArea.y1.mockReturnValue('#y1');
area.mockReturnValue(mockPath);
});
it('should setup context', () => {
getContext.mockReturnValue('test-context');
createAreaHitTester('test-coordinates');
expect(mockPath.x).toBeCalledWith('#x');
expect(mockPath.y0).toBeCalledWith('#y0');
expect(mockPath.y1).toBeCalledWith('#y1');
expect(mockPath.context).toBeCalledWith('test-context');
expect(mockPath).toBeCalledWith('test-coordinates');
});
it('should test points', () => checkContinuousHitTester(createAreaHitTester));
});
describe('#createLineHitTester', () => {
const mockPath = jest.fn();
mockPath.x = jest.fn();
mockPath.y0 = jest.fn();
mockPath.y1 = jest.fn();
mockPath.context = jest.fn();
beforeEach(() => {
dLine.x.mockReturnValue('#x');
dLine.y.mockReturnValue('#y');
area.mockReturnValue(mockPath);
});
it('should setup context', () => {
getContext.mockReturnValue('test-context');
createLineHitTester('test-coordinates');
expect(mockPath.x).toBeCalledWith('#x');
expect(mockPath.y0).toBeCalledWith(expect.any(Function));
expect(mockPath.y1).toBeCalledWith(expect.any(Function));
expect(mockPath.context).toBeCalledWith('test-context');
expect(mockPath).toBeCalledWith('test-coordinates');
});
it('should test points', () => checkContinuousHitTester(createLineHitTester));
});
describe('#createSplineHitTester', () => {
const mockPath = jest.fn();
mockPath.x = jest.fn();
mockPath.y0 = jest.fn();
mockPath.y1 = jest.fn();
mockPath.curve = jest.fn();
mockPath.context = jest.fn();
beforeEach(() => {
dSpline.x.mockReturnValue('#x');
dSpline.y.mockReturnValue('#y');
dSpline.curve.mockReturnValue('#curve');
area.mockReturnValue(mockPath);
});
it('should setup context', () => {
getContext.mockReturnValue('test-context');
createSplineHitTester('test-coordinates');
expect(mockPath.x).toBeCalledWith('#x');
expect(mockPath.y0).toBeCalledWith(expect.any(Function));
expect(mockPath.y1).toBeCalledWith(expect.any(Function));
expect(mockPath.curve).toBeCalledWith('#curve');
expect(mockPath.context).toBeCalledWith('test-context');
expect(mockPath).toBeCalledWith('test-coordinates');
});
it('should call context method', () => checkContinuousHitTester(createSplineHitTester));
});
describe('#createBarHitTester', () => {
it('should test bars', () => {
const hitTest = createBarHitTester([
{
x: 10, width: 4, y: 2, y1: 4, index: 'p1',
},
{
x: 20, width: 8, y: 3, y1: 5, index: 'p2',
},
{
x: 30, width: 5, y: 1, y1: 5, index: 'p3',
},
{
x: 31, width: 5, y: 0, y1: 4, index: 'p4',
},
]);
expect(hitTest([15, 1])).toEqual(null);
expect(hitTest([12, 4])).toEqual({ points: [{ index: 'p1', distance: matchFloat(1) }] });
expect(hitTest([25, 3])).toEqual({ points: [{ index: 'p2', distance: matchFloat(1.41) }] });
expect(hitTest([31, 2])).toEqual({
points: [{ index: 'p3', distance: matchFloat(1.8) }, { index: 'p4', distance: matchFloat(2.5) }],
});
});
});
describe('#createScatterHitTester', () => {
it('should test points', () => {
const hitTest = createScatterHitTester([
{ x: 10, y: 4, index: 'p1' },
{ x: 30, y: 5, index: 'p2' },
{ x: 50, y: 8, index: 'p3' },
{ x: 55, y: 10, index: 'p4' },
]);
expect(hitTest([15, -7])).toEqual(null);
expect(hitTest([14, 10])).toEqual({ points: [{ index: 'p1', distance: matchFloat(7.21) }] });
expect(hitTest([32, 4])).toEqual({ points: [{ index: 'p2', distance: matchFloat(2.24) }] });
expect(hitTest([49, 15])).toEqual({
points: [{ index: 'p3', distance: matchFloat(7.07) }, { index: 'p4', distance: matchFloat(7.81) }],
});
});
});
describe('#createPieHitTester', () => {
it('should test pies', () => {
const hitTest = createPieHitTester([
{
x: 60, y: 50, innerRadius: 1, outerRadius: 10, startAngle: 0, endAngle: Math.PI / 4, index: 'p1',
},
{
x: 60, y: 50, innerRadius: 1, outerRadius: 10, startAngle: Math.PI / 2, endAngle: Math.PI, index: 'p2',
},
{
x: 60, y: 50, innerRadius: 1, outerRadius: 10, startAngle: Math.PI, endAngle: 3 * Math.PI / 2, index: 'p3',
},
]);
expect(hitTest([60, 61])).toEqual(null);
expect(hitTest([64, 45])).toEqual({ points: [{ index: 'p1', distance: matchFloat(0.95) }] });
expect(hitTest([68, 52])).toEqual({ points: [{ index: 'p2', distance: matchFloat(2.8) }] });
expect(hitTest([60, 55])).toEqual({
points: [{ index: 'p2', distance: matchFloat(0.93) }, { index: 'p3', distance: matchFloat(0.93) }],
});
});
});
describe('#changeSeriesState', () => {
const series1 = { name: 's1', points: [] };
const series2 = { name: 's2', points: [] };
const series3 = { name: 's3', points: [{ index: 1 }, { index: 3 }] };
const series4 = { name: 's4', points: [{ index: 2 }, { index: 5 }, { index: 6 }] };
it('should change series and points', () => {
const [
newSeries1, newSeries2, newSeries3, newSeries4,
] = changeSeriesState([series1, series2, series3, series4], [
{ series: 's3', point: 3 },
{ series: 's4', point: 5 },
{ series: 's4', point: 2 },
], 'test-state');
expect(newSeries1).toBe(series1);
expect(newSeries2).toBe(series2);
expect(newSeries3).toEqual({
...series3,
state: 'test-state',
points: [
series3.points[0],
{ ...series3.points[1], state: 'test-state' },
],
});
expect(newSeries3.points[0]).toBe(series3.points[0]);
expect(newSeries4).toEqual({
...series4,
state: 'test-state',
points: [
{ ...series4.points[0], state: 'test-state' },
{ ...series4.points[1], state: 'test-state' },
series4.points[2],
],
});
expect(newSeries4.points[2]).toBe(series4.points[2]);
});
it('should return original list when there are no matches', () => {
const list = [series1, series2, series3, series4];
const result = changeSeriesState(list, [
{ series: 's5' },
{ series: 's6', point: 3 },
{ series: 's0', point: 0 },
], 'test-state');
expect(result).toBe(list);
});
});
});
|
/*
KULeuven/LIBIS (c) 2022
Mehmet Celik mehmet(dot)celik(at)kuleuven(dot)be
*/
import './generalMessage'
export default 'generalMessage' |
"""
Low-level implementations for the external functions of the 'os' module.
"""
# Implementation details about those functions
# might be found in doc/rffi.txt
import os, sys, errno
import py
from rpython.rtyper.module.support import (
UNDERSCORE_ON_WIN32, _WIN32, StringTraits, UnicodeTraits)
from rpython.tool.sourcetools import func_renamer
from rpython.rlib.rarithmetic import r_longlong
from rpython.rtyper.extfunc import (
BaseLazyRegistering, register_external)
from rpython.rtyper.extfunc import registering, registering_if, extdef
from rpython.annotator.model import (
SomeInteger, SomeString, SomeTuple, SomeFloat, s_Str0, s_Unicode0)
from rpython.annotator.model import s_ImpossibleValue, s_None, s_Bool
from rpython.rtyper.lltypesystem import rffi
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.tool import rffi_platform as platform
from rpython.rlib import rposix, jit
from rpython.translator.tool.cbuild import ExternalCompilationInfo
from rpython.rlib.objectmodel import specialize
from rpython.translator import cdir
str0 = s_Str0
unicode0 = s_Unicode0
def monkeypatch_rposix(posixfunc, unicodefunc, signature):
func_name = posixfunc.__name__
if hasattr(signature, '_default_signature_'):
signature = signature._default_signature_
arglist = ['arg%d' % (i,) for i in range(len(signature))]
transformed_arglist = arglist[:]
for i, arg in enumerate(signature):
if arg in (unicode, unicode0):
transformed_arglist[i] = transformed_arglist[i] + '.as_unicode()'
args = ', '.join(arglist)
transformed_args = ', '.join(transformed_arglist)
try:
main_arg = 'arg%d' % (signature.index(unicode0),)
except ValueError:
main_arg = 'arg%d' % (signature.index(unicode),)
source = py.code.Source("""
def %(func_name)s(%(args)s):
if isinstance(%(main_arg)s, str):
return posixfunc(%(args)s)
else:
return unicodefunc(%(transformed_args)s)
""" % locals())
miniglobals = {'posixfunc' : posixfunc,
'unicodefunc': unicodefunc,
'__name__': __name__, # for module name propagation
}
exec source.compile() in miniglobals
new_func = miniglobals[func_name]
specialized_args = [i for i in range(len(signature))
if signature[i] in (unicode, unicode0, None)]
new_func = specialize.argtype(*specialized_args)(new_func)
# Monkeypatch the function in rpython.rlib.rposix
setattr(rposix, func_name, new_func)
def registering_str_unicode(posixfunc, condition=True):
if not condition or posixfunc is None:
return registering(None, condition=False)
func_name = posixfunc.__name__
def register_posixfunc(self, method):
val = method(self, StringTraits())
register_external(posixfunc, *val.def_args, **val.def_kwds)
if sys.platform == 'win32':
val = method(self, UnicodeTraits())
@func_renamer(func_name + "_unicode")
def unicodefunc(*args):
return posixfunc(*args)
register_external(unicodefunc, *val.def_args, **val.def_kwds)
signature = val.def_args[0]
monkeypatch_rposix(posixfunc, unicodefunc, signature)
def decorator(method):
decorated = lambda self: register_posixfunc(self, method)
decorated._registering_func = posixfunc
return decorated
return decorator
posix = __import__(os.name)
includes = []
if not _WIN32:
# XXX many of these includes are not portable at all
includes += ['dirent.h', 'sys/stat.h',
'sys/times.h', 'utime.h', 'sys/types.h', 'unistd.h',
'signal.h', 'sys/wait.h', 'fcntl.h']
else:
includes += ['sys/utime.h', 'sys/types.h']
_CYGWIN = sys.platform == 'cygwin'
class CConfig:
"""
Definitions for platform integration.
Note: this must be processed through platform.configure() to provide
usable objects. For example::
CLOCK_T = platform.configure(CConfig)['CLOCK_T']
register(function, [CLOCK_T], ...)
"""
_compilation_info_ = ExternalCompilationInfo(
includes=includes
)
if not _WIN32:
CLOCK_T = platform.SimpleType('clock_t', rffi.INT)
TMS = platform.Struct(
'struct tms', [('tms_utime', rffi.INT),
('tms_stime', rffi.INT),
('tms_cutime', rffi.INT),
('tms_cstime', rffi.INT)])
# For now we require off_t to be the same size as LONGLONG, which is the
# interface required by callers of functions that thake an argument of type
# off_t
OFF_T_SIZE = platform.SizeOf('off_t')
SEEK_SET = platform.DefinedConstantInteger('SEEK_SET')
SEEK_CUR = platform.DefinedConstantInteger('SEEK_CUR')
SEEK_END = platform.DefinedConstantInteger('SEEK_END')
UTIMBUF = platform.Struct('struct %sutimbuf' % UNDERSCORE_ON_WIN32,
[('actime', rffi.INT),
('modtime', rffi.INT)])
class RegisterOs(BaseLazyRegistering):
def __init__(self):
self.configure(CConfig)
if not _WIN32:
assert self.OFF_T_SIZE == rffi.sizeof(rffi.LONGLONG)
if hasattr(os, 'getpgrp'):
self.GETPGRP_HAVE_ARG = platform.checkcompiles(
"getpgrp(0)",
'#include <unistd.h>',
[])
if hasattr(os, 'setpgrp'):
self.SETPGRP_HAVE_ARG = platform.checkcompiles(
"setpgrp(0,0)",
'#include <unistd.h>',
[])
# we need an indirection via c functions to get macro calls working on llvm XXX still?
if hasattr(os, 'WCOREDUMP'):
decl_snippet = """
RPY_EXTERN %(ret_type)s pypy_macro_wrapper_%(name)s (int status);
"""
def_snippet = """
%(ret_type)s pypy_macro_wrapper_%(name)s (int status) {
return %(name)s(status);
}
"""
decls = []
defs = []
for name in self.w_star:
if hasattr(os, name):
data = {'ret_type': 'int', 'name': name}
decls.append((decl_snippet % data).strip())
defs.append((def_snippet % data).strip())
self.compilation_info = self.compilation_info.merge(
ExternalCompilationInfo(
post_include_bits = decls,
separate_module_sources = ["\n".join(defs)]
))
# a simple, yet useful factory
def extdef_for_os_function_returning_int(self, name, **kwds):
c_func = self.llexternal(name, [], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO, **kwds)
def c_func_llimpl():
res = rffi.cast(rffi.SIGNED, c_func())
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
return res
c_func_llimpl.func_name = name + '_llimpl'
return extdef([], int, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
def extdef_for_os_function_accepting_int(self, name, **kwds):
c_func = self.llexternal(name, [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO, **kwds)
def c_func_llimpl(arg):
res = rffi.cast(rffi.SIGNED, c_func(arg))
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
c_func_llimpl.func_name = name + '_llimpl'
return extdef([int], None, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
def extdef_for_os_function_accepting_2int(self, name, **kwds):
c_func = self.llexternal(name, [rffi.INT, rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO, **kwds)
def c_func_llimpl(arg, arg2):
res = rffi.cast(rffi.SIGNED, c_func(arg, arg2))
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
c_func_llimpl.func_name = name + '_llimpl'
return extdef([int, int], None, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
def extdef_for_os_function_accepting_0int(self, name, **kwds):
c_func = self.llexternal(name, [], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO, **kwds)
def c_func_llimpl():
res = rffi.cast(rffi.SIGNED, c_func())
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
c_func_llimpl.func_name = name + '_llimpl'
return extdef([], None, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
def extdef_for_os_function_int_to_int(self, name, **kwds):
c_func = self.llexternal(name, [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO, **kwds)
def c_func_llimpl(arg):
res = rffi.cast(rffi.SIGNED, c_func(arg))
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
return res
c_func_llimpl.func_name = name + '_llimpl'
return extdef([int], int, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
@registering_if(os, 'execv')
def register_os_execv(self):
os_execv = self.llexternal(
'execv',
[rffi.CCHARP, rffi.CCHARPP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def execv_llimpl(path, args):
l_args = rffi.ll_liststr2charpp(args)
os_execv(path, l_args)
rffi.free_charpp(l_args)
raise OSError(rposix.get_saved_errno(), "execv failed")
return extdef([str0, [str0]], s_ImpossibleValue, llimpl=execv_llimpl,
export_name="ll_os.ll_os_execv")
@registering_if(os, 'execve')
def register_os_execve(self):
os_execve = self.llexternal(
'execve',
[rffi.CCHARP, rffi.CCHARPP, rffi.CCHARPP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def execve_llimpl(path, args, env):
# XXX Check path, args, env for \0 and raise TypeErrors as
# appropriate
envstrs = []
for item in env.iteritems():
envstr = "%s=%s" % item
envstrs.append(envstr)
l_args = rffi.ll_liststr2charpp(args)
l_env = rffi.ll_liststr2charpp(envstrs)
os_execve(path, l_args, l_env)
# XXX untested
rffi.free_charpp(l_env)
rffi.free_charpp(l_args)
raise OSError(rposix.get_saved_errno(), "execve failed")
return extdef(
[str0, [str0], {str0: str0}],
s_ImpossibleValue,
llimpl=execve_llimpl,
export_name="ll_os.ll_os_execve")
@registering_if(posix, 'spawnv')
def register_os_spawnv(self):
os_spawnv = self.llexternal('spawnv',
[rffi.INT, rffi.CCHARP, rffi.CCHARPP],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def spawnv_llimpl(mode, path, args):
mode = rffi.cast(rffi.INT, mode)
l_args = rffi.ll_liststr2charpp(args)
childpid = os_spawnv(mode, path, l_args)
rffi.free_charpp(l_args)
if childpid == -1:
raise OSError(rposix.get_saved_errno(), "os_spawnv failed")
return rffi.cast(lltype.Signed, childpid)
return extdef([int, str0, [str0]], int, llimpl=spawnv_llimpl,
export_name="ll_os.ll_os_spawnv")
@registering_if(os, 'spawnve')
def register_os_spawnve(self):
os_spawnve = self.llexternal('spawnve',
[rffi.INT, rffi.CCHARP, rffi.CCHARPP,
rffi.CCHARPP],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def spawnve_llimpl(mode, path, args, env):
envstrs = []
for item in env.iteritems():
envstrs.append("%s=%s" % item)
mode = rffi.cast(rffi.INT, mode)
l_args = rffi.ll_liststr2charpp(args)
l_env = rffi.ll_liststr2charpp(envstrs)
childpid = os_spawnve(mode, path, l_args, l_env)
rffi.free_charpp(l_env)
rffi.free_charpp(l_args)
if childpid == -1:
raise OSError(rposix.get_saved_errno(), "os_spawnve failed")
return rffi.cast(lltype.Signed, childpid)
return extdef([int, str0, [str0], {str0: str0}], int,
llimpl=spawnve_llimpl,
export_name="ll_os.ll_os_spawnve")
@registering(os.dup)
def register_os_dup(self):
os_dup = self.llexternal(UNDERSCORE_ON_WIN32 + 'dup',
[rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def dup_llimpl(fd):
rposix.validate_fd(fd)
newfd = rffi.cast(lltype.Signed, os_dup(rffi.cast(rffi.INT, fd)))
if newfd == -1:
raise OSError(rposix.get_saved_errno(), "dup failed")
return newfd
return extdef([int], int, llimpl=dup_llimpl, export_name="ll_os.ll_os_dup")
@registering(os.dup2)
def register_os_dup2(self):
os_dup2 = self.llexternal(UNDERSCORE_ON_WIN32 + 'dup2',
[rffi.INT, rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def dup2_llimpl(fd, newfd):
rposix.validate_fd(fd)
error = rffi.cast(lltype.Signed, os_dup2(rffi.cast(rffi.INT, fd),
rffi.cast(rffi.INT, newfd)))
if error == -1:
raise OSError(rposix.get_saved_errno(), "dup2 failed")
return extdef([int, int], s_None, llimpl=dup2_llimpl,
export_name="ll_os.ll_os_dup2")
@registering_if(os, "getlogin", condition=not _WIN32)
def register_os_getlogin(self):
os_getlogin = self.llexternal('getlogin', [], rffi.CCHARP,
releasegil=False,
save_err=rffi.RFFI_SAVE_ERRNO)
def getlogin_llimpl():
result = os_getlogin()
if not result:
raise OSError(rposix.get_saved_errno(), "getlogin failed")
return rffi.charp2str(result)
return extdef([], str, llimpl=getlogin_llimpl,
export_name="ll_os.ll_os_getlogin")
@registering_str_unicode(os.utime)
def register_os_utime(self, traits):
UTIMBUFP = lltype.Ptr(self.UTIMBUF)
os_utime = self.llexternal('utime', [rffi.CCHARP, UTIMBUFP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
if not _WIN32:
includes = ['sys/time.h']
else:
includes = ['time.h']
eci = ExternalCompilationInfo(includes=includes)
class CConfig:
_compilation_info_ = eci
HAVE_UTIMES = platform.Has('utimes')
config = platform.configure(CConfig)
# XXX note that on Windows, calls to os.utime() are ignored on
# directories. Remove that hack over there once it's fixed here!
if config['HAVE_UTIMES']:
class CConfig:
_compilation_info_ = eci
TIMEVAL = platform.Struct('struct timeval', [('tv_sec', rffi.LONG),
('tv_usec', rffi.LONG)])
config = platform.configure(CConfig)
TIMEVAL = config['TIMEVAL']
TIMEVAL2P = rffi.CArrayPtr(TIMEVAL)
os_utimes = self.llexternal('utimes', [rffi.CCHARP, TIMEVAL2P],
rffi.INT, compilation_info=eci,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_utime_platform(path, actime, modtime):
import math
l_times = lltype.malloc(TIMEVAL2P.TO, 2, flavor='raw')
fracpart, intpart = math.modf(actime)
rffi.setintfield(l_times[0], 'c_tv_sec', int(intpart))
rffi.setintfield(l_times[0], 'c_tv_usec', int(fracpart * 1E6))
fracpart, intpart = math.modf(modtime)
rffi.setintfield(l_times[1], 'c_tv_sec', int(intpart))
rffi.setintfield(l_times[1], 'c_tv_usec', int(fracpart * 1E6))
error = os_utimes(path, l_times)
lltype.free(l_times, flavor='raw')
return error
else:
# we only have utime(), which does not allow sub-second resolution
def os_utime_platform(path, actime, modtime):
l_utimbuf = lltype.malloc(UTIMBUFP.TO, flavor='raw')
l_utimbuf.c_actime = rffi.r_time_t(actime)
l_utimbuf.c_modtime = rffi.r_time_t(modtime)
error = os_utime(path, l_utimbuf)
lltype.free(l_utimbuf, flavor='raw')
return error
# NB. this function is specialized; we get one version where
# tp is known to be None, and one version where it is known
# to be a tuple of 2 floats.
if not _WIN32:
assert traits.str is str
@specialize.argtype(1)
def os_utime_llimpl(path, tp):
if tp is None:
error = os_utime(path, lltype.nullptr(UTIMBUFP.TO))
else:
actime, modtime = tp
error = os_utime_platform(path, actime, modtime)
error = rffi.cast(lltype.Signed, error)
if error == -1:
raise OSError(rposix.get_saved_errno(), "os_utime failed")
else:
from rpython.rtyper.module.ll_win32file import make_utime_impl
os_utime_llimpl = make_utime_impl(traits)
s_tuple_of_2_floats = SomeTuple([SomeFloat(), SomeFloat()])
def os_utime_normalize_args(s_path, s_times):
# special handling of the arguments: they can be either
# [str, (float, float)] or [str, s_None], and get normalized
# to exactly one of these two.
if not traits.str0.contains(s_path):
raise Exception("os.utime() arg 1 must be a string, got %s" % (
s_path,))
case1 = s_None.contains(s_times)
case2 = s_tuple_of_2_floats.contains(s_times)
if case1 and case2:
return [traits.str0, s_ImpossibleValue] #don't know which case yet
elif case1:
return [traits.str0, s_None]
elif case2:
return [traits.str0, s_tuple_of_2_floats]
else:
raise Exception("os.utime() arg 2 must be None or a tuple of "
"2 floats, got %s" % (s_times,))
os_utime_normalize_args._default_signature_ = [traits.str0, None]
return extdef(os_utime_normalize_args, s_None,
"ll_os.ll_os_utime",
llimpl=os_utime_llimpl)
@registering(os.times)
def register_os_times(self):
if sys.platform.startswith('win'):
from rpython.rlib import rwin32
GetCurrentProcess = self.llexternal('GetCurrentProcess', [],
rwin32.HANDLE)
GetProcessTimes = self.llexternal('GetProcessTimes',
[rwin32.HANDLE,
lltype.Ptr(rwin32.FILETIME),
lltype.Ptr(rwin32.FILETIME),
lltype.Ptr(rwin32.FILETIME),
lltype.Ptr(rwin32.FILETIME)],
rwin32.BOOL)
def times_lltypeimpl():
pcreate = lltype.malloc(rwin32.FILETIME, flavor='raw')
pexit = lltype.malloc(rwin32.FILETIME, flavor='raw')
pkernel = lltype.malloc(rwin32.FILETIME, flavor='raw')
puser = lltype.malloc(rwin32.FILETIME, flavor='raw')
hProc = GetCurrentProcess()
GetProcessTimes(hProc, pcreate, pexit, pkernel, puser)
# The fields of a FILETIME structure are the hi and lo parts
# of a 64-bit value expressed in 100 nanosecond units
# (of course).
result = (rffi.cast(lltype.Signed, pkernel.c_dwHighDateTime) * 429.4967296 +
rffi.cast(lltype.Signed, pkernel.c_dwLowDateTime) * 1E-7,
rffi.cast(lltype.Signed, puser.c_dwHighDateTime) * 429.4967296 +
rffi.cast(lltype.Signed, puser.c_dwLowDateTime) * 1E-7,
0, 0, 0)
lltype.free(puser, flavor='raw')
lltype.free(pkernel, flavor='raw')
lltype.free(pexit, flavor='raw')
lltype.free(pcreate, flavor='raw')
return result
self.register(os.times, [], (float, float, float, float, float),
"ll_os.ll_times", llimpl=times_lltypeimpl)
return
TMSP = lltype.Ptr(self.TMS)
os_times = self.llexternal('times', [TMSP], self.CLOCK_T,
save_err=rffi.RFFI_SAVE_ERRNO)
# Here is a random extra platform parameter which is important.
# Strictly speaking, this should probably be retrieved at runtime, not
# at translation time.
CLOCK_TICKS_PER_SECOND = float(os.sysconf('SC_CLK_TCK'))
def times_lltypeimpl():
l_tmsbuf = lltype.malloc(TMSP.TO, flavor='raw')
try:
result = os_times(l_tmsbuf)
result = rffi.cast(lltype.Signed, result)
if result == -1:
raise OSError(rposix.get_saved_errno(), "times failed")
return (
rffi.cast(lltype.Signed, l_tmsbuf.c_tms_utime)
/ CLOCK_TICKS_PER_SECOND,
rffi.cast(lltype.Signed, l_tmsbuf.c_tms_stime)
/ CLOCK_TICKS_PER_SECOND,
rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cutime)
/ CLOCK_TICKS_PER_SECOND,
rffi.cast(lltype.Signed, l_tmsbuf.c_tms_cstime)
/ CLOCK_TICKS_PER_SECOND,
result / CLOCK_TICKS_PER_SECOND)
finally:
lltype.free(l_tmsbuf, flavor='raw')
self.register(os.times, [], (float, float, float, float, float),
"ll_os.ll_times", llimpl=times_lltypeimpl)
@registering_if(os, 'setsid')
def register_os_setsid(self):
os_setsid = self.llexternal('setsid', [], rffi.PID_T,
save_err=rffi.RFFI_SAVE_ERRNO)
def setsid_llimpl():
result = rffi.cast(lltype.Signed, os_setsid())
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_setsid failed")
return result
return extdef([], int, export_name="ll_os.ll_os_setsid",
llimpl=setsid_llimpl)
@registering_if(os, 'chroot')
def register_os_chroot(self):
os_chroot = self.llexternal('chroot', [rffi.CCHARP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def chroot_llimpl(arg):
result = os_chroot(arg)
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_chroot failed")
return extdef([str0], None, export_name="ll_os.ll_os_chroot",
llimpl=chroot_llimpl)
@registering_if(os, 'uname')
def register_os_uname(self):
CHARARRAY = lltype.FixedSizeArray(lltype.Char, 1)
class CConfig:
_compilation_info_ = ExternalCompilationInfo(
includes = ['sys/utsname.h']
)
UTSNAME = platform.Struct('struct utsname', [
('sysname', CHARARRAY),
('nodename', CHARARRAY),
('release', CHARARRAY),
('version', CHARARRAY),
('machine', CHARARRAY)])
config = platform.configure(CConfig)
UTSNAMEP = lltype.Ptr(config['UTSNAME'])
os_uname = self.llexternal('uname', [UTSNAMEP], rffi.INT,
compilation_info=CConfig._compilation_info_,
save_err=rffi.RFFI_SAVE_ERRNO)
def uname_llimpl():
l_utsbuf = lltype.malloc(UTSNAMEP.TO, flavor='raw')
result = os_uname(l_utsbuf)
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_uname failed")
retval = (
rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_sysname)),
rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_nodename)),
rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_release)),
rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_version)),
rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_machine)),
)
lltype.free(l_utsbuf, flavor='raw')
return retval
return extdef([], (str, str, str, str, str),
"ll_os.ll_uname", llimpl=uname_llimpl)
@registering_if(os, 'sysconf')
def register_os_sysconf(self):
c_sysconf = self.llexternal('sysconf', [rffi.INT], rffi.LONG,
save_err=rffi.RFFI_FULL_ERRNO_ZERO)
def sysconf_llimpl(i):
res = c_sysconf(i)
if res == -1:
errno = rposix.get_saved_errno()
if errno != 0:
raise OSError(errno, "sysconf failed")
return res
return extdef([int], int, "ll_os.ll_sysconf", llimpl=sysconf_llimpl)
@registering_if(os, 'fpathconf')
def register_os_fpathconf(self):
c_fpathconf = self.llexternal('fpathconf',
[rffi.INT, rffi.INT], rffi.LONG,
save_err=rffi.RFFI_FULL_ERRNO_ZERO)
def fpathconf_llimpl(fd, i):
res = c_fpathconf(fd, i)
if res == -1:
errno = rposix.get_saved_errno()
if errno != 0:
raise OSError(errno, "fpathconf failed")
return res
return extdef([int, int], int, "ll_os.ll_fpathconf",
llimpl=fpathconf_llimpl)
@registering_if(os, 'pathconf')
def register_os_pathconf(self):
c_pathconf = self.llexternal('pathconf',
[rffi.CCHARP, rffi.INT], rffi.LONG,
save_err=rffi.RFFI_FULL_ERRNO_ZERO)
def pathconf_llimpl(path, i):
res = c_pathconf(path, i)
if res == -1:
errno = rposix.get_saved_errno()
if errno != 0:
raise OSError(errno, "pathconf failed")
return res
return extdef([str0, int], int, "ll_os.ll_pathconf",
llimpl=pathconf_llimpl)
@registering_if(os, 'confstr')
def register_os_confstr(self):
c_confstr = self.llexternal('confstr', [rffi.INT, rffi.CCHARP,
rffi.SIZE_T], rffi.SIZE_T,
save_err=rffi.RFFI_FULL_ERRNO_ZERO)
def confstr_llimpl(i):
n = c_confstr(i, lltype.nullptr(rffi.CCHARP.TO), 0)
n = rffi.cast(lltype.Signed, n)
if n > 0:
buf = lltype.malloc(rffi.CCHARP.TO, n, flavor='raw')
try:
c_confstr(i, buf, n)
return rffi.charp2strn(buf, n)
finally:
lltype.free(buf, flavor='raw')
else:
errno = rposix.get_saved_errno()
if errno != 0:
raise OSError(errno, "confstr failed")
return None
return extdef([int], SomeString(can_be_None=True),
"ll_os.ll_confstr", llimpl=confstr_llimpl)
@registering_if(os, 'getuid')
def register_os_getuid(self):
return self.extdef_for_os_function_returning_int('getuid')
@registering_if(os, 'geteuid')
def register_os_geteuid(self):
return self.extdef_for_os_function_returning_int('geteuid')
@registering_if(os, 'setuid')
def register_os_setuid(self):
return self.extdef_for_os_function_accepting_int('setuid')
@registering_if(os, 'seteuid')
def register_os_seteuid(self):
return self.extdef_for_os_function_accepting_int('seteuid')
@registering_if(os, 'setgid')
def register_os_setgid(self):
return self.extdef_for_os_function_accepting_int('setgid')
@registering_if(os, 'setegid')
def register_os_setegid(self):
return self.extdef_for_os_function_accepting_int('setegid')
@registering_if(os, 'getpid')
def register_os_getpid(self):
return self.extdef_for_os_function_returning_int('getpid', releasegil=False)
@registering_if(os, 'getgid')
def register_os_getgid(self):
return self.extdef_for_os_function_returning_int('getgid')
@registering_if(os, 'getegid')
def register_os_getegid(self):
return self.extdef_for_os_function_returning_int('getegid')
@registering_if(os, 'getgroups')
def register_os_getgroups(self):
GP = rffi.CArrayPtr(rffi.PID_T)
c_getgroups = self.llexternal('getgroups', [rffi.INT, GP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def getgroups_llimpl():
n = c_getgroups(0, lltype.nullptr(GP.TO))
if n >= 0:
groups = lltype.malloc(GP.TO, n, flavor='raw')
try:
n = c_getgroups(n, groups)
result = [rffi.cast(lltype.Signed, groups[i])
for i in range(n)]
finally:
lltype.free(groups, flavor='raw')
if n >= 0:
return result
raise OSError(rposix.get_saved_errno(), "os_getgroups failed")
return extdef([], [int], llimpl=getgroups_llimpl,
export_name="ll_os.ll_getgroups")
@registering_if(os, 'setgroups')
def register_os_setgroups(self):
GP = rffi.CArrayPtr(rffi.PID_T)
c_setgroups = self.llexternal('setgroups', [rffi.SIZE_T, GP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def setgroups_llimpl(list):
n = len(list)
groups = lltype.malloc(GP.TO, n, flavor='raw')
try:
for i in range(n):
groups[i] = rffi.cast(rffi.PID_T, list[i])
n = c_setgroups(rffi.cast(rffi.SIZE_T, n), groups)
finally:
lltype.free(groups, flavor='raw')
if n != 0:
raise OSError(rposix.get_saved_errno(), "os_setgroups failed")
return extdef([[int]], None, llimpl=setgroups_llimpl,
export_name="ll_os.ll_setgroups")
@registering_if(os, 'initgroups')
def register_os_initgroups(self):
c_initgroups = self.llexternal('initgroups',
[rffi.CCHARP, rffi.PID_T], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def initgroups_llimpl(user, group):
n = c_initgroups(user, rffi.cast(rffi.PID_T, group))
if n != 0:
raise OSError(rposix.get_saved_errno(), "os_initgroups failed")
return extdef([str, int], None, llimpl=initgroups_llimpl,
export_name="ll_os.ll_initgroups")
@registering_if(os, 'getpgrp')
def register_os_getpgrp(self):
name = 'getpgrp'
if self.GETPGRP_HAVE_ARG:
c_func = self.llexternal(name, [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_func_llimpl():
res = rffi.cast(rffi.SIGNED, c_func(0))
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
return res
c_func_llimpl.func_name = name + '_llimpl'
return extdef([], int, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
else:
return self.extdef_for_os_function_returning_int('getpgrp')
@registering_if(os, 'setpgrp')
def register_os_setpgrp(self):
name = 'setpgrp'
if self.SETPGRP_HAVE_ARG:
c_func = self.llexternal(name, [rffi.INT, rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_func_llimpl():
res = rffi.cast(rffi.SIGNED, c_func(0, 0))
if res == -1:
raise OSError(rposix.get_saved_errno(), "%s failed" % name)
c_func_llimpl.func_name = name + '_llimpl'
return extdef([], None, llimpl=c_func_llimpl,
export_name='ll_os.ll_os_' + name)
else:
return self.extdef_for_os_function_accepting_0int(name)
@registering_if(os, 'tcgetpgrp')
def register_os_tcgetpgrp(self):
c_tcgetpgrp = self.llexternal('tcgetpgrp', [rffi.INT], rffi.PID_T,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_tcgetpgrp_llimpl(fd):
res = c_tcgetpgrp(rffi.cast(rffi.INT, fd))
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "tcgetpgrp failed")
return res
return extdef([int], int, llimpl=c_tcgetpgrp_llimpl,
export_name='ll_os.ll_os_tcgetpgrp')
@registering_if(os, 'tcsetpgrp')
def register_os_tcsetpgrp(self):
c_tcsetpgrp = self.llexternal('tcsetpgrp', [rffi.INT, rffi.PID_T],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_tcsetpgrp_llimpl(fd, pgrp):
res = c_tcsetpgrp(rffi.cast(rffi.INT, fd),
rffi.cast(rffi.PID_T, pgrp))
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "tcsetpgrp failed")
return extdef([int, int], None, llimpl=c_tcsetpgrp_llimpl,
export_name='ll_os.ll_os_tcsetpgrp')
@registering_if(os, 'getppid')
def register_os_getppid(self):
return self.extdef_for_os_function_returning_int('getppid')
@registering_if(os, 'getpgid')
def register_os_getpgid(self):
return self.extdef_for_os_function_int_to_int('getpgid')
@registering_if(os, 'setpgid')
def register_os_setpgid(self):
return self.extdef_for_os_function_accepting_2int('setpgid')
@registering_if(os, 'setreuid')
def register_os_setreuid(self):
return self.extdef_for_os_function_accepting_2int('setreuid')
@registering_if(os, 'setregid')
def register_os_setregid(self):
return self.extdef_for_os_function_accepting_2int('setregid')
@registering_if(os, 'getsid')
def register_os_getsid(self):
return self.extdef_for_os_function_int_to_int('getsid')
@registering_if(os, 'setsid')
def register_os_setsid(self):
return self.extdef_for_os_function_returning_int('setsid')
@registering_if(os, 'getresuid')
def register_os_getresuid(self):
c_getresuid = self.llexternal('getresuid', [rffi.INTP] * 3, rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_getresuid_llimpl():
out = lltype.malloc(rffi.INTP.TO, 3, flavor='raw')
try:
res = c_getresuid(rffi.ptradd(out, 0),
rffi.ptradd(out, 1),
rffi.ptradd(out, 2))
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "getresuid failed")
return (rffi.cast(lltype.Signed, out[0]),
rffi.cast(lltype.Signed, out[1]),
rffi.cast(lltype.Signed, out[2]))
finally:
lltype.free(out, flavor='raw')
return extdef([], (int, int, int), llimpl=c_getresuid_llimpl,
export_name='ll_os.ll_os_getresuid')
@registering_if(os, 'getresgid')
def register_os_getresgid(self):
c_getresgid = self.llexternal('getresgid', [rffi.INTP] * 3, rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_getresgid_llimpl():
out = lltype.malloc(rffi.INTP.TO, 3, flavor='raw')
try:
res = c_getresgid(rffi.ptradd(out, 0),
rffi.ptradd(out, 1),
rffi.ptradd(out, 2))
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "getresgid failed")
return (rffi.cast(lltype.Signed, out[0]),
rffi.cast(lltype.Signed, out[1]),
rffi.cast(lltype.Signed, out[2]))
finally:
lltype.free(out, flavor='raw')
return extdef([], (int, int, int), llimpl=c_getresgid_llimpl,
export_name='ll_os.ll_os_getresgid')
@registering_if(os, 'setresuid')
def register_os_setresuid(self):
c_setresuid = self.llexternal('setresuid', [rffi.INT] * 3, rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_setresuid_llimpl(ruid, euid, suid):
res = c_setresuid(ruid, euid, suid)
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "setresuid failed")
return extdef([int, int, int], None, llimpl=c_setresuid_llimpl,
export_name='ll_os.ll_os_setresuid')
@registering_if(os, 'setresgid')
def register_os_setresgid(self):
c_setresgid = self.llexternal('setresgid', [rffi.INT] * 3, rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def c_setresgid_llimpl(rgid, egid, sgid):
res = c_setresgid(rgid, egid, sgid)
res = rffi.cast(lltype.Signed, res)
if res == -1:
raise OSError(rposix.get_saved_errno(), "setresgid failed")
return extdef([int, int, int], None, llimpl=c_setresgid_llimpl,
export_name='ll_os.ll_os_setresgid')
@registering_str_unicode(os.open)
def register_os_open(self, traits):
os_open = self.llexternal(traits.posix_function_name('open'),
[traits.CCHARP, rffi.INT, rffi.MODE_T],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_open_llimpl(path, flags, mode):
result = rffi.cast(lltype.Signed, os_open(path, flags, mode))
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_open failed")
return result
return extdef([traits.str0, int, int], int, traits.ll_os_name('open'),
llimpl=os_open_llimpl)
@registering_if(os, 'getloadavg')
def register_os_getloadavg(self):
AP = rffi.CArrayPtr(lltype.Float)
c_getloadavg = self.llexternal('getloadavg', [AP, rffi.INT], rffi.INT)
def getloadavg_llimpl():
load = lltype.malloc(AP.TO, 3, flavor='raw')
r = c_getloadavg(load, 3)
result_tuple = load[0], load[1], load[2]
lltype.free(load, flavor='raw')
if r != 3:
raise OSError
return result_tuple
return extdef([], (float, float, float),
"ll_os.ll_getloadavg", llimpl=getloadavg_llimpl)
@registering_if(os, 'makedev')
def register_os_makedev(self):
c_makedev = self.llexternal('makedev', [rffi.INT, rffi.INT], rffi.INT)
def makedev_llimpl(maj, min):
return c_makedev(maj, min)
return extdef([int, int], int,
"ll_os.ll_makedev", llimpl=makedev_llimpl)
@registering_if(os, 'major')
def register_os_major(self):
c_major = self.llexternal('major', [rffi.INT], rffi.INT)
def major_llimpl(dev):
return c_major(dev)
return extdef([int], int,
"ll_os.ll_major", llimpl=major_llimpl)
@registering_if(os, 'minor')
def register_os_minor(self):
c_minor = self.llexternal('minor', [rffi.INT], rffi.INT)
def minor_llimpl(dev):
return c_minor(dev)
return extdef([int], int,
"ll_os.ll_minor", llimpl=minor_llimpl)
# ------------------------------- os.read -------------------------------
@registering(os.read)
def register_os_read(self):
os_read = self.llexternal(UNDERSCORE_ON_WIN32 + 'read',
[rffi.INT, rffi.VOIDP, rffi.SIZE_T],
rffi.SSIZE_T, save_err=rffi.RFFI_SAVE_ERRNO)
def os_read_llimpl(fd, count):
if count < 0:
raise OSError(errno.EINVAL, None)
rposix.validate_fd(fd)
with rffi.scoped_alloc_buffer(count) as buf:
void_buf = rffi.cast(rffi.VOIDP, buf.raw)
got = rffi.cast(lltype.Signed, os_read(fd, void_buf, count))
if got < 0:
raise OSError(rposix.get_saved_errno(), "os_read failed")
return buf.str(got)
return extdef([int, int], SomeString(can_be_None=True),
"ll_os.ll_os_read", llimpl=os_read_llimpl)
@registering(os.write)
def register_os_write(self):
os_write = self.llexternal(UNDERSCORE_ON_WIN32 + 'write',
[rffi.INT, rffi.VOIDP, rffi.SIZE_T],
rffi.SIZE_T,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_write_llimpl(fd, data):
count = len(data)
rposix.validate_fd(fd)
with rffi.scoped_nonmovingbuffer(data) as buf:
written = rffi.cast(lltype.Signed, os_write(
rffi.cast(rffi.INT, fd),
buf, rffi.cast(rffi.SIZE_T, count)))
if written < 0:
raise OSError(rposix.get_saved_errno(), "os_write failed")
return written
return extdef([int, str], SomeInteger(nonneg=True),
"ll_os.ll_os_write", llimpl=os_write_llimpl)
@registering(os.close)
def register_os_close(self):
os_close = self.llexternal(UNDERSCORE_ON_WIN32 + 'close', [rffi.INT],
rffi.INT, releasegil=False,
save_err=rffi.RFFI_SAVE_ERRNO)
def close_llimpl(fd):
rposix.validate_fd(fd)
error = rffi.cast(lltype.Signed, os_close(rffi.cast(rffi.INT, fd)))
if error == -1:
raise OSError(rposix.get_saved_errno(), "close failed")
return extdef([int], s_None, llimpl=close_llimpl,
export_name="ll_os.ll_os_close")
@registering(os.lseek)
def register_os_lseek(self):
if sys.platform.startswith('win'):
funcname = '_lseeki64'
else:
funcname = 'lseek'
if self.SEEK_SET is not None:
SEEK_SET = self.SEEK_SET
SEEK_CUR = self.SEEK_CUR
SEEK_END = self.SEEK_END
else:
SEEK_SET, SEEK_CUR, SEEK_END = 0, 1, 2
if (SEEK_SET, SEEK_CUR, SEEK_END) != (0, 1, 2):
# Turn 0, 1, 2 into SEEK_{SET,CUR,END}
def fix_seek_arg(n):
if n == 0: return SEEK_SET
if n == 1: return SEEK_CUR
if n == 2: return SEEK_END
return n
else:
def fix_seek_arg(n):
return n
os_lseek = self.llexternal(funcname,
[rffi.INT, rffi.LONGLONG, rffi.INT],
rffi.LONGLONG, macro=True,
save_err=rffi.RFFI_SAVE_ERRNO)
def lseek_llimpl(fd, pos, how):
rposix.validate_fd(fd)
how = fix_seek_arg(how)
res = os_lseek(rffi.cast(rffi.INT, fd),
rffi.cast(rffi.LONGLONG, pos),
rffi.cast(rffi.INT, how))
res = rffi.cast(lltype.SignedLongLong, res)
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_lseek failed")
return res
return extdef([int, r_longlong, int],
r_longlong,
llimpl = lseek_llimpl,
export_name = "ll_os.ll_os_lseek")
@registering_if(os, 'ftruncate')
def register_os_ftruncate(self):
os_ftruncate = self.llexternal('ftruncate',
[rffi.INT, rffi.LONGLONG], rffi.INT,
macro=True,
save_err=rffi.RFFI_SAVE_ERRNO)
def ftruncate_llimpl(fd, length):
rposix.validate_fd(fd)
res = rffi.cast(rffi.LONG,
os_ftruncate(rffi.cast(rffi.INT, fd),
rffi.cast(rffi.LONGLONG, length)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_ftruncate failed")
return extdef([int, r_longlong], s_None,
llimpl = ftruncate_llimpl,
export_name = "ll_os.ll_os_ftruncate")
@registering_if(os, 'fsync')
def register_os_fsync(self):
if not _WIN32:
os_fsync = self.llexternal('fsync', [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
else:
os_fsync = self.llexternal('_commit', [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def fsync_llimpl(fd):
rposix.validate_fd(fd)
res = rffi.cast(rffi.SIGNED, os_fsync(rffi.cast(rffi.INT, fd)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "fsync failed")
return extdef([int], s_None,
llimpl=fsync_llimpl,
export_name="ll_os.ll_os_fsync")
@registering_if(os, 'fdatasync')
def register_os_fdatasync(self):
os_fdatasync = self.llexternal('fdatasync', [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def fdatasync_llimpl(fd):
rposix.validate_fd(fd)
res = rffi.cast(rffi.SIGNED, os_fdatasync(rffi.cast(rffi.INT, fd)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "fdatasync failed")
return extdef([int], s_None,
llimpl=fdatasync_llimpl,
export_name="ll_os.ll_os_fdatasync")
@registering_if(os, 'fchdir')
def register_os_fchdir(self):
os_fchdir = self.llexternal('fchdir', [rffi.INT], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def fchdir_llimpl(fd):
rposix.validate_fd(fd)
res = rffi.cast(rffi.SIGNED, os_fchdir(rffi.cast(rffi.INT, fd)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "fchdir failed")
return extdef([int], s_None,
llimpl=fchdir_llimpl,
export_name="ll_os.ll_os_fchdir")
@registering_str_unicode(os.access)
def register_os_access(self, traits):
os_access = self.llexternal(traits.posix_function_name('access'),
[traits.CCHARP, rffi.INT],
rffi.INT)
if sys.platform.startswith('win'):
# All files are executable on Windows
def access_llimpl(path, mode):
mode = mode & ~os.X_OK
error = rffi.cast(lltype.Signed, os_access(path, mode))
return error == 0
else:
def access_llimpl(path, mode):
error = rffi.cast(lltype.Signed, os_access(path, mode))
return error == 0
return extdef([traits.str0, int], s_Bool, llimpl=access_llimpl,
export_name=traits.ll_os_name("access"))
@registering_str_unicode(getattr(posix, '_getfullpathname', None),
condition=sys.platform=='win32')
def register_posix__getfullpathname(self, traits):
# this nt function is not exposed via os, but needed
# to get a correct implementation of os.path.abspath
from rpython.rtyper.module.ll_win32file import make_getfullpathname_impl
getfullpathname_llimpl = make_getfullpathname_impl(traits)
return extdef([traits.str0], # a single argument which is a str
traits.str0, # returns a string
traits.ll_os_name('_getfullpathname'),
llimpl=getfullpathname_llimpl)
@registering(os.getcwd)
def register_os_getcwd(self):
os_getcwd = self.llexternal(UNDERSCORE_ON_WIN32 + 'getcwd',
[rffi.CCHARP, rffi.SIZE_T],
rffi.CCHARP,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_getcwd_llimpl():
bufsize = 256
while True:
buf = lltype.malloc(rffi.CCHARP.TO, bufsize, flavor='raw')
res = os_getcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
if res:
break # ok
error = rposix.get_saved_errno()
lltype.free(buf, flavor='raw')
if error != errno.ERANGE:
raise OSError(error, "getcwd failed")
# else try again with a larger buffer, up to some sane limit
bufsize *= 4
if bufsize > 1024*1024: # xxx hard-coded upper limit
raise OSError(error, "getcwd result too large")
result = rffi.charp2str(res)
lltype.free(buf, flavor='raw')
return result
return extdef([], str0,
"ll_os.ll_os_getcwd", llimpl=os_getcwd_llimpl)
@registering(os.getcwdu, condition=sys.platform=='win32')
def register_os_getcwdu(self):
os_wgetcwd = self.llexternal(UNDERSCORE_ON_WIN32 + 'wgetcwd',
[rffi.CWCHARP, rffi.SIZE_T],
rffi.CWCHARP,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_getcwd_llimpl():
bufsize = 256
while True:
buf = lltype.malloc(rffi.CWCHARP.TO, bufsize, flavor='raw')
res = os_wgetcwd(buf, rffi.cast(rffi.SIZE_T, bufsize))
if res:
break # ok
error = rposix.get_saved_errno()
lltype.free(buf, flavor='raw')
if error != errno.ERANGE:
raise OSError(error, "getcwd failed")
# else try again with a larger buffer, up to some sane limit
bufsize *= 4
if bufsize > 1024*1024: # xxx hard-coded upper limit
raise OSError(error, "getcwd result too large")
result = rffi.wcharp2unicode(res)
lltype.free(buf, flavor='raw')
return result
return extdef([], unicode,
"ll_os.ll_os_wgetcwd", llimpl=os_getcwd_llimpl)
@registering_str_unicode(os.listdir)
def register_os_listdir(self, traits):
# we need a different approach on Windows and on Posix
if sys.platform.startswith('win'):
from rpython.rtyper.module.ll_win32file import make_listdir_impl
os_listdir_llimpl = make_listdir_impl(traits)
else:
assert traits.str is str
compilation_info = ExternalCompilationInfo(
includes = ['sys/types.h', 'dirent.h']
)
class CConfig:
_compilation_info_ = compilation_info
DIRENT = platform.Struct('struct dirent',
[('d_name', lltype.FixedSizeArray(rffi.CHAR, 1))])
DIRP = rffi.COpaquePtr('DIR')
config = platform.configure(CConfig)
DIRENT = config['DIRENT']
DIRENTP = lltype.Ptr(DIRENT)
os_opendir = self.llexternal('opendir', [rffi.CCHARP], DIRP,
compilation_info=compilation_info,
save_err=rffi.RFFI_SAVE_ERRNO)
# XXX macro=True is hack to make sure we get the correct kind of
# dirent struct (which depends on defines)
os_readdir = self.llexternal('readdir', [DIRP], DIRENTP,
compilation_info=compilation_info,
save_err=rffi.RFFI_FULL_ERRNO_ZERO,
macro=True)
os_closedir = self.llexternal('closedir', [DIRP], rffi.INT,
compilation_info=compilation_info)
def os_listdir_llimpl(path):
dirp = os_opendir(path)
if not dirp:
raise OSError(rposix.get_saved_errno(), "os_opendir failed")
result = []
while True:
direntp = os_readdir(dirp)
if not direntp:
error = rposix.get_saved_errno()
break
namep = rffi.cast(rffi.CCHARP, direntp.c_d_name)
name = rffi.charp2str(namep)
if name != '.' and name != '..':
result.append(name)
os_closedir(dirp)
if error:
raise OSError(error, "os_readdir failed")
return result
return extdef([traits.str0], # a single argument which is a str
[traits.str0], # returns a list of strings
traits.ll_os_name('listdir'),
llimpl=os_listdir_llimpl)
@registering(os.pipe)
def register_os_pipe(self):
# we need a different approach on Windows and on Posix
if sys.platform.startswith('win'):
from rpython.rlib import rwin32
CreatePipe = self.llexternal('CreatePipe', [rwin32.LPHANDLE,
rwin32.LPHANDLE,
rffi.VOIDP,
rwin32.DWORD],
rwin32.BOOL,
save_err=rffi.RFFI_SAVE_LASTERROR)
_open_osfhandle = self.llexternal('_open_osfhandle', [rffi.INTPTR_T,
rffi.INT],
rffi.INT)
null = lltype.nullptr(rffi.VOIDP.TO)
def os_pipe_llimpl():
pread = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
pwrite = lltype.malloc(rwin32.LPHANDLE.TO, 1, flavor='raw')
ok = CreatePipe(pread, pwrite, null, 0)
if ok:
error = 0
else:
error = rwin32.GetLastError_saved()
hread = rffi.cast(rffi.INTPTR_T, pread[0])
hwrite = rffi.cast(rffi.INTPTR_T, pwrite[0])
lltype.free(pwrite, flavor='raw')
lltype.free(pread, flavor='raw')
if error:
raise WindowsError(error, "os_pipe failed")
fdread = _open_osfhandle(hread, 0)
fdwrite = _open_osfhandle(hwrite, 1)
return (fdread, fdwrite)
else:
INT_ARRAY_P = rffi.CArrayPtr(rffi.INT)
os_pipe = self.llexternal('pipe', [INT_ARRAY_P], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_pipe_llimpl():
filedes = lltype.malloc(INT_ARRAY_P.TO, 2, flavor='raw')
error = rffi.cast(lltype.Signed, os_pipe(filedes))
read_fd = filedes[0]
write_fd = filedes[1]
lltype.free(filedes, flavor='raw')
if error != 0:
raise OSError(rposix.get_saved_errno(), "os_pipe failed")
return (rffi.cast(lltype.Signed, read_fd),
rffi.cast(lltype.Signed, write_fd))
return extdef([], (int, int),
"ll_os.ll_os_pipe",
llimpl=os_pipe_llimpl)
@registering_if(os, 'chown')
def register_os_chown(self):
os_chown = self.llexternal('chown', [rffi.CCHARP, rffi.INT, rffi.INT],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_chown_llimpl(path, uid, gid):
res = os_chown(path, uid, gid)
if res == -1:
raise OSError(rposix.get_saved_errno(), "os_chown failed")
return extdef([str0, int, int], None, "ll_os.ll_os_chown",
llimpl=os_chown_llimpl)
@registering_if(os, 'lchown')
def register_os_lchown(self):
os_lchown = self.llexternal('lchown',[rffi.CCHARP, rffi.INT, rffi.INT],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_lchown_llimpl(path, uid, gid):
res = os_lchown(path, uid, gid)
if res == -1:
raise OSError(rposix.get_saved_errno(), "os_lchown failed")
return extdef([str0, int, int], None, "ll_os.ll_os_lchown",
llimpl=os_lchown_llimpl)
@registering_if(os, 'fchown')
def register_os_fchown(self):
os_fchown = self.llexternal('fchown',[rffi.INT, rffi.INT, rffi.INT],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_fchown_llimpl(fd, uid, gid):
res = os_fchown(fd, uid, gid)
if res == -1:
raise OSError(rposix.get_saved_errno(), "os_fchown failed")
return extdef([int, int, int], None, "ll_os.ll_os_fchown",
llimpl=os_fchown_llimpl)
@registering_if(os, 'readlink')
def register_os_readlink(self):
os_readlink = self.llexternal('readlink',
[rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
# XXX SSIZE_T in POSIX.1-2001
def os_readlink_llimpl(path):
bufsize = 1023
while True:
l_path = rffi.str2charp(path)
buf = lltype.malloc(rffi.CCHARP.TO, bufsize,
flavor='raw')
res = rffi.cast(lltype.Signed, os_readlink(l_path, buf, bufsize))
lltype.free(l_path, flavor='raw')
if res < 0:
error = rposix.get_saved_errno() # failed
lltype.free(buf, flavor='raw')
raise OSError(error, "readlink failed")
elif res < bufsize:
break # ok
else:
# buf too small, try again with a larger buffer
lltype.free(buf, flavor='raw')
bufsize *= 4
# convert the result to a string
result = rffi.charp2strn(buf, res)
lltype.free(buf, flavor='raw')
return result
return extdef([str0], str0,
"ll_os.ll_os_readlink",
llimpl=os_readlink_llimpl)
@registering(os.waitpid)
def register_os_waitpid(self):
if sys.platform.startswith('win'):
# emulate waitpid() with the _cwait() of Microsoft's compiler
os__cwait = self.llexternal('_cwait',
[rffi.INTP, rffi.PID_T, rffi.INT],
rffi.PID_T,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_waitpid(pid, status_p, options):
result = os__cwait(status_p, pid, options)
# shift the status left a byte so this is more
# like the POSIX waitpid
tmp = rffi.cast(rffi.SIGNED, status_p[0])
tmp <<= 8
status_p[0] = rffi.cast(rffi.INT, tmp)
return result
else:
# Posix
if _CYGWIN:
os_waitpid = self.llexternal('cygwin_waitpid',
[rffi.PID_T, rffi.INTP, rffi.INT],
rffi.PID_T,
save_err=rffi.RFFI_SAVE_ERRNO)
else:
os_waitpid = self.llexternal('waitpid',
[rffi.PID_T, rffi.INTP, rffi.INT],
rffi.PID_T,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_waitpid_llimpl(pid, options):
status_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
status_p[0] = rffi.cast(rffi.INT, 0)
result = os_waitpid(rffi.cast(rffi.PID_T, pid),
status_p,
rffi.cast(rffi.INT, options))
result = rffi.cast(lltype.Signed, result)
status = status_p[0]
lltype.free(status_p, flavor='raw')
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_waitpid failed")
return (rffi.cast(lltype.Signed, result),
rffi.cast(lltype.Signed, status))
return extdef([int, int], (int, int),
"ll_os.ll_os_waitpid",
llimpl=os_waitpid_llimpl)
@registering(os.isatty)
def register_os_isatty(self):
os_isatty = self.llexternal(UNDERSCORE_ON_WIN32 + 'isatty',
[rffi.INT], rffi.INT)
def isatty_llimpl(fd):
if not rposix.is_valid_fd(fd):
return False
res = rffi.cast(lltype.Signed, os_isatty(rffi.cast(rffi.INT, fd)))
return res != 0
return extdef([int], bool, llimpl=isatty_llimpl,
export_name="ll_os.ll_os_isatty")
@registering(os.strerror)
def register_os_strerror(self):
os_strerror = self.llexternal('strerror', [rffi.INT], rffi.CCHARP, releasegil=False)
def strerror_llimpl(errnum):
res = os_strerror(rffi.cast(rffi.INT, errnum))
if not res:
raise ValueError("os_strerror failed")
return rffi.charp2str(res)
return extdef([int], str, llimpl=strerror_llimpl,
export_name="ll_os.ll_os_strerror")
@registering(os.system)
def register_os_system(self):
os_system = self.llexternal('system', [rffi.CCHARP], rffi.INT)
def system_llimpl(command):
res = os_system(command)
return rffi.cast(lltype.Signed, res)
return extdef([str0], int, llimpl=system_llimpl,
export_name="ll_os.ll_os_system")
@registering_str_unicode(os.unlink)
def register_os_unlink(self, traits):
os_unlink = self.llexternal(traits.posix_function_name('unlink'),
[traits.CCHARP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def unlink_llimpl(pathname):
res = rffi.cast(lltype.Signed, os_unlink(pathname))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_unlink failed")
if sys.platform == 'win32':
from rpython.rtyper.module.ll_win32file import make_win32_traits
win32traits = make_win32_traits(traits)
@func_renamer('unlink_llimpl_%s' % traits.str.__name__)
def unlink_llimpl(path):
if not win32traits.DeleteFile(path):
raise rwin32.lastSavedWindowsError()
return extdef([traits.str0], s_None, llimpl=unlink_llimpl,
export_name=traits.ll_os_name('unlink'))
@registering_str_unicode(os.chdir)
def register_os_chdir(self, traits):
os_chdir = self.llexternal(traits.posix_function_name('chdir'),
[traits.CCHARP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def os_chdir_llimpl(path):
res = rffi.cast(lltype.Signed, os_chdir(path))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_chdir failed")
# On Windows, use an implementation that will produce Win32 errors
if sys.platform == 'win32':
from rpython.rtyper.module.ll_win32file import make_chdir_impl
os_chdir_llimpl = make_chdir_impl(traits)
return extdef([traits.str0], s_None, llimpl=os_chdir_llimpl,
export_name=traits.ll_os_name('chdir'))
@registering_str_unicode(os.mkdir)
def register_os_mkdir(self, traits):
os_mkdir = self.llexternal(traits.posix_function_name('mkdir'),
[traits.CCHARP, rffi.MODE_T], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
if sys.platform == 'win32':
from rpython.rtyper.module.ll_win32file import make_win32_traits
win32traits = make_win32_traits(traits)
@func_renamer('mkdir_llimpl_%s' % traits.str.__name__)
def os_mkdir_llimpl(path, mode):
if not win32traits.CreateDirectory(path, None):
raise rwin32.lastSavedWindowsError()
else:
def os_mkdir_llimpl(pathname, mode):
res = os_mkdir(pathname, mode)
res = rffi.cast(lltype.Signed, res)
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_mkdir failed")
return extdef([traits.str0, int], s_None, llimpl=os_mkdir_llimpl,
export_name=traits.ll_os_name('mkdir'))
@registering_str_unicode(os.rmdir)
def register_os_rmdir(self, traits):
os_rmdir = self.llexternal(traits.posix_function_name('rmdir'),
[traits.CCHARP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def rmdir_llimpl(pathname):
res = rffi.cast(lltype.Signed, os_rmdir(pathname))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_rmdir failed")
return extdef([traits.str0], s_None, llimpl=rmdir_llimpl,
export_name=traits.ll_os_name('rmdir'))
@registering_str_unicode(os.chmod)
def register_os_chmod(self, traits):
os_chmod = self.llexternal(traits.posix_function_name('chmod'),
[traits.CCHARP, rffi.MODE_T], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def chmod_llimpl(path, mode):
res = rffi.cast(lltype.Signed, os_chmod(path, rffi.cast(rffi.MODE_T, mode)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_chmod failed")
if sys.platform == 'win32':
from rpython.rtyper.module.ll_win32file import make_chmod_impl
chmod_llimpl = make_chmod_impl(traits)
return extdef([traits.str0, int], s_None, llimpl=chmod_llimpl,
export_name=traits.ll_os_name('chmod'))
@registering_if(os, 'fchmod')
def register_os_fchmod(self):
os_fchmod = self.llexternal('fchmod', [rffi.INT, rffi.MODE_T],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def fchmod_llimpl(fd, mode):
mode = rffi.cast(rffi.MODE_T, mode)
res = rffi.cast(lltype.Signed, os_fchmod(fd, mode))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_fchmod failed")
return extdef([int, int], s_None, "ll_os.ll_os_fchmod",
llimpl=fchmod_llimpl)
@registering_str_unicode(os.rename)
def register_os_rename(self, traits):
os_rename = self.llexternal(traits.posix_function_name('rename'),
[traits.CCHARP, traits.CCHARP], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def rename_llimpl(oldpath, newpath):
res = rffi.cast(lltype.Signed, os_rename(oldpath, newpath))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_rename failed")
if sys.platform == 'win32':
from rpython.rtyper.module.ll_win32file import make_win32_traits
win32traits = make_win32_traits(traits)
@func_renamer('rename_llimpl_%s' % traits.str.__name__)
def rename_llimpl(oldpath, newpath):
if not win32traits.MoveFile(oldpath, newpath):
raise rwin32.lastSavedWindowsError()
return extdef([traits.str0, traits.str0], s_None, llimpl=rename_llimpl,
export_name=traits.ll_os_name('rename'))
@registering_str_unicode(getattr(os, 'mkfifo', None))
def register_os_mkfifo(self, traits):
os_mkfifo = self.llexternal(traits.posix_function_name('mkfifo'),
[traits.CCHARP, rffi.MODE_T], rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def mkfifo_llimpl(path, mode):
res = rffi.cast(lltype.Signed, os_mkfifo(path, mode))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_mkfifo failed")
return extdef([traits.str0, int], s_None, llimpl=mkfifo_llimpl,
export_name=traits.ll_os_name('mkfifo'))
@registering_str_unicode(getattr(os, 'mknod', None))
def register_os_mknod(self, traits):
os_mknod = self.llexternal(traits.posix_function_name('mknod'),
[traits.CCHARP, rffi.MODE_T, rffi.INT],
rffi.INT, # xxx: actually ^^^ dev_t
save_err=rffi.RFFI_SAVE_ERRNO)
def mknod_llimpl(path, mode, dev):
res = rffi.cast(lltype.Signed, os_mknod(path, mode, dev))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_mknod failed")
return extdef([traits.str0, int, int], s_None, llimpl=mknod_llimpl,
export_name=traits.ll_os_name('mknod'))
@registering(os.umask)
def register_os_umask(self):
os_umask = self.llexternal(UNDERSCORE_ON_WIN32 + 'umask',
[rffi.MODE_T], rffi.MODE_T)
def umask_llimpl(newmask):
res = os_umask(rffi.cast(rffi.MODE_T, newmask))
return rffi.cast(lltype.Signed, res)
return extdef([int], int, llimpl=umask_llimpl,
export_name="ll_os.ll_os_umask")
@registering_if(os, 'kill', sys.platform != 'win32')
def register_os_kill(self):
os_kill = self.llexternal('kill', [rffi.PID_T, rffi.INT],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def kill_llimpl(pid, sig):
res = rffi.cast(lltype.Signed, os_kill(rffi.cast(rffi.PID_T, pid),
rffi.cast(rffi.INT, sig)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_kill failed")
return extdef([int, int], s_None, llimpl=kill_llimpl,
export_name="ll_os.ll_os_kill")
@registering_if(os, 'killpg')
def register_os_killpg(self):
os_killpg = self.llexternal('killpg', [rffi.INT, rffi.INT],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def killpg_llimpl(pid, sig):
res = rffi.cast(lltype.Signed, os_killpg(rffi.cast(rffi.INT, pid),
rffi.cast(rffi.INT, sig)))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_killpg failed")
return extdef([int, int], s_None, llimpl=killpg_llimpl,
export_name="ll_os.ll_os_killpg")
@registering_if(os, 'link')
def register_os_link(self):
os_link = self.llexternal('link', [rffi.CCHARP, rffi.CCHARP],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def link_llimpl(oldpath, newpath):
res = rffi.cast(lltype.Signed, os_link(oldpath, newpath))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_link failed")
return extdef([str0, str0], s_None, llimpl=link_llimpl,
export_name="ll_os.ll_os_link")
@registering_if(os, 'symlink')
def register_os_symlink(self):
os_symlink = self.llexternal('symlink', [rffi.CCHARP, rffi.CCHARP],
rffi.INT,
save_err=rffi.RFFI_SAVE_ERRNO)
def symlink_llimpl(oldpath, newpath):
res = rffi.cast(lltype.Signed, os_symlink(oldpath, newpath))
if res < 0:
raise OSError(rposix.get_saved_errno(), "os_symlink failed")
return extdef([str0, str0], s_None, llimpl=symlink_llimpl,
export_name="ll_os.ll_os_symlink")
@registering_if(os, 'fork')
def register_os_fork(self):
from rpython.rlib import debug, rthread
os_fork = self.llexternal('fork', [], rffi.PID_T,
_nowrapper = True)
@jit.dont_look_inside
def fork_llimpl():
# NB. keep forkpty() up-to-date, too
ofs = debug.debug_offset()
opaqueaddr = rthread.gc_thread_before_fork()
childpid = rffi.cast(lltype.Signed, os_fork())
errno = rffi.cast(lltype.Signed, rposix._get_errno())
rthread.gc_thread_after_fork(childpid, opaqueaddr)
if childpid == -1:
raise OSError(errno, "os_fork failed")
if childpid == 0:
debug.debug_forked(ofs)
return rffi.cast(lltype.Signed, childpid)
return extdef([], int, llimpl=fork_llimpl,
export_name="ll_os.ll_os_fork")
@registering_if(os, 'openpty')
def register_os_openpty(self):
os_openpty = self.llexternal(
'openpty',
[rffi.INTP, rffi.INTP, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP],
rffi.INT,
compilation_info=ExternalCompilationInfo(libraries=['util']),
save_err=rffi.RFFI_SAVE_ERRNO)
def openpty_llimpl():
master_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
slave_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
result = os_openpty(master_p, slave_p, None, None, None)
master_fd = master_p[0]
slave_fd = slave_p[0]
lltype.free(master_p, flavor='raw')
lltype.free(slave_p, flavor='raw')
if result == -1:
raise OSError(rposix.get_saved_errno(), "os_openpty failed")
return (rffi.cast(lltype.Signed, master_fd),
rffi.cast(lltype.Signed, slave_fd))
return extdef([], (int, int), "ll_os.ll_os_openpty",
llimpl=openpty_llimpl)
@registering_if(os, 'forkpty')
def register_os_forkpty(self):
from rpython.rlib import debug, rthread
os_forkpty = self.llexternal(
'forkpty',
[rffi.INTP, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP],
rffi.PID_T,
compilation_info=ExternalCompilationInfo(libraries=['util']),
save_err=rffi.RFFI_SAVE_ERRNO)
def forkpty_llimpl():
master_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
master_p[0] = rffi.cast(rffi.INT, -1)
ofs = debug.debug_offset()
opaqueaddr = rthread.gc_thread_before_fork()
childpid = rffi.cast(lltype.Signed,
os_forkpty(master_p, None, None, None))
rthread.gc_thread_after_fork(childpid, opaqueaddr)
master_fd = master_p[0]
lltype.free(master_p, flavor='raw')
if childpid == -1:
raise OSError(rposix.get_saved_errno(), "os_forkpty failed")
if childpid == 0:
debug.debug_forked(ofs)
return (rffi.cast(lltype.Signed, childpid),
rffi.cast(lltype.Signed, master_fd))
return extdef([], (int, int), "ll_os.ll_os_forkpty",
llimpl=forkpty_llimpl)
@registering(os._exit)
def register_os__exit(self):
from rpython.rlib import debug
os__exit = self.llexternal('_exit', [rffi.INT], lltype.Void)
def _exit_llimpl(status):
debug.debug_flush()
os__exit(rffi.cast(rffi.INT, status))
return extdef([int], s_None, llimpl=_exit_llimpl,
export_name="ll_os.ll_os__exit")
@registering_if(os, 'nice')
def register_os_nice(self):
os_nice = self.llexternal('nice', [rffi.INT], rffi.INT,
save_err=rffi.RFFI_FULL_ERRNO_ZERO)
def nice_llimpl(inc):
# Assume that the system provides a standard-compliant version
# of nice() that returns the new priority. Nowadays, FreeBSD
# might be the last major non-compliant system (xxx check me).
res = rffi.cast(lltype.Signed, os_nice(inc))
if res == -1:
err = rposix.get_saved_errno()
if err != 0:
raise OSError(err, "os_nice failed")
return res
return extdef([int], int, llimpl=nice_llimpl,
export_name="ll_os.ll_os_nice")
@registering_if(os, 'ctermid')
def register_os_ctermid(self):
os_ctermid = self.llexternal('ctermid', [rffi.CCHARP], rffi.CCHARP)
def ctermid_llimpl():
return rffi.charp2str(os_ctermid(lltype.nullptr(rffi.CCHARP.TO)))
return extdef([], str, llimpl=ctermid_llimpl,
export_name="ll_os.ll_os_ctermid")
@registering_if(os, 'tmpnam')
def register_os_tmpnam(self):
os_tmpnam = self.llexternal('tmpnam', [rffi.CCHARP], rffi.CCHARP)
def tmpnam_llimpl():
return rffi.charp2str(os_tmpnam(lltype.nullptr(rffi.CCHARP.TO)))
return extdef([], str, llimpl=tmpnam_llimpl,
export_name="ll_os.ll_os_tmpnam")
# --------------------------- os.stat & variants ---------------------------
@registering(os.fstat)
def register_os_fstat(self):
from rpython.rtyper.module import ll_os_stat
return ll_os_stat.register_stat_variant('fstat', StringTraits())
@registering_str_unicode(os.stat)
def register_os_stat(self, traits):
from rpython.rtyper.module import ll_os_stat
return ll_os_stat.register_stat_variant('stat', traits)
@registering_str_unicode(os.lstat)
def register_os_lstat(self, traits):
from rpython.rtyper.module import ll_os_stat
return ll_os_stat.register_stat_variant('lstat', traits)
@registering_if(os, 'fstatvfs')
def register_os_fstatvfs(self):
from rpython.rtyper.module import ll_os_stat
return ll_os_stat.register_statvfs_variant('fstatvfs', StringTraits())
if hasattr(os, 'statvfs'):
@registering_str_unicode(os.statvfs)
def register_os_statvfs(self, traits):
from rpython.rtyper.module import ll_os_stat
return ll_os_stat.register_statvfs_variant('statvfs', traits)
# ------------------------------- os.W* ---------------------------------
w_star = ['WCOREDUMP', 'WIFCONTINUED', 'WIFSTOPPED',
'WIFSIGNALED', 'WIFEXITED', 'WEXITSTATUS',
'WSTOPSIG', 'WTERMSIG']
# last 3 are returning int
w_star_returning_int = dict.fromkeys(w_star[-3:])
def declare_new_w_star(self, name):
""" stupid workaround for the python late-binding
'feature'
"""
def fake(status):
return int(getattr(os, name)(status))
fake.func_name = 'fake_' + name
os_c_func = self.llexternal("pypy_macro_wrapper_" + name,
[lltype.Signed], lltype.Signed,
_callable=fake)
if name in self.w_star_returning_int:
def llimpl(status):
return os_c_func(status)
resulttype = int
else:
def llimpl(status):
return bool(os_c_func(status))
resulttype = bool
llimpl.func_name = name + '_llimpl'
return extdef([int], resulttype, "ll_os." + name,
llimpl=llimpl)
for name in w_star:
locals()['register_w_' + name] = registering_if(os, name)(
lambda self, xname=name : self.declare_new_w_star(xname))
@registering_if(os, 'ttyname')
def register_os_ttyname(self):
os_ttyname = self.llexternal('ttyname', [lltype.Signed], rffi.CCHARP,
releasegil=False,
save_err=rffi.RFFI_SAVE_ERRNO)
def ttyname_llimpl(fd):
l_name = os_ttyname(fd)
if not l_name:
raise OSError(rposix.get_saved_errno(), "ttyname raised")
return rffi.charp2str(l_name)
return extdef([int], str, "ll_os.ttyname",
llimpl=ttyname_llimpl)
# ____________________________________________________________
# Support for os.environ
# XXX only for systems where os.environ is an instance of _Environ,
# which should cover Unix and Windows at least
assert type(os.environ) is not dict
from rpython.rtyper.controllerentry import ControllerEntryForPrebuilt
class EnvironExtRegistry(ControllerEntryForPrebuilt):
_about_ = os.environ
def getcontroller(self):
from rpython.rtyper.module.ll_os_environ import OsEnvironController
return OsEnvironController()
# ____________________________________________________________
# Support for the WindowsError exception
if sys.platform == 'win32':
from rpython.rlib import rwin32
class RegisterFormatError(BaseLazyRegistering):
def __init__(self):
pass
@registering(rwin32.FormatError)
def register_rwin32_FormatError(self):
return extdef([lltype.Signed], str,
"rwin32_FormatError",
llimpl=rwin32.llimpl_FormatError)
|
var book = {
"name": "Deuteronoma",
"numChapters": 34,
"chapters": {
"1": {
"1": "<sup>1</sup> Ke wona mantswe ao Moshe a kileng a a bolella Baiseraele kaofela, mose o kwana ho Jordane, feelleng, thoteng e lebaneng le Sufe, mahareng a Parane le Tofele, le Labane, le Hatserothe, le Di-Sahabe.",
"2": "<sup>2</sup> Ho tloha Horebe, ho ya fihla Kadeshe-Barnea, ka tsela ya thaba ya Seire, ke matsatsi a leshome le motso o mong.",
"3": "<sup>3</sup> Ka selemo sa mashome a mane, ka tsatsi le qalang kgwedi ya leshome le motso o mong, Moshe a bolella bana ba Iseraele tsohle tseo Jehova a neng a mo laetse hore a ba bolelle tsona.",
"4": "<sup>4</sup> Ke ha a sa tswa bolaya Sihone, morena wa Baamore, ya neng a ahile Heshbone, le Oge, morena wa Bashane, ya neng a ahile Ashtarothe le Edrei.",
"5": "<sup>5</sup> Moshe eitse ha a le mose o kwana wa Jordane, naheng ya Moabe, a qala ho hlalosetsa Baiseraele molao ona, a re:",
"6": "<sup>6</sup> Jehova, Modimo wa rona, o buile le rona re le Horebe, a re: Le dutse nako e lekaneng thabeng ena.",
"7": "<sup>7</sup> Sokolohang, le tsamaye, le ye thabeng ya Baamore le ditjhabeng tsohle tse bapileng le bona, lehwatateng, le thabeng, le thoteng, le nqa borwa, le lebopong la lewatle, naheng ya Bakanana, le Lebanone, ho ya fihla nokeng e kgolo, e leng noka ya Eufrate.",
"8": "<sup>8</sup> Bonang, ke beile lefatshe pela lona; kenang, mme le rue lefatshe leo Jehova a anetseng bontata lona, Abrahama, le Isaaka, le Jakobo, hore o tla le nea bona le ditloholo tsa bona kamora bona.",
"9": "<sup>9</sup> Mohlang oo, ka le bolella, ka re: Ke sitwa ho le jara ke nnotshi.",
"10": "<sup>10</sup> Jehova, Modimo wa lona, o le atisitse, mme ke mona kajeno le le ka ka dinaledi tsa lehodimo ka bongata.",
"11": "<sup>11</sup> Jehova, Modimo wa bontata lona, a boele a le atise hape ha sekete ho feta kamoo le leng kateng, mme a le hlohonolofatse, jwalokaha a le boleletse.",
"12": "<sup>12</sup> Nka jara jwang ke nnotshi phahlo ya lona, le boima ba lona, le ditseko tsa lona?",
"13": "<sup>13</sup> Ikgetheleng melokong ya lona banna ba bohlale, ba kelello, ba tsejwang, ke tle ke ba bee dihlooho tsa lona.",
"14": "<sup>14</sup> La mphetola, la re: Seo o reng se etswe, se molemo.",
"15": "<sup>15</sup> Yaba ke kgetha dihlooho tsa meloko ya lona, banna ba bohlale, ba tsejwang, ka ba bea dihlooho tsa lona, hore e be balaodi ba dikete, le balaodi ba makgolo, le balaodi ba mashome a mahlano, le balaodi ba mashome, hape e be bahlahlobi ba meloko ya lona.",
"16": "<sup>16</sup> Mohlang oo, ka laela baahlodi ba lona, ka re: Mamelang ditaba tsa banababo lona, mme le ahlolele ka ho loka motho le ngwanabo, le moditjhaba ya ahileng le lona.",
"17": "<sup>17</sup> Le se ke la ya ka tshobotsi ya motho dikahlolong tsa lona; hape, le mamele e monyenyane le e moholo; le ke ke la tshaba motho le a mong, hobane kahlolo ke ya Modimo. Ha taba e le teng e le sitang, e tliseng ho nna, ke tle ke e utlwe.",
"18": "<sup>18</sup> Mohlang oo, nkile ka le laela tsohle tseo le neng le tshwanetse ho di etsa.",
"19": "<sup>19</sup> Eitse ha re tloha Horebe, ra tsamaya le nahathothe yane kaofela e kgolo, e tshabehang, eo le e boneng, ra ya ka tsela ya thaba ya Baamore, jwalokaha Jehova, Modimo wa rona, a ne a re laetse, mme ra fihla Kadeshe-Barnea.",
"20": "<sup>20</sup> Yaba ke re ho lona: Le fihlile thabeng ya Baamore eo Jehova, Modimo wa rona, a re neang yona.",
"21": "<sup>21</sup> Bonang, Jehova, Modimo wa hao, o beile lefatshe pela hao; nyoloha, o le rue, jwalokaha Jehova, Modimo wa bontatao, a o boleletse. O se ke wa tshaba, mme o se tshohe.",
"22": "<sup>22</sup> La tla ho nna bohle, la re: A re romeng batho, ba re etelle pele, ba ye ho re hlwella lefatshe, ba re tlisetse taba tsa tsela eo re tla nyoloha ka yona, le tsa metse eo re tla fihla ho yona.",
"23": "<sup>23</sup> Ka dumela taba eo, ka kgetha banna ba leshome le metso e mmedi hara lona, e mong lelokong le leng le le leng.",
"24": "<sup>24</sup> Yaba ba tloha, ba nyolohela thabeng, ba fihla kgohlong ya Eshkole, mme ba hlwela naha.",
"25": "<sup>25</sup> Ba nka ditholwana tsa naha eo matsohong a bona, ba re tlisetsa tsona, mme ba re tsebisa, ba re: E molemo, naha eo Jehova, Modimo wa rona, a re fang yona.",
"26": "<sup>26</sup> La mpa la hana ho nyoloha, la ikgantshetsa taelo ya Jehova, Modimo wa lona;",
"27": "<sup>27</sup> la ngangella ditenteng tsa lona, la re: Ke kahobane Jehova o re hloile a re ntshitseng lefatsheng la Egepeta, ho tla re neela matsohong a Baamore, hore ba tle ba re timetse.",
"28": "<sup>28</sup> Re tla nyolohela kae? Banababo rona ba re nyahamisitse dipelo, ha ba itse: Ke setjhaba se re fetang ka bongata le ka boemo bo bolelele; ke metse e meholo e haheleditseng ka marako a fihlang lehodimong; re bone bana ba Anake teng.",
"29": "<sup>29</sup> Empa nna ka re ho lona: Le se ke la tshoha, mme le se ke la ba tshaba.",
"30": "<sup>30</sup> Jehova, Modimo wa lona, ya le eteletseng pele, yena ka sebele o tla le lwanela, jwalokaha a se a entse pontsheng ya lona Egepeta,",
"31": "<sup>31</sup> le lefeelleng leo o le boneng, e leng moo Jehova, Modimo wa hao, a o pepileng, jwaloka monna ha a pepile mora wa hae, tseleng yohle eo le tsamaileng ka yona ho tlisa ho fihleng ha lona bakeng sena.",
"32": "<sup>32</sup> Leha ho le jwalo, ha le a ka la tshepa Jehova, Modimo wa lona,",
"33": "<sup>33</sup> ya neng a ntse a le etella pele tseleng ho le batlela dibaka tseo le tla emisa ho tsona, bosiu a le bonesetse ka mollo tsela ya lona eo le neng le tshwanetse ho ya ka yona, mme motshehare a le tsamaise ka leru.",
"34": "<sup>34</sup> Jehova a utlwa modumo wa dipolelo tsa lona, a halefa, a hlapanya, a re:",
"35": "<sup>35</sup> Ha ho le a mong wa banna ba mofuta oo o mobe ya tlang ho bona lefatshe le molemo leo ke anneng, ka re, ke tla le nea bontata lona,",
"36": "<sup>36</sup> haese Kalebe, mora Jefunne. Yena o tla le bona, mme ke tla nea yena le bara ba hae lefatshe leo a le hatileng ka maoto, hobane o tiiseditse ho latela Jehova kahohle.",
"37": "<sup>37</sup> Le nna, Jehova a nkgalefela ka baka la lona, a re: Le wena o ke ke wa kena teng.",
"38": "<sup>38</sup> Ya tla kena ke Joshua, mora Nune, ya emang pela hao. Mo kgothatse, etswe e le yena ya tla ruisa bana ba Iseraele lefatshe lena.",
"39": "<sup>39</sup> Bana ba banyenyane ba lona, bao le neng le re, ba tla hapuwa, le bana ba lona ba sa tsebeng botle leha e le bobe kajeno lena, bona ba tla kena, ke tla nea bona lefatshe, mme ke bona ba tla le rua.",
"40": "<sup>40</sup> Haele lona, kgutlang le boele le tsamaye feelleng, ka tsela ya Lewatle le Lefubedu.",
"41": "<sup>41</sup> Yaba le a mphetola, la re ho nna: Re sitetswe Jehova. Re tla nyoloha, re lwane kahohle kamoo Jehova, Modimo wa rona, a re laetseng kateng. La nka dibetsa tsa lona, mme la phehella ho nyolohela thabeng.",
"42": "<sup>42</sup> Jehova a re ho nna: E re ho bona: Le ke ke la nyoloha, mme le ke ke la lwana, hobane ha ke yo hara lona; le se ke la ya hlolwa ke dira tsa lona.",
"43": "<sup>43</sup> Ka le bolella jwalo, la mpa la hana ho utlwa; la ikgantshetsa taelo ya Jehova; la etsa ka boikgohomoso, mme la nyolohela thabeng.",
"44": "<sup>44</sup> Baamore ba neng ba ahile thabeng eo, ba le kgahlanyetsa, ba le phallela jwaloka hoja ke dinotshi, mme a le hlola Seire, ho ya fihla Horma.",
"45": "<sup>45</sup> La kgutla, la lla pela Jehova, empa Jehova a hana ho utlwa mantswe a lona le ho le sekehela tsebe.",
"46": "<sup>46</sup> Ke ha le tla hlola Kadeshe tshiu tse ngata, e leng tshiu tseo le nnileng la di hlola teng."
},
"2": {
"1": "<sup>1</sup> Ra sokoloha, ra leba nqa lefeelleng ka tsela ya Lewatle le Lefubedu, kamoo Jehova a neng a mpoleletse kateng, mme ra potoloha thaba ya Seire ka ditshiu tse telele.",
"2": "<sup>2</sup> Jehova a mpolella, a re:",
"3": "<sup>3</sup> Le potolohile thaba ena nako e lekaneng; lebang nqa leboya.",
"4": "<sup>4</sup> O laele setjhaba, o re: Le a feta meeding ya banababo lona, bana ba Esau ba ahileng Seire, mme ba tla le tshaba. Iponeleng haholo ke hona;",
"5": "<sup>5</sup> le se ke la qabana le bona, hobane ha nka ke ka le nea letho naheng ya bona, leha e le sebaka se ka ka se ka hatwang ke leoto; hobane ke neile Esau thaba ye Seire, e be lefa la hae.",
"6": "<sup>6</sup> Le tla reka ho bona ka tjhelete dijo tseo le tla di ja; le tla ba lefa ka tjhelete bakeng sa metsi ao le tla a nwa.",
"7": "<sup>7</sup> Hobane Jehova, Modimo wa hao, o o hlohonolofaditse mesebetsing yohle ya matsoho a hao; o lemohile ho tsamaya ha hao lefeelleng leno le leholo; e se e le dilemo tse mashome a mane Jehova, Modimo wa hao, a leng ho wena, mme ha o a ka wa hloka letho.",
"8": "<sup>8</sup> Ra feta jwalo, ra kwekwetla banababo rona, bana ba Esau ba ahileng Seire, le tsela ya lehwatata, le Elathe, le Etsione-Gebere, ra ntoo fapoha, ra ya tsamaya ka tsela ya lefeella la Moabe.",
"9": "<sup>9</sup> Jehova a re ho nna: O se ke wa qala Bamoabe, mme o se ke wa ba lwantsha, hobane ha nka ke ka o nea letho naheng ya bona; kahobane ke neile bana ba Lota Are, hore e be lefa la bona.",
"10": "<sup>10</sup> [Baemime ba ne ba ahile teng pele; e ne e le setjhaba se seholo, se sengata, se boemo bo bolelele jwaloka ba Baanake.",
"11": "<sup>11</sup> Le bona ba ne ba tumile, ho thwe, ke Barefaime (diqhobane), jwaloka Baanake; empa Bamoabe ba ne ba ba bitsa Baemime.",
"12": "<sup>12</sup> Mohla monene Bahore ba ne ba ahile Seire, empa bana ba Esau ba ne ba ba falatse, ba ba qeta pela bona, mme ba aha tulong tsa bona, jwalokaha le bona Baiseraele ba entse lefatsheng leo ba le filweng ke Jehova.]",
"13": "<sup>13</sup> Emang jwale, mme le tshele nokana ya Serede. Mme ra tshela nokana ya Serede.",
"14": "<sup>14</sup> Haele dilemo tseo re nnileng ra tsamaya ka tsona, ho tloha Kadeshe-Barnea, ho isa tsatsing leo re tshetseng nokana ya Serede ka lona, ya eba dilemo tse mashome a mararo a metso e robileng meno e le mmedi, mofuta wohle wa bana ba ntwa o be o fele diahelong, kamoo Jehova a neng a ba hlapanyeditse kateng.",
"15": "<sup>15</sup> Efela letsoho la Jehova la nna la eba hodima bona hore le ba timetse diahelong, ho fihlela ba ba ba fela.",
"16": "<sup>16</sup> Eitse hobane banna bohle ba ntwa ba timele setjhabeng,",
"17": "<sup>17</sup> Jehova a bua le nna, a re:",
"18": "<sup>18</sup> Kajeno, o ya feta meeding ya Moabe, Are;",
"19": "<sup>19</sup> mme o tla atamela pela bana ba Ammone. O se ke wa ba qala, mme o se ke wa ba lwantsha; hobane ha nka ke ka o nea letho naheng ya bana ba Ammone; hobane ke e neile bana ba Lota hore e be lefa la bona.",
"20": "<sup>20</sup> [Le yona naha eo e ne e tumile, ka ho re, ke naha ya Barefaime; mohla monene Barefaime ba ne ba ahile ho yona; empa Baammone ba ne ba re, ke Basamsummime.",
"21": "<sup>21</sup> E ne e le setjhaba se seholo, se sengata, se boemo bo bolelele jwaloka Baanake. Jehova a ba fedisa pela bana ba Ammone; yaba bao ba ba lelekisa, mme ba aha tulong tsa bona.",
"22": "<sup>22</sup> Jehova o ne a etse jwalo le bakeng sa bana ba Esau ba ahileng Seire, mohla a fedisang Bahore pela bona, ba ba ba ba lelekisa; ba ile ba aha tulong tsa bona ho fihlela kajeno.",
"23": "<sup>23</sup> Haele Baavvime ba neng ba ahile metebong ho ya fihla Gasa, Bakaftorime ba tswileng Kaftore, ba ba fedisa, ba ba ba aha tulong tsa bona.]",
"24": "<sup>24</sup> Tlohang, le tsamaye, mme le tshele nokana ya Arnone. Bona, ke neetse Sihone, morena wa Heshbone, le Maomore, le naha ya hae, matsohong a hao. Qala ho hapa naha eo, mme o mo lwantshe.",
"25": "<sup>25</sup> Kajeno, ke tla qala ho tshollela ditjhaba tse katlasa lehodimo lohle tshoho le tshabo ya hao; etlere ha di utlwa botumo ba hao, di thothomele, mme di tsielehe pela hao.",
"26": "<sup>26</sup> Eitse ha re fihla lefeelleng la Kedemothe, ka romela manqosa ho Sihone, morena wa Heshbone, ka mantswe a kgotso, ka re:",
"27": "<sup>27</sup> A nke ke fete ka naha ya hao. Ke tla tsamaya ka tsela a bohle feela, ke sa fapohe ho ya ka letsoho le letona, leha e le ka ho le letshehadi.",
"28": "<sup>28</sup> Ke tla reka ho wena ka tjhelete dijo tseo ke tla di ja, mme o nnee ka tjhelete metsi ao ke tla a nwa; ke rata ho feta feela ka maoto a ka.",
"29": "<sup>29</sup> O nketsetse jwalokaha bana ba Esau ba ahileng Seire ba nketseditse, le jwaloka Bamoabe ba ahileng Are, ke be ke tshele Jordane, ke fihle lefatsheng leo Jehova, Modimo wa rona, a re neang lona.",
"30": "<sup>30</sup> Empa Sihone, morena wa Heshbone, a hana ho re nea sebaka sa ho feta ha hae; hobane Jehova, Modimo wa hao, o ne a thatafaditse moya wa hae, a sataladitse le pelo ya hae, hore a mo neele matsohong a hao, jwalokaha ho le jwalo kajeno.",
"31": "<sup>31</sup> Yaba Jehova o re ho nna: Bona, ke qadile ho neela Sihone le naha ya hae matsohong a hao. Qala ho hapa naha ya hae, o e rue.",
"32": "<sup>32</sup> Yaba Sihone o tswa le setjhaba sa hae, a re kgahlanyetsa Jahatse ka ntwa.",
"33": "<sup>33</sup> Jehova, Modimo wa rona, a re neela yena, mme ra mo hlola, yena le bana ba hae, le setjhaba sa hae kaofela.",
"34": "<sup>34</sup> Motsotsong oo, ra hapa metse yohle ya hae, ra e neela anathema, le banna, le basadi, le bana, re se ke ra tlohela le a mong ya phonyohang.",
"35": "<sup>35</sup> Feela ra ikgapela makgomo le thepa ya metse eo re e nkileng.",
"36": "<sup>36</sup> Ho qala ka Aroere, e lebopong la nokana ya Arnone, le motse o leng pela nokana, ho isa Gileade, ha ho a ka ha eba motse o re sitang. Jehova, Modimo wa rona, a re neela yona kaofela.",
"37": "<sup>37</sup> Haele naha ya bana ba Ammone, ha o a ka wa e atamela, leha e le lebopo lohle la nokana ya Jabboke, le metse e thabeng, leha e le sebaka sefe le sefe seo Jehova, Modimo wa rona, a neng a re hanetse ho atamela pela sona."
},
"3": {
"1": "<sup>1</sup> Yaba re a kgutla, ra nyoloha ka tsela ya Bashane. Oge, morena wa Bashane, a tswa le setjhaba sa hae kaofela, a tla re kgahlanyetsa Edrei ka ntwa.",
"2": "<sup>2</sup> Jehova a re ho nna: Se mo tshabe, hobane ke mo neetse matsohong a hao, yena le setjhaba sa hae kaofela, le naha ya hae, o tle o etse ka yena kamoo o entseng kateng ka Sihone, morena wa Baamore, ya neng a ahile Heshbone.",
"3": "<sup>3</sup> Jehova, Modimo wa rona, a neela matsohong a rona le yena Oge, morena wa Bashane, le setjhaba sa hae kaofela, mme ra ba bolaya, ho se ke ha phonyoha le a mong wa batho ba hae.",
"4": "<sup>4</sup> Motsotsong oo, ra nka metse yohle ya hae; ha ho motse oo re sa kang ra o hapa; ra nka metse e mashome a tsheletseng, naha yohle ya Argobe, ke ho re, mmuso wa Oge, morena wa Bashane.",
"5": "<sup>5</sup> Metse eo yohle e ne e teetswe hare ke marako a malelele, e na le menyako le mekwallo, ho sa balwe metse e mengatangata e se nang marako.",
"6": "<sup>6</sup> Ra e neela anathema, jwalokaha re ne re entse ka Sihone, morena wa Heshbone; ra neela metse yohle hammoho le banna le basadi le bana anathema.",
"7": "<sup>7</sup> Ra mpa ra ikgapela makgomo wohle le thepa ya metse.",
"8": "<sup>8</sup> Ka mokgwa oo, mohlang oo, ra amoha marena a mabedi a Baamore naha e mose o kwana ho Jordane, ho tloha nokaneng ya Arnone, ho isa thabeng ya Hermone.",
"9": "<sup>9</sup> [Basidone ba bitsa Hermone Sirione, Baamore bona ba e bitsa Senire.]",
"10": "<sup>10</sup> Ra nka metse yohle e lehwatateng, le naha yohle ya Gileade, le ya Bashane, ho ya fihla Salka le Edrei, metse ya mmuso wa Oge, Bashane.",
"11": "<sup>11</sup> [Hobane Oge, morena wa Bashane, o ne a setse a nnotshi wa mofuta wa Barefaime. Ha ke re, malao a hae, e leng malao a tshepe a ntse a le Rabba, motseng wa bana ba Ammone? Bolelele ba wona ke ditswe tse robileng mono o le mong, mme bophara ba wona ke ditswe tse nne, ha ho lekanngwe ka setswe sa motho.]",
"12": "<sup>12</sup> Mohlang oo, ra hapa naha eo. Naha yohle, ho tloha Aroere e lebopong la nokana ya Arnone, ho isa bohareng ba thaba ya Gileade, le metse ya teng, ka e nea Barubene le Bagade.",
"13": "<sup>13</sup> Ho setseng ha Gileade, le naha yohle ya Bashane, e leng mmuso wa Oge, ka e nea mothapo o mong wa leloko la Manasse; ke naha ya Argobe, hammoho le naha yohle ya Bashane; ke yona naha e neng e bitswa naha ya Barefaime.",
"14": "<sup>14</sup> Jaire, mora Manasse, a nka naha yohle ya Argobe ho isa moeding wa Bageshure le wa Bamaakathe, mme a reella metse ya Bashane lebitso la hae; e ntse e le Havvoth-Jaire le kajeno.",
"15": "<sup>15</sup> Makire yena ka mo nea Gileade.",
"16": "<sup>16</sup> Haele Barubene le Bagade, ka ba nea karolo e nngwe ya naha ya Gileade ho isa nokaneng ya Arnone (bohare ba noka ke moedi) le ho isa nokaneng ya Jabboke, e leng moedi wa bana ba Ammone.",
"17": "<sup>17</sup> Ka ba nea le lehwatata, leo moedi wa lona e leng Jordane, ho tloha Kinnerethe ho isa Lewatleng la Lehwatata, e leng Lewatle la Letswai, katlasa Pisga, nqa botjhabatsatsi.",
"18": "<sup>18</sup> Mohlang oo, ka le laela, ka re: Jehova, Modimo wa lona, o le neile naha eo, hore le e rue. Haele lona, banna bohle ba bahale, etellang banababo lona, bana ba Iseraele, pele, le hlometse.",
"19": "<sup>19</sup> Feela basadi ba lona, le bana ba lona le mehlape ya lona (hobane ke a tseba hobane le na le mehlape e mengata) ba sale metseng eo ke le neileng yona,",
"20": "<sup>20</sup> ho fihlela mohla Jehova a neileng banababo lona phomolo, jwalokaha a le neile, le bona ba tle ba rue lefatshe leo Jehova, Modimo wa lona, a ba neang lona mose wane ho Jordane; ke hona le tla kgutlela e mong le e mong lefeng leo ke le neileng lona.",
"21": "<sup>21</sup> Mohlang oo, ka laela Joshua ka re: Mahlo a hao a bone tsohle tseo Jehova, Modimo wa lona, a di entseng ho marena ao a mabedi: Jehova o tla etsa jwalo le ka mebuso yohle eo le tla e futuhela.",
"22": "<sup>22</sup> Le se ke la e tshaba, hobane Jehova, Modimo wa lona, o tla le lwanela e le yena.",
"23": "<sup>23</sup> Mohlang oo, ka rapela Jehova ka re:",
"24": "<sup>24</sup> Morena Jehova, o se o qadile ho bontsha mohlanka wa hao boholo ba hao le letsoho la hao le matla. Hobane modimo ke ofe mahodimong le lefatsheng, o ka etsang mesebetsi le diketso tse phahameng jwaloka tsena tsa hao?",
"25": "<sup>25</sup> Ntumelle hle ke fete, mme ke bone lefatshe le molemo, le mose wane ho Jordane, le thaba tseno tse molemo, le Lebanone!",
"26": "<sup>26</sup> Empa Jehova a nkgalefela ka baka la lona, a se ke a nkutlwa; mme Jehova a re ho nna: Ho lekane, o se ke wa hlola o bua le nna ka taba eo.",
"27": "<sup>27</sup> Hlwella qhoweng ya Pisga, mme o ise mahlo nqa bophirimatsatsi, le nqa leboya, le nqa borwa, le nqa botjhabatsatsi, mme o bohe ka mahlo a hao; hobane haele Jordane eo, o ke ke wa ba wa e tshela.",
"28": "<sup>28</sup> O mpe o laele Joshua, o mo kgothatse, o mo natlafatse, hobane ke yena ya tla etella setjhaba sena pele, hape ke yena ya tla ba ruisa lefatshe leo o tlang ho le bona.",
"29": "<sup>29</sup> Ra dula sekgutlong, mabapa le Bethe-Peore."
},
"4": {
"1": "<sup>1</sup> Mme jwale, lona Baiseraele, mamelang melao le ditaelo tseo ke le rutang tsona, hore le tle le etse ka tsona, le tle le phele, mme le kene, mme le rue lefatshe leo Jehova, Modimo wa bontata lona, a le neang lona.",
"2": "<sup>2</sup> Le ke ke la eketsa ka letho hodima lentswe leo ke le laelang lona, hape, le ke ke la le fokotsa, le tla mpe le boloke ditaelo tsa Jehova, Modimo wa lona, tseo ke le laelang tsona.",
"3": "<sup>3</sup> Mahlo a lona a bone seo Jehova a se entseng ka baka la Baale-Peore, kamoo Jehova, Modimo wa hao, a timeditseng hara lona bohle ba neng ba latetse Baale-Peore kateng.",
"4": "<sup>4</sup> Athe lona ba ileng ba kgomarela Jehova, Modimo wa lona, le sa ntsane le phela le kajeno kaofela ha lona.",
"5": "<sup>5</sup> Bonang, ke le rutile melao le ditaelo, kamoo Jehova, Modimo wa ka, a ntaetseng kateng, hore le tle le etse ka tsona lefatsheng leo le yang ho le rua.",
"6": "<sup>6</sup> Di bolokeng, le etse ka tsona, hobane ke tsona tseo e tla ba bohlale ba lona, le kelello ya lona pela ditjhaba tse tlang ho utlwa melao ena kaofela; di tla re: Tjhaba seno se seholo, ruri ke setjhaba se hlalefileng, se nang le kelello.",
"7": "<sup>7</sup> Hobane ke sefe setjhaba se seholo seo medimo ya sona e leng haufi le sona, jwalokaha Jehova, Modimo wa rona, a le haufi le rona kamehla ha re mo bitsa?",
"8": "<sup>8</sup> Ke sefe setjhaba se seholo se nang le melao le ditaelo tse lokileng jwalokaha molao ona wohle oo ke o beang pela lona kajeno?",
"9": "<sup>9</sup> Feela, iponele, mme o lebele moya wa hao haholo, o tle o se ke wa lebala ditaba tseo mahlo a hao a di boneng, mme di se ke tsa tswa pelong ya hao le ka letsatsi le le leng la ho phela ha hao. Hape, o di phetele bana ba hao le bana ba bana ba hao.",
"10": "<sup>10</sup> Letsatsing leo o neng o itlhahise Horebe pela Jehova, Modimo wa hao, Jehova o ne a itse ho nna: Mphuthele setjhaba, ke tle ke se utlwise mantswe a ka, hore ba tle ba ithute ho ntshaba ka matsatsi wohle a ho phela ha bona lefatsheng, mme ba rute bana ba bona.",
"11": "<sup>11</sup> La atamela, mme la ema tlasa thaba, mme thaba e ne e tuka ke mollo o fihlang lehodimong; ho ne ho le lefifi, le maru, le botsho.",
"12": "<sup>12</sup> Jehova a bua le lona, a le hara mollo; la na la utlwa modumo wa mantswe, le mpa le sa bone sebopeho sa hae, le utlwa lentswe feela.",
"13": "<sup>13</sup> A le tsebisa selekane sa hae, seo a le laetseng hore le etse ka sona, mantswe a leshome; mme a a ngola matlapeng a mabedi.",
"14": "<sup>14</sup> Mohlang oo, Jehova a ntaela hore ke le rute melao le ditaelo, hore le etse ka tsona lefatsheng leo le yang ho le rua.",
"15": "<sup>15</sup> Lebelang meya ya lona haholo; hobane ha le a ka la bona sebopeho leha se le seng letsatsing leo Jehova a buileng le lona Horebe, a le hara mollo;",
"16": "<sup>16</sup> esere la itshenya, mme la iketsetsa setshwantsho se betlilweng, e leng setshwantsho sa ntho e nngwe, leha e le setshwantsho sa monna, kapa sa mosadi,",
"17": "<sup>17</sup> leha e le setshwantsho sa phoofolo e leng teng lefatsheng, leha e le setshwantsho sa nonyana e rurang sebakeng,",
"18": "<sup>18</sup> leha e le setshwantsho sa ntho e hahabang fatshe, leha e le setshwantsho sa hlapi e phelang metsing katlase ho lefatshe.",
"19": "<sup>19</sup> Esebe mohlomong, ha o emisetsa mahlo a hao lehodimong, mme o bona letsatsi, le kgwedi, le dinaledi, e leng makgotla wohle a mahodimo, wa dumela ho kgumama pela tsona, le ho di sebeletsa; athe ke ntho tseo Jehova, Modimo wa hao, a di abetseng ditjhaba kaofela, tse katlasa mahodimo wohle.",
"20": "<sup>20</sup> Haele lona, Jehova o le nkile, mme o le ntshitse Egepeta, seboping sa tshepe, hore le be setjhaba sa hae ka sebele, jwalokaha ho le jwalo kajeno.",
"21": "<sup>21</sup> Empa Jehova a nkgalefela ka baka la lona, mme a hlapanya hore nke ke ka tshela Jordane, leha e le ho kena lefatsheng le molemo leo Jehova, Modimo wa hao, a o neang lona e be lefa la hao.",
"22": "<sup>22</sup> Haele nna, ke tla shwela naheng ena; ha nka ke ka tshela Jordane; empa lona le tla e tshela, hape le tla rua lefatshe leno le molemo.",
"23": "<sup>23</sup> Iponeleng, esere la lebala selekane seo Jehova, Modimo wa lona, a se entseng le lona, mme la iketsetsa setshwantsho se betlilweng, leha e le setshwantsho sa tsohle tseo Jehova, Modimo wa hao, a o hanetseng le tsona.",
"24": "<sup>24</sup> Hobane Jehova, Modimo wa hao, ke mollo o timeletsang, ke Modimo o boulelang.",
"25": "<sup>25</sup> Etlare hobane o tswale bana le ditloholo, ha e se e le kgale le ahile lefatsheng leo, ekare ha le ka itshenya, la etsa setshwantsho se betlilweng, kapa setshwantsho sa eng le eng, mme la etsa tse mpe pela Jehova, Modimo wa hao, la mo halefisa,",
"26": "<sup>26</sup> kajeno ke le biletsa lehodimo le lefatshe hore e be dipaki tsa hore le tla timela, le timele kapele lefatsheng leo le tla kena ho lona ka ho tshela Jordane, ho ya le rua. Le ke ke la atisa ditshiu tsa lona teng, empa le tla timeletswa ruri.",
"27": "<sup>27</sup> Jehova o tla le qhalanyetsa hara ditjhaba, le be le sale le le sehlotshwana hara ditjhaba tseo Jehova a tla le isa hara tsona.",
"28": "<sup>28</sup> Teng, le tla sebeletsa medimo, e leng mosebetsi wa matsoho a batho, mahong le majwe, e sa boneng, e sa utlweng, e sa jeng, e sa fofoneleng.",
"29": "<sup>29</sup> Teng, le tla batla Jehova, Modimo wa hao, mme o tla mo fumana, ha o ka mmatla ka pelo ya hao yohle le ka moya wa hao wohle.",
"30": "<sup>30</sup> Etlare ha o le tsietsing, mme tsena kaofela di o hlahetse, mehleng ya morao, o tla sokolohela ho Jehova, Modimo wa hao, o utlwe lentswe la hae.",
"31": "<sup>31</sup> Hobane Jehova, Modimo wa hao, ke Modimo o mohau; a ke ke a o tlohela, a ke ke a o timetsa, mme a ke ke a lebala selekane sa bontatao, seo a ba hlapanyeditseng sona.",
"32": "<sup>32</sup> Botsa he ditaba tsa mehla ya boholoholo, tsa mohla o neng o sa ntsane o le siyo, ho qala ka tsatsi leo Modimo o neng o bope motho lefatsheng, le ho tloha pheletsong e nngwe ya mahodimo ho isa ho e nngwe, na taba e kalo e se e kile ya hlaha, kapa e jwalo e se e kile ya utlwahala na?",
"33": "<sup>33</sup> Na se teng setjhaba se seng se utlwileng lentswe la Modimo o buang o le hara mollo, jwalokaha o le utlwile wena, sa ba sa phela na?",
"34": "<sup>34</sup> Kapa a o teng Modimo o mong o kileng wa leka ho tla inkela setjhaba ka hara setjhaba se seng, ka meleko, le ka dipontsho, le ka mehlolo, le ka ntwa, le ka letsoho le matla, le ka letsoho le otlolohileng, le ka matsoso a maholo, jwalokaha Jehova, Modimo wa lona, a le etseditse tsohle tse jwalo Egepeta, pela mahlo a lona na?",
"35": "<sup>35</sup> Tseo o ile wa di bontshwa hore o tle o tsebe hobane Jehova, ke Modimo, le hobane ha ho o mong kantle ho yena.",
"36": "<sup>36</sup> A le lehodimong, o ile a o utlwisa lentswe la hae hore a o rute; le lefatsheng o o bontshitse mollo wa hae o moholo, mme o utlwile mantswe a hae a etswa hara mollo.",
"37": "<sup>37</sup> Kahobane a ratile bontatao, o ikgethetse ditloholo tsa bona kamora bona, mme o o ntshitse Egepeta ka sebele sa hae le ka matla a hae a maholo,",
"38": "<sup>38</sup> hore a falatse pela hao ditjhaba tseo o fetang ka boholo le ka matla, hore a tle a o kenye lefatsheng la tsona, mme a o nee lona, hore e be lefa la hao jwalokaha ho le jwalo kajeno.",
"39": "<sup>39</sup> Tseba kajeno lena, mme o boloke pelong ya hao hobane Jehova ke Modimo mahodimong a hodimo, le tlase lefatsheng; ha ho o mong kantle ho yena.",
"40": "<sup>40</sup> Boloka melao ya hae le ditaelo tsa hae tseo ke o laelang tsona kajeno, hore o tle o be le lehlohonolo, wena le bana ba hao kamora hao, mme o tle o atise ditshiu tsa hao ka ho sa feleng lefatsheng leo Jehova, Modimo wa hao, a o neang lona.",
"41": "<sup>41</sup> Yaba Moshe o kgetha metse e meraro mose o kwana ho Jordane, nqa botjhabatsatsi;",
"42": "<sup>42</sup> hore ho balehele teng mmolai ya bolaileng wa habo e seng ka boomo, a sa mo hloya maobane leha e le maoba, mme a pholohe ka ho balehela ho o mong wa metse eo.",
"43": "<sup>43</sup> Ke Betsere, feelleng, lehwatateng, naheng ya Barubene; le Ramothe-Gileade, naheng ya Bagade; le Golane, Bashane, naheng ya Bamanasse.",
"44": "<sup>44</sup> Ke ona molao oo Moshe a kileng a o beela bana ba Iseraele.",
"45": "<sup>45</sup> Ke tsena ditemoso, le melao, le ditaelo tseo Moshe a kileng a di bolella bana ba Iseraele, ha ba se ba tswile Egepeta,",
"46": "<sup>46</sup> ba le mose o kwano ho Jordane, sekgutlong se mabapa le Bethe-Peore, naheng ya Sihone, morena wa Baamore, ya neng a ahile Heshbone, eo Moshe le bana ba Iseraele ba neng ba mo hlotse ha ba se ba tswile Egepeta.",
"47": "<sup>47</sup> Ba hapa naha ya hae le naha ya Oge, morena wa Bashane, e leng marena a mabedi a Baamore a neng a ahile mose o kwana ho Jordane, nqa botjhabatsatsi.",
"48": "<sup>48</sup> Ba nka naha ho tloha Aroere e lebopong la nokana ya Arnone, ho ya fihla thabeng ya Sione, e leng Hermone,",
"49": "<sup>49</sup> hammoho le lehwatata lohle le mose o kwana ho Jordane, nqa botjhabatsatsi, ho isa Lewatleng la Lehwatata, tlasa Pisga."
},
"5": {
"1": "<sup>1</sup> Moshe a bitsa Baiseraele bohle, a re ho bona: Baiseraele, mamelang melao le ditaelo tseo ke le bolellang tsona kajeno, tsebeng tsa lona, le tle le ithute tsona, le di boloke, mme le di etse.",
"2": "<sup>2</sup> Jehova, Modimo wa rona, o entse selekane le rona Horebe.",
"3": "<sup>3</sup> Jehova ha a ka a etsa selekane seo le bontata rona, empa o se entse le rona bohle bao re leng mona, re sa phelang kajeno.",
"4": "<sup>4</sup> Jehova o buile le lona, difahleho di tadimane, a le thabeng, hara mollo.",
"5": "<sup>5</sup> Nna, mohlang oo, ke ne ke eme mahareng a Jehova le lona ke tle ke le phetele lentswe la Jehova; hobane le ne le tshaba mollo; mme ha le a ka la hlwa thabeng. Jehova a re:",
"6": "<sup>6</sup> Ke nna Jehova, Modimo wa hao, ya o ntshitseng lefatsheng la Egepeta, tlung ya bohlanka.",
"7": "<sup>7</sup> O se ke wa ba le medimo e meng pela sefahleho sa ka.",
"8": "<sup>8</sup> O se ke wa iketsetsa setshwantsho se betlilweng, leha e le setshwantsho se seng sa tse hodimo mahodimong, leha e le sa tse tlase lefatsheng, leha e le sa tse metsing katlase ho lefatshe.",
"9": "<sup>9</sup> O se ke wa di kgumamela, o se ke wa di sebeletsa; hobane nna Jehova, Modimo wa hao, ke Modimo o boulelang, o otlang bana ka bokgopo ba batswadi ba bona ho isa molokong wa boraro le wa bone wa ba ntlhoyang;",
"10": "<sup>10</sup> mme ke hauhela ba nthatang, ba bolokang melao ya ka, ho isa melokong e sekete.",
"11": "<sup>11</sup> O se ke wa tlaela ka lebitso la Jehova, Modimo wa hao; hobane Jehova a ke ke a latola molato wa ya tlaelang ka lebitso hae.",
"12": "<sup>12</sup> Boloka letsatsi la phomolo ho le kgetha, jwalokaha Jehova, Modimo wa hao, a o laetse.",
"13": "<sup>13</sup> O tla sebetsa ka matsatsi a tsheletseng, o etse mosebetsi wa hao wohle;",
"14": "<sup>14</sup> empa letsatsi la bosupa ke phomolo ya Jehova, Modimo wa hao; o se ke wa etsa mosebetsi le o mong ka lona, leha e le wena, leha e le mora wa hao, kapa morali wa hao, leha e le mohlanka wa hao e motona, kapa e motshehadi, leha e le kgomo ya hao, leha e le esele ya hao, leha e le phoofolo e nngwe ya hao, leha e le moeti wa hao ya menyakong ya hao; hore mohlanka wa hao e motona le e motshehadi ba phomole jwaloka wena.",
"15": "<sup>15</sup> O hopole hobane o bile mofo fatsheng la Egepeta, le hobane Jehova, Modimo wa hao, o o ntshitse teng ka letsoho le matla, le ka letsoho le otlolohileng; ke ka baka leo, Jehova, Modimo wa hao, a o laetseng ho boloka letsatsi la phomolo.",
"16": "<sup>16</sup> Hlonepha ntatao le mmao, jwalokaha Jehova, Modimo wa hao, a o laetse, matsatsi a hao a tle a anafale, mme o be le lehlohonolo lefatsheng leo o le newang ke Jehova, Modimo wa hao.",
"17": "<sup>17</sup> O se ke wa bolaya.",
"18": "<sup>18</sup> O se ke wa feba.",
"19": "<sup>19</sup> O se ke wa utswa.",
"20": "<sup>20</sup> O se ke wa etselletsa wa heno ka leshano.",
"21": "<sup>21</sup> U se ke wa lakatsa mosadi wa wa heno; o se ke wa lakatsa ntlo ya wa heno, leha e le tshimo ya hae, leha e le mohlanka wa hae e motona, kapa e motshehadi, leha e le kgomo ya hae, leha e le esele ya hae, leha e le ntho e nngwe e leng ya wa heno.",
"22": "<sup>22</sup> Dipolelo tseo Jehova o di boleletse phutheho ya lona yohle, a le thabeng hara mollo, le lerung, le lefifing, ka lentswe le leholo, mme ha a ka a eketsa letho. A di ngola matlapeng a mabedi, mme a nnea wona.",
"23": "<sup>23</sup> Eitse ha le utlwa lentswe le buang hara lefifi, thaba e ntse e tuka mollo kahohle la nkatamela, lona dihlooho tsohle tsa meloko ya lona, le baholo ba lona;",
"24": "<sup>24</sup> la re: Bona, Jehova, Modimo wa rona, o re bontshitse kganya ya hae le boholo ba hae; re utlwile lentswe la hae, le buang le le hara mollo; re bone kajeno ha Modimo o bua le motho, mme motho a phela.",
"25": "<sup>25</sup> Empa jwale, re ka shwelang? Athe mollo oo o moholo o ya re qeta. Ha re ka boela ra utlwa lentswe la Jehova, Modimo wa rona, re tla shwa.",
"26": "<sup>26</sup> Hobane motho ke ofe ya utlwileng lentswe la Modimo o utlwang, o buang o le hara mollo, jwalokaha re le utlwile, mme a phela?",
"27": "<sup>27</sup> Wena, atamela, o mamele tsohle tseo Jehova, Modimo wa rona, a tla di bua, mme wena o tle o re phetele tsohle tseo Jehova, Modimo wa rona, a tla o bolella tsona, mme re tla di mamela, re di etse.",
"28": "<sup>28</sup> Jehova a mamela dipolelo tsa lona, ha le bua le nna; Jehova a re ho nna: Ke utlwile dipolelo tseo setjhaba seno se o boleletseng tsona; tsohle tseo ba di boletseng ba di buile hantle.",
"29": "<sup>29</sup> Oho! hoja ba ka ba le pelo e jwalo kamehla, ya ho ntshaba, le ya ho boloka ditaelo tsa ka tsohle kamehla, ba tle ba be le lehlohonolo, bona, le bana ba bona, ka ho sa feleng!",
"30": "<sup>30</sup> Eya, o re ho bona: Boelang ditenteng tsa lona.",
"31": "<sup>31</sup> Empa haele wena, dula mona, le nna ke tle ke o bolelle ditaelo tsohle, le melao, le dikahlolo tseo o tla ba ruta tsona, ba tle ba etse ka tsona lefatsheng leo ke ba neang lona ho le rua.",
"32": "<sup>32</sup> Itiiseng ke hona, le etse jwalokaha Jehova, Modimo wa lona, a le laetse. Le se ke la fapohela letsohong le letona, leha e le ho le letshehadi.",
"33": "<sup>33</sup> Le tsamaye ka mokgwa o phethehileng tseleng eo Jehova, Modimo wa lona, a le laetseng yona, le tle le phele, le be le lehlohonolo, mme le atise matsatsi a lona lefatsheng leo le yang ho le rua."
},
"6": {
"1": "<sup>1</sup> Ke yona melao, le ditaelo, le dikahlolo, tseo Jehova, Modimo wa lona a ntaetseng ho le ruta tsona, hore le tle le etse ka tsona lefatseng leo le yang ho le rua;",
"2": "<sup>2</sup> o tle o tshabe Jehova, Modimo wa hao, ka ho boloka melao ya hae yohle, le ditaelo tsa hae tsohle, tseo ke o laelang tsona, hore o di boloke, e le wena, le mora wa hao, le mora wa mora wa hao, ka ditshiu tsohle tsa ho phela ha hao, matsatsi a hao a tle a ngatafale.",
"3": "<sup>3</sup> Oho! Iseraele, di utlwe hle, mme o itiise ho boloka melao eo, o tle o be le lehlohonolo, mme le ate haholo lefatsheng le kollang lebese le dinotshi, jwalokaha Jehova, Modimo wa bontatao, a o boleletse.",
"4": "<sup>4</sup> Utlwa, Iseraele! Modimo wa rona ke Jehova, Jehova a nnotshi.",
"5": "<sup>5</sup> Rata Jehova, Modimo wa hao, ka pelo ya hao yohle, le ka moya wa hao wohle, le ka matla a hao wohle.",
"6": "<sup>6</sup> Ditaelo tseo ke o laelang tsona kajeno, di be pelong ya hao.",
"7": "<sup>7</sup> O tle o di rute bana ba hao, mme o bue ka tsona, ha o dutse tlung ya hao, leha o le tseleng o tsamaya, leha o ya robala, leha o tsoha.",
"8": "<sup>8</sup> O di tlame matsohong a hao hore e be dipontsho ho wena, mme di be jwaloka moqhaka phatleng pakeng tsa mahlo a hao.",
"9": "<sup>9</sup> O di ngole difateng tsa menyako ya ntlo ya hao, le mamating a yona.",
"10": "<sup>10</sup> Etlere hobane Jehova, Modimo wa hao, a o kenye lefatsheng leo a anetseng bontatao, Abrahama, Isaaka, le Jakobo, hore o tla o nea lona, e leng metse e meholo, e metle, eo o sa kang wa e haha,",
"11": "<sup>11</sup> le matlo a tletseng menono yohle, a sa kang a tlatswa ke wena, le didiba tse tjhekilweng, tseo o sa kang wa di tjheka, le merara, le mehlwaare eo o sa kang wa e hloma, mme ha o se o jele, o kgotse;",
"12": "<sup>12</sup> o iponele hore o se lebale Jehova ya o ntshitseng lefatsheng la Egepeta, tlung ya bohlanka.",
"13": "<sup>13</sup> Tshaba Jehova, Modimo wa hao, o mo sebeletse, o ane ka lebitso la hae.",
"14": "<sup>14</sup> Le se ke la latela medimo esele, medimo ya ditjhaba tse ahileng kamathoko ho lona;",
"15": "<sup>15</sup> hobane Jehova, Modimo wa hao, ya leng ha eno, ke Modimo o boulelang. Bohale ba Jehova, Modimo wa hao, bo ka o tukela, mme Jehova a ka o timetsa lefatsheng.",
"16": "<sup>16</sup> Se lekeng Jehova, Modimo wa lona, jwalokaha le mo lekile Massa.",
"17": "<sup>17</sup> Bolokang ka ho tiya ditaelo tsa Jehova, Modimo wa lona, le dikahlolo tsa hae, le melao eo a o laetseng yona.",
"18": "<sup>18</sup> O etse se lokileng le se molemo pela mahlo a Jehova, o tle o iketle, mme o kene, o rue lefatshe le molemo leo Jehova a anetseng bontatao hore o tla ba fa lona,",
"19": "<sup>19</sup> ka ho lelekisa pela hao dira tsohle tsa hao, jwalokaha Jehova a boletse.",
"20": "<sup>20</sup> Etlere ha mora wa hao a o botsa kamoso, a re: Na ditemoso, le melao, le ditaelo tseo Jehova, Modimo wa rona, a re laetseng tsona, di reng?",
"21": "<sup>21</sup> O tle o bolelle mora wa hao, o re: Re ne re le bafo ba Faro Egepeta, mme Jehova o re ntshitse Egepeta, ka letsoho le matla;",
"22": "<sup>22</sup> Jehova o entse dipontsho le mehlolo e meholo e tshabehang pela mahlo a rona, ho lwantsha Egepeta le Faro, le ntlo ya hae kaofela ha yona;",
"23": "<sup>23</sup> o re ntshitse teng, hore a re tlise kwano ho re nea lefatshe leo a neng a anetse bontata rona, hore o tla re nea lona.",
"24": "<sup>24</sup> Jehova o re laetse ho etsa ka melao eo kaofela, re ntse re tshaba Jehova, Modimo wa rona, re tle re be le lehlohonolo kamehla, mme re bolokwe ke yena, jwaloka kajeno.",
"25": "<sup>25</sup> Mme hoo e tla ba ho loka ha rona, ha re tiya ho boloka ditaelo tseo tsohle pela Jehova, Modimo wa rona, jwalokaha a re laetse."
},
"7": {
"1": "<sup>1</sup> Etlere ha Jehova, Modimo wa hao, a se a o kentse lefatsheng leo o yang ho le rua, mme a se a faladitse ditjhaba tse ngata pela hao, Bahethe, le Bagirgashe, le Baamore, le Bakanana, le Baferese, le Baheve, le Bajebuse, tjhaba tse supileng tse o fetang ka bongata le ka matla,",
"2": "<sup>2</sup> ha Jehova, Modimo wa hao, a se a di neetse matsohong a hao, mme o di qhadile, o ke o di neele anathema; o se ke wa etsa selekane le tsona, mme o se ke wa di qenehela.",
"3": "<sup>3</sup> O se ke wa nyallana le bona; o se ke wa nea bara ba bona baradi ba hao, mme o se ke wa nkela bara ba hao baradi ba bona;",
"4": "<sup>4</sup> hobane bara ba hao ba ka kgeloswa ke bona, hore ba ntlohele, mme ba sebeletse medimo esele, mme kgalefo ya Jehova e ka le tukela, a o fedisa hang.",
"5": "<sup>5</sup> Empa seo le tshwanetseng ho ba etsa sona, ke sena: Le qhaqhe dialetare tsa bona, le bolaye ditshiya tsa bona, le reme diashera tsa bona, le tjhese ditshwantsho tsa bona tse betlilweng.",
"6": "<sup>6</sup> Hobane o setjhaba se kgethetsweng Jehova, Modimo wa hao; Jehova, Modimo wa hao, o o kgethile hore o be setjhaba sa hae sa sebele, hara ditjhaba tsohle tse lefatsheng.",
"7": "<sup>7</sup> Hase kahobane le fetisa ditjhaba tse ding ka bongata Jehova a le ratileng, a le kgethileng; hobane le setjhaba se senyenyane ho ditjhaba tsohle.",
"8": "<sup>8</sup> Empa kahobane Jehova a le ratile, mme a bolokile kano eo a e anetseng bontata lona, Jehova o le ntshitse Egepeta, ka letsoho le matla, mme o le lopolotse tlung ya bohlanka, le letsohong la Faro, Morena wa Egepeta.",
"9": "<sup>9</sup> Tseba ka hona hobane Jehova, Modimo wa hao, ke Modimo, Modimo o tshepehang, o bolokelang ba o ratang, ba bolokang ditaelo tsa wona, selekane le mohau ho isa melokong e sekete;",
"10": "<sup>10</sup> o busetsang pontsheng ho ba o hloyang ka ho ba timetsa. Ha a diehe ho otla ya mo hloyang, a busetse ho eena pontsheng.",
"11": "<sup>11</sup> Ha ho le jwalo, boloka ditaelo, le melao, le dikahlolo tseo ke o laelang tsona kajeno hore o etse ka tsona.",
"12": "<sup>12</sup> Ha le fela le ka utlwa ditaelo tseo, la di boloka, mme la etsa ka tsona, Jehova, Modimo wa hao, o tla o bolokela selekane le mohau, kamoo a anetseng bontatao kateng.",
"13": "<sup>13</sup> O tla o rata, a o hlohonolofatse, mme a o atise; o tla hlohonolofatsa ditholwana tsa popelo le tsa mobu wa hao, koro ya hao, le veine e ntjha ya hao, le ole ya hao, le ho tswalwang ke dikgomo tsa hao, le dikonyana tsa dinku tsa hao lefatsheng leo a anetseng bontatao, a re, o tla o fa lona.",
"14": "<sup>14</sup> O tla hlohonolofatswa ho fetisa ditjhaba tsohle; banna le basadi ba nyopileng ba tla hlokahala hara lona, le metshelo e tla ba siyo mehlapeng ya lona.",
"15": "<sup>15</sup> Jehova o tla suthisetsa malwetse wohle hole le wena; a ke ke a o otla ka lefu le leng la mafu a mabe a Egepeta, ao o a tsebileng; empa bohle ba o hloileng, o tla ba otla ka wona.",
"16": "<sup>16</sup> O tla fedisa ditjhaba tsohle tseo Jehova, Modimo wa hao, a tla o neela tsona; mahlo a hao a se ke a di qenehela, mme o se ke wa sebeletsa medimo ya tsona, hobane hoo e ka ba leraba ho wena.",
"17": "<sup>17</sup> Ekare ha o re pelong ya hao: Ditjhaba tseno di mphetisa ka bongata; na nka di falatsa jwang?",
"18": "<sup>18</sup> o se ke wa di tshaba, o mpe o hopole tseo Jehova, Modimo wa hao, a di entseng ho Faro le ho Baegepeta kaofela.",
"19": "<sup>19</sup> Hopola meleko e meholo eo o e boneng ka mahlo a hao, le dipontsho, le mehlolo, le letsoho le matla, le letsoho le otlolohileng, tseo Jehova, Modimo wa hao, a o ntshitseng Egepeta ka tsona: Jehova, Modimo wa hao, o tla etsa jwalo ho ditjhaba tsohle tseo le di tshabang.",
"20": "<sup>20</sup> Hape, Jehova, Modimo wa hao, o tla romela diboba ho ya lwantsha ditjhaba tseo, ho fihlela ba setseng le ba ipatileng pela hao ba fela.",
"21": "<sup>21</sup> O se ke wa ba tshaba, hobane Jehova, Modimo wa hao, Modimo o moholo, o tshabehang, o ha eno.",
"22": "<sup>22</sup> Jehova, Modimo wa hao, o tla falatsa ditjhaba tseo pela hao butle; o ke ke wa di qeta kaofela hang, esere mohlomong dibatana tsa naha tsa o atela haholo;",
"23": "<sup>23</sup> empa Jehova, Modimo wa hao, o tla o neela ditjhaba tseo, a di tshose ka tshoho e tshabehang, di be di fediswe.",
"24": "<sup>24</sup> O tla neela marena a tsona matsohong a hao, mme o tla hlakola mabitso a wona tlasa lehodimo; ha ho motho ya tla tseba ho ema pela hao, ho fihlela o ba qeta kaofela.",
"25": "<sup>25</sup> Le tla tjhesa ditshwantsho tse betlilweng tsa medimo ya bona; o se ke wa lakatsa, mme o se ke wa inkela silefera, leha e le kgauta tse ho tsona, esere hoo ya eba sefi ho wena; hobane ke manyala pela Jehova, Modimo wa hao.",
"26": "<sup>26</sup> O se ke wa kenya ntho e manyala tlung ya hao, esere mohlomong wa neelwa anathema jwaloka ntho eo; e tshabe haholo, mme o e ile haholo, hobane ke anathema."
},
"8": {
"1": "<sup>1</sup> Iponeleng, le boloke ditaelo tsohle tseo ke o laelang tsona kajeno, le tle le phele, le ate, mme le kene lefatsheng leo Jehova a anetseng bontata lona hore o tla ba nea lona, le le rue.",
"2": "<sup>2</sup> Hopola tsela yohle eo Jehova, Modimo wa hao, a o tsamaisitseng ka yona feelleng ka dilemo tsena tse mashome a mane, hore o kokobetswe, o lekwe, mme ho bonwe tse pelong ya hao, hore na o tla boloka ditaelo tsa hae, kapa tjhe.",
"3": "<sup>3</sup> O o kokobeditse, a o lapisa, a ntano o fepa ka manna, eo o neng o sa e tsebe pele, eo bontatao ba sa kanga ba e tseba, o tle o tsebe hobane motho a ke ke a phela ke bohobe feela, motho o tla mpe a phele ke tsohle tse tswang molomong wa Jehova.",
"4": "<sup>4</sup> Diaparo tsa hao ha di a ka tsa senyeha hodima hao, mme maoto a hao ha a ka a ruruha ka dilemo tseo tse mashome a mane.",
"5": "<sup>5</sup> Kgolwa pelong ya hao hobane Jehova, Modimo wa hao, o o laile jwaloka motho ha a laya mora wa hae.",
"6": "<sup>6</sup> Boloka ditaelo tsa Jehova, Modimo wa hao, o tsamaye ditseleng tsa hae, o mo tshabe.",
"7": "<sup>7</sup> Hobane Jehova, Modimo wa hao, o ya o kenya lefatsheng le molemo, lefatshe la melapo, la didiba, la matsha, la metsi a kollang dikgutlong le dithabeng;",
"8": "<sup>8</sup> lefatshe la koro, la harese, la merara, la difeiye, la digaranata, lefatshe la mehlwaare e nang le ole, le la dinotshi,",
"9": "<sup>9</sup> lefatshe leo o tla ja bohobe ho lona, ho se tlala, mme o ke ke wa hloka letho ho lona; lefatshe leo majwe a lona e leng tshepe, mme dithabeng tsa lona o tla tjheka koporo.",
"10": "<sup>10</sup> O tla ja o kgore, mme o tla boka Jehova, Modimo wa hao, ka baka la lefatshe le molemo leo a o neang lona.",
"11": "<sup>11</sup> Iponele, o se lebale Jehova, Modimo wa hao, ka ho se boloke ditaelo tsa hae, le dikahlolo tsa hae, le melao ya hae, eo ke o laelang yona kajeno,",
"12": "<sup>12</sup> esere mohlomong, ha o se o jele, o kgotshe, mme o hahile matlo a matle, o dutse ho wona,",
"13": "<sup>13</sup> ha dikgomo tsa hao, le dinku tsa hao di atile haholo, ha o ruile silefera le kgauta e ngata, mme dintho tsohle tsa hao di atile,",
"14": "<sup>14</sup> pelo ya hao ya ikgohomosa, mme wa lebala Jehova, Modimo wa hao, ya o nyolotseng naheng ya Egepeta, tlung ya bohlanka;",
"15": "<sup>15</sup> ya o tsamaisitseng nahathothe eo e kgolo, e tshabehang, e nang le dinoha tse tjhesang le diphepheng, naha e omeletseng, e se nang metsi; Jehova, ya o ntsheditseng metsi lefikeng le thata,",
"16": "<sup>16</sup> ya o fepileng nahathothe ka manna, eo bontatao ba sa kang ba e tseba; a tle a o kokobetse, a o leke, hore a tle a o hlohonolofatse mehleng e tlang.",
"17": "<sup>17</sup> Iponele, o tle o se ke wa re ka pelong ya hao: Ke ruile dintho tseo ka matla a ka, ka matla a matsoho a ka.",
"18": "<sup>18</sup> O mpe o hopole Jehova, Modimo wa hao, hobane ke yena ya o neang matla a ho rua dintho tseo, hore a tiise selekane sa hae, seo a se anetseng bontatao, jwalokaha ho le jwalo le kajeno.",
"19": "<sup>19</sup> Empa ekare ha o leballa ruri Jehova, Modimo wa hao, o latela medimo esele, o e sebeletsa, o e kgumamela, kajeno ke a le pakela, ke re, le tla timella ruri.",
"20": "<sup>20</sup> Le tla timela jwaloka ditjhaba tseo Jehova a yang ho di fedisa pela lona, ha le ka hana ho utlwa lentswe la Jehova, Modimo wa lona."
},
"9": {
"1": "<sup>1</sup> Iseraele, mamela! Kajeno o tla tshela Jordane ho ya rua ditjhaba tse o fetisang ka bongata le ka matla, le metse e meholo e nang le marako a malelele ho isa lehodimong.",
"2": "<sup>2</sup> Ke setjhaba se seholo, se boemo bo bolelele, ke ditloholo tsa Baanake bao o ba tsebang, bao o utlwileng ha ho thwe: Ho ka ema mang pela bana ba Anake?",
"3": "<sup>3</sup> Tseba kajeno hobane Jehova, Modimo wa hao, o ya o etella pele, a le jwaloka mollo o timeletsang; o tla ba fedisa, a ba kokobetse pela hao; mme o tla ba falatsa, o ba fedise kapele, jwalokaha Jehova a o boleletse.",
"4": "<sup>4</sup> Etlere ha Jehova, Modimo wa hao, a ba lelekile pela hao, o se ke wa bua pelong ya hao, wa re: Ke ka baka la ho loka ha ka Jehova a nkentseng naheng ena hore ke e rue; athe ke ka baka la bokgopo ba ditjhaba tseo Jehova a tlang ho di falatsa pela hao.",
"5": "<sup>5</sup> Hase ka baka la ho loka ha hao, leha e le ka baka la bokgabane ba pelo ya hao, o yang ho kena lefatsheng la bona ho le rua; empa ke ka baka la bokgopo ba ditjhaba tseo Jehova, Modimo wa hao, a tlang ho di falatsa pela hao, a tle a tiise lentswe leo Jehova a le boleletseng bontatao, Abrahama, Isaaka le Jakobo, ka kano.",
"6": "<sup>6</sup> Tseba hobane hase ka baka la ho loka ha hao, Jehova, Modimo wa hao, a o neang lefatshe leo ho le rua; hobane o setjhaba se molala o thata.",
"7": "<sup>7</sup> Hopola, o se lebale, kamoo o halefisitseng Jehova, Modimo wa hao kateng, feelleng lena; ho qala ka letsatsi leo o tswileng lefatsheng la Egepeta ka lona ho tlisa ho leo le fihlileng ka lona bakeng sena, le nnile la ikgantshetsa Jehova.",
"8": "<sup>8</sup> Esita le Horebe, le phepheditse Jehova; Jehova a le halefela, a ba a hopola ho le timetsa.",
"9": "<sup>9</sup> Eitse ha ke nyolohela thabeng ho ya nka matlapa, matlapa a selekane seo Jehova a se entseng le lona, ka hlola thabeng matsatsi a mashome a mane, le masiu a mashome a mane, ke sa je bohobe, ke sa nwe metsi.",
"10": "<sup>10</sup> Jehova a nnea matlapa a mabedi, a ngodilweng ka monwana wa Modimo, ao ho neng ho ngodilwe ho wona dipolelo tsohle tseo Jehova a le boleletseng tsona a le thabeng, kahara mollo, letsatsing la phutheho.",
"11": "<sup>11</sup> Eitse hobane matsatsi a mashome a mane a fete, Jehova a nnea matlapa a mabedi, e leng matlapa a selekane;",
"12": "<sup>12</sup> mme Jehova a re ho nna: Ema, o phakise ho theoha; hobane setjhaba sa hao, seo o se ntshitseng Egepeta, se itshentse; ba phakisitse ho fapoha tsela eo ke neng ke ba laetse ho tsamaya ka yona; ba iketseditse setshwantsho se tsholotsweng.",
"13": "<sup>13</sup> Hape, Jehova a mpolella a re: Ke tadimile setjhaba sena, mme bona, ke setjhaba se molala o thata.",
"14": "<sup>14</sup> Ntesele, mme ke tla ba fedisa, ke hlakole lebitso la bona tlasa lehodimo, mme wena ke tla o etsa setjhaba se fetisang sena ka matla le ka bongata.",
"15": "<sup>15</sup> Yaba ke a tloha, ka theoha thabeng; thaba e ne e tuka mollo; ke ne ke tshwere matlapa a mabedi a selekane matsohong a ka.",
"16": "<sup>16</sup> Ka tadima, ka bona hobane le ne le sitetswe Jehova, Modimo wa lona, le iketseditse namane e tsholotsweng; le ne le fapohile kapele tsela eo Jehova a neng a le laetse yona.",
"17": "<sup>17</sup> Ka tshwara matlapa a mabedi, ka a lahlela fatshe ka matsoho a ka, ka a bolaya pela mahlo a lona.",
"18": "<sup>18</sup> Ka itihela fatshe pela Jehova jwaloka pele, ka matsatsi a mashome a mane, le masiu a mashome a mane, ke sa je bohobe, ke sa nwe metsi, ka baka la dibe tsohle tsa lona, tseo le di entseng ka ho etsa bobe pela Jehova, ho mo phephetsa.",
"19": "<sup>19</sup> Hobane ke ne ke tshohile bohale le kgalefo tseo Jehova a neng a le halefetse ka tsona ho le timetsa. Jehova a boela a nkutlwa le mohlang oo.",
"20": "<sup>20</sup> Hape, Jehova o ne a halefetse Aarone haholo, a rata ho mo timetsa; empa ka rapella le Aarone nakong eo.",
"21": "<sup>21</sup> Yaba ke nka sebe sa lona, namane eo le e entseng; ka e besa, ka e tula, ka e sila, ka e etsa phofo, mme ka akgela phofo ya yona molapong o theohang thabeng.",
"22": "<sup>22</sup> Hape, Tabeera, le Massa, le Kibrothe-Hattaava, le phepheditse Jehova.",
"23": "<sup>23</sup> Le mohla re leng Kadeshe-Barnea, ha Jehova a le roma, a re: Nyolohang, le rue lefatshe leo ke le neileng lona, la ikgantshetsa taelo ya Jehova, Modimo wa lona; ha le a ka la mo tshepa, mme ha le a ka la etsa ka lentswe la hae.",
"24": "<sup>24</sup> Le ikgantsheditse Jehova haesale le mohla ke qadileng ho le tseba.",
"25": "<sup>25</sup> Efela ka itihela fatshe pela Jehova ka matsatsi a mashome a mane le masiu a mashome a mane, jwalokaha ke ne ke itihetse pele, kahobane Jehova a ne a itse, o rata ho le fedisa.",
"26": "<sup>26</sup> Ka rapela Jehova, ka re: Oho, Morena Jehova, o se ke wa fedisa setjhaba sa hao sa lefa la hao, seo o se lopolotseng ka boholo ba hao, seo o se ntshitseng Egepeta ka letsoho le matla.",
"27": "<sup>27</sup> Hopola bahlanka ba hao, Abrahama, Isaaka, le Jakobo; o se ke wa tadima bothata ba setjhaba sena, leha e le bokgopo ba sona, leha e le sebe sa sona,",
"28": "<sup>28</sup> esere mohlomong ba ahileng naheng eo o re ntshitseng ho yona, ba re: Erekaha Jehova a sitilwe ho ba kenya lefatsheng leo a ba baletseng lona, hape a ba hloile, ke ka hona a ba ntsheditseng ho ba bolaela lefeelleng.",
"29": "<sup>29</sup> Leha ho le jwalo, ke setjhaba sa hao sa lefa la hao, seo o se ntshitseng Egepeta ka matla a hao a maholo, le ka letsoho la hao le otlolohileng."
},
"10": {
"1": "<sup>1</sup> Mohlang oo, Jehova a re ho nna: Betla matlapa a mabedi a kang a pele, o nyolohele ho nna thabeng; hape o tla etsa areka ya difate.",
"2": "<sup>2</sup> Ke tla ngola matlapeng ao mantswe a neng a ngodilwe matlapeng a pele ao o a bolaileng, mme o tla a kenya arekeng.",
"3": "<sup>3</sup> Yaba ke etsa areka ya sefate sa leoka, ka betla matlapa a mabedi a kang a pele; ka nyolohela thabeng ke tshwere matlapa a mabedi matsohong a ka.",
"4": "<sup>4</sup> Jehova a ngola matlapeng seo a neng a se ngodile pele, mantswe a leshome ao Jehova a neng a le boleletse wona, a le thabeng, hara mollo, la letsatsi la phutheho; mme Jehova a nnea matlapa ao.",
"5": "<sup>5</sup> Ka kgutla, ka theoha thabeng, ka bea matlapa arekeng eo ke e entseng, mme a dula teng jwalokaha Jehova a ne a ntaetse.",
"6": "<sup>6</sup> [Yaba bana ba Iseraele ba tloha Beerothe-Bene-Jaakane, ba ya Mosera; ke moo Aarone a shwetseng teng, a ba a patwa teng; mme Eleasare, mora wa hae, ya eba yena moprista tulong tsa hae.",
"7": "<sup>7</sup> Ba ntoo tloha teng, ba tla Gudegoda; ha ba tloha Gudegoda, ba ya Jothbatha, e leng naha ya melapo.",
"8": "<sup>8</sup> Mohlang oo, Jehova a kgetha leloko la Levi ho jara areka ya selekane sa Jehova, le ho ema pela Jehova, le ho mo sebeletsa, le ho hlohonolofatsa setjhaba ka lebitso la hae, ho fihlela la kajeno.",
"9": "<sup>9</sup> Ke ka baka leo Levi a se nang karolo, leha e le lefa, le banababo; Jehova ke yena e leng lefa la hae, jwalokaha Jehova, Modimo wa hao, a mmoleletse.]",
"10": "<sup>10</sup> Haele nna, ka hlola thabeng matsatsi a mashome a mane, le masiu a mashome a mane, jwaloka mohla pele. Jehova a boela a nkutlwa le mohlang oo; mme Jehova ha a ka a rata ho o timetsa.",
"11": "<sup>11</sup> Yaba Jehova o re ho nna: Ema o tsamaye, o etelle setjhaba pele, hore ba kene lefatsheng leo ke anetseng bontata bona hore ke tla ba fa lona, ba le rue.",
"12": "<sup>12</sup> Mme jwale, Iseraele, Jehova, Modimo wa hao, o batlang ho wena, haese hore o tshabe Jehova, Modimo wa hao, o tsamaye tseleng tsa hae tsohle, o mo rate, mme o sebeletse Jehova, Modimo wa hao, ka pelo ya hao yohle, le ka moya wa hao wohle,",
"13": "<sup>13</sup> o boloke ditaelo tsa Jehova, le melao ya hae eo ke o laelang yona kajeno, hore o be o iketle?",
"14": "<sup>14</sup> Bona, mahodimo le mahodimo a mahodimo ke a Jehova, Modimo wa hao, le lona lefatshe le dintho tsohle tse ho lona.",
"15": "<sup>15</sup> Jehova o kgomaretse bontatao ba nnotshi hore a ba rate, mme kamora bona, o kgethile ditloholo tsa bona, ke ho re lona, hara ditjhaba tsohle, kamoo ho leng kateng le kajeno.",
"16": "<sup>16</sup> Ha ho le jwalo, bolotsang dipelo tsa lona, mme le se ke la hlola le satalatsa melala ya lona.",
"17": "<sup>17</sup> Hobane, Jehova, Modimo wa lona, ke Modimo wa medimo, le Morena wa marena, Modimo o moholo, o matla, o tshabehang, o sa tadimeng tshobotsi ya motho, o sa amoheleng dimpho,",
"18": "<sup>18</sup> o ahlolelang kgutsana le mosadi wa mohlolohadi, o ratang moditjhaba, o mo neang dijo le diaparo.",
"19": "<sup>19</sup> Le lona, ratang moditjhaba, etswe le bile baditjhaba naheng ya Egepeta.",
"20": "<sup>20</sup> Tshaba Jehova, Modimo wa hao, o mo sebeletse, o mo kgomarele, mme o ane ka lebitso la hae.",
"21": "<sup>21</sup> Ke yena e leng letlotlo la hao, ke yena e leng Modimo wa hao, o o etseditseng ntho tse kgolo tsena, tse tshabehang, tseo mahlo a hao a di boneng.",
"22": "<sup>22</sup> Bontatao ba ne ba theohetse Egepeta, ba le mashome a supileng, mme jwale Jehova, Modimo wa hao, o o atisitse, o bile o o entse bongata bo ka ka dinaledi tsa lehodimo."
},
"11": {
"1": "<sup>1</sup> Rata ke hona Jehova, Modimo wa hao, mme o boloke ditemoso tsa hae kamehla, le melao ya hae, le dikahlolo tsa hae, le ditaelo tsa hae.",
"2": "<sup>2</sup> Hape, lemoha ditaba kajeno; hobane ha ke bue le bana ba lona ba sa kang ba tseba le ho bona kgalemelo ya Jehova, Modimo wa lona, le boholo ba hae, le letsoho la hae le matla, le letsoho la hae le otlolohileng,",
"3": "<sup>3</sup> le mehlolo ya hae, le diketso tsa hae tseo a di entseng hara Egepeta, ho Faro, morena wa Egepeta, le naheng ya hae kaofela,",
"4": "<sup>4</sup> le seo a se entseng ka makgotla a Egepeta, le ka dipere tsa bona, le ka makoloi a bona; kamoo a ba apesitseng kateng, ka metsia Lewatle le Lefubedu, mohla ba neng ba le phallela, le kamoo Jehova a ba timeditseng kateng, ho fihlela la kajeno;",
"5": "<sup>5</sup> le seo a se etseditseng lona, lefeelleng leo, ho isa nakong eo le fihlileng sebakeng sena ka yona;",
"6": "<sup>6</sup> le seo a se entseng Dathane le Abirame, bara ba Eliabe, mora Rubene, kamoo lefatshe le ahlamisitseng molomo wa lona, la ba metsa le ba matlo a bona, le ditente tsa bona, le dintho tsohle tsa bona, ba le hara Baiseraele kaofela.",
"7": "<sup>7</sup> Hobane mahlo a lona a bone diketso tsohle tse kgolo tseo Jehova a di entseng.",
"8": "<sup>8</sup> Bolokang ditaelo tsohle tseo ke o laelang tsona kajeno, le tle le be matla, mme le kene, le hape lefatshe leo le yang ho le rua;",
"9": "<sup>9</sup> mme le atise matsatsi a lona lefatsheng le kollang lebese le dinotshi, leo Jehova a anetseng bontata lona hore o tla le fa bona le ditloholo tsa bona.",
"10": "<sup>10</sup> Hobane naha eo o yang ho kena ho yona ho e rua, hase naha e tshwanang le ya Egepeta, eo le tswileng ho yona, moo o neng o jala peo ya hao, le moo o neng o nosetsa masimo a hao ka maoto a hao, jwalokaha ho nosetswa tshimo ya meroho.",
"11": "<sup>11</sup> Naha eo le yang ho e rua, ke naha ya dithaba, le ya dikgutlo, e nosetswang ke metsi a pula ya lehodimo.",
"12": "<sup>12</sup> Ke naha eo Jehova, Modimo wa hao, a e baballang, eo mahlo a Jehova, Modimo wa hao, a e tadimang kamehla, ho qala ha selemo se thwasa, ho isa ha selemo se fela.",
"13": "<sup>13</sup> Etlare ha le mamedisisa ditaelo tsa ka tseo ke le laelang tsona kajeno, ha le rata Jehova, Modimo wa lona, le mo sebeletsa ka dipelo tsa lona tsohle, le ka meya ya lona yohle,",
"14": "<sup>14</sup> ke tla nesetsa naha ya lona pula, nakong e tshwanelehang, pula ya tsheola le pula ya hwetla, o tle o kotule koro ya hao, le veine e ntjha ya hao, le ole ya hao.",
"15": "<sup>15</sup> Naheng ya hao ke tla medisa jwang ba mehlape ya hao; mme o tla ja, o kgore.",
"16": "<sup>16</sup> Iponeleng, pelo tsa lona di se ke tsa thetswa, mme le se ke la kgeloha, la ya sebeletsa medimo esele, la e kgumamela;",
"17": "<sup>17</sup> esere kgalefo ya Jehova ya le tukela, mme Jehova a kwala mahodimo, hore pula e be siyo, mme lefatshe le se ke la hlola le bea dijo tsa lona, mme lona la timela kapele lefatsheng leo le molemo, leo Jehova a le neang lona.",
"18": "<sup>18</sup> Kenyang ke hona mantswe ana ao ke le bolellang wona ka dipelong tsa lona, le meyeng ya lona, mme le a tlame ho ba pontsho matsohong a lona, mme a be jwaloka meqhaka pakeng tsa mahlo a lona.",
"19": "<sup>19</sup> Le a rute bana ba lona, o bue ka wona ha o dutse tlung ya hao, leha o tsamaya tseleng, leha o robala, leha o tsoha borokong.",
"20": "<sup>20</sup> A ngole le difateng tsa menyako ya ntlo ya hao, le mamating a hao;",
"21": "<sup>21</sup> hore matsatsi a lona, le matsatsi a bana ba lona, a tle a ngatafale lefatsheng leo Jehova a anetseng bontata lona hore o tla ba nea lona, a be ka ka matsatsi a mahodimo a okametseng lefatshe.",
"22": "<sup>22</sup> Hobane, ekare ha le boloka hantle ditaelo tsohle tseo ke le laelang tsona kajeno ho etsa ka tsona, le rata Jehova, Modimo wa lona, le tsamaya ditseleng tsa hae kaofela, le mo kgomarela,",
"23": "<sup>23</sup> ke moo Jehova a tla falatsa pela lona ditjhaba tseno tsohle, mme le tla rua naha ya ditjhaba tse le fetisang ka bongata le ka matla.",
"24": "<sup>24</sup> Nqalo e nngwe le e nngwe e tla hatwa ke bohato ba maoto a lona, e tla ba ya lona. Meedi ya lona e tla ba ho tloha feelleng ho isa Lebanone, ho tloha nokeng ya Eufrate ho isa Lewatleng la Bophirimela.",
"25": "<sup>25</sup> Ha ho ka ke ha eba motho ya emang pela lona; Jehova, Modimo wa lona, o tla kenya letsoso la lona le tshabo ya lona naheng yohle eo le tla e hata ka maoto a lona, jwalokaha a le boleletse.",
"26": "<sup>26</sup> Bonang, kajeno ke bea hlohonolofatso le thohako pela lona;",
"27": "<sup>27</sup> hlohonolofatso ha le ka utlwa ditaelo tsa Jehova, Modimo wa lona, tseo ke le laelang tsona kajeno;",
"28": "<sup>28</sup> thohako ha le sa utlwe ditaelo tsa Jehova, Modimo wa lona, mme le kgeloha tsela eo ke le laelang yona kajeno, le latela medimo esele, eo le sa kang la e tseba, le mehla.",
"29": "<sup>29</sup> Etlare hobane Jehova, Modimo wa hao, a o kenye lefatsheng leo o yang ho le rua, o tle o bolele hlohonolofatso thabeng ya Gerisime, le thohako thabeng ya Ebale.",
"30": "<sup>30</sup> Thaba tseo, ha ke re, di mose wane, ho Jordane, kamora tsela e lebileng nqa bophirimatsatsi, naheng ya Bakanana ba ahileng lehwatateng, mabapa le Gilgale, haufi le dieike tsa More?",
"31": "<sup>31</sup> Hobane le se le ya tshela Jordane ho ya rua lefatshe leo Jehova, Modimo wa lona, a le neang lona; le tla le rua, le ahe ho lona.",
"32": "<sup>32</sup> Itiiseng, le phethe melao yohle, le ditaelo tsohle tseo ke di beang pela lona kajeno."
},
"12": {
"1": "<sup>1</sup> Ke ena melao le ditaelo tseo le tshwanetseng ho hlokomela ho etsa ka tsona ka matsatsi wohle a ho phela ha lona lefatsheng leo Jehova, Modimo wa bontatao, a o neang lona, hore o le rue.",
"2": "<sup>2</sup> Le tla fedisisa nqalo tsohle tseo ditjhaba tseo le yang ho di falatsa ha tsona di sebeleditseng medimo ya tsona teng, dithabeng tse telele, le maralleng, le tlasa difate tsohle tse tala.",
"3": "<sup>3</sup> Le qhaqhe dialetare tsa tsona, le bolaye ditshiya tsa tsona, le tjhese diashera tsa tsona, le heletse ditshwantsho tse betlilweng tsa medimo ya tsona, mme le hlakole mabitso a tsona nqalong tseo.",
"4": "<sup>4</sup> Haele Jehova, Modimo wa lona, le ke ke la mo etsa jwalo.",
"5": "<sup>5</sup> Le mpe le batle bodulo ba hae nqalong eo Jehova, Modimo wa lona, a tla e kgetha hara meloko ya lona yohle ho bea lebitso la hae teng, mme o ye teng.",
"6": "<sup>6</sup> Le tla isa teng ditjheso le mahlabelo a lona, le karolo ya leshome ya dintho tsa lona, le dikabelo tse ntshwang ke matsoho a lona, le mahlabelo a dikano tsa lona, le dinyehelo tsa lona tsa boithatelo, le matsibolo a dikgomo le a dinku tsa lona.",
"7": "<sup>7</sup> Le tla ja teng pela Jehova, Modimo wa lona, le ithabise, lona le ba matlo a lona, ka mesebetsi yohle ya matsoho a lona, eo Jehova, Modimo wa hao, a o hlohonolofaditseng ka yona.",
"8": "<sup>8</sup> Le ke ke la etsa kamoo re etsang mona kateng, kajeno, ha e mong le e mong a etsa seo a se lekanyang hore se lokile.",
"9": "<sup>9</sup> Hobane le jwale ha le eso ho kene phomolong le lefeng leo Jehova, Modimo wa hao, a o fang lona.",
"10": "<sup>10</sup> Empa le se le tla tshela Jordane, mme le tla aha lefatsheng leo Jehova, Modimo wa lona, a le fang lona, e be lefa la lona; o tla le nea phomolo ka ho le namolela direng tsa lona tsohle tse ka mathokong a lona, mme le tla aha le iketlile.",
"11": "<sup>11</sup> Nqalo e tla ba teng eo Jehova, Modimo wa lona, a tla e kgetha ho bea lebitso la hae ho yona; ke moo le tla tlisa ntho tsohle tseo ke le laelang tsona, ditjheso tsa lona, le mahlabelo a lona, le karolo ya leshome ya dintho tsa lona, le dikabelo tse ntshwang ke matsoho a lona, le tsohle tse kegthilweng tsa dikano tsa lona, tseo le di baletseng Jehova.",
"12": "<sup>12</sup> Le tla thaba pela Jehova, Modimo wa lona, lona le bara ba lona, le baradi ba lona, le bahlanka ba lona ba batona, le ba batshehadi, le Molevi ya menyakong ya lona; hobane yena ha a na kabelo le lefa jwaloka lona.",
"13": "<sup>13</sup> Iponele, o se ke wa hlahisa ditjheso tsa hao nqalong tsohle tseo o tla di bona.",
"14": "<sup>14</sup> Empa o tla hlahisa ditjheso tsa hao nqalong eo Jehova a tla e kgetha lelokong le leng la heno, mme, teng o etse tsohle tseo ke o laelang tsona.",
"15": "<sup>15</sup> Leha ho le jwalo, kamehla ha o rata, o tla hlaba, o je nama menyakong ya motse o mong le o mong, kamoo ditshitso tseo Jehova, Modimo wa hao, a o neang tsona, di leng kateng; ya sa hlwekang le ya hlwekileng ba je nama eo, jwaloka hoja ho jewa tshephe le kgama.",
"16": "<sup>16</sup> Feela, le ke ke la ja madi; o mpe o a tshollele fatshe jwaloka metsi.",
"17": "<sup>17</sup> O ke ke wa ja menyakong ya metse ya hao karolo ya leshome ya koro ya hao, le ya veine ya hao e ntjha, le ya ole ya hao, le matsibolo a dikgomo tsa hao, le a dinku tsa hao, leha e le mahlabelo a dikano tsa hao, tseo o itlamang ka tsona, le dinyehelo tsa hao tsa boithatelo, le tse ntshwang ke matsoho a hao;",
"18": "<sup>18</sup> empa ke pela Jehova, Modimo wa hao, nqalong eo Jehova, Modimo wa hao, a tla e kgetha, o tla ja tseo, wena, le mora wa hao, le moradi wa hao, le mohlanka wa hao e motona le e motshehadi, le Molevi ya menyakong ya hao, mme o tla nyakalla pela Jehova, Modimo wa hao, ka tsohle tseo o di ruileng ka matsoho a hao.",
"19": "<sup>19</sup> Iponele, o se ke wa lebala Molevi ka matsatsi wohle a ho phela ha hao lefatsheng la hao.",
"20": "<sup>20</sup> Etlare hobane Jehova, Modimo wa hao, a namise meedi ya hao, jwalokaha a o boleletse, leha o ka re: Ke lakatsa ho ja nama; kahobane pelo ya hao e lakaditse ho ja nama, o tle o je nama kahohle kamoo pelo ya hao e lakatsang kateng.",
"21": "<sup>21</sup> Etlare ha nqalo eo Jehova, Modimo wa hao, a tlang ho e kgetha ho bea lebitso la hae ho yona e le hole le wena, o tla hlaba dikgomo le dinku tsa hao tseo Jehova, Modimo wa hao, a o neileng tsona, o hlabe kamoo ke o laetseng kateng, mme o tla ja nama menyakong ya metse ya hao, kahohle kamoo pelo ya hao e lakatsang kateng.",
"22": "<sup>22</sup> O tla di ja jwaloka hoja ho jewa tshephe le kgama; ya sa hlwekang le ya hlwekileng ba di je.",
"23": "<sup>23</sup> Feela o iponele, o se ke wa ja madi: hobane madi ke moya; ha o na ho ja moya hammoho le nama;",
"24": "<sup>24</sup> o se ke wa a ja, empa o a tshollele fatshe jwaloka metsi.",
"25": "<sup>25</sup> O se ke wa a ja, o tle o iketle, wena, le bana ba hao kamora hao, ha o ntse o etsa se lokileng pela Jehova.",
"26": "<sup>26</sup> Empa haele dintho tseo o tla rata ho di kgethela Modimo, le tseo o tla di hlahisa hodima dikano tsa hao, o tla di nka, o ye le tsona, nqalong eo Jehova a tla e kgetha.",
"27": "<sup>27</sup> O tla hlahisa ditjheso tsa hao, nama le madi, aletareng ya Jehova, Modimo wa hao; madi a mahlabelo a hao a tla tshollelwa aletareng ya Jehova, Modimo wa hao, mme o tla ja nama ya wona.",
"28": "<sup>28</sup> Ela sedi, o utlwe ditaba tsena tsohle tseo ke o laelang tsona, o tle o iketle kamehla, wena, le bana ba hao kamora hao, ha o ntse o etsa se molemo, se lokileng pela Jehova, Modimo wa hao.",
"29": "<sup>29</sup> Etlare hobane Jehova, Modimo wa hao, a fedisa pela hao ditjhaba tseo o yang ho rua naha ya tsona, ha o se o dutse tulong tsa tsona, mme o ahile naheng ya tsona,",
"30": "<sup>30</sup> o iponele, esere mohlomong wa tshawaswa lerabeng ka ho di etsisa ha di se di fedisitswe pela hao, wa batla medimo ya tsona ka ho re: Na ditjhaba tseo di ne di sebeletsa medimo ya tsona jwang? Le nna ke rata ho etsa jwalo.",
"31": "<sup>31</sup> O se ke wa etsa Jehova, Modimo wa hao, jwalo, hobane manyala wohle ao Jehova a a hloileng, ba ditjhaba tseo ba a etseditse medimo ya bona; esita le bara ba bona le baradi ba bona, ba ne ba ba tjhesetsa medimo ya bona.",
"32": "<sup>32</sup> Iponeleng, le etse tsohle tseo ke le laelang tsona. O se ke wa di eketsa ka letho, mme o se ke wa tlosa letho ho tsona."
},
"13": {
"1": "<sup>1</sup> Ekare ha ho hlaha ha eno moporofeta, kapa molori wa ditoro, ya o tsebisang pontsho, kapa mohlolo,",
"2": "<sup>2</sup> ha pontsho eo, kapa mohlolo oo a o boleletseng wona, o etsahala, mme a re ho wena: A re lateleng medimo esele, eo o sa e tsebeng, mme re e sebeletse;",
"3": "<sup>3</sup> o se ke wa mamela dipolelo tsa moporofeta eo, kapa tsa molori eo wa ditoro; hobane ke Jehova, Modimo wa lona, ya le lekang hore a tsebe ha le rata Jehova, Modimo wa lona, ka pelo tsa lona tsohle, le ka meya ya lona yohle.",
"4": "<sup>4</sup> Latelang Jehova, Modimo wa lona, le tshabe yena, le boloke ditaelo tsa hae, mme le utlwe lentswe la hae; le mo sebeletse, mme le mo kgomarele.",
"5": "<sup>5</sup> Empa moporofeta eo, kapa molori eo wa ditoro, o tla bolawa, kahobane a boletse tsa ho fetohela Jehova, Modimo wa lona, ya le ntshitseng naheng ya Egepeta, ya o lopolotseng tlung ya bohlanka; o ratile ho o faposa tsela eo Jehova, Modimo wa hao, a o laetseng ho tsamaya ka yona. O tlose bobe ha eno jwalo.",
"6": "<sup>6</sup> Ekare ha ngwaneno, mora wa mmao, kapa mora wa hao, kapa moradi wa hao, kapa mosadi wa sefuba sa hao, leha e ka ba motswalle wa hao ya leng jwaloka moya wa hao, a o susumetsa, a re ho wena ka sephiring: a re yeng, re sebeletse medimo esele, eo o sa kang wa e tseba, wena le bontatao,",
"7": "<sup>7</sup> e leng medimo ya ditjhaba tse kamathoko ho lona, leha e le tse leng haufi, leha e le tse leng hole, ho qala pheletsong e nngwe ya lefatshe ho isa pheletsong e nngwe;",
"8": "<sup>8</sup> o se ke wa mo dumella, mme o se ke wa mo utlwa, leihlo la hao le se ke la mo qenehela; o se ke wa mo utlwela bohloko, mme o se ke wa mo pata;",
"9": "<sup>9</sup> o mpe o mmolaye ruri; letsoho la hao e be lona le emang pele hodima hae ho mmolaya, e ntoo ba matsoho a setjhaba kaofela.",
"10": "<sup>10</sup> O mo tlapunye ka majwe, a shwe; kahobane a ratile ho o tlosa ho Jehova, Modimo wa hao, ya o ntshitseng naheng ya Egepeta, tlung ya bohlanka.",
"11": "<sup>11</sup> Baiseraele bohle ba tla utlwa, ba tshabe, mme ho ke ke ha hlola ho etswa bobe bo bokalo ha eno.",
"12": "<sup>12</sup> Ekare ha motseng o mong wa metse ya hao eo Jehova, Modimo wa hao, a tla o fa yona ho aha teng, o utlwa ho thwe:",
"13": "<sup>13</sup> Batho ba bolotsana ba tswile ho wena, mme ba kgelositse ba ahileng motseng wa bona, ka ho re: A re yeng, re sebeletse medimo esele eo le sa e tsebeng;",
"14": "<sup>14</sup> o tla batla o batlisise, o botsisise haholo. Ha o fumana hobane ke nnete le taba e tiileng, le hobane ho entswe manyala a kalo haeno,",
"15": "<sup>15</sup> teng o bolaye ruri ba ahileng motseng oo ka bohale ba lerumo, mme o o neele anathema, le dintho tsohle tse ho wona; esita le dikgomo tsa teng di bolawe ka bohale ba lerumo.",
"16": "<sup>16</sup> O tla bokella thepa yohle ya wona kahara lepatlelo, mme o tla tjhesetsa Jehova, Modimo wa hao, motse oo, le mesebetsi ya wona yohle, e tla nne e be qubu ya dithako kamehla, tse ke keng tsa boela tsa hahuwa.",
"17": "<sup>17</sup> Ho ke ke ha eba letho la tse neetsweng anathema le kgomarelang matsoho a hao, hore Jehova a kgutle pefong ya bohale ba hae, mme a o hauhele, a o rekolohele, mme a o atise jwalokaha a anetse bontatao,",
"18": "<sup>18</sup> ha o utlwa lentswe la Jehova, Modimo wa hao, o boloka ditaelo tsa hae tsohle, tseo ke o laelang tsona kajeno, mme o etsa se lokileng pela Jehova, Modimo wa hao."
},
"14": {
"1": "<sup>1</sup> Le bana ba Jehova, Modimo wa lona; le se ke la iphatsa, mme le se ke la ipeola pakeng tsa mahlo ka baka la mofu.",
"2": "<sup>2</sup> Hobane o setjhaba se kgethetsweng Jehova, Modimo wa hao, mme Jehova o o kgethile hara ditjhaba tsohle tse lefatsheng hore o tle o be setjhaba sa hae sa sebele.",
"3": "<sup>3</sup> O se ke wa ja ntho tse manyala.",
"4": "<sup>4</sup> Diphoofolo tseo le ka di jang ke tsena: Ke kgomo, nku, le podi,",
"5": "<sup>5</sup> kgama, tshephe, nare, none, letsa, tholo le phuthi.",
"6": "<sup>6</sup> Hara diphoofolo, le ka ja tsohle tse ditlhako di arohaneng, tse dikgola tse pedi, tse thuisang.",
"7": "<sup>7</sup> Empa le se ke la ja tse thuisang feela, leha e le tse ditlhako di arohaneng feela, jwaloka kamele, moutla, le pela; hobane di a thuisa, empa ha di na ditlhako tse arohaneng; tsena ke tse ditshila ho lona;",
"8": "<sup>8</sup> le yona kolobe, hobane leha tlhako tsa yona di arohane, ha e thuise; e be ditshila ho lona. Le se ke la ja nama ya tsona, mme le se ame ditopo tsa tsona.",
"9": "<sup>9</sup> Tseo le ka di jang ho tsohle tse metsing ke tsena: Le je tsohle tse nang le dipheonyana le makgakgapha.",
"10": "<sup>10</sup> Empa le se ke la ja tse se nang dipheonyana, leha e le makgakgapha; tsena e be tse ditshila ho lona.",
"11": "<sup>11</sup> Le ka ja dinonyana tsohle tse hlwekileng.",
"12": "<sup>12</sup> Empa tseo e ka kgonang le se ke la di ja, ke tsena: Ntsu, seodi, le seitlhwaeledi;",
"13": "<sup>13</sup> nkgodi, letlaka, le mohakajane, le mefuta ya tsona;",
"14": "<sup>14</sup> le makgwaba wohle ka mefuta ya wona;",
"15": "<sup>15</sup> le mpshe, kgohoyadira, letlakapipi, le phakwe ka mefuta ya yona;",
"16": "<sup>16</sup> sephooko, lehalanyane le lengangane;",
"17": "<sup>17</sup> moholodi, kokolofitwe, le seinodi,",
"18": "<sup>18</sup> mokotatsie le masianoke, ka mefuta ya tsona, le lehehemu, le mmankgane.",
"19": "<sup>19</sup> Le dikokwanyana tsohle tse rurang, e be tse ditshila ho lona; di se ke tsa jewa.",
"20": "<sup>20</sup> Jang dinonyana tsohle tse hlwekileng.",
"21": "<sup>21</sup> Le se ke la ja nama ya tse itjhweletseng; o mpe o e nee moditjhaba ya menyakong ya hao, a e je; mohlomong o reke ho moditjhaba ka yona; hobane wena o setjhaba se kgethetsweng Jehova, Modimo wa hao. O se ke wa hladiya potsanyane lebeseng la mma yona.",
"22": "<sup>22</sup> O kgethisise karolo ya leshome ya dintho tsohle tse hlahiswang ke peo tsa hao, tse melang masimong a hao ka selemo se seng le se seng.",
"23": "<sup>23</sup> O je pela Jehova, Modimo wa hao, nqalong eo a tla ikgethela yona ho bea lebitso la hae teng, karolo ya leshome ya koro ya hao, le ya veine e ntjha ya hao, le ya ole ya hao, le matsibolo a dikgomo le a dinku tsa hao, o tle o ithute ho tshaba Jehova, Modimo wa hao, kamehla.",
"24": "<sup>24</sup> Empa etlare ha tsela e le telele haholo, mme o sitwa ho isa dintho tseo, kahobane mohlomong nqalo eo Jehova, Modimo wa hao, a tla ikgethela yona ho bea lebitso la hae teng, e tla ba hole le wena, mohla Jehova, Modimo wa hao, a o hlohonolofaditseng,",
"25": "<sup>25</sup> o tla reka tjhelete ka dintho tsena; o tla fupara tjhelete tseo matsohong a hao, o ye nqalong eo Jehova, Modimo wa hao, a tla e kgetha;",
"26": "<sup>26</sup> mme o tla reka ka tjhelete tseo tsohle tseo pelo ya hao e ka di lakatsang, dikgomo, dinku, kapa veine, kapa seno se seng se matla, leha e le ntho tsohle tseo pelo ya hao e ka di lakatsang, o di je hona teng, pela Jehova, Modimo wa hao, mme o thabe, wena, le ba ntlo ya hao;",
"27": "<sup>27</sup> le Molevi ya menyakong ya hao, o se ke wa mo tlohela, hobane ha a na kabelo le lefa jwaloka wena.",
"28": "<sup>28</sup> Qetellong ya dilemo tse tharo, o ntshe karolo yohle ya leshome ya tseo o di kotutseng tsa selemo seo, mme o e bokelle menyakong ya hao.",
"29": "<sup>29</sup> Jwale Molevi ya se nang kabelo le lefa jwaloka wena, le moditjhaba, le kgutsana, le mosadi wa mohlolohadi, ba metseng ya hao, ba tla tla, mme ba je, ba kgore; Jehova, Modimo wa hao, a tle a o hlohonolofatse mesebetsing yohle ya matsoho a hao, eo o e etsang."
},
"15": {
"1": "<sup>1</sup> Selemong sa bosupa se seng le se seng o tla etsa teselo.",
"2": "<sup>2</sup> Mokgwa wa ho etsa teselo ke wona: E mong le e mong ya nametsweng, a leselle wa habo seo a mo nametseng ka sona; a se ke a kgathatsa wa habo, kapa ngwanabo, hobane ho boletswe teselo ya Jehova.",
"3": "<sup>3</sup> O ka kgathatsa moditjhaba, empa haele ngwaneno, o tele ditokelo tsa hao hodima se sa hao se ho yena.",
"4": "<sup>4</sup> Ho ke ke ha eba bafumanehi ha eno, (hobane Jehova o tla o hlohonolofatsa haholo lefatsheng leo Jehova, Modimo wa hao, a o neang lona hore e be lefa le ruwang ke wena)",
"5": "<sup>5</sup> ha o ka mpa wa utlwa lentswe la Jehova, Modimo wa hao, mme wa itiisa ho boloka ditaelo tsohle tseo ke o laelang tsona kajeno.",
"6": "<sup>6</sup> Hobane Jehova, Modimo wa hao, o tla o hlohonolofatsa jwalokaha a o boleletse; ditjhaba tse ngata di tla nama ho wena; empa wena ha o ka ke wa di namela; o tla busa ditjhaba tse ngata, empa ha di ka ke tsa o busa.",
"7": "<sup>7</sup> Empa ha mofumanehi a ka ba teng ha eno, e leng e mong wa banabeno, a leng motseng ofe le ofe wa heno, naheng eo Jehova, Modimo wa hao, a o neang yona, o se ke wa thatafatsa pelo ya hao, mme o se fupare diatla tsa hao pela ngwaneno ya fumanehileng.",
"8": "<sup>8</sup> O mpe o mo fuparollele diatla tsa hao, o mo adime seo a se hlokang sebakeng sa bofumanehi ba hae.",
"9": "<sup>9</sup> Iponele, kgopolo ya bolotsana e se ke ya eba teng pelong ya hao ya ho re: Selemo sa bosupa, selemo sa teselo, se atametse; mme mahlo a hao a se ke a hauhela ngwaneno ya fumanehileng, o sa mo fe letho, mme yena a ka bitsa ho Jehova ka baka la bothata ba hao, mme sebe se eba teng ho wena.",
"10": "<sup>10</sup> O mo fe hle, mme pelo ya hao e se belaele ha o mo fa; hobane ka baka la taba eo, Jehova, Modimo wa hao, o tla o hlohonolofatsa mesebetsing ya hao yohle, le ditabeng tsohle tseo o tla bea matsoho a hao ho tsona.",
"11": "<sup>11</sup> Hobane mohloki a ke ke a hlokahala lefatsheng le ka mohla o le mong; ke ka baka leo ke o laelang, ke re: o fuparollele ngwaneno eo e leng mohloki le mofumanehi naheng ya hao diatla tsa hao.",
"12": "<sup>12</sup> Etlare ha e mong wa banabeno, e leng Moheberu wa monna, kapa wa mosadi, a ithekisa ho wena, o tla o sebeletsa ka dilemo tse tsheletseng; empa ka selemo sa bosupa o tla mo kgutlisa ho wena a lokolohile.",
"13": "<sup>13</sup> Ha o mo kgutlisa ho wena a lokolohile, o se ke wa mo lesa a ya a le feela.",
"14": "<sup>14</sup> O mpe o mo baballe ka mpho e nngwe ya dinku tsa hao, le ya tsa seotlo sa hao, le ya tsa sehatelo sa hao sa veine; o mo fe tsa tseo Jehova, Modimo wa hao, a o hlohonolofaditseng ka tsona.",
"15": "<sup>15</sup> O tla hopola hobane o bile mofo naheng ya Egepeta le hobane o lopolotswe teng ke Jehova, Modimo wa hao; ke ka baka leo ke o laelang hoo kajeno.",
"16": "<sup>16</sup> Empa ekare ha a o bolella, a re: Ha ke rate ho tloha ho wena; kahobane o a o rata, wena le ntlo ya hao, le hobane o iketlile ha hao;",
"17": "<sup>17</sup> o tle o nke lemao, mme ka lona o mo phunyetse tsebe lemating la monyako, mme e tla ba mohlanka wa hao kamehla; le bakeng sa mohlanka wa hao e motshehadi o etse jwalo.",
"18": "<sup>18</sup> E se ke ya eba taba e bohloko ho wena ho mo lokolla feela hore a tle a tlohe ho wena; hobane o o sebeleditse ka dilemo tse tsheletseng, e le ya loketsweng ke moputso wa mohlanka habedi; mme Jehova, Modimo wa hao, o tla o hlohonolofatsa ho tsohle tse o di etsang.",
"19": "<sup>19</sup> Matsibolo a matona wohle a tswallwang dikgomong le dinkung tsa hao, o a kgethele Jehova, Modimo wa hao; o se ke wa sebetsa ka matsibolo a dikgomo tsa hao, mme o se ke wa kuta matsibolo a dinku tsa hao.",
"20": "<sup>20</sup> Ka selemo se seng le se seng, a jewe ke wena le ke ba ntlo ya hao, pela Jehova, Modimo wa hao, nqalong eo Jehova a tla ikgethela yona.",
"21": "<sup>21</sup> Empa ekare ha phoofolo eo e na le sekodi, kapa e le sehlotsa, kapa sefofu, mohlomong e na le bohole bo bong, o se ke wa e hlabela Jehova, Modimo wa hao.",
"22": "<sup>22</sup> E jewe ke wena menyakong ya hao; ya sa hlwekang le ya hlwekileng ba je jwalokaha ho jewa tshephe le kgama.",
"23": "<sup>23</sup> Feela o se ke wa ja madi; o a tshollele fatshe jwaloka metsi."
},
"16": {
"1": "<sup>1</sup> Elellwa kgwedi ya Abibe, mme o etsetse Jehova, Modimo wa hao, Paseka ka yona; hobane ke ka kgwedi ya Abibe, Jehova, Modimo wa hao, a o ntshitseng naheng ya Egepeta bosiu.",
"2": "<sup>2</sup> O tla hlabela Jehova, Modimo wa hao, Paseka, o mo hlabele dikgomo le dinku tsa hao, nqalong eo Jehova a tla e kgetha ho bea lebitso la hae ho yona.",
"3": "<sup>3</sup> O se ke wa jellela Paseka le bohobe bo lomositsweng; ka matsatsi a supileng, o je mahobe a sa lomoswang, mahobe a mahlomola; kahobane o tswile naheng ya Egepeta ka potlako; o tle o hopole ka matsatsi wohle a ho phela ha hao letsatsi leo o tswileng naheng ya Egepeta ka lona.",
"4": "<sup>4</sup> Ka matsatsi a supileng ho se ke ha bonwa ditomoso ha hao, naheng yohle ya hao; haele nama ya sehlabelo seo o se etsang ka mantsiboya a letsatsi la pele, e ka kgona ho se ke ha salla hosanane letho.",
"5": "<sup>5</sup> O se ke wa hlaba Paseka ho ofe kapa ofe wa metse ya hao, eo Jehova, Modimo wa hao, a o neang yona;",
"6": "<sup>6</sup> e mpe e be nqalong eo Jehova, Modimo wa hao, a tla e kgetha ho bea lebitso la hae ho yona; ke hona moo o tla hlaba Paseka, mantsiboya ha letsatsi le dikela, nakong e jwaloka eo o tswileng Egepeta ka yona.",
"7": "<sup>7</sup> O tla e apeha, o e je nqalong eo Jehova, Modimo wa hao, a tla e kgetha, mme hosasane o kgutle, o boele ditenteng tsa hao.",
"8": "<sup>8</sup> Ka matsatsi a tsheletseng, o je bohobe bo sa lomoswang; haele letsatsi la bosupa ke la phutheho e kgolo ya Jehova, Modimo wa hao; o se ke wa etsa mosebetsi leha o le mong ka lona.",
"9": "<sup>9</sup> O tla bala diveke tse supileng, o qale ho bala diveke tse supileng hona ka nako eo o kenyang sekele korong ya hao ka yona;",
"10": "<sup>10</sup> mme o etsetse Jehova, Modimo wa hao, mokete wa Diveke, o abele Modimo kabelo kamoo matsoho a hao a ratang ho leboha kateng, o nee ho seo Jehova, Modimo wa hao, a o hlohonolofaditseng ka sona.",
"11": "<sup>11</sup> O thabe pela Jehova, Modimo wa hao, wena, le mora wa hao, le moradi wa hao, le mohlanka wa hao e motona, le e motshehadi, le Molevi ya menyakong ya hao, le moditjhaba, le kgutsana, le mosadi wa mohlolohadi ya leng ha eno, nqalong eo Jehova, Modimo wa hao, a tla e kgetha ho bea lebitso la hae ho yona.",
"12": "<sup>12</sup> O tla hopola hobane o bile mofo Egepeta, o boloke melao eo, mme o etse ka yona.",
"13": "<sup>13</sup> Ha o se o bokeletse hae tsa diotlo le tsa dihatelo tsa hao, o tla etsa mokete wa metlotlwane ka matsatsi a supileng.",
"14": "<sup>14</sup> Mokete oo wa hao o thabelwe ke wena, le ke mora wa hao, le ke moradi wa hao, le mohlanka wa hao e motona, le e motshehadi, le Molevi, le moditjhaba, le kgutsana, le mosadi wa mohlolohadi, ba ahileng menyakong ya hao.",
"15": "<sup>15</sup> Etsetsa Jehova, Modimo wa hao, mokete wa matsatsi a supileng, nqalong eo Jehova a tla e kgetha; hobane Jehova, Modimo wa hao, o tla o hlohonolofatsa kotulong yohle ya hao, le mesebetsing yohle ya matsoho a hao; mme o tla thaba kannete.",
"16": "<sup>16</sup> Hararo ka selemo, ba batona bohle ba heno ba tla itlhahisa pela Jehova, Modimo wa hao, nqalong eo a tla e kgetha, mohla mokete wa mahobe a sa lomoswang, le mohla mokete wa Diveke, le mohla mokete wa Metlotlwane: ba se ke ba itlhahisa pela Jehova ba le feela;",
"17": "<sup>17</sup> ba mpe ba tle, e mong le e mong ka mpho ya matsoho a hae, le kamoo Jehova, Modimo wa hao, a o hlohonolofaditseng kateng.",
"18": "<sup>18</sup> Bea baahlodi le dihlooho metseng yohle ya hao, eo Jehova, Modimo wa hao, a o neang yona melokong ya hao, ba tle ba ahlole setjhaba ka kahlolo ya ho loka.",
"19": "<sup>19</sup> O se ke wa fapoha ho loka, mme o se ke wa ya ka tshobotsi ya batho; o se ke wa amohela dimpho; hobane mpho e foufatsa mahlo a ba bohlale, mme e kgopamisa dipolelo tsa ba lokileng.",
"20": "<sup>20</sup> O ye ka ho lokileng ruri, o tle o phele, mme o rue lefatshe leo Jehova, Modimo wa hao, a o neang lona.",
"21": "<sup>21</sup> O se ke wa hloma diashera tsa sefate sefe le sefe pela aletare ya Jehova, Modimo wa hao, eo o tla iketsetsa yona.",
"22": "<sup>22</sup> Leha e le setshwantsho, o se ke wa iketsetsa sona, hobane Jehova, Modimo wa hao, o hloile ntho tseo."
},
"17": {
"1": "<sup>1</sup> O se ke wa hlabela Jehova, Modimo wa hao, kgomo, leha e le nku, e nang le sekodi kapa molato o mong; hobane hoo ke manyala ho Jehova, Modimo wa hao.",
"2": "<sup>2</sup> Ha ho fumanwa ha eno, motseng o mong wa eo Jehova, Modimo wa hao, a tla o nea yona, monna, kapa mosadi ya etsang bobe pela Jehova, Modimo wa hao, ka ho tlola selekane sa hae;",
"3": "<sup>3</sup> leha e le ya yang ho sebeletsa le ho kgumamela medimo esele, leha e ka ba letsatsi, kapa kgwedi, kapa makgotla wohle a dinaledi tsa lehodimo, e leng taba eo ke sa kang ka o laela yona;",
"4": "<sup>4</sup> ha o ka bolellwa, wa utlwa hoo, batlisisa hantle, mme ha o fumana hobane taba e boletsweng ke ya nnete, mme ho tiiswa hore manyala a itseng a entswe Iseraeleng;",
"5": "<sup>5</sup> ntsha monna eo, kapa mosadi eo, ya entseng taba eo e mpe, o mo ise dikgorong tsa hao; mme kapa e leng monna, kapa e leng mosadi, o tle o mo tlepetse ka majwe, a shwe.",
"6": "<sup>6</sup> Ya tshwanelwang ke lefu, a bolawe ka melomo ya dipaki tse pedi, kapa tse tharo; empa a se ke a bolawa ka molomo wa paki e le nngwe.",
"7": "<sup>7</sup> Matsoho a dipaki e be wona a bewang pele hodima hae ho mmolaya, e ntano ba matsoho a batho bohle. Tlosa bobe haeno jwalo.",
"8": "<sup>8</sup> Ekare ha ho hlaha taba e thata, eo o sitwang ho e ahlola mahareng a madi le madi, le mahareng a nyewe le nyewe, le mahareng a leqeba le leqeba, e leng ditaba tse tsekwang metseng ya hao, teng o tla tloha, o nyolohele nqalong eo Jehova, Modimo wa hao, a tla e kgetha;",
"9": "<sup>9</sup> o tla ya ho baprista ba Balevi, le ho moahlodi ya tla bang teng mohlang oo, o ba botse; mme ba tla o tsebisa kahlolo e loketseng.",
"10": "<sup>10</sup> O tla etsa ka tseo ba tla o bolella tsona nqalong e tla kgethwa ke Jehova, o hlokomele ho etsa ka tsohle tseo ba tla o ruta tsona.",
"11": "<sup>11</sup> O etse se bolelwang ke molao oo ba tla o ruta ka wona, le ka kahlolo eo ba tla o bolella yona; o se fapohe taba tseo ba tla o bolella tsona ka ho ya ka letsohong le letona, leha e le ho le letshehadi.",
"12": "<sup>12</sup> Haele motho ya etsang ka boikgohomoso, ya hanang ho utlwa moprista ya emeng hona teng ho sebeletsa Jehova, Modimo wa hao, kapa moahlodi, motho eo a shwe, mme o tlose bobe Iseraeleng.",
"13": "<sup>13</sup> Batho bohle ba tla utlwa, ba tshabe, mme ba ke ke ba hlola ba ikgantsha le ka mohla o le mong.",
"14": "<sup>14</sup> Etlare hobane o kene naheng eo Jehova, Modimo wa hao, a o neang yona, ha o se o e ruile, o ahile ho yona, leha o ka re: Ke tla ipeela morena jwaloka ditjhaba tsohle tse nteetseng hare;",
"15": "<sup>15</sup> o ipeele morena ya tla kgethwa ke Jehova, Modimo wa hao; motho ya tla bewa morena ke wena, e be e mong wa banabeno; o ke ke wa bea moditjhaba, e leng motho eo e seng ngwaneno.",
"16": "<sup>16</sup> Feela a se ke a ipokellela dipere tse ngata, mme a se ke a busetsa setjhaba Egepeta, ho bokella dipere tse ngata; hobane Jehova o le boleletse, a re: Le se ke la boela la tsamaya ka tsela eo.",
"17": "<sup>17</sup> Hape, a se ke a nyala basadi ba bangata, pelo ya hae e tle e se ke ya kgeloha; silefera le kgauta a se ke a ipokellela tsona haholo.",
"18": "<sup>18</sup> Etlare hobane a dule setulong sa borena ba hae, a ingolle buka ya molao oo, a nke ditaba bukeng e leng ho baprista ba Balevi.",
"19": "<sup>19</sup> Buka eo e dule ho yena, a e bale ka matsatsi wohle a ho phela ha hae, a tle a ithute ho tshaba Jehova, Modimo wa hae, le ho boloka ditaba tsohle tsa molao ona, le tsa taelo tsena, mme a etse ka tsona.",
"20": "<sup>20</sup> Pelo ya hae e tle e se ke ya ikgohomosetsa banababo, mme a se ke a kgeloha molao ona ho ya ka letsohong le letona, kapa ho le letshehadi, a tle a ngatafatse matsatsi a hae a puso ya hae, e le yena le bana ba hae, hara setjhaba sa Iseraele."
},
"18": {
"1": "<sup>1</sup> Baprista ba Balevi, leloko lohle la Levi, ba ke ke ba eba le kabelo, leha e le lefa, jwaloka Baiseraele ba bang; ba tla ja mahlabelo a Jehova a ditjheso, le lefa la hae.",
"2": "<sup>2</sup> Ba ke ke ba eba le lefa hara banababo bona; Jehova ke lefa la bona, jwalokaha a ba boleletse.",
"3": "<sup>3</sup> Tseo baprista ba tla ba le tokelo ya ho di nka ho ba hlahisetsang Modimo sehlabelo, ke tsena: leha e ka ba kgomo, kapa nku, ho newe moprista letsoho, le dihlaya, le mohodu.",
"4": "<sup>4</sup> O mo nee le dilopotsiya tsa koro ya hao, le tsa veine e ntjha ya hao, le tsa ole ya hao, le dilopotsiya tsa boya ba dinku tsa hao.",
"5": "<sup>5</sup> Hobane Jehova, Modimo wa hao o mo kgethile hara meloko ya hao yohle, hore a eme pela hae ho sebetsa ka lebitso la Jehova, e le yena le bara ba hae kamehla.",
"6": "<sup>6</sup> Ekare ha Molevi a etswa motseng o mong wa metse ya hao, nqalong tsohle tse Iseraeleng tseo a ahileng ho tsona, mme a etla ka takatso yohle ya moya wa hae nqalong eo Jehova a tla e kgetha;",
"7": "<sup>7</sup> o tla etsa tshebeletso ya teng ka lebitso la Jehova, Modimo wa hae, jwaloka banababo bohle ba Balevi ba emang teng pela Jehova,",
"8": "<sup>8</sup> a je kabelo e tshwanang le tsa ba bang, ho sa balwe seo a ka bang le sona ka thekiso ya ntho tsa baholo ba hae.",
"9": "<sup>9</sup> Etlare hobane o kene lefatsheng leo Jehova, Modimo wa hao, a o neang lona, o ke ke wa ithuta ho etsa ka manyala a ditjhaba tsa teng.",
"10": "<sup>10</sup> Ho se ke ha fumanwa haeno motho ya fetisang mora wa hae, leha e le moradi wa hae mollong, leha e le mophofi ya phofang, kapa selaodi se laolang, kapa senohe, kapa moloi,",
"11": "<sup>11</sup> le moupelli, leha e le ya botsang badimo, le ngaka e reng e a porofeta, leha e le ya botsang bafu;",
"12": "<sup>12</sup> hobane bohle ba etsang ditaba tseo, ba manyala ho Jehova, mme ke ka baka la manyala ao Jehova, Modimo wa hao, a falatsang ditjhaba tseno pela hao.",
"13": "<sup>13</sup> O be wa Jehova, Modimo wa hao, ka botho ba hao bohle.",
"14": "<sup>14</sup> Hobane ditjhaba tseno o tla rua lefatshe la tsona, di mamela dilaodi le dinohe; empa haele wena, Jehova, Modimo wa hao, ha a ka a o dumella ho etsa tse jwalo.",
"15": "<sup>15</sup> Jehova, Modimo wa hao, o tla o hlahisetsa moporofeta ya tswang haeno, hara banabeno ya jwaloka nna; le tla utlwa yena;",
"16": "<sup>16</sup> jwaloka ha o kile wa kopa ho Jehova, Modimo wa hao, Horebe, tsatsing la phutheho, wa re: Ke se ke ka boela ka utlwa lentswe la Jehova, Modimo wa ka; mme ke se hlole ke bona mollo oo o moholo, ke tle ke se ke ka shwa:",
"17": "<sup>17</sup> mme Jehova a re ho nna: Seo ba se boletseng ba se buile hantle;",
"18": "<sup>18</sup> ke tla ba hlahisetsa moporofeta ya tswang hara banababo bona, ya jwaloka wena; ke tla bea mantswe a ka molomong wa hae, mme o tla ba bolella tsohle tseo ke tla mo laela tsona.",
"19": "<sup>19</sup> Etlare ha e mong a ka hana ho utlwa mantswe a ka ao a tla a bolela ka lebitso la ka, ke nna ke tla mmotsa hoo.",
"20": "<sup>20</sup> Empa haele moporofeta ya ipeang ka boikgohomoso hore a bolele ka lebitso la ka taba eo ke sa kang ka mo laela yona hore a e bolele, leha mohlomong a bua ka lebitso la medimo esele, moporofeta eo a shwe.",
"21": "<sup>21</sup> Ekare ha o re pelong ya hao: Na re tla kgetha jwang lentswe le sa kang la bolelwa ke Jehova?",
"22": "<sup>22</sup> ke re: Etlare moporofeta eo, ha a bolela taba ka lebitso la Jehova, mme taba e boletsweng ke yena e sa hlahe, e sa etsahale etlaba ke taba eo Jehova a sa kang a e bolela; moporofeta eo o e boletse ka boikgohomoso; se mo tshabe."
},
"19": {
"1": "<sup>1</sup> Etlare hobane Jehova, Modimo wa hao, a fedise ditjhaba tseo Jehova, Modimo wa hao, a o neang lefatshe la tsona, mme o se o ruile lefatshe la bona, mme o ahile metseng ya bona le matlung a bona,",
"2": "<sup>2</sup> o tla ikgethela metse e meraro lefatsheng leo Jehova, Modimo wa hao, a o fang lona ho le rua.",
"3": "<sup>3</sup> O tla lokisa ditsela, mme o tla arola dinaha tsa lefatshe leo Jehova o a fang lona ho le rua, o etse dikarolo tse tharo, hore mmolai e mong le e mong a balehele teng.",
"4": "<sup>4</sup> Haele mmolai ya ka balehelang teng ho boloka ho phela ha hae, ha e ke e be ya tshohileng a bolaya wa habo a sa rate, eo a neng a sa mo hloya maoba le maobane.",
"5": "<sup>5</sup> Jwaloka e mong ha a ka ya le wa habo morung ho rema difate, mme ha a otlolla letsoho la hae ho rema sefate ka selepe, tshepe ya pshemoha morianeng, mme wa habo a batwa ke yona, a shwa; motho eo a ke a balehele ho o mong wa metse eo, mme a pholohe;",
"6": "<sup>6</sup> esere mohlomong mophetetsi wa madi a phallela mmolai, ha pelo ya hae e sa le bohale, mme ha tsela e le telele, a mo tshwara, mme a mmolaya, leha a sa tshwanelwa ke lefu; athe o ne a sa hloya wa habo maobane le maoba.",
"7": "<sup>7</sup> Ke ka baka leo ke o laelang, ke re: Ikgethele metse e meraro.",
"8": "<sup>8</sup> Etlare ha Jehova, Modimo wa hao, a namisa meedi ya hao, kamoo a anetseng bontatao kateng, mme a o nea lefatshe lohle leo a le baletseng bontatao hore o tla ba fa lona;",
"9": "<sup>9</sup> ha efela wena o boloka ditaelo tsohle tseo ke o laelang tsona kajeno, o rata Jehova, Modimo wa hao, mme o tsamaya kamehla tseleng tsa hae, o tla eketsa metse eo e meraro ka metse e meng e meraro,",
"10": "<sup>10</sup> hore madi a se nang molato a se ke a tshollwa lefatsheng la hao, leo Jehova, Modimo wa hao, a o fang lona ho le rua, mme molato wa madi o be siyo ho wena.",
"11": "<sup>11</sup> Empa ekare ha e mong a hloile wa habo, a mo lalla, a mo tsohela matla, mme a mmolaya a eshwa, mme a balehela ho o mong wa metse eo,",
"12": "<sup>12</sup> moo, baholo ba motse wa habo ba tla romela ho mo ntsha teng, ba mo neele matsohong a mophetetsi wa madi, a tle a shwe.",
"13": "<sup>13</sup> Mahlo a hao a se ke a mo qenehela, o mpe o tlose Iseraeleng madi a se nang molato, o tle o be le lehlohonolo.",
"14": "<sup>14</sup> O se ke wa suthisa mekolokotwane ya wa heno e beilweng ke baholo ba hao, lefeng leo o tla le rua naheng eo Jehova, Modimo wa hao, a o fang yona hore o e rue.",
"15": "<sup>15</sup> Paki e le nngwe e ke ke ya lekana ho bea motho molato wa bokgopo, kapa wa sebe sefe le sefe, kapa wa tshito efe le efe eo a ka beng a sitilwe ka yona; empa taba e tla tiiswa ke melomo ya paki tse pedi, kapa ke melomo ya dipaki tse tharo.",
"16": "<sup>16</sup> Ekare ha paki ya leshano e ema ho qosa motho ka taba ya molato,",
"17": "<sup>17</sup> batho ba babedi ba nang le nyewe hammoho, ba tla hlaha pela Jehova, pela baprista le baahlodi ba leng teng mehleng eo;",
"18": "<sup>18</sup> Baahlodi ba tla batlisisa haholo, mme ha ho fumanwa hobane paki eo ke paki ya leshano e qositseng ngwanabo yona ka leshano,",
"19": "<sup>19</sup> moo le tla etsa ho motho eo jwalokaha a ne a hopotse ho etsa ho ngwanabo. Tlosa bobe haeno jwalo.",
"20": "<sup>20</sup> Ba bang ba tla utlwa hoo, ba tla tshaba, mme ba ke ke ba etsa bobe bo bokalo haeno le ka mohla o le mong.",
"21": "<sup>21</sup> Mahlo a hao a se ke a mo qenehela; bophelo bo lefuwe ka bophelo, leihlo ka leihlo, leino ka leino, letsoho ka letsoho, le leoto ka leoto."
},
"20": {
"1": "<sup>1</sup> Etlere ha o futuhela dira tsa hao, mme o bona dipere, le makoloi, le batho ba o fetisang ka bongata, o se ke wa ba tshaba, hobane Jehova, Modimo wa hao, ya o ntshitseng naheng ya Egepeta, o na le wena.",
"2": "<sup>2</sup> Etlere ha le se le ya lwana, moprista a ke a atamele, a bue le setjhaba,",
"3": "<sup>3</sup> a re ho bona: Baiseraele, mamelang! Kajeno, le ya atamela dira tsa lona ho di lwantsha. Pelo tsa lona di se ke tsa fokola, mme le se tshabe, le se makale, mme le se tshohe ka baka la tsona;",
"4": "<sup>4</sup> hobane Jehova, Modimo wa lona, o tsamaya le lona ho le lwantshetsa dira tsa lona, le ho le namolela.",
"5": "<sup>5</sup> Bahlahlobi ba tla bua le setjhaba, ba re: Motho ke ofe ya hahileng ntlo e ntjha, mme ha a eso ho e kgakole na? A ke a tlohe, a kgutlele tlung ya hae, esere mohlomong a shwa ntweng, mme ya kgakolwa ke e mong.",
"6": "<sup>6</sup> Motho ke ofe ya hlomileng morara, mme ha a eso ho kge ditholwana tsa wona na? a ke a tlohe, a kgutlele tlung ya hae, esere mohlomong a shwa ntweng, mme ditholwana tsa wona tsa kguwa ke e mong.",
"7": "<sup>7</sup> Motho ke ofe ya lebeleditseng mosadi, mme ha a eso ho mo nyale? A ke a tlohe, a kgutlele tlung ya hae, esere mohlomong a shwa ntweng, mme mosadi a nyalwa ke e mong.",
"8": "<sup>8</sup> Bahlahlobi ba tla eketsa ho bua le setjhaba, ba re: Motho ya lekwala, ya nang le pelo e boi, ke ofe na? A ke a tlohe, a kgutlele tlung ya hae, esere mohlomong pelo tsa banababo tsa qhibidiha jwaloka ya hae.",
"9": "<sup>9</sup> Mme etlare ha bahlahlobi ba qetile ho bua le setjhaba, ba tla bea balaodi ba makgotla ho tsamaisa setjhaba.",
"10": "<sup>10</sup> Etlere ha o atametse motse ho o lwantsha, o o beele tsa kgotso;",
"11": "<sup>11</sup> mme ekare ha batho ba motse ba o nea karabo ya kgotso, mme ba o bulela dikgoro tsa wona, batho bohle ba wona ba tla o ntshetsa lekgetho, ba o sebeletse.",
"12": "<sup>12</sup> Ha ba hana ho etsa kgotso le wena, ba mpa ba re ba lwana le wena, teng o tla thibella motse.",
"13": "<sup>13</sup> Ha Jehova, Modimo wa hao, a o neela matsohong a hao, o tla bolaya ba batona bohle ka bohale ba lerumo.",
"14": "<sup>14</sup> Haele basadi, le bana, le dikgomo, le tsohle tsa motse, thepa yohle ya wona, o ikgapele tsona, mme o je thepa ya dira tsa hao, eo o e neilweng ke Jehova, Modimo wa hao.",
"15": "<sup>15</sup> Etsa jwalo ka metse yohle e hole haholo le wena, eo e seng metse ya ditjhaba tsena.",
"16": "<sup>16</sup> Empa haele metse ya ditjhaba tsena Jehova, Modimo wa hao, a o fang lefatshe la tsona ho le rua, o se ke wa lesa ntho e phefumolohang e phela;",
"17": "<sup>17</sup> o mpe o ba neele anathema e leng Bahethe, le Baamore, le Bakanana, le Baferese, le Baheve, le Bajebuse, jwalokaha Jehova, Modimo wa hao, a o laetse;",
"18": "<sup>18</sup> hore ba tle ba se ke ba le ruta ho etsa manyala wohle a bona, e leng manyala ao ba a etsetsang medimo ya bona, mme le se sitelwe Jehova, Modimo wa lona.",
"19": "<sup>19</sup> Etlare ha o thibella motse o mong ka matsatsi a mangata o ntse o o lwantsha ho o kena, o ke ke wa senya difate ka ho di rema ka selepe, o mpe o je ditholwana tsa tsona, mme o se ke wa di rema hore o ithuse ka tsona. Hobane sefate se naheng na ke motho hore se lwantshwe ke wena na?",
"20": "<sup>20</sup> Empa difate tseo le tsebang hobane ha se tse behang dijo, o ka di senya wa di rema, mme ka tsona wa haha mesebetsi ya ho thibella motse o nang le ntwa le wena o be o kenwe ke wena."
},
"21": {
"1": "<sup>1</sup> Etlare lefatsheng leo Jehova, Modimo wa hao, a o fang lona ho le rua, ha setopo sa motho ya bolailweng, se fumanwa se rapaletse naheng, ho sa tsejwe ya mmolaileng;",
"2": "<sup>2</sup> baholo ba hao le baahlodi ba hao ba tla tswa, ba lekanye sebaka se tlohang ho motho ya bolailweng ho isa metseng e kamathokong ka nqa tsohle.",
"3": "<sup>3</sup> Ha ho tsebilwe motse o leng haufi le motho ya bolailweng, baholo ba motse oo ba tla nka kgomo ya sethole eo ho esong ho sebetswe ka yona, e esong ho hule jokong;",
"4": "<sup>4</sup> baholo ba motse oo ba tla theosetsa sethole seo molapong oo metsi a wona a mathang kamehla, moo ho sa lengweng, le moo ho sa jalweng, mme teng molapong, ba tla roba molala wa sethole seo.",
"5": "<sup>5</sup> Baprista, bara ba Levi, ba tla atamela; hobane ke bona ba kgethilweng ke Jehova, Modimo wa hao, hore ba mo sebeletse le ho hlohonolofatsa ka lebitso la Jehova, le hore dinyewe tsohle le dikotsi tsohle di ahlolwe ke melomo ya bona.",
"6": "<sup>6</sup> Baholo bohle ba motse oo o leng haufi le motho ya bolailweng, ba tla hatlela matsoho hodima sethole seo se robilweng molala molapong.",
"7": "<sup>7</sup> Ba tla bolela, ba re: matsoho a rona ha a ka a tsholla madi ana, le mahlo a rona ha a ka a bona letho.",
"8": "<sup>8</sup> Oho Jehova, o tshwarele setjhaba sa hao sa Iseraele, seo o se lopolotseng, mme o se ke wa balla setjhaba sa hao sa Iseraele madi a se nang molato. Mme ba tla leselwa molato wa madi ao.",
"9": "<sup>9</sup> Ke moo o tla tlosa madi a se nang molato haeno, ha o entse se lokileng pela Jehova.",
"10": "<sup>10</sup> Etlare ha o futuhela dira tsa hao, mme Jehova, Modimo wa hao, a di neela matsohong a hao, mme o kgutla o ena le bao o ba hapileng;",
"11": "<sup>11</sup> ha o bona hara ba hapilweng mosadi e motle, mme o mo rata, o mo nka hore e be mosadi wa hao;",
"12": "<sup>12</sup> o tla mo isa tlung ya hao; a beole hlooho ya hae, a pome dinala tsa hae;",
"13": "<sup>13</sup> a hlobole diaparo tsa hae tsa bohapuwa, mme a dule tlung ya hao, a llele ntatae le mmae ka kgwedi e le nngwe; o ntoo kena ho yena, o be monna wa hae, yena e be mosadi wa hao.",
"14": "<sup>14</sup> Empa mohlomong, ha o se o sa kgahliswe ke yena, o tla mo lesela, a ye moo a ratang teng; o se ke wa reka tjhelete ka yena, leha e le ho mo etsa lekgoba, hobane o mo kokobeditse.",
"15": "<sup>15</sup> Ekare ha motho a ena le basadi ba babedi, e mong e le ya ratwang, e mong e le ya hloilweng, mme ya ratwang le ya sa ratweng ba mo tswaletse bana, mme mora wa letsibolo e le mora wa mosadi ya hloilweng;",
"16": "<sup>16</sup> mohla ntata bona a abelang bana ba hae lefa la tseo a nang le tsona, a ke ke a bea mora wa ya ratilweng e moholo bakeng sa mora wa ya hloilweng, e leng yena letsibolo;",
"17": "<sup>17</sup> a mpe a tiise boholo ba mora wa ya hloilweng ka ho mo nea kabelo tse pedi tsa dintho tsohle tsa hae, hobane ke yena sehlooho sa bonna ba hae; tokelo ya letsibolo ke ya hae.",
"18": "<sup>18</sup> Etlare ha motho a ena le mora ya lonya, ya ikgantshang, ya hanang ho utlwa lentswe la ntatae le lentswe la mmae, mme leha ba ntse ba mo laya, a ntse a hana ho ba utlwa;",
"19": "<sup>19</sup> ntatae le mmae ba tla mo tshwara, ba mo tlise ho baholo ba motse wa habo, kgorong ya motse wa habo;",
"20": "<sup>20</sup> ba bolelle baholo ba motse wa habo, ba re: Mora enwa wa rona o lonya, o a ikgantsha; o hana ho utlwa lentswe la rona; ke mohlakafollela, hape ke letahwa.",
"21": "<sup>21</sup> Jwale batho bohle ba motse wa habo ba tla mo tlapunya ka majwe, a shwe. Tlosa bobe haeno jwalo, hore Baiseraele bohle ba utlwe, mme ba tshabe.",
"22": "<sup>22</sup> Etlere ha motho a entse sebe se lokelwang ke lefu, mme a bolawa, wa mo fanyeha sefateng,",
"23": "<sup>23</sup> setopo sa hae se se ke sa sala sefateng bosiu bohle, o mpe o se epele ka lona letsatsi leo; hobane ya fanyehilweng o rohakilwe ke Modimo, mme ha o na ho silafatsa lefatshe leo Jehova, Modimo wa hao, a o fang lona ho le rua."
},
"22": {
"1": "<sup>1</sup> Etlere ha o bona kgomo ya ngwaneno, kapa nku ya hae, di lahlehile, o se ke wa di fapoha, o mpe o di busetse ho ngwaneno.",
"2": "<sup>2</sup> Ekare ha ngwaneno a sa aha haufi le wena, mohlomong o sa mo tsebe, o di tlise hae, di dule ho wena, ngwaneno a be a tle ho di batla, e be moo o di busetsang ho yena.",
"3": "<sup>3</sup> Etsa jwalo le ka esele ya hae; etsa jwalo le ka diaparo tsa hae, le ka dintho tsohle tsa ngwaneno, tse lahlehileng. Ha o di bona di lahlehile, o se ke wa di fapoha.",
"4": "<sup>4</sup> Etlere ha o bona esele ya ngwaneno, kapa kgomo ya hae, di wetse tseleng, o se ke wa di fapoha; o mpe o mo thuse ho di tsosa.",
"5": "<sup>5</sup> Mosadi a se ke a apara diaparo tsa monna, mme monna a se ke a apara diaparo tsa mosadi; hobane bohle ba etsang jwalo, ba manyala ho Jehova, Modimo wa hao.",
"6": "<sup>6</sup> Etlere ha o tshoha o bona tseleng hodima sefate, kapa fatshe, sehlaha sa dinonyana se nang le madinyane, kapa mahe, mma wona a alamile madinyane, kapa mahe, o se ke wa nka nonyana le madinyane a yona;",
"7": "<sup>7</sup> o nke madinyane, mme o tlohele mma wona, o tle o be le lehlohonolo, mme o ngatafatse matsatsi a hao.",
"8": "<sup>8</sup> Etlere ha o haha ntlo e ntjha, o tle o etse lehora le potang marulelo a hao, esere mohlomong ntlo ya hlahelwa ke molato wa madi a motho ya leng hodima yona, a wela fatshe.",
"9": "<sup>9</sup> O se ke wa jala peo tsa mefuta tshimong ya hao ya morara, esere ho beha ha tseo o di jadileng, le ho beha ha morara, tsa o senyehela.",
"10": "<sup>10</sup> O se ke wa lema ka kgomo le esele di bofilwe hammoho.",
"11": "<sup>11</sup> O se ke wa apara seaparo se lohilweng ka dintho tse sa tshwaneng, jwaloka boya ba dinku le lene hammoho.",
"12": "<sup>12</sup> Etsa ditjellane masotong a mane a kobo eo o ikapesang ka yona.",
"13": "<sup>13</sup> Etlare ha monna e mong a nyala mosadi, mme a ya ho yena, a ntoo mo hloya,",
"14": "<sup>14</sup> mme a mo tlama ka ditaba tse mpehadi, tse senyang lebitso la hae, a mo hobosa, a re: Ke nkile mosadi eo, mme ha ke tlile ho yena, ha ke a ka ka fumana dipontsho tsa borwetsana ho yena;",
"15": "<sup>15</sup> moo ntata morwetsana le mmae ba tla nka dipontsho tsa borwetsana ba mosadi eo, ba di hlahise pela baholo ba motse, kgorong.",
"16": "<sup>16</sup> Ntata morwetsana o tla bolella baholo, a re: Ke neile monna enwa moradi wa ka hore e be mosadi wa hae, mme jwale o mo hloile;",
"17": "<sup>17</sup> bonang, o mmeile taba tse mpehadi, a re: Ha ke a ka ka fumana dipontsho tsa borwetsana ho moradi wa hao. Athe bonang, dipontsho tsa borwetsana tsa moradi wa ka ke tsena. Jwale ba tla phutholla kobo pela baholo ba motse.",
"18": "<sup>18</sup> Baholo ba motse oo ba tla tshwara monna eo, ba mo otle.",
"19": "<sup>19</sup> Mme kahobane o hobositse morwetsana wa Iseraele ka ho senya lebitso le hae, ba tla mo lefisa ka dishekele tse lekgolo tsa silefera, tse tla newa ntata morwetsana; mme e tla nne e be mosadi wa hae; a ke ke a mo hlala, ha a ntse a phela.",
"20": "<sup>20</sup> Empa etlare ha taba e boletsweng ke yena e le ya nnete, e reng, dipontsho tsa borwetsana ha di a ka tsa fumanwa ho morwetsana eo;",
"21": "<sup>21</sup> ba tla ntsha morwetsana, ba mo tlise pela monyako wa ntlo ya ntatae, mme batho ba motse oo ba tla mo tlapunya ka majwe, a shwe, kahobane o entse manyala Iseraeleng, ka ho ineela bohlola tlung ya ntatae. Tlosa bobe haeno jwalo.",
"22": "<sup>22</sup> Ha ho ka fumanwa monna ya robalang le mosadi ya nyetsweng ke e mong, ba shwe ba babedi, monna le mosadi ba robetseng hammoho. Tlosa bobe jwalo Iseraeleng.",
"23": "<sup>23</sup> Etlare ha morwetsana a lebeleditswe ke monna, mme monna e mong a mo fumana motseng, a robala le yena,",
"24": "<sup>24</sup> moo le tla ba ntsha ba babedi, le ba ise kgorong ya motse, mme le ba tlapunye ka majwe, ba shwe: morwetsana, kahobane ha a ka a memetsa a le motseng, monna, kahobane a sentse mosadi wa ngwanabo. Tlosa bobe haeno jwalo.",
"25": "<sup>25</sup> Etlare ha monna a fumana naheng morwetsana ya lebeleditsweng, mme monna eo a mmeta, a robala le yena, moo monna ya robetseng le morwetsana eo o tla shwa yena a nnotshi.",
"26": "<sup>26</sup> Haele morwetsana, o ke ke wa mo etsa letho; morwetsana ha a ka a etsa sebe se tshwanelang lefu; hobane taba eo e dutse jwaloka ya motho ha a tsohela e mong matla, mme a mmolaya;",
"27": "<sup>27</sup> hobane morwetsana ya lebeleditsweng o fumanwe ke eo naheng, mme o memeditse, mme ho ne ho se e mong ya ka mo namolelang.",
"28": "<sup>28</sup> Etlare ha monna a fumana morwetsana ya sa lebeletswang, mme a mmeta, a robala le yena, mme ba bonwa;",
"29": "<sup>29</sup> monna ya robetseng le yena o tla nea ntata morwetsana dishekele tse mashome a mahlano tsa silefera, mme morwetsana e tla ba mosadi wa hae, kahobane o mo tlotlolotse; mme a ke ke a mo lahla, ha a ntse a phela.",
"30": "<sup>30</sup> Monna a se ke a nka mosadi wa ntatae, mme a se ke a apola kobo ya ntatae."
},
"23": {
"1": "<sup>1</sup> Monna ya lehaole, kapa e leng ya entsweng lona ka kotsi, kapa e leng ya entsweng lona ke batho ka thipa, a ke ke a kena phuthehong ya Jehova.",
"2": "<sup>2</sup> Ya tswetsweng ka bohlola a ke ke a kena phuthehong ya Jehova, esita le ditlohotloholwana tsa hae tsa leloko la leshome di ke ke tsa kena phuthehong ya Jehova.",
"3": "<sup>3</sup> Moammone le Momoabe ba ke ke ba kena phuthehong ya Jehova; esita le ditlohotloholwana tsa bona tsa leloko la leshome di ke ke tsa kena phuthehong ya Jehova, le ka mohla o le mong;",
"4": "<sup>4</sup> kahobane ha ba ka ba tla le kgahlanyetsa tseleng ka bohobe le ka metsi, mohla le tswang Egepeta; le kahobane ba ne ba putse Balaame, mora Peore, wa Pethore naheng ya Mesopotamia, hore a o rohake.",
"5": "<sup>5</sup> Leha ho le jwalo, Jehova, Modimo wa hao, ha a ka a dumela ho utlwa Balaame, empa Jehova, Modimo wa hao, thohako eo o o fetoletse yona hlohonolofatso, kahobane Jehova, Modimo wa hao, o a o rata.",
"6": "<sup>6</sup> O se ke wa ba batlela kgotso, leha e le molemo, ka matsatsi wohle a hao.",
"7": "<sup>7</sup> O se ke wa hloya Moedomo, hobane ke ngwaneno; o se ke wa hloya Moegepeta, hobane o ne o le mojaki naheng ya hae.",
"8": "<sup>8</sup> Bana ba bona, ba tswallwang bona molokong wa boraro wa ditloholwana, ba tla kena phuthehong ya Jehova.",
"9": "<sup>9</sup> Ha o futuhela dira tsa hao, o itshabise tsohle tse mpe.",
"10": "<sup>10</sup> Ekare ha e mong wa heno a sa hlweka ka baka la taba e mo hlahetseng bosiu, a tswele kantle ho diahelo, mme a se ke a kena diahelong.",
"11": "<sup>11</sup> Ha e se e batla e eba mantsiboya, a ke a itlhatswe ka metsi, mme a boele diahelong, ha letsatsi le diketse.",
"12": "<sup>12</sup> O be le nqalo kantle ho diahelo eo o tswelang ho yona, mohlabeng.",
"13": "<sup>13</sup> O be le kepa diphahlong tsa hao, mme ha o etswa ho ya dula kantle, o tjheke sekoti ka yona, o ntoo kwahela se tswileng ho wena.",
"14": "<sup>14</sup> Hobane Jehova, Modimo wa hao, o tsamaya hara diahelo tsa hao ho o boloka, le ho neela dira tsa hao matsohong a hao. Diahelo tsohle tsa hao di ke di hlweke ke hona, mme Jehova a se ke a bona taba e ditshila ha hao, a tle a se ke a o furalla.",
"15": "<sup>15</sup> Mohlanka ya tshabetseng ha eno, ya balehelang monga hae, o se ke wa mo busetsa ho monga hae;",
"16": "<sup>16</sup> a mpe a dule le wena, haeno, nqalong eo a tla e kgetha motseng o mong wa hao, moo a tla rata teng; mme o se ke wa mo tshwenya.",
"17": "<sup>17</sup> Ho se ke ha eba seotswa hara baradi ba Iseraele; hape, ho se ke ha eba le a mong wa bara ba Iseraele ya ineelang bohlola.",
"18": "<sup>18</sup> O se ke wa hlahisa ka tlung ya Jehova, Modimo wa hao, moputso wa seotswa, leha e le theko ya ntja, bakeng sa kano eo o itlamileng ka yona; hobane ntho tse pedi tseo ke manyala pela Jehova, Modimo wa hao.",
"19": "<sup>19</sup> O se ke wa adima ngwaneno ka ho batla phahello ya ditjhelete, kapa phahello ya dijo, leha e le phahello ya dintho tse ding tse ka namuwang ka phahello.",
"20": "<sup>20</sup> O ka adima moditjhaba ka ho batla phahello; o mpe o adime ngwaneno o sa batle phahello, hore Jehova, Modimo wa hao, a tle a o hlohonolofatse mesebetsing yohle ya matsoho a hao naheng eo o yang ho e rua.",
"21": "<sup>21</sup> Etlere ha o itlamile ka kano ho Jehova, Modimo wa hao, o se ke wa dieha ho e phetha; hobane Jehova, Modimo wa hao, o tla e botsa ho wena, mme sebe se tla ba teng ha o ka dieha.",
"22": "<sup>22</sup> Empa ha o sa itlame ka kano, sebe se tla ba siyo ho wena.",
"23": "<sup>23</sup> Se boletsweng ke melomo ya hao, o se hopole, o se etse kamoo o itlamileng ho Jehova kateng, Modimo wa hao, e be mpho ya boithatelo ba hao, e boletsweng ke melomo ya hao.",
"24": "<sup>24</sup> Ha o kena tshimong ya wa heno ya morara, o ka ja ditholwana tsa wona kamoo o lakatsang kateng, wa ba wa kgora; empa ha o tloha teng, o se ke wa nka letho serotong sa hao.",
"25": "<sup>25</sup> Leha o kena tshimong ya wa heno ya koro, o ka kga diqwapi ka matsoho a hao, o mpe o se ke wa kenya sekele korong ya wa heno."
},
"24": {
"1": "<sup>1</sup> Etlere motho ha a nkile mosadi, a mo nyetse, ha a sa kgahliswe ke yena, kahobane a fumane taba e mpe ho yena, a ke a mo ngolle lengolo la tlhalo, a le bee letsohong la mosadi eo, mme a mo kgutlise tlung ya hae.",
"2": "<sup>2</sup> Etlare hobane mosadi a tswe tlung ya hae, o tla ikela, a be le tokelo ya ho nyalwa ke monna e mong.",
"3": "<sup>3</sup> Ha monna eo wa morao a mo hloya, mme a mo ngolla lengolo la tlhalo, a mo nea lona letsohong la hae, mme a mo kgutlisa tlung ya hae; kapa leha mohlomong ho eshwa monna ya mo nkileng morao ho mo etsa mosadi wa hae;",
"4": "<sup>4</sup> monna eo wa pele, ya mo hladileng, a ke ke a boela a mo nka ho mo etsa mosadi wa hae, ha mosadi a se a silafaditswe; hobane hoo ke manyala pela Jehova; lefatshe leo Jehova, Modimo wa hao, a o fang lona ho le rua, o se ke wa le jarisa sebe.",
"5": "<sup>5</sup> Etlere motho ha a sa tswa nyala mosadi, a se ke a ya ntweng, mme a se ke a jariswa mosebetsi o mong. O tla newa sebaka sa ho itulela hae selemo, a thabise mosadi eo a mo nyetseng.",
"6": "<sup>6</sup> Ho se ke ha eba motho ya nkang lelwala, leha e le tshilo e silang, ho e etsa tebeletso; hobane ke ho nka bophelo ba motho ho bo etsa tebeletso.",
"7": "<sup>7</sup> Ekare ha o fumana motho ya utswitseng e mong wa banababo, e mong wa bana ba Iseraele, mme a mo entse lekgoba, kapa a rekile ka yena, leshodu leo le ke le shwe; ho tloswe bobe haeno jwalo.",
"8": "<sup>8</sup> Lemoha lefu la lepera, o tle o hlokomele ho etsa tsohle tseo baprista ba Balevi ba tla le ruta tsona. Itiseng, le etse ka tseo ke ba laetseng tsona.",
"9": "<sup>9</sup> Hopola seo Jehova, Modimo wa hao, a se entseng Miriame, tseleng, ha le sa tswa tloha Egepeta.",
"10": "<sup>10</sup> Ha o namelwa dintho tse ding ke ngwaneno, o se ke wa kena tlung ya hae.",
"11": "<sup>11</sup> O mpe o eme kantle, mme motho ya o nametseng, o tla o tlisetsa tebeletso kantle.",
"12": "<sup>12</sup> Ekare ha e le motho ya fumanehileng, o se ke wa robala o ena le tebeletso ya hae;",
"13": "<sup>13</sup> o mpe o busetse tebeletso ho yena, ha letsatsi le dikela, a tle a robale ka kobo ya hae, mme a o hlohonolofatse; ho wena hoo e tla ba ho loka pela Jehova, Modimo wa hao.",
"14": "<sup>14</sup> O se ke wa ja mothoduwa, ya fumanehileng, ya hlokang, kapa e leng e mong wa banabeno, kapa e leng wa baditjhaba ba ahileng naheng ya hao le metseng ya hao.",
"15": "<sup>15</sup> Ha letsatsi le eso ho dikele o tle o mo nee moputso wa hae wa letsatsi leo a sebeditseng ka lona; hobane ke mofumanehi, mme pelo ya hae e lebeletse moputso; o mo nee, esere mohlomong a howeletsa ho Jehova ka baka la hao, mme sebe sa eba teng ho wena.",
"16": "<sup>16</sup> Bontata bana ba se ke ba bolawa ka baka la bana ba bona, le bana ba se ke ba bolawa ka baka la bontata bona; e mong le e mong a bolaelwe sebe seo e leng sa hae.",
"17": "<sup>17</sup> O se ke wa kgopamisa nyewe ya moditjhaba, leha e le ya kgutsana, mme o se ke wa nka kobo ya mosadi wa mohlolohadi ho e etsa tebeletso.",
"18": "<sup>18</sup> O mpe o hopole hobane o bile mofo Egepeta, le hobane Jehova, Modimo wa hao, o o lopolotse teng; ke ka baka leo ke o laelang ho etsa jwalo.",
"19": "<sup>19</sup> Etlere ha o hela koro masimong a hao, ha o lebetse ngata e nngwe tshimong, o se ke wa kgutlela ho ya e nka; e ke e tlohellwe moditjhaba, le kgutsana, le mosadi wa mohlolohadi, hore Jehova, Modimo wa hao, a o hlohonolofatse mesebetsing yohle ya matsoho a hao.",
"20": "<sup>20</sup> Etlere ha o hlohlorile mehlwaare ya hao, o se ke wa romela ho kgwahlapisa kamora hao; se setseng e be sa moditjhaba, le sa kgutsana, le sa mosadi wa mohlolohadi.",
"21": "<sup>21</sup> Leha o kotula merara ya hao, o se ke wa kgwahlapisa se setseng kamora hao, e be sa moditjhaba, le sa kgutsana, le sa mosadi wa mohlolohadi.",
"22": "<sup>22</sup> O nne o hopole hobane o bile mofo naheng ya Egepeta; ke ka baka leo ke o laelang ho etsa ditaba tsena."
},
"25": {
"1": "<sup>1</sup> Etlere ha batho ba bang ba ena le tseko, mme ba etla nyeweng ho tla ahlolwa, ya lokileng a ke a bolelwe hoba o lokile, mme ya molato a tsuwe.",
"2": "<sup>2</sup> Ya molato ha a tshwanelwa ke ho shapuwa, moahlodi o tla laela hore a paqamiswe fatshe, mme a shapuwe pontsheng ya hae ka ditjhapo tse tshwanelang molato wa hae.",
"3": "<sup>3</sup> Moahlodi a ka mo shapa ka ditjhapo tse mashome a mane, a se ke a di tlola, esere ha a ka tlola ka ho mo shapa ka ditjhapo tse fetisang tseo, ngwaneno a ka nyediseha pela hao.",
"4": "<sup>4</sup> O se ke wa thiba molomo wa kgomo ha e pola.",
"5": "<sup>5</sup> Etlere ha bana ba motho a le mong ba ahile hammoho, mme e mong wa bona a eshwa a se na mora, mosadi wa mofu a se ke a nyalwa kantle ke monna osele, empa ngwanabo monna wa hae a tle ho yena, a mo nke ho mo etsa mosadi wa hae, mme a etse ho yena se tshwanelang ngwanabo monna ya shweleng.",
"6": "<sup>6</sup> Ngwana wa letsibolo ya tswalwang ke yena, o tla nka sebaka sa monna eo ya shweleng, a reellwe lebitso la hae, hore lebitso la eo le tle le se ke la hlakolwa Iseraeleng.",
"7": "<sup>7</sup> Ekare ha motho eo a sa rate ho nka mosadi wa ngwanabo, mosadi eo wa ngwanabo o tla ya kgorong ho baholo, a re ho bona: Ngwanabo monna wa ka o hana ho tsosetsa ngwanabo lebitso Iseraeleng, o hana ho nketsa se tshwanelang ngwanabo monna wa ka.",
"8": "<sup>8</sup> Baholo ba motse ba tla mmitsa, ba bue le yena; ha a ka phehella, a re: Ha ke rate ho mo nka;",
"9": "<sup>9</sup> mosadi wa ngwanabo o tla mo atamela pontsheng ya baholo, a mo role seeta leotong la hae, a mo tshwele ka mathe sefahlehong, mme a bolele, a re: Ho etswa jwalo ho monna ya hanang ho haha ntlo ya ngwanabo.",
"10": "<sup>10</sup> Lebitso leo a tla bitswa Iseraeleng ka lona, ho tla thwe: Ntlo ya ya rotsweng seeta.",
"11": "<sup>11</sup> Etlere ha banna ba lwana hammoho, mme mosadi wa e mong a etla ho namolela monna wa hae matsohong a ya mo otlang, mme a isa letshoho la hae, a mo tshwara dipele,",
"12": "<sup>12</sup> o ke o mo pome letsoho, mme leihlo la hao le se ke la mo hauhela.",
"13": "<sup>13</sup> Mekotleng ya hao o se ke wa ba le majwe a ho lekanya a sa lekaneng, ke ho re, lejwe le leng le leholo, le le leng le lenyenyane.",
"14": "<sup>14</sup> O se ke wa ba le ditekanyo tse sa lekaneng tlung ya hao, e nngwe ya eba kgolo, e nngwe ya eba nyenyane.",
"15": "<sup>15</sup> O be le majwe a ho lekanya a sebele, a lokileng; le yona efa ya hao e be ya sebele, ya nnete, matsatsi a hao a tle a ngatafale lefatsheng leo Jehova, Modimo wa hao, a o fang lona.",
"16": "<sup>16</sup> Hobane bohle ba etsang tse jwalo, bohle ba etsang ka bokgopo, ba manyala ho Jehova, Modimo wa hao.",
"17": "<sup>17</sup> Hopola seo Baamaleke ba o entseng sona, tseleng, mohlang le tswang Egepeta;",
"18": "<sup>18</sup> Kamoo ba o kgahlanyeditseng kateng tseleng, ba lwantsha masala a hao, ba bolaya bohle ba hao ba setseng morao ke ho fokola, ha o ne o tepeletse, o kgathetse; mme ha ba ka ba tshaba Modimo.",
"19": "<sup>19</sup> Ka baka leo, etlere hobane Jehova, Modimo wa hao, a o nee phomolo ka ho fedisa dira tsa hao kaofela tse o teetseng hare, lefatsheng leo Jehova, Modimo wa hao, a o fang lona ho ba lefa le ruwang ke wena, o hlakole lebitso la Baamaleke tlasa lehodimo. O se ke wa ba lebala."
},
"26": {
"1": "<sup>1</sup> Etlare hobane o kene lefatsheng leo Jehova, Modimo wa hao, a o fang lona, ho ba lefa la hao, ha o se o le ruile, o ahile ho lona,",
"2": "<sup>2</sup> o tla nka dilopotsiya tsa tsohle tse behwang ke lefatshe, e leng tseo o di fumanang naheng eo Jehova, Modimo wa hao, a o fang yona o di bee serotong, o ye le tsona nqalong eo Jehova, Modimo wa hao a tla e kgetha, ho bea lebitso la hae ho yona.",
"3": "<sup>3</sup> O tla ya ho moprista ya tla ba teng mohlang oo, o re ho yena: Ke bolela kajeno pela Jehova, Modimo wa hao, hore ke kene lefatsheng leo Jehova a anetseng bontata rona hore o tla re fa lona.",
"4": "<sup>4</sup> Moprista o tla nka seroto matsohong a hao a se bee pela aletare ya Jehova, Modimo wa hao.",
"5": "<sup>5</sup> Teng o tla bolela, o re pela Jehova, Modimo wa hao: Ntate e ne e le Moarame wa mosepedi; o ne a theohele Egepeta, a ahella teng a ena le batho ba seng bakaenyana; a fetoha teng setjhaba se seholo, se matla, se atileng haholo.",
"6": "<sup>6</sup> Baegepeta ba re etsa hampe, ba re hlorisa, ba re jarisa bohlanka bo thata.",
"7": "<sup>7</sup> Ke ha re tla howeletsa ho Jehova, Modimo wa bontata rona, mme Jehova a utlwa lentswe la rona, a tadima mahlomola a rona, le ho sebetsa ha rona, le ho tujwa ha rona.",
"8": "<sup>8</sup> Jehova a re ntsha Egepeta ka letsoho le matla, le ka letsoho le otlolohileng, ka letsoso le leholo, ka dipontsho le ka mehlolo.",
"9": "<sup>9</sup> O re tlisitse nqalong ena, mme o re neile lefatshe lena, lefatshe le kollang lebese le dinotshi.",
"10": "<sup>10</sup> Mme jwale, bona, ke tlisitse dilopotsiya tsa tse behwang ke lefatshe leo o nneileng lona, wena Jehova! O tla di bea pela Jehova, Modimo wa hao, o iname pela Jehova, Modimo wa hao.",
"11": "<sup>11</sup> O tla thabela molemo wohle oo Jehova, Modimo wa hao, a o neileng wona, wena le ba ntlo ya hao; o thabe, wena, le Molevi, le moditjhaba ya ahileng haeno.",
"12": "<sup>12</sup> Etlare ha o qetile ho ntsha karolo ya leshome ya tseo o di kotulang selemong sa boraro, e leng selemo sa ho ntsha karolo ya leshome, o tla e nea Molevi, le moditjhaba, le kgutsana, le mosadi wa mohlolohadi, ba tle ba e je metseng ya hao, mme ba kgore.",
"13": "<sup>13</sup> O tla re pela Jehova, Modimo wa hao: Ke ntshitse tlung ya ka tsohle tse kgethilweng, ke di neile Molevi, le moditjhaba, le kgutsana, le mosadi wa mohlolohadi, ka ditaelo tsa hao tsohle tseo o nneileng tsona; ha ke a ka ka tlola letho la ditaelo tsa hao, mme ha ke a ka ka di lebala.",
"14": "<sup>14</sup> Ha ke a ka ka di ja bofifing ba ka; ha ke a ka ka nka letho ho tsona hore ke etse taba e ditshila, mme ha ke a ka ka di neela mofu. Ke bolokile lentswe la Jehova, Modimo wa ka, ke entse ka tsohle tseo o ntaetseng tsona.",
"15": "<sup>15</sup> Tadima, o le mahodimong, nqalong ya hao ya bokgethehi ba hao, mme o hlohonolofatse setjhaba sa hao sa Iseraele, le lefatshe leo o re neileng lona, jwalokaha o anetse bontata rona, e leng lefatshe le kollang lebese le dinotshi.",
"16": "<sup>16</sup> Kajeno, Jehova, Modimo wa hao, o o laela ho etsa ka melao ena le ditaelo tsena. Itise ke hona, o tle o di boloke, o di etse ka pelo ya hao yohle, le ka moya wa hao wohle.",
"17": "<sup>17</sup> O tiisitse kajeno hoba Jehova ke Modimo wa hao, le hoba o tla tsamaya ditseleng tsa hae, o boloke melao ya hae, le ditaelo tsa hae, le dikahlolo tsa hae, mme o utlwe lentswe la hae.",
"18": "<sup>18</sup> Jehova le yena o tiisitse ho wena kajeno hoba o tla ba setjhaba sa hae sa sebele, jwalokaha a o baletse, o tle o boloke ditaelo tsa hae tsohle;",
"19": "<sup>19</sup> mme a o hodise, o phahame ka poko, ka botumo le ka kganya ho feta ditjhaba tsohle tseo a di entseng, mme o be setjhaba se kgethetsweng Jehova, Modimo wa hao, jwalokaha a boletse."
},
"27": {
"1": "<sup>1</sup> Moshe le baholo ba Iseraele, ba laela setjhaba, ba re: Bolokang ditaelo tsohle tseo ke le laelang tsona kajeno.",
"2": "<sup>2</sup> Etlere mohla le tshelang Jordane ho kena naheng eo Jehova, Modimo wa hao, a o fang yona, o ke o ikemisetse majwe a maholo, o a tlotse ka kalaka;",
"3": "<sup>3</sup> mme o tla ngola ho wona dipolelo tsohle tsa molao ona, ha o sa tswa tshela ho ya kena lefatsheng leo Jehova, Modimo wa hao, a o fang lona, e leng lefatshe le kollang lebese le dinotshi, jwalokaha Jehova, Modimo wa bontatao, a o baletse.",
"4": "<sup>4</sup> Etlare hobane le tshele Jordane, le tla emisa majwe ao thabeng ya Ebale, kamoo ke le laetseng kateng kajeno, o a tlotse ka kalaka.",
"5": "<sup>5</sup> Teng o tla hahela Jehova, Modimo wa hao, aletare ya majwe, ao o ke keng wa fihlisa tshepe ho wona.",
"6": "<sup>6</sup> Haha aletare ya Jehova, Modimo wa hao, ka majwe a sa betlwang, mme hodima yona o tle o hlabele Jehova, Modimo wa hao, mahlabelo a ditjheso.",
"7": "<sup>7</sup> O tla hlaba le mahlabelo a teboho, mme o tla a ja hona teng, o thabe pela Jehova, Modimo wa hao.",
"8": "<sup>8</sup> Majweng ao o tla ngola dipolelo tsohle tsa molao ona, di ke di bonahale haholo.",
"9": "<sup>9</sup> Moshe le baprista ba Balevi ba bolella Baiseraele bohle, ba re: Iseraele, kgutsa, mme o mamele: Kajeno, o entswe setjhaba sa Jehova, Modimo wa hao.",
"10": "<sup>10</sup> Utlwa ke hona lentswe la Jehova, Modimo wa hao, o boloke ditaelo tsa hae le melao ya hae eo ke o laelang yona kajeno.",
"11": "<sup>11</sup> Hape, Moshe a laela setjhaba ka lona letsatsi leo, a re:",
"12": "<sup>12</sup> Etlere ha le tshetse Jordane, ba tla ema thabeng ya Gerisime ho hlohonolofatsa setjhaba e be bana: Simeone, Levi, Juda, Issaskare, Josefa le Benjamine.",
"13": "<sup>13</sup> Ba tla ema thabeng ya Ebale ho bolela dithohako e be bana: Rubene, Gade, Asere, Sabulone, Dane le Nefthali.",
"14": "<sup>14</sup> Balevi ba tla bua, ba re ho batho bohle ba Iseraele ka lentswe le phahameng:",
"15": "<sup>15</sup> Ho rohakwe motho ya etsang setshwantsho se betlilweng, kapa se tsholotsweng, e leng ntho e manyala ho Jehova, mosebetsi wa matsoho a sebetli, mme a se bea nqalong e itseng e sephiri! Mme setjhaba sohle se tla dumela, se re: Amen!",
"16": "<sup>16</sup> Ho rohakwe ya nyedisang ntatae, kapa mmae! Mme setjhaba sohle se tla re: Amen!",
"17": "<sup>17</sup> Ho rohakwe ya suthisang mekolokotwane ya wa habo! Mme setjhaba sohle se tla re: Amen!",
"18": "<sup>18</sup> Ho rohakwe ya kgelosang sefofu tsela! Mme setjhaba sohle se tla re: Amen!",
"19": "<sup>19</sup> Ho rohakwe ya kgopamisang tokelo ya moditjhaba, le ya kgutsana, kapa ya mosadi wa mohlolohadi! Mme setjhaba sohle se tla re: Amen!",
"20": "<sup>20</sup> Ho rohakwe ya robalang le mosadi wa ntatae, hobane o apotse kobo ya ntatae! Mme setjhaba sohle se tla re: Amen!",
"21": "<sup>21</sup> Ho rohakwe ya robalang le phoofolo e nngwe! Mme setjhaba sohle se tla re: Amen!",
"22": "<sup>22</sup> Ho rohakwe ya robalang le kgaitsedi ya hae, kapa e leng moradi wa ntatae, kapa e leng moradi wa mmae! Mme setjhaba sohle se tla re: Amen!",
"23": "<sup>23</sup> Ho rohakwe ya robalang le matsalae! Mme setjhaba sohle se tla re: Amen!",
"24": "<sup>24</sup> Ho rohakwe ya otlang wa habo sephiring! Mme setjhaba sohle se tla re: Amen!",
"25": "<sup>25</sup> Ho rohakwe ya amohelang moputso ho bolaya motho ya se nang molato! Mme setjhaba sohle se tla re: Amen!",
"26": "<sup>26</sup> Ho rohakwe ya sa tiisetseng dipolelong tsa molao ona ho di etsa! Mme setjhaba sohle se tla re: Amen!"
},
"28": {
"1": "<sup>1</sup> Etlare ha o utlwa lentswe la Jehova, Modimo wa hao, o itisa ho etsa ditaelo tsa hae tsohle tseo ke o laelang tsona kajeno, Jehova, Modimo wa hao, o tla o phahamisa ho feta ditjhaba tsohle tsa lefatshe.",
"2": "<sup>2</sup> Dihlohonolofatso tsena tsohle di tla o fihlela, di o tlele, ha o ka utlwa lentswe le Jehova, Modimo wa hao.",
"3": "<sup>3</sup> O tla hlohonolofatswa motseng, o hlohonolofatswe masimong.",
"4": "<sup>4</sup> Bana ba hao ba tla hlohonolofatswa, le dijo tse behwang ke lefatshe la hao, le tse tswalwang ke makgomo a hao le katiso ya dikgomo tsa hao, le dikonyana tsa manku a hao.",
"5": "<sup>5</sup> Seroto sa hao se tla hlohonolofatswa, le morifi wa hao wa ho dubela bohobe.",
"6": "<sup>6</sup> O tla hlohonolofatswa ho keneng ha hao, o hlohonolofatswe le ho tsweng ha hao.",
"7": "<sup>7</sup> Jehova o tla etsa hore dira tsa hao tse o tsohelang matla di hlolwe pontsheng ya hao; di tla le futuhela di etla ka tsela e le nngwe, mme di tla le balehela ka tsela tse supileng.",
"8": "<sup>8</sup> Jehova o tla laela hlohonolofatso hore e be le wena medikong ya hao, le mererong yohle eo o tla kenya letsoho la hao ho yona; o tla o hlohonolofatsa lefatsheng leo Jehova, Modimo wa hao, a o fang lona.",
"9": "<sup>9</sup> Jehova o tla o bea hore o be setjhaba se kgethehilweng, jwalokaha a o anetse, ha o ka boloka ditaelo tsa Jehova, Modimo wa hao, wa tsamaya tseleng tsa hae.",
"10": "<sup>10</sup> Ditjhaba tsohle tsa lefatshe di tla bona hoba o bitswa ka lebitso la Jehova, mme di tla o tshaba.",
"11": "<sup>11</sup> Jehova o tla etsa hore dintho tsohle di tlale ho wena, ka ho atisa bana ba hao, le tse tswalwang ke makgomo a hao, le tse behwang ke naha ya hao, e leng lefatshe leo Jehova a anetseng bontatao hore o tla o nea lona.",
"12": "<sup>12</sup> Jehova o tla o bulela letlotlo la hae le molemo la mahodimo, a nesetse lefatshe la hao pula nakong ya teng, a hlohonolofatse mesebetsi yohle ya matsoho a hao; o tla namelwa ke ditjhaba tse ngata, empa wena ha o ka ke wa nama.",
"13": "<sup>13</sup> Jehova o tla o bea hlooho ya ditjhaba, e seng marao a tsona; o tla ba kahodimo kamehla, e seng katlase, ha o fela o utlwa ditaelo tsa Jehova, Modimo wa hao, tseo ke o laelang tsona kajeno, hore o di boloke, mme o etse ka tsona.",
"14": "<sup>14</sup> Hape, ke ha o ke ke wa fapoha taba leha e le nngwe ya tsohle tseo ke le laelang tsona kajeno, leha e le ho ya letsohong le letona, leha e le ho le letshehadi, ho latela medimo esele, le ho e sebeletsa.",
"15": "<sup>15</sup> Empa ekare ha o sa utlwe lentswe la Jehova, Modimo wa hao, mme ha o sa itise ho boloka ditaelo tsa hae tsohle, le melao ya hae eo ke o laelang yona kajeno, dithohako tsena tsohle di tla o fihlela, di o tlele.",
"16": "<sup>16</sup> O tla rohakwa motseng, o rohakwe masimong.",
"17": "<sup>17</sup> Seroto sa hao, le morifi wa hao wa ho dubela bohobe, di tla rohakwa;",
"18": "<sup>18</sup> se tswalwang ke wena se tla rohakwa, le se behwang ke lefatshe la hao, le katiso ya makgomo a hao, le dikonyana tsa manku a hao.",
"19": "<sup>19</sup> O tla rohakwa ho keneng ha hao, o rohakwe le ho tsweng ha hao.",
"20": "<sup>20</sup> Jehova o tla o romela thohako, letsoso, le tshwenyo, mererong yohle eo o tla kenya letsoho la hao ho yona, a be a o fedise, o timele kapele, ka baka la diketso tsa bolotsana tseo o tla mphuralla ka tsona.",
"21": "<sup>21</sup> Jehova o tla etsa hore lefu le o kgomarele, a be a o fedise lefatsheng leo o yang ho le rua.",
"22": "<sup>22</sup> Jehova o tla o otla ka lefu la matshwafo, ka febere, ka lefu le fubisang, ka pabo e tjhesang haholo, ka lerumo, ka komello, le ka phori; mme o tla lelekwa ke tsona, o be o timele.",
"23": "<sup>23</sup> Lehodimo la hao le kahodimo ho hlooho ya hao e tla ba koporo, mme lefatshe le katlasa hao e tla ba tshepe.",
"24": "<sup>24</sup> Jehova o tla nea lefatshe la hao lerole le lehlabathe bakeng sa pula; di tla o wela di tswa hodimo, o be o timele.",
"25": "<sup>25</sup> Jehova o tla etsa hore o hlolwe pontsheng ya dira tsa hao; o tla di futuhela ka tsela e le nngwe, mme o tla di balehela ka tsela tse supileng, mme o tla qhalanyetswa mebusong yohle ya lefatshe.",
"26": "<sup>26</sup> Setopo sa hao e tla ba sejo sa dinonyana tsohle tsa lehodimo, le sa dibatana tsa lefatshe, ho se motho ya di tshosang.",
"27": "<sup>27</sup> Jehova o tla o otla ka mofetshe wa Egepeta le ka dithopane, le ka lekgwekgwe, le ka lekgopho le ke keng la fola.",
"28": "<sup>28</sup> Jehova o tla o otla ka bohlanya, le ka bofofu, le ka ho ferekanngwa ha pelo.",
"29": "<sup>29</sup> O tla phopholetsa motshehare jwaloka sefofu se phopholetsang lefifing. O ke ke wa atleha ditabeng tsa hao. O tla hatakelwa, dintho tsa hao di hapuwe kamehla, ho se motho ya o namolelang.",
"30": "<sup>30</sup> O tla nyala mosadi, mme e mong o tla robala le yena; o tla haha ntlo, empa ha o ka ke wa dula ho yona; o tla hloma morara, empa ha o ka ke wa ikotulela ditholwana tsa wona.",
"31": "<sup>31</sup> Dikgomo tsa hao di tla hlajwa mahlong a hao, mme ha o ka ke wa ja nama ya tsona; o tla amohuwa diesele tsa hao pontsheng ho wena, mme di ke ke tsa boela ho wena. Dira tsa hao di tla newa dinku tsa hao, mme o tla hloka ya o namolelang.",
"32": "<sup>32</sup> Bara ba hao le baradi ba hao ba tla neelwa setjhaba sesele, mme mahlo a hao a tla bona hoo, mme a tla teneha ke ho ba lebella letsatsi lohle, mme matla a tla ba siyo matsohong a hao.",
"33": "<sup>33</sup> Dijo tsa lefatshe la hao, le tsohle tsa ho sebetsa ha hao, di tla jewa ke setjhaba seo o sa se tsebeng; mme o tla hloriswa, o hatakelwe ka matsatsi wohle.",
"34": "<sup>34</sup> O tla be o hlanye ka baka la ditaba tseo o tla di bona ka mahlo a hao.",
"35": "<sup>35</sup> Jehova o tla o otla mangoleng le diropeng tsa hao ka diphatshwa tse bohlokohloko tse ke keng tsa fola, ho qala bohatong ba leoto ho isa hara hlooho.",
"36": "<sup>36</sup> Jehova o tla o isa, wena, le morena wa hao eo o tla ipeela yena setjhabeng seo wena le baholo ba hao o sa kang wa se tseba, mme teng o tla sebeletsa medimo esele e entsweng ka mahong le ka majwe;",
"37": "<sup>37</sup> mme o tla fetoha makalo, le sesomo, le tshomo hara ditjhaba tsohle tseo Jehova a tla o isa hara tsona.",
"38": "<sup>38</sup> O tla isa peo e ngata masimong a hao, empa o tla kotula ho seng hokae, hobane tsie e tla e ja.",
"39": "<sup>39</sup> O tla hloma merara, o e leme; empa ha o ka ke wa nwa veine ya yona, leha e le ho kotula ditholwana tsa yona, hobane di tla jewa ke diboko.",
"40": "<sup>40</sup> O tla ba le mehlwaare naheng yohle ya hao, empa ha o ka ke wa tlola ole, kahobane ditholwana tsa mehlwaare ya hao di tla hlohlorehela fatshe.",
"41": "<sup>41</sup> O tla tswala bara le baradi, empa e ke ke ya eba ba hao, hobane ba tla iswa kgolehong.",
"42": "<sup>42</sup> Difate tsa hao tsohle, le tse behwang ke lefatshe, di tla senngwa ke makgokolo.",
"43": "<sup>43</sup> Baditjhaba ba ahileng haeno ba tla hola, ba o phahamele, haholoholo, mme wena o tla kokobela tlasetlase.",
"44": "<sup>44</sup> Ba tla namelwa ke wena, mme o ke ke wa namelwa ke bona; bona e tla ba hlooho, wena o tla ba marao.",
"45": "<sup>45</sup> Dithohako tseo kaofela di tla o hlahela, di o phallele, di o tshware, o be o timele; kahobane o tla be o hanne ho utlwa lentswe la Jehova, Modimo wa hao, le ho boloka ditaelo tsa hae le melao ya hae, eo a o laelang yona;",
"46": "<sup>46</sup> mme dithohako tseo di tla ba hodima hao, le hodima ditloholo tsa hao, kamehla, e be dipontsho le mehlolo.",
"47": "<sup>47</sup> Kahobane o tla be o sa ka wa sebeletsa Jehova, Modimo wa hao, ka thabo le ka pelo e monate, ka baka la ho atelwa ke ntho tsohle,",
"48": "<sup>48</sup> o tla sebeletsa dira tsa hao, tseo Jehova a tla di roma ho tla o lwantsha, o di sebeletse o lapile, o nyorilwe, o hlobotse, o hloka ntho tsohle; mme di tla bea joko ya tshepe molaleng wa hao, di be di o fedise.",
"49": "<sup>49</sup> Jehova o tla lata setjhaba se hole se qetellong ya lefatshe, se lebelo jwaloka ntsu e fofang, ho tla o lwantsha, setjhaba seo o ke keng wa utlwa puo ya sona,",
"50": "<sup>50</sup> setjhaba se thata, se ke keng sa tadima maqheku ka mohau, leha e le ho hauhela ba batjha.",
"51": "<sup>51</sup> Se tla ja katiso ya makgomo a hao, le dijo tsa lefatshe la hao, o be o fele; se ke ke sa o tlohella letho leha e le koro, leha e le veine e ntjha, leha e le ole, leha e le se tswalwang ke dikgomo le dinku tsa hao, se be se o fedise.",
"52": "<sup>52</sup> Se tla o thibella metseng yohle ya hao, marako a hao a malelele, a matla, ao o a tshepileng naheng yohle ya hao, a be a wele fatshe; se tla o thibella metseng yohle ya hao lefatsheng lohle leo Jehova, Modimo wa hao, a o neang lona.",
"53": "<sup>53</sup> Etlare ha o thibeletswe jwalo, mme o le tsietsing e kgolo ya kamoo dira tsa hao di tla o tsietsa kateng, o tla ja se tswetsweng ke wena, nama ya bara ba hao le ya baradi ba hao, bao Jehova, Modimo wa hao, a o neileng bona.",
"54": "<sup>54</sup> Monna ya ithatang, ya kgesang ka ho fetisa hara lona, o tla tadima ka leihlo le lebe ngwanabo, le mosadi wa sefuba sa hae, le masala a bana ba hae, ao a sa setseng le wona;",
"55": "<sup>55</sup> o tla tima e mong le e mong wa bona nama ya bana ba hae bao a tla ba ja; kahobane a se a se na letho le salang ho yena, ka baka la ho thibellwa, le ho tsietswa haholo ke dira tsa hao, metseng yohle ya hao.",
"56": "<sup>56</sup> Mosadi ya ithatang, ya kgesang ka ho fetisa hara lona, ya tshabang ho bea bohato ba leoto la hae fatshe, ka baka la bonolo ba hae le la ho kgesa, o tla tadima ka leihlo le lebe monna wa sefuba sa hae, le mora wa hae, le moradi wa hae;",
"57": "<sup>57</sup> o tla hana le mohlana wa hae, o tswang pakeng tsa maoto a hae, a hane le bana bao a tla ba tswala, hobane o tla ba ja sephiring ka ho hloka dintho tsohle, ka baka la ho thibellwa le la tsietsi e kgolo eo dira tsa hao di tla o tsietsa ka yona metseng yohle ya hao.",
"58": "<sup>58</sup> Ekare ha o sa itise ho etsa ka dipolelo tsohle tsa molao ona, tse ngodilweng bukeng ena, mme ha o sa tshabe lebitso leo le kganyang, le tshabehang la Jehova, Modimo wa hao,",
"59": "<sup>59</sup> Jehova o tla etsa hore dikotsi tsa hao, le dikotsi tsa ditloholo tsa hao, e be dikotsi tse makatsang, tse kgolo, tse sa feleng kapele, le mafu a mabe a hanellang ho wena.",
"60": "<sup>60</sup> O tla busetsa ho wena mafu wohle a Egepeta ao o a tshabileng, mme a tla o kgomarela.",
"61": "<sup>61</sup> Hape, Jehova o tla o hlahisetsa dipabo tsohle le dikotsi tsohle tse sa ngolwang bukeng ya molao ona, o be o fele.",
"62": "<sup>62</sup> Le tla sala le se bakae, leha pele le ne le le ka ka dinaledi tsa lehodimo ka bongata; kahobane o tla be o hanne ho utlwa lentswe la Jehova, Modimo wa hao.",
"63": "<sup>63</sup> Jwalokaha Jehova a ne a le thabela ka ho le etsetsa molemo, le ka ho le atisa, le hona Jehova o tla thabela jwalo ho le fedisa, le ho le timeletsa; mme le tla fotholwa lefatsheng leo o yang ho le rua.",
"64": "<sup>64</sup> Jehova o tla o qhalanyetsa hara ditjhaba tsohle, ho qala pheletsong e nngwe ya lefatshe, ho isa ho e nngwe; mme teng o tla sebeletsa medimo esele, e sa kang ya tsejwa ke wena le ke bontatao, e leng medimo e entsweng ka mahong le ka majwe.",
"65": "<sup>65</sup> Ha o ka ke wa fumana kgatholoho hara ditjhaba tseo, mme bohato ba leoto la hao bo tla hloka phomolo; hobane hona teng Jehova o tla o nea pelo e thothomelang, le mahlo a bolea, le moya o tepeletseng.",
"66": "<sup>66</sup> Bophelo ba hao bo tla ba jwaloka ntho e tsukutlehang pela hao; o tla thothomela motshehare le bosiu, o se na tshepo ya ho pholoha.",
"67": "<sup>67</sup> Hosasa a tla re: Hoja e ka ba mantsiboya! Mantsiboya o re: Hoja e ka ba hosasa! ka baka la tshoho eo pelo ya hao e tla tshoswa ke yona, le ka baka la ditaba tsohle tseo mahlo a hao a tla di bona.",
"68": "<sup>68</sup> Jehova o tla o busetsa Egepeta ka dikepe, o boele o tsamaye tseleng eo ke neng ke itse ho wena: O ke ke wa boela wa e bona. Mme teng le tla ithekisa ho dira tsa lona, le be bafo ba batona le ba batshehadi; empa ho tla hlokwa ya le rekang."
},
"29": {
"1": "<sup>1</sup> Dipolelo tsa selekane seo Jehova a laetseng Moshe ho se etsa le bana ba Iseraele, naheng ya Moabe, kantle ho selekane seo a neng a se entse le bona Horebe, ke tsena:",
"2": "<sup>2</sup> Moshe a bitsa Baiseraele bohle, mme a re ho bona: Le bone tsohle tseo Jehova a di entseng pontsheng ya lona Egepeta, ho Faro le ho bahlanka ba hae kaofela le ho naha ya hae yohle;",
"3": "<sup>3</sup> le meleko e meholo eo mahlo a hao a e boneng, le dipontsho, le mehlolo yane e meholo.",
"4": "<sup>4</sup> Empa ho fihlela letsatsi la kajeno, Jehova ha a ka a le nea pelo tse utlwisisang, le mahlo a bonang, le ditsebe tse utlwang.",
"5": "<sup>5</sup> Ke le tsamaisitse feelleng ka dilemo tse mashome a mane; diaparo tsa lona ha di a ka tsa senyeha ho lona, le dieta tsa hao ha di a ka tsa haraswana maotong a hao.",
"6": "<sup>6</sup> Ha le a ka la ja bohobe, ha le a ka la nwa veine, leha e le tse bodila, le tle le tsebe hobane ke nna Jehova, Modimo wa lona.",
"7": "<sup>7</sup> Eitse mohla le fihlang nqalong ena, Sihone, morena wa Heshbone, le Oge, morena wa Bashane, ba ile ba tswa, ba tla ho re lwantsha, empa ra ba bolaya;",
"8": "<sup>8</sup> ra nka naha ya bona, ra e nea Barubene, le Bagade, le ba mothapo o mong wa leloko la Manasse, e be lefa la bona.",
"9": "<sup>9</sup> Bolokang ke hona ditaba tsa selekane sena, le di etse, le tle le atlehe tabeng tsohle tseo le tla di etsa.",
"10": "<sup>10</sup> Kajeno, emang kaofela ha lona pela Jehova, Modimo wa lona, le ena le dihlooho tsa meloko ya lona, le baholo ba lona, le bahlahlobi ba lona, le banna bohle ba Iseraele;",
"11": "<sup>11</sup> le bana ba lona, le basadi ba lona, le moditjhaba ya leng ho wena diahelong tsa hao, ho qala ka ya o rathelang patsi, ho isa ho ya o kgellang metsi;",
"12": "<sup>12</sup> o eme hore o tle o kene selekaneng sa Jehova, Modimo wa hao, mme o itlame ka kano ya hao, eo Jehova, Modimo wa hao, a e etsang le wena kajeno;",
"13": "<sup>13</sup> hore a o bee setjhaba sa hae kajeno, mme yena e be Modimo wa hao, jwalokaha a o boleletse, le jwalokaha a anetse bontatao, Abrahama, Isaaka, le Jakobo.",
"14": "<sup>14</sup> Hase le lona feela ke etsang selekane sena le kano ena;",
"15": "<sup>15</sup> empa ke e etsa le ya leng mona le rona kajeno, pela Jehova, Modimo wa rona, le eo ya leng siyo mona ho rona kajeno.",
"16": "<sup>16</sup> Hobane le a tseba le lona kamoo re neng re ahile lefatsheng la Egepeta kateng, le kamoo re fetileng hara ditjhaba tseo le tsamaileng hara tsona kateng;",
"17": "<sup>17</sup> le bone manyala a tsona, le ditshwantsho tsa tsona tse entsweng ka mahong le ka majwe, ka silefera le ka kgauta, tse leng hara tsona.",
"18": "<sup>18</sup> Iponeleng ke hona hore kajeno ho se be monna hara lona, kapa mosadi, kapa ntlo, kapa leloko leo pelo tsa lona di ka fapohang Jehova, Modimo wa rona, ho ya sebeletsa medimo ya ditjhaba tseo, mme ho se ke ha eba ho lona motso o hlahisang bore le lengana.",
"19": "<sup>19</sup> E mong ha a utlwile dipolelo tsa thohako ya kano ena ya lona, ekare ha a ka ithorisa pelong ya hae, a re: Ke tla ba le kgotso, leha ke tsamaya kamoo pelo ya ka e thata e lakatsang kateng, hore ke timetse se noseditsweng le se omileng;",
"20": "<sup>20</sup> Jehova o tla hana ho mo tshwarela; empa kgalefo ya Jehova le poulelo ya hae di tla tukela motho eo; dithohako tsohle tse ngodilweng bukeng ena di tla mo wela hodimo; mme Jehova o tla hlakola lebitso la hae tlasa lehodimo.",
"21": "<sup>21</sup> Jehova o tla mo kgetha melokong yohle ya Iseraele, a hlahelwe ke ditlokotsi tsa dithohako tsohle tsa selekane se ngodilweng bukeng ena ya melao.",
"22": "<sup>22</sup> Meloko e tlang, bana ba lona ba tla hlaha kamora lona, le moditjhaba ya tla tla a etswa naheng e hole, ha ba bona ditlokotsi tsa lefatshe lena, le dipabo tseo Jehova a le otlang ka tsona;",
"23": "<sup>23</sup> le lefatshe lena lohle e le sebabole, le letswai, le ho tjha, le sa jallwe, le sa behe letho, ho se jwang bo melang ho lona, ho tshwana le ho ripitlwa ha Sodoma, le ha Gomorra, le ha Adma, le ha Tseboime, metse e ripitlilweng ke Jehova bohaleng ba hae le kgalefong ya hae;",
"24": "<sup>24</sup> bona le ditjhaba tsohle ba tla re: Na ke ka baka lang ha Jehova a entse lefatshe lena jwalo? Kgalefo ya bohale bona bo boholo hakalo e tswa kae na?",
"25": "<sup>25</sup> Ho tla thwe: Ke kahobane ba lahlile selekane sa Jehova, Modimo wa bontata bona, seo a neng a se entse le bona, mohla a ba ntshang naheng ya Egepeta.",
"26": "<sup>26</sup> Hobane ba ile, mme ba sebeleditse medimo esele, ba e kgumametse, e leng medimo eo ba neng ba sa e tsebe, eo ba sa kang ba e newa ke Jehova.",
"27": "<sup>27</sup> Ke ka baka leo kgalefo ya Jehova e tuketseng lefatshe lena, ho hlahisa hodima lona dithohako tsohle tse ngodilweng bukeng ena.",
"28": "<sup>28</sup> Jehova o ba fothotse lefatsheng la bona ka kgalefo, ka bohale, le ka hlonamo e kgolo, mme o ba lahletse naheng esele, jwalokaha ho le jwalo le kajeno.",
"29": "<sup>29</sup> Ditaba tse patilweng ke tsa Jehova, Modimo wa rona, empa tse senotsweng ke tsa rona, le tsa bana ba rona ka ho sa feleng, re tle re etse ka ditaba tsohle tsa molao ona."
},
"30": {
"1": "<sup>1</sup> Etlare hobane o hlahelwe ke ditaba tseo tsohle tseo ke di beileng pela hao, e leng lehlohonolo le thohako, ha o ikgopotsa tsona pelong ya hao, o le hara ditjhaba tsohle tseo Jehova, Modimo wa hao, a tla o qhalanyetsa hara tsona,",
"2": "<sup>2</sup> ha o sokolohela ho Jehova, Modimo wa hao, o utlwa lentswe la hae, wena, le bana ba hao, ka pelo yohle ya hao, le ka moya wohle wa hao, kahohle kamoo ke o laelang kateng kajeno,",
"3": "<sup>3</sup> Jehova, Modimo wa hao, o tla o kgutlisa kgolehong ya hao, mme o tla o hauhela, a boele a o bokelle ditjhabeng tsohle tseo Jehova, Modimo wa hao, a o qhalanyeditseng hara tsona.",
"4": "<sup>4</sup> Esita le hoja ba bang ba hao ba qhalantsweng ba ka ba pheletsong ya lehodimo, Jehova, Modimo wa hao, o tla o phutha teng, a o late hona teng.",
"5": "<sup>5</sup> Jehova, Modimo wa hao, o tla o busetsa lefatsheng leo bontatao ba kileng ba le rua, mme o tla le rua; mme o tla o etsa hantle, a o ngatafatse haholo ho fetisa bontatao.",
"6": "<sup>6</sup> Jehova, Modimo wa hao, o tla bolotsa pelo ya hao, le dipelo tsa ditloholo tsa hao, o tle o rate Jehova, Modimo wa hao, ka pelo yohle ya hao, le ka moya wohle wa hao, o tle o phele.",
"7": "<sup>7</sup> Jehova, Modimo wa hao, o tla bea dithohako tseo tsohle hodima dira tsa hao; le hodima ba o hloyang, ba o hlorisang.",
"8": "<sup>8</sup> Wena, o tla boela o utlwe lentswe la Jehova, o boloke ditaelo tsohle tsa hae tseo ke o laelang tsona kajeno;",
"9": "<sup>9</sup> Jehova, Modimo wa hao, o tla o hlohonolofatsa mesebetsing yohle ya matsoho a hao, dintho di tle di tlale ho wena; a o hlohonolofatse baneng ba tswalwang ke wena, le ho tse tswalwang ke makgomo a hao, le ho tse behwang ke lefatshe la hao. Hobane Jehova o tla boela a ithatele ho o etsa hantle, jwalokaha a ne a thabetse bontatao.",
"10": "<sup>10</sup> Ke ha o fela o ka utlwa lentswe la Jehova, Modimo wa hao, wa boloka melao ya hae le ditaelo tsa hae tse ngodilweng bukeng ena ya molao, mme wa sokolohela ho Jehova, Modimo wa hao, ka pelo yohle ya hao, le ka moya wohle wa hao.",
"11": "<sup>11</sup> Hobane taelo eo ke o laelang yona kajeno, hase e phahameng haholo hore e ka o sita, mme ha e hole le wena.",
"12": "<sup>12</sup> Ha e lehodimong moo o ka reng: Ke mang ya tla nyolohela lehodimong bakeng sa rona, ho ya re latela yona, re tle re e utlwe, mme re etse ka yona?",
"13": "<sup>13</sup> Hape, ha e mose wane ho lewatle leo o ka reng: Ke mang ya tla tshela lewatle bakeng sa rona ho ya re latela yona, re tle re e utlwe, mme re etse ka yona?",
"14": "<sup>14</sup> Empa lentswe le haufiufi le wena, le molomong wa hao, le ka pelong ya hao, hore o etse ka lona.",
"15": "<sup>15</sup> Lemoha, kajeno ke beile pela hao bophelo le molemo, lefu le bobe.",
"16": "<sup>16</sup> Hobane ke a o laela kajeno hore o rate Jehova, Modimo wa hao, le ho tsamaya tseleng tsa hae, le ho boloka ditaelo tsa hae, le melao ya hae, le dikahlolo tsa hae, o tle o phele, o ngatafale, mme Jehova, Modimo wa hao, a tle a o hlohonolofatse naheng eo o yang ho e rua.",
"17": "<sup>17</sup> Empa ekare ha pelo ya hao e kgeloha, mme o hana ho utlwa, mme o hulelwa ho kgumamela medimo esele, le ho e sebeletsa,",
"18": "<sup>18</sup> ke a le bolella kajeno hore le tla timela ruri, mme le ke ke la ngatafatsa matsatsi a lona lefatsheng leo o tla kena ho lona ho ya le rua, ka ho tshela Jordane.",
"19": "<sup>19</sup> Kajeno, ke bitsa lehodimo le lefatshe hore e be dipaki ho lona. Ke beile pela hao bophelo le lefu, lehlohonolo le thohako. Ikgethele bophelo o tle o phele, wena, le ditloholo tsa hao;",
"20": "<sup>20</sup> o tle o rate Jehova, Modimo wa hao, o utlwe lentswe la hae, mme o mo kgomarele; hobane ke yena bophelo ba hao, le bolelele ba matsatsi a hao, o tle o ahe lefatsheng leo Jehova a anetseng bontatao, Abrahama, Isaaka le Jakobo, hore o tla ba nea lona."
},
"31": {
"1": "<sup>1</sup> Moshe a boela a ya, mme a bolella Iseraele kaofela ditaba tseo;",
"2": "<sup>2</sup> a re ho bona: Kajeno, ke na le dilemo tse lekgolo le nang le mashome a mabedi; ha ke sa na ho tswa le ho kena; hape, Jehova o mpoleletse, a re: O ke ke wa tshela Jordane.",
"3": "<sup>3</sup> Jehova, Modimo wa hao, ke yena ya tla o etella pele, mme o tla fedisa ditjhaba tseno pela hao, o tle o rue naha ya tsona. Joshua ke yena ya tla o etella pele, jwalokaha Jehova a boletse.",
"4": "<sup>4</sup> Jehova o tla etsa ka ditjhaba tseo jwalokaha a entse ka Sihone le ka Oge, marena a Baamore, le ka naha ya bona, kamoo a ba fedisitseng kateng.",
"5": "<sup>5</sup> Jehova o tla neela ditjhaba tseo matsohong a lona, le tle le di etse ka ditaelo tsohle tseo ke le laelang tsona.",
"6": "<sup>6</sup> Ipheng matla, mme le tiye dipelo; se tshabeng, mme le se ke la ba tshoha, hobane Jehova, Modimo wa hao, ke yena ya tsamayang le wena; a ke ke a o tlohela, a ke ke a o lahla.",
"7": "<sup>7</sup> Moshe a bitsa Joshua, pontsheng ho Baiseraele kaofela, a re ho yena: Iphe matla, mme o tiye pelo; hobane ke wena ya tla kena le setjhaba sena lefatsheng leo Jehova a anetseng bontata bona hore o tla ba fa lona.",
"8": "<sup>8</sup> Jehova, ka sebele sa hae, o tla o etella pele; o tla ba le wena, mme a ke ke a o tlohela, a ke ke a o lahla; se tshabe, mme o se ke wa tepella.",
"9": "<sup>9</sup> Moshe a ngola molao ona, mme a o nea baprista, bana ba Levi, ba jarang areka ya selekane sa Jehova, le baholo bohle ba Iseraele.",
"10": "<sup>10</sup> Moshe a ba laela, a re: Qetellong ya dilemo tse supileng, ka selemo sa teselo, moketeng wa Metlotlwane,",
"11": "<sup>11</sup> ha Baiseraele bohle ba tlile ho itlhahisa pela Jehova, Modimo wa hao, nqalong eo a tla e khetha, o tla bala molao ona pela Baiseraele kaofela, ba tle ba o utlwe.",
"12": "<sup>12</sup> O tla phutha setjhaba, banna, le basadi, le bana, le moditjhaba ya metseng ya hao, ba tle ba utlwe, mme ba ithute ho tshaba Jehova, Modimo wa lona, mme ba hlokomele ho etsa ditaba tsohle tsa molao ona.",
"13": "<sup>13</sup> Bana ba bona ba sa kang ba tseba ditaba tseo, ba tla utlwa, mme ba tla ithuta ho tshaba Jehova, Modimo wa lona, ka matsatsi wohle a ho phela ha lona lefatsheng leo le yang ho le rua ka ho tshela Jordane.",
"14": "<sup>14</sup> Jehova a re ho Moshe: Bona, letsatsi la ho falla ha hao le atametse; bitsa Joshua, mme le itlhahise tenteng ya pokano, ke tle ke mo laele. Moshe le Joshua ba ya, ba itlhahisa tenteng ya pokano.",
"15": "<sup>15</sup> Jehova a itlhahisa tenteng topallong ya leru, mme topallo ya leru ya ema e okametse monyako wa tente.",
"16": "<sup>16</sup> Jehova a re ho Moshe: Bona, o se o ya orohela ho bontatao, mme setjhaba sena se tla tloha se itshilafatsa ka ho ineela medimo esele ya lefatshe leo se yang ho aha hara lona; se tla mphuralla, se tlole selekane sa ka, seo ke se entseng le sona.",
"17": "<sup>17</sup> Mohlang oo, kgalefo ya ka e tla ba tukela; ke tla ba tlohela, ke ba patele sefahleho sa ka; ba tla jewa ke mahloko a mangata, ba fihlelwe le ke mahlomola a mangata. Mohlang oo, ba tla re: Na hase kahobane Modimo wa rona o le siyo hara rona, re hlahetsweng ke mahloko ao na?",
"18": "<sup>18</sup> Mohlang oo, ruri ke tla pata sefahleho sa ka ka baka la bobe bohle boo ba tla bo etsa; hobane etlaba ba fapohile, ba tle ba latele medimo e meng.",
"19": "<sup>19</sup> Jwale he, le ingolleng sefela sena, mme o se rute bana ba Iseraele, o se bee melomong ya bona hore sefela sena e tle e be paki ya ka ho bana ba Iseraele.",
"20": "<sup>20</sup> Hobane ke ya isa setjhaba sena lefatsheng le kollang lebese le dinotshi, leo ke anetseng bontata bona hore ke tla ba nea lona; etlare ha ba jele ba kgotse, ba nonne, ba tla kgelohela ho medimo esele, ba e sebeletse; ba tla nkgesa, ba tla tlola selekane sa ka.",
"21": "<sup>21</sup> Etlare ha ba hlahelwa ke mahloko le mahlomola a mangata, sefela sena se tla ba qosa, jwaloka paki, hobane se ke ke sa lebalwa ke melomo ya ditloholo tsa bona; etswe ke tseba merero ya dipelo tsa bona, eo ba e etsang kweno, ha ke eso ho ba kenye lefatsheng leo ke anneng hore ke tla ba nea lona.",
"22": "<sup>22</sup> Moshe a ngola sefela sena hona mohlang oo, mme a se ruta bana ba Iseraele.",
"23": "<sup>23</sup> Jehova a laela Joshua, mora Nune, a re ho yena: Iphe matla, o tiye pelo, hobane ke wena o tla kenya bana ba Iseraele lefatsheng leo ke ba anetseng hore ke tla ba fa lona, mme nna ke tla ba le wena.",
"24": "<sup>24</sup> Eitse hobane Moshe a qete ho ngola ditaba tsa molao oo bukeng, ho sa hlokwe leha e le e nngwe,",
"25": "<sup>25</sup> a laela Balevi, ba jarang areka ya selekane sa Jehova, a re:",
"26": "<sup>26</sup> Nkang buka ena ya molao, mme le e bee haufi le areka ya selekane sa Jehova, Modimo wa lona, e tle e be paki ho wena hona teng.",
"27": "<sup>27</sup> Hobane ke tseba boikgantsho ba hao le molala wa hao o thata. Bonang, ha esita ke sa ntsane ke phela le lona kajeno, le nnile la ikgantshetsa Jehova, le tla ikgantsha haholo hakakang, ha ke se ke shwele!",
"28": "<sup>28</sup> Mphutheleng baholo bohle ba meloko ya lona, le bahlahlobi ba lona, mme ke tla ba bolella ditaba tsena, ba tle ba di utlwe; mme ke tla bitsa lehodimo le lefatshe ho ba dipaki ho bona.",
"29": "<sup>29</sup> Hobane ke a tseba hoba ha ke se ke shwele le tla itshenya ruri; mme le tla fapoha tsela eo ke le laetseng yona; mme mehleng ya morao, le tla hlahelwa ke tlokotsi, kahobane le tla etsa ho leng hobe pela Jehova, mme le tla mo phephetsa ka mesebetsi ya matsoho a lona.",
"30": "<sup>30</sup> Moshe a bolella phutheho yohle ya Baiseraele mantswe a sefela sena, a ba a a qeta kaofela."
},
"32": {
"1": "<sup>1</sup> Lona mahodimo, sekehang ditsebe, mme ke tla bua; le wena lefatshe, mamela mantswe a molomo wa ka.",
"2": "<sup>2</sup> Thuto ya ka e tla rotha jwaloka pula; dipolelo tsa ka di tla qhitsa jwaloka phoka, di be jwaloka pula e tshesane e kolobisang jwang bo botjha, le jwaloka marothodi a nelang jwang.",
"3": "<sup>3</sup> Hobane ke tla bolela lebitso la Jehova: Rorisang Modimo wa rona!",
"4": "<sup>4</sup> Ke Lefika; mosebetsi wa hae o phethehile, hobane ditsela tsa hae kaofela di lokile: ke Modimo o tshepehang, o se nang bokgopo; o lokile, o kgabane.",
"5": "<sup>5</sup> Ba itshentse pela wona; ke bana ba ditshila; ke mofuta o kgelohileng, o nang le mano.",
"6": "<sup>6</sup> Setjhaba se se nang kelello, se hlokang bohlale, na ke hona hoo le putsang Jehova ka hona na? Na hase yena ntatao, ya o ruileng, ya o entseng, ya o tiisitseng na?",
"7": "<sup>7</sup> Elellwa mehla ya kgale, o lemohe dilemo tsa meloko e mengata; botsa ntatao, mme o tla o ruta; botsa maqheku a hao, mme a tla o bolella.",
"8": "<sup>8</sup> Yanayare mohla E moholoholo a abelang ditjhaba lefa la tsona, mohla a arohanyang bana ba batho, a bea meedi ya ditjhaba ka palo ya bana ba Iseraele;",
"9": "<sup>9</sup> hobane kabelo ya Jehova ke setjhaba sa hae; mme Jakobo ke kabelo ya lefa la hae.",
"10": "<sup>10</sup> Jehova o mo fumane a le nahathothe, feelleng le tshabehang ka bobe le ka mehoo ya tshenyeho; a mo teela hare kahohle, a mo hlokomela, a mo boloka jwaloka hoja e le thaka ya leihlo la hae.",
"11": "<sup>11</sup> A etsa jwaloka ntsu ha e tsosa madinyane a yona, mme e okaokela hodima wona, e emisa mapheo a yona, e nka bana ba yona, mme e ba pepa mapheong a yona.",
"12": "<sup>12</sup> Jehova o mo tsamaisitse e le yena a nnotshi; mme ho ne ho se modimo osele le yena.",
"13": "<sup>13</sup> O mo hlwesitse dithota tse phahameng tsa lefatshe, a ba a ja dijo tsa naha; a mo momontshitse dinotshi tse tswang mafikeng, le ole e tswang majweng a thata;",
"14": "<sup>14</sup> o mo fepile ka sereledi sa dikgomo, le ka lebese la dinku, le ka mafura a dikonyana, le ka dipheleu tse tswaletsweng Bashane; ka diphooko, le ka lefi la koro ya sebelebele e nonneng; mme o nwele veine ya sebele, metsi a mafubedu a morara.",
"15": "<sup>15</sup> Empa Jeshurune a nona, mme a raha. Wa nona, wa iketsa ya nyenya, le ya kgurumeditsweng ke mafura. O lahlile Modimo o mo entseng, o nyedisitse Lefika la poloko ya hae.",
"16": "<sup>16</sup> Ba o bouledisitse ka medimo esele, ba o halefisitse ka manyala.",
"17": "<sup>17</sup> Ba hlabetse bademona, bao e seng Modimo, le medimo eo ba neng ba sa e tsebe, medimo e metjha, e tswang ho hlaha, eo bontata lona ba sa kang ba e tshaba.",
"18": "<sup>18</sup> O lahlile Lefika le o entseng, o lebetse Modimo o o tswetseng.",
"19": "<sup>19</sup> Jehova o bone hoo, mme kgalefong ya hae o lahlile bara ba hae le baradi ba hae;",
"20": "<sup>20</sup> mme o itse: Ke tla ba patela sefahleho sa ka, mme ke tla bona qetello ya bona hore na e tla ba eng? Hobane ke mofuta o kgelohileng, ke bana ba ke keng ba tshepjwa.",
"21": "<sup>21</sup> Ba mpouledisitse ka seo e seng Modimo, ba nkgalefisitse ka masawana a bona; le nna ke tla ba bouledisa ka setjhaba seo e seng setjhaba, ke ba halefise ka setjhaba se se nang kelello.",
"22": "<sup>22</sup> Hobane mollo o hoteditswe kgalefong ya ka, mme o tla tjhesa ho isa tlase nqalong ya bafu; o tla tjhesa lefatshe le tse behwang ke lona, o tjhese le metheo ya dithaba.",
"23": "<sup>23</sup> Ke tla bokella ditlokotsi kaofela hodima bona, mme ke tla ba fula ka metsu ya ka yohle.",
"24": "<sup>24</sup> Ba tla qetwa ke tlala, ba jewe ke mofuthu wa febere, le ke tshenyo e babang; ke tla ba romela meno a dibatana le mahloko a dinoha tse hahabang leroleng.",
"25": "<sup>25</sup> Kantle, lerumo le tla bolaya, ka tlung tshoho e tla ba teng; e tla nka mohlankana le morwetsana, lesea le anyang le motho e moputswa.",
"26": "<sup>26</sup> Nka be ke itse: Ke tla ba fedisa, ke hlakole lebitso la bona hara batho,",
"27": "<sup>27</sup> hoja ke sa ka ka tshaba phephetso ya dira, le hore bao e leng dira ho bona ba ka fosa ditaba, ba re: Matsoho a rona a phahame, ntho tseo kaofela hase Jehova ya di entseng.",
"28": "<sup>28</sup> Hobane ke setjhaba se hlokang kelello; ha ho kutlwisiso ho bona.",
"29": "<sup>29</sup> Hojane ba le bohlale ba ka be ba lemohile taba tsena, le ho ela ho fela ha bona hloko!",
"30": "<sup>30</sup> Motho a le mong o ne a tla phallela ba sekete jwang, mme ba babedi ba ne ba tla lelekisa ba dikete tse leshome jwang, hojane Lefika la bona le sa ka la rekisa ka bona, le hojane Jehova a sa ka a ba lahla?",
"31": "<sup>31</sup> Hobane lefika la bona ha le jwaloka Lefika la rona; esita le bao e leng dira ho rona, ba ka ahlola jwalo.",
"32": "<sup>32</sup> Hobane morara wa bona o tswa morareng wa Sodoma le masimong a Gomorra ditholwana tsa bona ke ditholwana tse nang le mahloko, ditholwana tsa bona di a baba.",
"33": "<sup>33</sup> Veine ya bona ke mahloko a didrakone, ke mahloko a bolayang a qowane.",
"34": "<sup>34</sup> Na taba tseo ha di a bokellwa ho nna, ha di a kwahelwa matlotlong a ka na?",
"35": "<sup>35</sup> Phetetso e tla ba ya ka, le yona tefetso mohla maoto a bona a thekeselang; hobane letsatsi la tlokotsi ya bona le haufi, mme tse lokiseditsweng bona di a akofa.",
"36": "<sup>36</sup> Hobane Jehova o tla ahlolela setjhaba sa hae, mme o tla rekolohela bahlanka ba hae, ha a bona hobane matla a bona a fedile, mme ho se ho se motho ya ruileng, leha e le motho ya lokolohileng.",
"37": "<sup>37</sup> O tla re: Medimo ya bona e kae na? Le kae lefika leo ba le tshepileng?",
"38": "<sup>38</sup> E kae medimo e neng e eja mafura a mahlabelo a bona, e neng e enwa veine ya ditshelo tsa bona? A e eme, e le thuse, e be setshabelo sa lona.",
"39": "<sup>39</sup> Tadimang jwale hobane ke nna, e, ke nna feela, mme ha ho modimo o mong, haese nna; ke a bolaya, mme ke a phedisa; ke etsa leqeba, mme ke a le fodisa; ha ho motho ya ka o namolelang letsohong la ka.",
"40": "<sup>40</sup> Hobane ke emisetsa letsoho la ka lehodimong, mme ke re: Ke phela ka ho sa feleng!",
"41": "<sup>41</sup> Ha ke leotsa lerumo la ka le benyang, mme letsoho la ka ha le tshwara kahlolo, ke tla iphetetsa ho dira tsa ka, ke busetse ho ba ntlhoileng.",
"42": "<sup>42</sup> Ke tla tahisa metsu ya ka madi, mme lerumo la ka le tla ja nama, e leng madi a ba bolawang, le a ba hapilweng, le a dihlooho tsa marena a dira.",
"43": "<sup>43</sup> Etsang ditlatse tsa thabo, lona ditjhaba, hammoho le setjhaba sa hae; hobane o ya pheteletsa madi a bahlanka ba hae, a itefetse ho dira tsa hae; mme o tla etsetsa lefatshe la hae le setjhaba sa hae pheko.",
"44": "<sup>44</sup> Moshe a tla, mme a bolela mantswe wohle a sefela sena ditsebeng tsa setjhaba, a ena le Joshua, mora Nune.",
"45": "<sup>45</sup> Eitse hobane Moshe a qete ho bolella Baiseraele bohle mantswe ao wohle,",
"46": "<sup>46</sup> a re ho bona: Beang dipelo tsa lona tabeng tsohle tseo ke le pakelang tsona kajeno, le tle le di laele bana ba lona, ba tle ba itise ho etsa ka dipolelo tsohle tsa molao oo.",
"47": "<sup>47</sup> Hobane hase lentswe la lefeela leo le le beelwang, empa ke bophelo ba lona, mme ke ka lentswe lena le tla ngatafatsa matsatsi a lona lefatsheng leo le yang ho le rua ka ho tshela Jordane.",
"48": "<sup>48</sup> Ka lona letsatsi leo, Jehova a bolella Moshe, a re:",
"49": "<sup>49</sup> Nyolohela thabeng eo ya Abarime, qhoweng ya Nebo, e naheng ya Moabe, mabapa le Jeriko, mme o tadime lefatshe la Kanana leo ke le neang bana ba Iseraele, ba tle ba le rue.",
"50": "<sup>50</sup> O tla shwela thabeng eo o tla nyolohela ho yona, mme o tla phuthelwa ditjhabeng tsa heno, jwaloka Aarone, ngwaneno, ya shweleng thabeng ya Hore, mme a phuthetswe ditjhabeng tsa habo;",
"51": "<sup>51</sup> kahobane le ntshitetswe hara bana ba Iseraele, metsing a Meriba a Kadeshe, nahathotheng ya Tsine, kamoo le sa kang la ntlotlisa kateng, hara bana ba Iseraele.",
"52": "<sup>52</sup> Hobane o tla bona lefatshe le le pela hao, empa o ke ke wa kena ho lona, e leng lefatshe leo ke le neang bana ba Iseraele."
},
"33": {
"1": "<sup>1</sup> Ke yona hlohonolofatso Moshe eo monna wa Modimo, a hlohonolofaditseng bana ba Israele ka yona, a eso ho shwe.",
"2": "<sup>2</sup> A re: Jehova o tlile a etswa Sinai; o ba tjhabetse a etswa Seire; a kganya a le thabeng ya Parane; o tlile a etswa makgotleng a diketekete a kgethehileng; ka letsoho la hae le letona, a ba romela mollo wa molao.",
"3": "<sup>3</sup> Efela o rata ditjhaba; bakgethwa ba hae kaofela ba letsohong la hao; ba dula maotong a hao, ba amohela ditaba tsa hao.",
"4": "<sup>4</sup> Moshe o re laetse molao, e leng lefa la phutheho ya Jakobo.",
"5": "<sup>5</sup> E ne e le morena ho Jeshurune, ha dihlooho tsa setjhaba di ne di bokane di ena le meloko ya Iseraele.",
"6": "<sup>6</sup> Rubene a ke a phele, a se ke a shwa, mme palo ya batho ba hae e se ke ya eba nyenyane.",
"7": "<sup>7</sup> Hlohonolofatso ya Juda ke ena: Moshe a re: Jehova, utlwa lentswe la Juda, o mo ise setjhabeng sa hae; matsoho a hae a mo lwanele, mme o be thuso ya hae ho lwantsha dira tsa hae.",
"8": "<sup>8</sup> Haele bakeng sa Levi, a re: Thummime tsa hao le Urime tsa hao di ho mokhethwa wa hao ya o ratang, eo o mo lekileng Massa, eo o mo tsekisitseng metsing a Meriba;",
"9": "<sup>9</sup> ya itseng bakeng sa ntatae le mmae: Ha ke a ka ka ba bona; mme ha ba tsebe banababo, leha e le bana ba hae ha a ba tsebe; hobane ba tiisitse lentswe la hao, mme ba bolokile selekane sa hao.",
"10": "<sup>10</sup> Ba tla ruta Jakobo dikahlolo tsa hao, ba rute Iseraele molao wa hao. A ba ke ba o beele dibano dinkong tsa hao, le mahlabelo a phethehileng aletareng ya hao.",
"11": "<sup>11</sup> Jehova, hlohonolofatsa matla a bona, mme o amohele mosebetsi wa matsoho a bona! Hlaba matheka a ba ba tsohelang matla le a ba ba hloileng, ba tle ba se ke ba boela ba tsoha.",
"12": "<sup>12</sup> Haele bakeng sa Benjamine, a re: Ke moratuwa wa Jehova; o tla aha ka tshepo pela hae: o tla kgurumetswa ke Jehova, ka matsatsi wohle, mme o tla dula pakeng tsa mahetla a hae.",
"13": "<sup>13</sup> Haele bakeng sa Josefa, a re: Naha ya hae e tla hlohonolofatswa ke Jehova ka tse molemo haholo tsa mahodimo, ka phoka le ka tsa bodiba bo leng tlasa lehodimo;",
"14": "<sup>14</sup> le ka tse monate tse mediswang ke letsatsi le ka tse monate tse melang ka dikgwedi tsohle;",
"15": "<sup>15</sup> le ka tse molemo tsa dithaba tsa kgale, le ka tsa bohlokwa tsa maralla a kamehla,",
"16": "<sup>16</sup> le ka tse molemo tsa lefatshe, le ka ho tlala ha lona; mme mohau wa ya hlahileng sehlahleng o tle o dule hloohong ya Josefa, hloohong ya eo e leng morena hara banababo.",
"17": "<sup>17</sup> Bokgabane ba hae bo jwaloka ba letsibolo la dikgomo tsa hae, mme dinaka tsa hae di jwaloka dinaka tsa nare; ka tsona o tla hlaba ditjhaba tsohle ho isa dipheletsong tsa lefatshe; ke dikete tse mashome tsa Efraime, ke dikete tsa Manasse.",
"18": "<sup>18</sup> Haele bakeng sa Sabulone, a re: Thaba, Sabulone, ho tsweng ha hao; le wena Issaskare, o thabe ditenteng tsa hao.",
"19": "<sup>19</sup> Ba tla biletsa ditjhaba thabeng, ba hlahise mahlabelo a ho loka teng; hobane ba tla anya letlotlo la lewatle, le dintho tsa bohlokwa tse patilweng lehlabatheng.",
"20": "<sup>20</sup> Haele bakeng sa Gade, a re: Ho bokwe ya phatlalatsang Gade. Gade o ahile jwaloka tau e tshehadi, o harola letsoho le hlooho.",
"21": "<sup>21</sup> O ipatletse dilopotsiya tsa naha, kahobane kabelo ya mmei wa molao e boloketswe yena hona teng; o tsamaya le dihlooho tsa setjhaba; o entse ho loka ha Jehova le dikahlolo tsa hae, tseo a di laetseng Iseraele.",
"22": "<sup>22</sup> Haele tsa Dane, a re: Dane ke tauana, o tla tlola, a le Bashane.",
"23": "<sup>23</sup> Haele tsa Nefthali, a re: Nefthali, o kgotshe melemo, mme o tletse hlohonolofatso ya Jehova. Rua Bophirimela le Borwa.",
"24": "<sup>24</sup> Haele bakeng sa Asere, a re: Asere o tla hlohonolofatswa ke bana, o tla ratwa ke banababo, mme a tsobunye maoto a hae oleng.",
"25": "<sup>25</sup> Mekwallo ya hao ke ya tshepe le ya koporo, mme matla a hao a tla lekana le matsatsi a hao.",
"26": "<sup>26</sup> Jeshurune, ha ho ya tshwanang le Modimo; ya o tiisang o kaletse mahodimo le maru bokgabaneng ba hae.",
"27": "<sup>27</sup> Modimo wa kamehla ke setshabelo sa hao, mme matsoho a sa feleng a katlasa hao. O lelekisa dira pela hao, o re: Di fediswe!",
"28": "<sup>28</sup> Iseraele o tla aha ka tshepo a nnotshi; sediba sa Jakobo se kolla naheng ya koro le ya veine e ntjha, mme mahodimo a Jakobo a qhitsa phoka.",
"29": "<sup>29</sup> O lehlohonolo hakakang, Iseraele! Setjhaba ke sefe se tshwanang le wena, setjhaba se pholositsweng ke Jehova, e leng thebe ya thuso ya hao, le lerumo la boholo ba hao? Dira tsa hao di tla ikokobetsa pela hao, mme o tla hatakela nqalo tsa bona tse phahameng."
},
"34": {
"1": "<sup>1</sup> Moshe a tloha mahwatateng a Moabe, a nyolohela thabeng ya Nebo, qhoweng ya Pisga malebana le Jeriko; Jehova a mmontsha lefatshe lohle: naha yohle ya Gileade ho isa Dane,",
"2": "<sup>2</sup> le naha yohle ya Nefthali, le naha ya Efraime, le ya Manasse, le naha yohle ya Juda, ho isa Lewatleng la Bophirimela,",
"3": "<sup>3</sup> le naha e ka nqa borwa, le naha ya Jordane, le lehwatata la Jeriko, motse wa dipalema, ho isa Tsoware.",
"4": "<sup>4</sup> Jehova a re ho yena: Ke lona lefatshe leo ke anetseng Abrahama, Isaaka le Jakobo, ka re: Ke tla le nea ditloholo tsa lona. Ke o bontsha lona, o tle o le bone ka mahlo; empa u ke ke wa kena ho lona.",
"5": "<sup>5</sup> Moshe, mohlanka wa Modimo, a shwela hona teng, naheng ya Moabe, ka taelo ya Jehova.",
"6": "<sup>6</sup> A patwa naheng ya Moabe, sekgutlong se lebaneng le Bethe-Peore; empa ha ho motho ya tsebileng lebitla la hae ho fihlela letsatsing la kajeno.",
"7": "<sup>7</sup> Mohla Moshe a shwang, o ne a le dilemo tse lekgolo le nang le mashome a mabedi; mahlo a hae a ne a eso ho fifale; mme matla a hae a ne a eso ho kokobele.",
"8": "<sup>8</sup> Bana ba Iseraele ba llela Moshe, mahwatateng a Moabe, ka matsatsi a mashome a mararo; matsatsi a dillo le a bofifi ba Moshe a ba a fela.",
"9": "<sup>9</sup> Haele Joshua, mora Nune, o ne a tletse moya wa bohlale; hobane Moshe o ne a mmeile matsoho hodimo; bana ba Iseraele ba mo utlwa, mme ba etsa jwalokaha Jehova a ne a laetse Moshe.",
"10": "<sup>10</sup> Ha ho a ka ha boela ha eba moporofeta Iseraeleng ya jwaloka Moshe, eo Jehova a mo tsebileng, sefahleho se tadimane le sefahleho.",
"11": "<sup>11</sup> Ha ho e mong ya ileng a tshwana le yena ka dipontsho tsohle, le mehlolo eo Jehova a mo romileng ho e etsa naheng ya Egepeta, ho Faro, le ho bahlanka ba hae kaofela, le ho naha ya hae yohle;",
"12": "<sup>12</sup> le ka tsohle tseo a di entseng ka letsoho le matla, le ka letsoso lohle le leholo leo Moshe a le hlahisitseng pontsheng ya Baiseraele bohle."
}
}
};
module.exports = book; |
export const REQUEST = 'REQUEST';
export const SUCCESS = 'SUCCESS';
export const ERROR = 'ERROR';
|
/* https://stackoverflow.com/questions/33145762/parse-a-srt-file-with-jquery-javascript/33147421 */
var PF_SRT = function () {
var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
var _regExp;
var init = function () {
_regExp = new RegExp(pattern);
};
var parse = function (f) {
if (typeof (f) != "string")
throw "Sorry, Parser accept string only.";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n')
//console.log(pattern.exec(f));
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
//console.log(result);
return result;
}
var toLineObj = function (group) {
return {
line: group[1],
startTime: group[2],
endTime: group[3],
text: group[4]
};
}
init();
return {
parse: parse
}
}();
var captions;
$(function () {
$("#doParse").on('click', function () {
try {
var text = $("#source").val();
var result = PF_SRT.parse(text);
var wrapper = $("#result");
var paras = $("#paras");
wrapper.html('');
paras.html('');
for (var line in result) {
var obj = result[line];
//console.log(obj);
if (line % 3 == 0) {
wrapper.append("// " + obj.text + "\n");
}
let regexp = /([0-9]{2}):([0-9]{2}):([0-9]{2}),([0-9]{3})/g;
var str = obj.startTime;
var array = [...str.matchAll(regexp)];
var hh = (array[0][1] * 3600);
var mm = (array[0][2] * 60);
var ss = (array[0][3] * 1);
var mls = (array[0][4] / 1000);
var stt = hh + mm + ss + mls;
str = obj.endTime;
array = [...str.matchAll(regexp)];
var hh = (array[0][1] * 3600);
var mm = (array[0][2] * 60);
var ss = (array[0][3] * 1);
var mls = (array[0][4] / 1000);
var ett = hh + mm + ss + mls;
//console.log(startTime);
wrapper.append("captions[" + (obj.line - 1) + "] = ['" + stt + "','" + ett + "'];\n");
}
var result = PF_SRT.parse(text);
for (line in result) {
var obj = result[line];
paras.append("<p class=\"\">" + obj.text + "</p>\n");
}
} catch (e) {
alert(e);
}
console.log(captions[3]);
});
$("#doParse").click();
});
|
from collections import defaultdict
from django.conf import settings
from mongodbforms.documentoptions import DocumentMetaWrapper, LazyDocumentMetaWrapper
from mongodbforms.fieldgenerator import MongoDefaultFormFieldGenerator
try:
from django.utils.module_loading import import_by_path
except ImportError:
# this is only in Django's devel version for now
# and the following code comes from there. Yet it's too nice to
# pass on this. So we do define it here for now.
import sys
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.utils import six
def import_by_path(dotted_path, error_prefix=''):
"""
Import a dotted module path and return the attribute/class designated
by the last name in the path. Raise ImproperlyConfigured if something
goes wrong.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
raise ImproperlyConfigured("%s%s doesn't look like a module path" %
(error_prefix, dotted_path))
try:
module = import_module(module_path)
except ImportError as e:
msg = '%sError importing module %s: "%s"' % (
error_prefix, module_path, e)
six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
sys.exc_info()[2])
try:
attr = getattr(module, class_name)
except AttributeError:
raise ImproperlyConfigured(
'%sModule "%s" does not define a "%s" attribute/class' %
(error_prefix, module_path, class_name))
return attr
def load_field_generator():
if hasattr(settings, 'MONGODBFORMS_FIELDGENERATOR'):
return import_by_path(settings.MONGODBFORMS_FIELDGENERATOR)
return MongoDefaultFormFieldGenerator
def init_document_options(document):
if not isinstance(document._meta, (DocumentMetaWrapper, LazyDocumentMetaWrapper)):
document._meta = DocumentMetaWrapper(document)
# Workaround for Django 1.7+
document._deferred = False
# FIXME: Wrong implementation for Relations (https://github.com/django/django/blob/master/django/db/models/base.py#L601)
document.serializable_value = lambda self, field_name: self._meta.get_field(field_name)
return document
def get_document_options(document):
return DocumentMetaWrapper(document)
def format_mongo_validation_errors(validation_exception):
"""Returns a string listing all errors within a document"""
def generate_key(value, prefix=''):
if isinstance(value, list):
value = ' '.join([generate_key(k) for k in value])
if isinstance(value, dict):
value = ' '.join([
generate_key(v, k) for k, v in value.iteritems()
])
results = "%s.%s" % (prefix, value) if prefix else value
return results
error_dict = defaultdict(list)
for k, v in validation_exception.to_dict().iteritems():
error_dict[generate_key(v)].append(k)
return ["%s: %s" % (k, v) for k, v in error_dict.iteritems()]
# Taken from six (https://pypi.python.org/pypi/six)
# by "Benjamin Peterson <[email protected]>"
#
# Copyright (c) 2010-2013 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta("NewBase", bases, {})
|
/**
* @fileoverview EventEmitter
*/
/**
* @augments JsSIP
* @class Class creating an event emitter.
*/
(function(JsSIP) {
var
EventEmitter,
Event,
LOG_PREFIX = JsSIP.name +' | '+ 'EVENT EMITTER' +' | ';
EventEmitter = function(){};
EventEmitter.prototype = {
/**
* Initialize events dictionary.
* @param {Array} events
*/
initEvents: function(events) {
var i = events.length;
this.events = {};
this.onceNotFired = []; // Array containing events with _once_ defined tat didn't fire yet.
this.maxListeners = 10;
this.events.newListener = function(event) { // Default newListener callback
console.log(LOG_PREFIX +'new listener added to event '+ event);
};
while (i--) {
console.log(LOG_PREFIX +'adding event '+ events[i]);
this.events[events[i]] = [];
}
},
/**
* Check whether an event exists or not.
* @param {String} event
* @returns {Boolean}
*/
checkEvent: function(event) {
if (!this.events[event]) {
console.error(LOG_PREFIX +'no event named '+ event);
return false;
} else {
return true;
}
},
/**
* Add a listener to the end of the listeners array for the specified event.
* @param {String} event
* @param {Function} listener
*/
addListener: function(event, listener) {
if (!this.checkEvent(event)) {
return;
}
if (this.events[event].length >= this.maxListeners) {
console.warn(LOG_PREFIX +'max listeners exceeded for event '+ event);
}
this.events[event].push(listener);
this.events.newListener.call(null, event);
},
on: function(event, listener) {
this.addListener(event, listener);
},
/**
* Add a one time listener for the event.
* The listener is invoked only the first time the event is fired, after which it is removed.
* @param {String} event
* @param {Function} listener
*/
once: function(event, listener) {
this.events[event].unshift(listener);
this.onceNotFired.push(event);
},
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param {String} event
* @param {Function} listener
*/
removeListener: function(event, listener) {
if (!this.checkEvent(event)) {
return;
}
var array = this.events[event], i = 0, length = array.length;
while ( i < length ) {
if (array[i] && array[i].toString() === listener.toString()) {
array.splice(i, 1);
} else {
i++;
}
}
},
/**
* Remove all listeners from the listener array for the specified event.
* @param {String} event
*/
removeAllListener: function(event) {
if (!this.checkEvent(event)) {
return;
}
this.events[event] = [];
},
/**
* By default EventEmitter will print a warning
* if more than 10 listeners are added for a particular event.
* This function allows that limit to be modified.
* @param {Number} listeners
*/
setMaxListeners: function(listeners) {
if (Number(listeners)) {
this.maxListeners = listeners;
}
},
/**
* Get the listeners for a specific event.
* @param {String} event
* @returns {Array} Array of listeners for the specified event.
*/
listeners: function(event) {
return this.events[event];
},
/**
* Execute each of the listeners in order with the supplied arguments.
* @param {String} events
* @param {Array} args
*/
emit: function(event, sender, data) {
var listeners, length,
emitter = this;
if (!this.checkEvent(event)) {
return;
}
console.log(LOG_PREFIX +'emitting event '+event);
listeners = this.events[event];
length = listeners.length;
var e = new JsSIP.Event(event, sender, data);
window.setTimeout(
function(){
var idx=0;
for (idx; idx<length; idx++) {
listeners[idx].call(null, e);
}
// Check whether _once_ was defined for the event
idx = emitter.onceNotFired.indexOf(event);
if (idx !== -1) {
emitter.onceNotFired.splice(idx,1);
emitter.events[event].shift();
}
}, 0);
},
/**
* This function is executed anytime a new listener is added to EventEmitter instance.
* @param {Function} listener
*/
newListener: function(listener) {
this.events.newListener = listener;
}
};
Event = function(type, sender, data) {
this.type = type;
this.sender= sender;
this.data = data;
};
JsSIP.EventEmitter = EventEmitter;
JsSIP.Event = Event;
}(JsSIP));
|
from openpyxl.drawing.image import Image
from openpyxl.styles import Border, Side, Font
import openpyxl
import os
# 目录路径
currentPath = os.path.dirname(os.path.abspath(__file__))
wb = openpyxl.Workbook()
for root, dirs, files in os.walk("."):
dirs.sort()
for name in dirs:
# print(name)
ws = wb.create_sheet(name)
i = 2
dirs2 = os.listdir("../script")
for file in dirs2:
script = file[0:-3]
img = Image(currentPath+"/"+name+"/"+script+".png")
ws["A%d"%(i)] = script
ws["A%d"%(i)].font = Font(name='Yu Gothic',size=22,bold=False,italic=False,vertAlign=None,underline='none',strike=False,color='FF000000')
ws.add_image(img, "B%d"%(i+1))
if script == "1024×768":
i += (32 + 13)
elif script == "1152×864":
i += (36 + 14)
elif script == "1280×600":
i += (26 + 9)
elif script == "1360×768":
i += (32 + 13)
elif script == "1366×768":
i += (32 + 13)
elif script == "1400×1050":
i += (43 + 18)
elif script == "1440×900":
i += (37 + 16)
elif script == "1600×900":
i += (37 + 16)
elif script == "1680×1050":
i += (43 + 18)
elif script == "1920×1080":
i += (44 + 19)
wb.save(currentPath+"/screenshots3.xlsx") |
import React from 'react'
import { graphql, StaticQuery, Link } from 'gatsby'
import Layout from '../components/layout'
const getImageData = graphql`
{
allFile {
edges {
node {
relativePath
size
extension
birthTime
}
}
}
}`
export default () => (
<Layout>
<h1>Hello from Page 3!</h1>
<StaticQuery
query={getImageData}
render={data => (
<table>
<thead>
<tr>
<th>Relative Path</th>
<th>Size of Image</th>
<th>Extension</th>
<th>Birthtime</th>
</tr>
</thead>
<tbody>
{data.allFile.edges.map(({ node }, index) => (
<tr key={index}>
<td>{node.relativePath}</td>
<td>{node.size}</td>
<td>{node.extension}</td>
<td>{node.birthTime}</td>
</tr>
))}
</tbody>
</table>
)}
/>
<Link to="/page-2">Go to page 2</Link>
</Layout>
) |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import logging
import six
import abc
from azure.iot.device import constant
logger = logging.getLogger(__name__)
DEFAULT_KEEPALIVE = 60
@six.add_metaclass(abc.ABCMeta)
class BasePipelineConfig(object):
"""A base class for storing all configurations/options shared across the Azure IoT Python Device Client Library.
More specific configurations such as those that only apply to the IoT Hub Client will be found in the respective
config files.
"""
def __init__(
self,
hostname,
gateway_hostname=None,
sastoken=None,
x509=None,
server_verification_cert=None,
websockets=False,
cipher="",
proxy_options=None,
keep_alive=DEFAULT_KEEPALIVE,
auto_connect=True,
connection_retry=True,
connection_retry_interval=10,
):
"""Initializer for BasePipelineConfig
:param str hostname: The hostname being connected to
:param str gateway_hostname: The gateway hostname optionally being used
:param sastoken: SasToken to be used for authentication. Mutually exclusive with x509.
:type sastoken: :class:`azure.iot.device.common.auth.SasToken`
:param x509: X509 to be used for authentication. Mutually exclusive with sastoken.
:type x509: :class:`azure.iot.device.models.X509`
:param str server_verification_cert: The trusted certificate chain.
Necessary when using connecting to an endpoint which has a non-standard root of trust,
such as a protocol gateway.
:param bool websockets: Enabling/disabling websockets in MQTT. This feature is relevant
if a firewall blocks port 8883 from use.
:param cipher: Optional cipher suite(s) for TLS/SSL, as a string in
"OpenSSL cipher list format" or as a list of cipher suite strings.
:type cipher: str or list(str)
:param proxy_options: Details of proxy configuration
:type proxy_options: :class:`azure.iot.device.common.models.ProxyOptions`
:param int keepalive: Maximum period in seconds between communications with the
broker.
:param bool auto_connect: Indicates if automatic connects should occur
:param bool connection_retry: Indicates if dropped connection should result in attempts to
re-establish it
:param int connection_retry_interval: Interval (in seconds) between connection retries
"""
# Network
self.hostname = hostname
self.gateway_hostname = gateway_hostname
self.keep_alive = self._validate_keep_alive(keep_alive)
# Auth
self.sastoken = sastoken
self.x509 = x509
if (not sastoken and not x509) or (sastoken and x509):
raise ValueError("One of either 'sastoken' or 'x509' must be provided")
self.server_verification_cert = server_verification_cert
self.websockets = websockets
self.cipher = self._sanitize_cipher(cipher)
self.proxy_options = proxy_options
# Pipeline
self.auto_connect = auto_connect
self.connection_retry = connection_retry
self.connection_retry_interval = connection_retry_interval
@staticmethod
def _sanitize_cipher(cipher):
"""Sanitize the cipher input and convert to a string in OpenSSL list format
"""
if isinstance(cipher, list):
cipher = ":".join(cipher)
if isinstance(cipher, str):
cipher = cipher.upper()
cipher = cipher.replace("_", "-")
else:
raise TypeError("Invalid type for 'cipher'")
return cipher
@staticmethod
def _validate_keep_alive(keep_alive):
try:
keep_alive = int(keep_alive)
except (ValueError, TypeError):
raise ValueError("Invalid type for 'keep alive'. Permissible types are integer.")
if keep_alive <= 0 or keep_alive > constant.MAX_KEEP_ALIVE_SECS:
# Not allowing a keep alive of 0 as this would mean frequent ping exchanges.
raise ValueError(
"'keep alive' can not be zero OR negative AND can not be more than 29 minutes. "
"It is recommended to choose 'keep alive' around 60 secs."
)
return keep_alive
|
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParsingContext = exports.Chrono = void 0;
var results_1 = require("./results");
var en_1 = require("./locales/en");
var Chrono = (function () {
function Chrono(configuration) {
configuration = configuration || en_1.createCasualConfiguration();
this.parsers = __spread(configuration.parsers);
this.refiners = __spread(configuration.refiners);
}
Chrono.prototype.parseDate = function (text, refDate, opt) {
var results = this.parse(text, refDate, opt);
return (results.length > 0) ? results[0].start.date() : null;
};
Chrono.prototype.parse = function (text, refDate, opt) {
var context = new ParsingContext(text, refDate || new Date(), opt || {});
var results = [];
this.parsers.forEach(function (parser) {
var parsedResults = Chrono.executeParser(context, parser);
results = results.concat(parsedResults);
});
results.sort(function (a, b) {
return a.index - b.index;
});
this.refiners.forEach(function (refiner) {
results = refiner.refine(context, results);
});
return results;
};
Chrono.prototype.clone = function () {
return new Chrono({
parsers: __spread(this.parsers),
refiners: __spread(this.refiners)
});
};
Chrono.executeParser = function (context, parser) {
var results = [];
var pattern = parser.pattern(context);
var originalText = context.text;
var remainingText = context.text;
var match = pattern.exec(remainingText);
var _loop_1 = function () {
var index = match.index + originalText.length - remainingText.length;
match.index = index;
var result = parser.extract(context, match);
if (!result) {
remainingText = originalText.substring(match.index + 1);
match = pattern.exec(remainingText);
return "continue";
}
var parsedResult = null;
if (result instanceof results_1.ParsingResult) {
parsedResult = result;
}
else if (result instanceof results_1.ParsingComponents) {
parsedResult = context.createParsingResult(match.index, match[0]);
parsedResult.start = result;
}
else {
parsedResult = context.createParsingResult(match.index, match[0], result);
}
context.debug(function () {
return console.log(parser.constructor.name + " extracted result " + parsedResult);
});
results.push(parsedResult);
remainingText = originalText.substring(index + parsedResult.text.length);
match = pattern.exec(remainingText);
};
while (match) {
_loop_1();
}
return results;
};
return Chrono;
}());
exports.Chrono = Chrono;
var ParsingContext = (function () {
function ParsingContext(text, refDate, option) {
this.text = text;
this.refDate = refDate;
this.option = option;
}
ParsingContext.prototype.createParsingComponents = function (components) {
return new results_1.ParsingComponents(this.refDate, components);
};
ParsingContext.prototype.createParsingResult = function (index, textOrEndIndex, startComponents, endComponents) {
var text = (typeof textOrEndIndex === 'string') ? textOrEndIndex :
this.text.substring(index, textOrEndIndex);
var start = startComponents ? this.createParsingComponents(startComponents) : null;
var end = endComponents ? this.createParsingComponents(endComponents) : null;
return new results_1.ParsingResult(this.refDate, index, text, start, end);
};
ParsingContext.prototype.debug = function (block) {
if (this.option.debug) {
if (this.option.debug instanceof Function) {
this.option.debug(block);
}
else {
var handler = this.option.debug;
handler.debug(block);
}
}
};
return ParsingContext;
}());
exports.ParsingContext = ParsingContext;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field } from 'redux-form';
import { FormattedMessage, intlShape, injectIntl } from 'react-intl';
import { RadioButton, RadioButtonGroup } from '@folio/stripes/components';
import styles from './visibility-field.css';
class VisibilityField extends Component {
static propTypes = {
disabled: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string
]),
intl: intlShape.isRequired
};
render() {
let { disabled, intl } = this.props;
let disabledReason = typeof disabled === 'string' ? disabled : '';
return (
<div
className={styles['visibility-field']}
data-test-eholdings-resource-visibility-field
>
<Field
name="isVisible"
label={<FormattedMessage id="ui-eholdings.label.showToPatrons" />}
component={RadioButtonGroup}
disabled={!!disabled}
>
<RadioButton label={intl.formatMessage({ id: 'ui-eholdings.yes' })} value="true" />
<RadioButton label={intl.formatMessage({ id: 'ui-eholdings.label.no.reason' }, { disabledReason })} value="false" />
</Field>
</div>
);
}
}
export default injectIntl(VisibilityField);
|
import React from "react";
import { connect } from "react-redux";
import { updateRequest } from "../actions";
import "./RequestForm.css";
class UpdateForm extends React.Component {
state = {
request: this.props.activeRequest || {
food_location: "",
food_amount: "",
food_type: "",
food_expiration: ""
}
};
// componentDidUpdate(prevProps) {
// if (this.props.activeRequest && prevProps === this.props.activeRequest) {
// this.setState({
// request: this.props.activeRequest
// });
// }
// }
handleChanges = e => {
e.persist();
// e.preventDefault();
// if (e.target.name === 'food_expiration') {
// const expVal = new Date(e.target.value)
// this.setState({
// request: {
// ...this.state,
// food_expiration: expVal
// }
// });
// if (e.target.name === 'food_amount') {
// const quantity = Number(e.target.value)
// this.setState({
// request: {
// ...this.state,
// food_amount: quantity
// }
// });
// } else {
this.setState({
request: {
...this.state.request,
[e.target.name]: e.target.value
}
});
// }
};
handleSubmit = e => {
e.preventDefault();
this.props.updateRequest(this.state.request);
this.setState({
request: {
food_location: "",
food_amount: "",
food_type: "",
food_expiration: ""
}
});
// this.props.history.push('/business');
setTimeout(() => this.props.history.push("/business"), 1000);
};
render() {
return (
<div className="add-request">
<h1 className="request-form-title">Update Request</h1>
<form
className="request-form"
onSubmit={e => this.handleSubmit(e, this.state.request)}
>
<input
className="request-form-input"
type="text"
name="food_location"
onChange={this.handleChanges}
placeholder="Location"
value={this.state.request.food_location}
/>
{/* TODO: Fix uncontrolled input */}
<input
className="request-form-input"
type="text"
name="food_amount"
onChange={this.handleChanges}
placeholder="Quantity"
value={this.state.request.food_amount}
/>
<input
className="request-form-input"
type="text"
name="food_type"
onChange={this.handleChanges}
placeholder="Type of Food"
value={this.state.request.food_type}
/>
<input
className="request-form-input"
type="datetime-local"
name="food_expiration"
onChange={this.handleChanges}
placeholder="Expiration"
value={this.state.request.food_expiration}
/>
<button className="request-form-btn">Update Request</button>
</form>
</div>
);
}
}
const mapStateToProps = state => ({
activeRequest: state.activeRequest
});
export default connect(
mapStateToProps,
{ updateRequest }
)(UpdateForm);
|
""" template for python scripts following Pauliuk et al 2015 - Fig 1
In the file there is only one place to define/specify folders - the function
file_folder_specs().
Notes
------
The docstrings follow roughly the guidelines for numpy docstrings: http://sphinx-doc.org/latest/ext/example_numpy.html
AUTHOR timestamp
KST 20150625
"""
# general
import sys
import os
import logging
import collections
import subprocess
import pickle
# scientific
#import numpy as np
#import scipy.stats as ss
#import scipy.optimize as so
#import pandas as pd
# graphics
#import matplotlib.pyplot as plt
#import seaborn as sns
# testing - if tests should run with each script
#import pytest
def file_folder_specs():
""" Get file and folder structure - the place to change folder information.
Returns
-------
dict
File and folder specs
"""
root = 'D:\KST\proj\template\template'
files_folders = {
'root' : root,
#'data' : os.path.abspath(
#os.path.join(root, 'data')
#)
}
# we can also check for existence here to put everything in place
#if not os.path.exists(files_folders[data]): os.makedirs(files_folders[data])
return files_folders
def _start_logger(logfile = 'log.txt', filemode = 'w', detail = False):
log = logging.getLogger()
log.setLevel(logging.DEBUG)
loghandler = logging.FileHandler(logfile,filemode)
loghandler.setLevel(logging.DEBUG)
if detail:
format = logging.Formatter("%(asctime)s %(msecs)d - %(levelname)s - %(module)s.%(funcName)s(%(lineno)d) - %(message)s [%(processName)s(%(process)d) %(threadName)s(%(thread)d)]" , datefmt='%Y%m%d %H%M%S')
else:
format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s" , datefmt='%Y%m%d %H%M%S')
loghandler.setFormatter(format)
log.addHandler(loghandler)
return loghandler
def _stop_logger(handler):
handler.flush()
handler.close()
log = logging.getLogger()
log.removeHandler(handler)
def main():
# The programm code comes here
# SETTINGS
ff = file_folder_specs()
# READ DATA
# ORGANIZE/CLEAN DATA
# CALCULATIONS
# FORMAT RESULTS
# VISUALIZE
# STORE
return locals()
if __name__ == "__main__":
# The main routine gets only started if the script is run directly.
# It only includes the logging boilerplate and a top level try-except for catching and logging all exceptions.
# START LOGGING
if not os.path.exists('./log'): os.makedirs('./log')
log_summary = _start_logger(logfile = './log/process.log')
#log_detail = _start_logger(logfile = './log/process_details.log', detail = True)
logging.info('Start logging of {}'.format(__file__))
# remove/change this try-excep depending on the version control used
try:
logging.info("Current git commit: %s",
subprocess.check_output(["git", "log", "--pretty=format:%H", "-n1"]).decode("utf-8"))
except:
logging.warn('Running without version control')
# If you have quick test you can run them within the script, otherwise use py.test from the command line and delete these lines
#if pytest.main() == 0:
#logging.info("All tests passed")
#else:
#logging.error("Some tests not passed!")
# MAIN PROGRAMM
# remove the try-except if exception should just stop the programm, but remember to end the program with the _stop_logger functions.
try:
# The following update your local namespace with the variables from main()
locals().update(main())
# if you don't want the script to pollute your namespace use
# which gives you all varibales from main in a dict called 'results'
#results = main()
except Exception as exc:
logging.exception(exc)
raise
finally:
# STOP LOGGER - clean
_stop_logger(log_summary)
#_stop_logger(log_detail)
|
$(function(){
var eventClick = new MouseEvent('click', {
'bubbles': true,
'cancelable': true
});
/*chrome.extension.sendRequest({which:'12306', cmd: 'get_person'}, function(response) {
});*/
g_person = sessionStorage.getItem('pass_person');
if (!g_person)
return;
var persons = g_person.replace(/[ ,]+/g, '|');
var regx = new RegExp(persons);
$('#normal_passenger_id label').filter(function(){return $(this).text().match(regx)}).each(function(){this.dispatchEvent(eventClick)});
$('#submitOrder_id')[0].dispatchEvent(eventClick);
setTimeout(function checkok(){
if (!$('#qr_submit_id').hasClass("btn92s"))
{
setTimeout(checkok, 100);
return;
}
$('#qr_submit_id')[0].dispatchEvent(eventClick)
}, 100);
$('<audio src="/otn/resources/js/framework/audio/message.wav" loop="true" autoplay="true"></audio>').appendTo('body');
}); |
var searchData=
[
['x',['X',['../class_joystick.html#ac84ba4b69b1aa3d6082025bc8ac82f2b',1,'Joystick::X()'],['../class_keyboard.html#ae0234dd8601eeffdb3ed87ffe8a23322',1,'Keyboard::X()'],['../class_motion_controller.html#ab10eb9ead64b5bdff110bf95a9b1504a',1,'MotionController::X()'],['../class_mouse.html#adc7051776b157b45d73708f056ff782f',1,'Mouse::X()'],['../class_mouse_controller.html#aa0286582e93a6a46482c5475c2b6a1ac',1,'MouseController::X()'],['../class_multi_controller.html#a1361424d903f358201dbf2097aa07650',1,'MultiController::X()'],['../class_window.html#a505a19de4bee440e4abe4ff7c9f72b80',1,'Window::X()']]],
['xangle',['XAngle',['../class_projector.html#ae94b7cd2c8cf79e09af05ede625164e3',1,'Projector']]]
];
|
'use strict'
import SCNConstraint from './SCNConstraint'
/**
*
* @access public
* @extends {SCNConstraint}
* @see https://developer.apple.com/documentation/scenekit/scnaccelerationconstraint
*/
export default class SCNAccelerationConstraint extends SCNConstraint {
/**
* constructor
* @access public
* @constructor
*/
constructor() {
super()
// Instance Properties
/**
*
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnaccelerationconstraint/2873359-damping
*/
this.damping = 0
/**
*
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnaccelerationconstraint/2873367-decelerationdistance
*/
this.decelerationDistance = 0
/**
*
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnaccelerationconstraint/2873355-maximumlinearacceleration
*/
this.maximumLinearAcceleration = 0
/**
*
* @type {number}
* @see https://developer.apple.com/documentation/scenekit/scnaccelerationconstraint/2873384-maximumlinearvelocity
*/
this.maximumLinearVelocity = 0
}
}
|
"""Test Z-Wave locks."""
from unittest.mock import MagicMock, patch
import pytest
from homeassistant import config_entries
from homeassistant.components.zwave import const, lock
from tests.mock.zwave import MockEntityValues, MockNode, MockValue, value_changed
# Integration is disabled
pytest.skip("Integration has been disabled in the manifest", allow_module_level=True)
def test_get_device_detects_lock(mock_openzwave):
"""Test get_device returns a Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=None,
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert isinstance(device, lock.ZwaveLock)
def test_lock_turn_on_and_off(mock_openzwave):
"""Test turning on a Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=None,
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert not values.primary.data
device.lock()
assert values.primary.data
device.unlock()
assert not values.primary.data
def test_lock_value_changed(mock_openzwave):
"""Test value changed for Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=None,
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert not device.is_locked
values.primary.data = True
value_changed(values.primary)
assert device.is_locked
def test_lock_state_workaround(mock_openzwave):
"""Test value changed for Z-Wave lock using notification state."""
node = MockNode(manufacturer_id="0090", product_id="0440")
values = MockEntityValues(
primary=MockValue(data=True, node=node),
access_control=MockValue(data=1, node=node),
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values)
assert device.is_locked
values.access_control.data = 2
value_changed(values.access_control)
assert not device.is_locked
def test_track_message_workaround(mock_openzwave):
"""Test value changed for Z-Wave lock by alarm-clearing workaround."""
node = MockNode(
manufacturer_id="003B",
product_id="5044",
stats={"lastReceivedMessage": [0] * 6},
)
values = MockEntityValues(
primary=MockValue(data=True, node=node),
access_control=None,
alarm_type=None,
alarm_level=None,
)
# Here we simulate an RF lock. The first lock.get_device will call
# update properties, simulating the first DoorLock report. We then trigger
# a change, simulating the openzwave automatic refreshing behavior (which
# is enabled for at least the lock that needs this workaround)
node.stats["lastReceivedMessage"][5] = const.COMMAND_CLASS_DOOR_LOCK
device = lock.get_device(node=node, values=values)
value_changed(values.primary)
assert device.is_locked
assert device.extra_state_attributes[lock.ATTR_NOTIFICATION] == "RF Lock"
# Simulate a keypad unlock. We trigger a value_changed() which simulates
# the Alarm notification received from the lock. Then, we trigger
# value_changed() to simulate the automatic refreshing behavior.
values.access_control = MockValue(data=6, node=node)
values.alarm_type = MockValue(data=19, node=node)
values.alarm_level = MockValue(data=3, node=node)
node.stats["lastReceivedMessage"][5] = const.COMMAND_CLASS_ALARM
value_changed(values.access_control)
node.stats["lastReceivedMessage"][5] = const.COMMAND_CLASS_DOOR_LOCK
values.primary.data = False
value_changed(values.primary)
assert not device.is_locked
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS]
== "Unlocked with Keypad by user 3"
)
# Again, simulate an RF lock.
device.lock()
node.stats["lastReceivedMessage"][5] = const.COMMAND_CLASS_DOOR_LOCK
value_changed(values.primary)
assert device.is_locked
assert device.extra_state_attributes[lock.ATTR_NOTIFICATION] == "RF Lock"
def test_v2btze_value_changed(mock_openzwave):
"""Test value changed for v2btze Z-Wave lock."""
node = MockNode(manufacturer_id="010e", product_id="0002")
values = MockEntityValues(
primary=MockValue(data=None, node=node),
v2btze_advanced=MockValue(data="Advanced", node=node),
access_control=MockValue(data=19, node=node),
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert device._v2btze
assert not device.is_locked
values.access_control.data = 24
value_changed(values.primary)
assert device.is_locked
def test_alarm_type_workaround(mock_openzwave):
"""Test value changed for Z-Wave lock using alarm type."""
node = MockNode(manufacturer_id="0109", product_id="0000")
values = MockEntityValues(
primary=MockValue(data=True, node=node),
access_control=None,
alarm_type=MockValue(data=16, node=node),
alarm_level=None,
)
device = lock.get_device(node=node, values=values)
assert not device.is_locked
values.alarm_type.data = 18
value_changed(values.alarm_type)
assert device.is_locked
values.alarm_type.data = 19
value_changed(values.alarm_type)
assert not device.is_locked
values.alarm_type.data = 21
value_changed(values.alarm_type)
assert device.is_locked
values.alarm_type.data = 22
value_changed(values.alarm_type)
assert not device.is_locked
values.alarm_type.data = 24
value_changed(values.alarm_type)
assert device.is_locked
values.alarm_type.data = 25
value_changed(values.alarm_type)
assert not device.is_locked
values.alarm_type.data = 27
value_changed(values.alarm_type)
assert device.is_locked
def test_lock_access_control(mock_openzwave):
"""Test access control for Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=MockValue(data=11, node=node),
alarm_type=None,
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert device.extra_state_attributes[lock.ATTR_NOTIFICATION] == "Lock Jammed"
def test_lock_alarm_type(mock_openzwave):
"""Test alarm type for Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=None,
alarm_type=MockValue(data=None, node=node),
alarm_level=None,
)
device = lock.get_device(node=node, values=values, node_config={})
assert lock.ATTR_LOCK_STATUS not in device.extra_state_attributes
values.alarm_type.data = 21
value_changed(values.alarm_type)
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS] == "Manually Locked None"
)
values.alarm_type.data = 18
value_changed(values.alarm_type)
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS]
== "Locked with Keypad by user None"
)
values.alarm_type.data = 161
value_changed(values.alarm_type)
assert device.extra_state_attributes[lock.ATTR_LOCK_STATUS] == "Tamper Alarm: None"
values.alarm_type.data = 9
value_changed(values.alarm_type)
assert device.extra_state_attributes[lock.ATTR_LOCK_STATUS] == "Deadbolt Jammed"
def test_lock_alarm_level(mock_openzwave):
"""Test alarm level for Z-Wave lock."""
node = MockNode()
values = MockEntityValues(
primary=MockValue(data=None, node=node),
access_control=None,
alarm_type=MockValue(data=None, node=node),
alarm_level=MockValue(data=None, node=node),
)
device = lock.get_device(node=node, values=values, node_config={})
assert lock.ATTR_LOCK_STATUS not in device.extra_state_attributes
values.alarm_type.data = 21
values.alarm_level.data = 1
value_changed(values.alarm_type)
value_changed(values.alarm_level)
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS]
== "Manually Locked by Key Cylinder or Inside thumb turn"
)
values.alarm_type.data = 18
values.alarm_level.data = "alice"
value_changed(values.alarm_type)
value_changed(values.alarm_level)
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS]
== "Locked with Keypad by user alice"
)
values.alarm_type.data = 161
values.alarm_level.data = 1
value_changed(values.alarm_type)
value_changed(values.alarm_level)
assert (
device.extra_state_attributes[lock.ATTR_LOCK_STATUS]
== "Tamper Alarm: Too many keypresses"
)
async def setup_ozw(hass, mock_openzwave):
"""Set up the mock ZWave config entry."""
hass.config.components.add("zwave")
config_entry = config_entries.ConfigEntry(
1,
"zwave",
"Mock Title",
{"usb_path": "mock-path", "network_key": "mock-key"},
"test",
)
await hass.config_entries.async_forward_entry_setup(config_entry, "lock")
await hass.async_block_till_done()
async def test_lock_set_usercode_service(hass, mock_openzwave):
"""Test the zwave lock set_usercode service."""
mock_network = hass.data[const.DATA_NETWORK] = MagicMock()
node = MockNode(node_id=12)
value0 = MockValue(data=" ", node=node, index=0)
value1 = MockValue(data=" ", node=node, index=1)
node.get_values.return_value = {value0.value_id: value0, value1.value_id: value1}
mock_network.nodes = {node.node_id: node}
await setup_ozw(hass, mock_openzwave)
await hass.async_block_till_done()
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_SET_USERCODE,
{
const.ATTR_NODE_ID: node.node_id,
lock.ATTR_USERCODE: "1234",
lock.ATTR_CODE_SLOT: 1,
},
)
await hass.async_block_till_done()
assert value1.data == "1234"
mock_network.nodes = {node.node_id: node}
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_SET_USERCODE,
{
const.ATTR_NODE_ID: node.node_id,
lock.ATTR_USERCODE: "123",
lock.ATTR_CODE_SLOT: 1,
},
)
await hass.async_block_till_done()
assert value1.data == "1234"
async def test_lock_get_usercode_service(hass, mock_openzwave):
"""Test the zwave lock get_usercode service."""
mock_network = hass.data[const.DATA_NETWORK] = MagicMock()
node = MockNode(node_id=12)
value0 = MockValue(data=None, node=node, index=0)
value1 = MockValue(data="1234", node=node, index=1)
node.get_values.return_value = {value0.value_id: value0, value1.value_id: value1}
await setup_ozw(hass, mock_openzwave)
await hass.async_block_till_done()
with patch.object(lock, "_LOGGER") as mock_logger:
mock_network.nodes = {node.node_id: node}
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_GET_USERCODE,
{const.ATTR_NODE_ID: node.node_id, lock.ATTR_CODE_SLOT: 1},
)
await hass.async_block_till_done()
# This service only seems to write to the log
assert mock_logger.info.called
assert len(mock_logger.info.mock_calls) == 1
assert mock_logger.info.mock_calls[0][1][2] == "1234"
async def test_lock_clear_usercode_service(hass, mock_openzwave):
"""Test the zwave lock clear_usercode service."""
mock_network = hass.data[const.DATA_NETWORK] = MagicMock()
node = MockNode(node_id=12)
value0 = MockValue(data=None, node=node, index=0)
value1 = MockValue(data="123", node=node, index=1)
node.get_values.return_value = {value0.value_id: value0, value1.value_id: value1}
mock_network.nodes = {node.node_id: node}
await setup_ozw(hass, mock_openzwave)
await hass.async_block_till_done()
await hass.services.async_call(
lock.DOMAIN,
lock.SERVICE_CLEAR_USERCODE,
{const.ATTR_NODE_ID: node.node_id, lock.ATTR_CODE_SLOT: 1},
)
await hass.async_block_till_done()
assert value1.data == "\0\0\0"
|
data = (
'ddwim', # 0x00
'ddwib', # 0x01
'ddwibs', # 0x02
'ddwis', # 0x03
'ddwiss', # 0x04
'ddwing', # 0x05
'ddwij', # 0x06
'ddwic', # 0x07
'ddwik', # 0x08
'ddwit', # 0x09
'ddwip', # 0x0a
'ddwih', # 0x0b
'ddyu', # 0x0c
'ddyug', # 0x0d
'ddyugg', # 0x0e
'ddyugs', # 0x0f
'ddyun', # 0x10
'ddyunj', # 0x11
'ddyunh', # 0x12
'ddyud', # 0x13
'ddyul', # 0x14
'ddyulg', # 0x15
'ddyulm', # 0x16
'ddyulb', # 0x17
'ddyuls', # 0x18
'ddyult', # 0x19
'ddyulp', # 0x1a
'ddyulh', # 0x1b
'ddyum', # 0x1c
'ddyub', # 0x1d
'ddyubs', # 0x1e
'ddyus', # 0x1f
'ddyuss', # 0x20
'ddyung', # 0x21
'ddyuj', # 0x22
'ddyuc', # 0x23
'ddyuk', # 0x24
'ddyut', # 0x25
'ddyup', # 0x26
'ddyuh', # 0x27
'ddeu', # 0x28
'ddeug', # 0x29
'ddeugg', # 0x2a
'ddeugs', # 0x2b
'ddeun', # 0x2c
'ddeunj', # 0x2d
'ddeunh', # 0x2e
'ddeud', # 0x2f
'ddeul', # 0x30
'ddeulg', # 0x31
'ddeulm', # 0x32
'ddeulb', # 0x33
'ddeuls', # 0x34
'ddeult', # 0x35
'ddeulp', # 0x36
'ddeulh', # 0x37
'ddeum', # 0x38
'ddeub', # 0x39
'ddeubs', # 0x3a
'ddeus', # 0x3b
'ddeuss', # 0x3c
'ddeung', # 0x3d
'ddeuj', # 0x3e
'ddeuc', # 0x3f
'ddeuk', # 0x40
'ddeut', # 0x41
'ddeup', # 0x42
'ddeuh', # 0x43
'ddyi', # 0x44
'ddyig', # 0x45
'ddyigg', # 0x46
'ddyigs', # 0x47
'ddyin', # 0x48
'ddyinj', # 0x49
'ddyinh', # 0x4a
'ddyid', # 0x4b
'ddyil', # 0x4c
'ddyilg', # 0x4d
'ddyilm', # 0x4e
'ddyilb', # 0x4f
'ddyils', # 0x50
'ddyilt', # 0x51
'ddyilp', # 0x52
'ddyilh', # 0x53
'ddyim', # 0x54
'ddyib', # 0x55
'ddyibs', # 0x56
'ddyis', # 0x57
'ddyiss', # 0x58
'ddying', # 0x59
'ddyij', # 0x5a
'ddyic', # 0x5b
'ddyik', # 0x5c
'ddyit', # 0x5d
'ddyip', # 0x5e
'ddyih', # 0x5f
'ddi', # 0x60
'ddig', # 0x61
'ddigg', # 0x62
'ddigs', # 0x63
'ddin', # 0x64
'ddinj', # 0x65
'ddinh', # 0x66
'ddid', # 0x67
'ddil', # 0x68
'ddilg', # 0x69
'ddilm', # 0x6a
'ddilb', # 0x6b
'ddils', # 0x6c
'ddilt', # 0x6d
'ddilp', # 0x6e
'ddilh', # 0x6f
'ddim', # 0x70
'ddib', # 0x71
'ddibs', # 0x72
'ddis', # 0x73
'ddiss', # 0x74
'dding', # 0x75
'ddij', # 0x76
'ddic', # 0x77
'ddik', # 0x78
'ddit', # 0x79
'ddip', # 0x7a
'ddih', # 0x7b
'ra', # 0x7c
'rag', # 0x7d
'ragg', # 0x7e
'rags', # 0x7f
'ran', # 0x80
'ranj', # 0x81
'ranh', # 0x82
'rad', # 0x83
'ral', # 0x84
'ralg', # 0x85
'ralm', # 0x86
'ralb', # 0x87
'rals', # 0x88
'ralt', # 0x89
'ralp', # 0x8a
'ralh', # 0x8b
'ram', # 0x8c
'rab', # 0x8d
'rabs', # 0x8e
'ras', # 0x8f
'rass', # 0x90
'rang', # 0x91
'raj', # 0x92
'rac', # 0x93
'rak', # 0x94
'rat', # 0x95
'rap', # 0x96
'rah', # 0x97
'rae', # 0x98
'raeg', # 0x99
'raegg', # 0x9a
'raegs', # 0x9b
'raen', # 0x9c
'raenj', # 0x9d
'raenh', # 0x9e
'raed', # 0x9f
'rael', # 0xa0
'raelg', # 0xa1
'raelm', # 0xa2
'raelb', # 0xa3
'raels', # 0xa4
'raelt', # 0xa5
'raelp', # 0xa6
'raelh', # 0xa7
'raem', # 0xa8
'raeb', # 0xa9
'raebs', # 0xaa
'raes', # 0xab
'raess', # 0xac
'raeng', # 0xad
'raej', # 0xae
'raec', # 0xaf
'raek', # 0xb0
'raet', # 0xb1
'raep', # 0xb2
'raeh', # 0xb3
'rya', # 0xb4
'ryag', # 0xb5
'ryagg', # 0xb6
'ryags', # 0xb7
'ryan', # 0xb8
'ryanj', # 0xb9
'ryanh', # 0xba
'ryad', # 0xbb
'ryal', # 0xbc
'ryalg', # 0xbd
'ryalm', # 0xbe
'ryalb', # 0xbf
'ryals', # 0xc0
'ryalt', # 0xc1
'ryalp', # 0xc2
'ryalh', # 0xc3
'ryam', # 0xc4
'ryab', # 0xc5
'ryabs', # 0xc6
'ryas', # 0xc7
'ryass', # 0xc8
'ryang', # 0xc9
'ryaj', # 0xca
'ryac', # 0xcb
'ryak', # 0xcc
'ryat', # 0xcd
'ryap', # 0xce
'ryah', # 0xcf
'ryae', # 0xd0
'ryaeg', # 0xd1
'ryaegg', # 0xd2
'ryaegs', # 0xd3
'ryaen', # 0xd4
'ryaenj', # 0xd5
'ryaenh', # 0xd6
'ryaed', # 0xd7
'ryael', # 0xd8
'ryaelg', # 0xd9
'ryaelm', # 0xda
'ryaelb', # 0xdb
'ryaels', # 0xdc
'ryaelt', # 0xdd
'ryaelp', # 0xde
'ryaelh', # 0xdf
'ryaem', # 0xe0
'ryaeb', # 0xe1
'ryaebs', # 0xe2
'ryaes', # 0xe3
'ryaess', # 0xe4
'ryaeng', # 0xe5
'ryaej', # 0xe6
'ryaec', # 0xe7
'ryaek', # 0xe8
'ryaet', # 0xe9
'ryaep', # 0xea
'ryaeh', # 0xeb
'reo', # 0xec
'reog', # 0xed
'reogg', # 0xee
'reogs', # 0xef
'reon', # 0xf0
'reonj', # 0xf1
'reonh', # 0xf2
'reod', # 0xf3
'reol', # 0xf4
'reolg', # 0xf5
'reolm', # 0xf6
'reolb', # 0xf7
'reols', # 0xf8
'reolt', # 0xf9
'reolp', # 0xfa
'reolh', # 0xfb
'reom', # 0xfc
'reob', # 0xfd
'reobs', # 0xfe
'reos', # 0xff
)
|
/*
---------------------------------------
| All rights reserved to KIGNAMN |
| If there is any error, just visit the|
| KINGMANDEV Discord Server |
| Phone Number: +962792914245 |
---------------------------------------
______███████████████████████
______█████████████████████████
______███████████████████████__██
____▒░██████████████████████____██
___▒░░████████████████████▒▒____██
__▒▒░░███████████████████▒░▒___██
__▒░░░▒█████████████████▒░░▒__██
_▒▒░░░░▒███████████████▒░░▒_██
▒░▒░░░░░▒█████████████▒░░░▒█
▒▒░▒▒░░░▒▒███████████▒░░▒▒
▒▒░░▒▒░░░▒███████████▒▒░░
▒░▒▒░░▒▒░░░░▒▒░░░░░░░░▒▒
▒▒░░▒░░▒▒░░░░▒░░░░░░░▒▒
▒▒▒░░▒░░▒▒░░░░░░░░░░▒▒
_▒░▒░░░▒▒░░░░░░░░░░▒▒
__▒░▒░░░▒░░░░░░░░░░▒▒
___▒░▒▒░░░░░░░░░░░░▒▒
____▒░▒▒░░░░░░░░░░░▒▒
______▒▒░░░░░░░░░░░▒▒
_______▒▒░░░░░░░░░░▒▒
________▒▒░░░░░░░░░▒▒
_________▒▒░░░░░░░░▒▒
_________▒▒░░░░░░░░▒▒
_________▒▒░░░░░░░░▒▒
*/
const { Schema, model } = require('mongoose');
const copypasterusers = Schema({
userID: {
type: String,
required: true
},
des : {
type: String,
default: "",
},
ocode:{
type: String,
},
cpcode:{
type: String,
},
reprteduser:{
type: String,
}
});
module.exports = model('copypasterusers', copypasterusers);
|
import { pluginActivate, pluginDeactivate } from '../../commonMethods/controller'
import constants from '../../commonMethods/constants'
import { getKeyCodeDetails } from '../../commonMethods/remoteControl'
export default {
title: 'RemoteControl Key - 004',
description: 'Validate Thunder response when Key is invoked with Invalid Json Format',
context: {
deviceName: 'DevInput',
code: '1,',
},
plugin: [constants.remoteControlPlugin],
setup() {
return this.$sequence([
() => pluginDeactivate.call(this, constants.remoteControlPlugin),
() => pluginActivate.call(this, constants.remoteControlPlugin),
])
},
steps: [
{
description: 'Invoke Key with invalid json format and validate the result',
test() {
return getKeyCodeDetails.call(
this,
this.$context.read('deviceName'),
this.$context.read('code')
)
},
validate(res) {
if (res.code === 30 && res.message === 'ERROR_BAD_REQUEST') {
return true
} else {
throw new Error(
`Error message is improper while getting key with invalid json format and Error: {code: ${res.code}, message:${res.message}}`
)
}
},
},
],
}
|
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""This module detects whether third-party libraries, utilized by third-party
drivers, are present on the system. If they are not, it mocks them and tinkers
with sys.modules so that the drivers can be loaded by unit tests, and the unit
tests can continue to test the functionality of those drivers without the
respective external libraries' actually being present.
Any external library required by a third-party driver should be mocked here.
Current list of mocked libraries:
- seamicroclient
- ipminative
- proliantutils
- pysnmp
- scciclient
"""
import sys
import mock
from oslo_utils import importutils
import six
from ironic.drivers.modules import ipmitool
from ironic.tests.drivers import third_party_driver_mock_specs as mock_specs
# attempt to load the external 'seamicroclient' library, which is
# required by the optional drivers.modules.seamicro module
seamicroclient = importutils.try_import("seamicroclient")
if not seamicroclient:
smc = mock.MagicMock(spec_set=mock_specs.SEAMICRO_SPEC)
smc.client = mock.MagicMock(spec_set=mock_specs.SEAMICRO_CLIENT_MOD_SPEC)
smc.exceptions = mock.MagicMock(spec_set=mock_specs.SEAMICRO_EXC_SPEC)
smc.exceptions.ClientException = Exception
smc.exceptions.UnsupportedVersion = Exception
sys.modules['seamicroclient'] = smc
sys.modules['seamicroclient.client'] = smc.client
sys.modules['seamicroclient.exceptions'] = smc.exceptions
# if anything has loaded the seamicro driver yet, reload it now that
# the external library has been mocked
if 'ironic.drivers.modules.seamicro' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.seamicro'])
# IPMITool driver checks the system for presence of 'ipmitool' binary during
# __init__. We bypass that check in order to run the unit tests, which do not
# depend on 'ipmitool' being on the system.
ipmitool.TIMING_SUPPORT = False
ipmitool.DUAL_BRIDGE_SUPPORT = False
ipmitool.SINGLE_BRIDGE_SUPPORT = False
pyghmi = importutils.try_import("pyghmi")
if not pyghmi:
p = mock.MagicMock(spec_set=mock_specs.PYGHMI_SPEC)
p.exceptions = mock.MagicMock(spec_set=mock_specs.PYGHMI_EXC_SPEC)
p.exceptions.IpmiException = Exception
p.ipmi = mock.MagicMock(spec_set=mock_specs.PYGHMI_IPMI_SPEC)
p.ipmi.command = mock.MagicMock(spec_set=mock_specs.PYGHMI_IPMICMD_SPEC)
p.ipmi.command.Command = mock.MagicMock(spec_set=[])
sys.modules['pyghmi'] = p
sys.modules['pyghmi.exceptions'] = p.exceptions
sys.modules['pyghmi.ipmi'] = p.ipmi
sys.modules['pyghmi.ipmi.command'] = p.ipmi.command
# FIXME(deva): the next line is a hack, because several unit tests
# actually depend on this particular string being present
# in pyghmi.ipmi.command.boot_devices
p.ipmi.command.boot_devices = {'pxe': 4}
if 'ironic.drivers.modules.ipminative' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.ipminative'])
proliantutils = importutils.try_import('proliantutils')
if not proliantutils:
proliantutils = mock.MagicMock(spec_set=mock_specs.PROLIANTUTILS_SPEC)
sys.modules['proliantutils'] = proliantutils
sys.modules['proliantutils.ilo'] = proliantutils.ilo
sys.modules['proliantutils.ilo.client'] = proliantutils.ilo.client
sys.modules['proliantutils.exception'] = proliantutils.exception
proliantutils.exception.IloError = type('IloError', (Exception,), {})
command_exception = type('IloCommandNotSupportedError', (Exception,), {})
proliantutils.exception.IloCommandNotSupportedError = command_exception
if 'ironic.drivers.ilo' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.ilo'])
# attempt to load the external 'pywsman' library, which is required by
# the optional drivers.modules.drac and drivers.modules.amt module
pywsman = importutils.try_import('pywsman')
if not pywsman:
pywsman = mock.MagicMock(spec_set=mock_specs.PYWSMAN_SPEC)
sys.modules['pywsman'] = pywsman
# Now that the external library has been mocked, if anything had already
# loaded any of the drivers, reload them.
if 'ironic.drivers.modules.drac' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.drac'])
if 'ironic.drivers.modules.amt' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.amt'])
# attempt to load the external 'iboot' library, which is required by
# the optional drivers.modules.iboot module
iboot = importutils.try_import("iboot")
if not iboot:
ib = mock.MagicMock(spec_set=mock_specs.IBOOT_SPEC)
ib.iBootInterface = mock.MagicMock(spec_set=[])
sys.modules['iboot'] = ib
# if anything has loaded the iboot driver yet, reload it now that the
# external library has been mocked
if 'ironic.drivers.modules.iboot' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.iboot'])
# attempt to load the external 'pysnmp' library, which is required by
# the optional drivers.modules.snmp module
pysnmp = importutils.try_import("pysnmp")
if not pysnmp:
pysnmp = mock.MagicMock(spec_set=mock_specs.PYWSNMP_SPEC)
sys.modules["pysnmp"] = pysnmp
sys.modules["pysnmp.entity"] = pysnmp.entity
sys.modules["pysnmp.entity.rfc3413"] = pysnmp.entity.rfc3413
sys.modules["pysnmp.entity.rfc3413.oneliner"] = (
pysnmp.entity.rfc3413.oneliner)
sys.modules["pysnmp.entity.rfc3413.oneliner.cmdgen"] = (
pysnmp.entity.rfc3413.oneliner.cmdgen)
sys.modules["pysnmp.error"] = pysnmp.error
pysnmp.error.PySnmpError = Exception
sys.modules["pysnmp.proto"] = pysnmp.proto
sys.modules["pysnmp.proto.rfc1902"] = pysnmp.proto.rfc1902
# Patch the RFC1902 integer class with a python int
pysnmp.proto.rfc1902.Integer = int
# if anything has loaded the snmp driver yet, reload it now that the
# external library has been mocked
if 'ironic.drivers.modules.snmp' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.snmp'])
# attempt to load the external 'scciclient' library, which is required by
# the optional drivers.modules.irmc module
scciclient = importutils.try_import('scciclient')
if not scciclient:
mock_scciclient = mock.MagicMock(spec_set=mock_specs.SCCICLIENT_SPEC)
sys.modules['scciclient'] = mock_scciclient
sys.modules['scciclient.irmc'] = mock_scciclient.irmc
sys.modules['scciclient.irmc.scci'] = mock.MagicMock(
spec_set=mock_specs.SCCICLIENT_IRMC_SCCI_SPEC,
POWER_OFF=mock.sentinel.POWER_OFF,
POWER_ON=mock.sentinel.POWER_ON,
POWER_RESET=mock.sentinel.POWER_RESET)
# if anything has loaded the iRMC driver yet, reload it now that the
# external library has been mocked
if 'ironic.drivers.modules.irmc' in sys.modules:
six.moves.reload_module(sys.modules['ironic.drivers.modules.irmc'])
pyremotevbox = importutils.try_import('pyremotevbox')
if not pyremotevbox:
pyremotevbox = mock.MagicMock(spec_set=mock_specs.PYREMOTEVBOX_SPEC)
pyremotevbox.exception = mock.MagicMock(
spec_set=mock_specs.PYREMOTEVBOX_EXC_SPEC)
pyremotevbox.exception.PyRemoteVBoxException = Exception
pyremotevbox.exception.VmInWrongPowerState = Exception
pyremotevbox.vbox = mock.MagicMock(
spec_set=mock_specs.PYREMOTEVBOX_VBOX_SPEC)
sys.modules['pyremotevbox'] = pyremotevbox
if 'ironic.drivers.modules.virtualbox' in sys.modules:
six.moves.reload_module(
sys.modules['ironic.drivers.modules.virtualbox'])
ironic_discoverd = importutils.try_import('ironic_discoverd')
if not ironic_discoverd:
ironic_discoverd = mock.MagicMock(
spec_set=mock_specs.IRONIC_DISCOVERD_SPEC)
ironic_discoverd.__version_info__ = (1, 0, 0)
ironic_discoverd.__version__ = "1.0.0"
sys.modules['ironic_discoverd'] = ironic_discoverd
sys.modules['ironic_discoverd.client'] = ironic_discoverd.client
if 'ironic.drivers.modules.discoverd' in sys.modules:
six.moves.reload_module(
sys.modules['ironic.drivers.modules.discoverd'])
|
/* eslint no-console: "off"*/
require('colors');
let async = require('async');
let express = require('express');
let glob = require('glob');
let merge = require('merge');
let passport = require('passport');
let path = require('path');
let sass_middleware = require('node-sass-middleware');
let cleanup = require('./middleware/cleanup');
let noSniff = require('dont-sniff-mimetype');
let mongoose = require('mongoose');
// var sass_middleware = require('node-sass-middleware');
// ////////////////////////////////////////////////////////////////////////////////////////////////
// Load configuration
// ////////////////////////////////////////////////////////////////////////////////////////////////
global.config = require('./../config');
// ////////////////////////////////////////////////////////////////////////////////////////////////
// Express application
// ////////////////////////////////////////////////////////////////////////////////////////////////
let app = express();
let api = {};
let webhooks = {};
// redirect from http to https
app.use(function (req, res, next) {
if (!req.headers['x-forwarded-proto'] || req.headers['x-forwarded-proto'] === 'https') {
next();
return;
}
let host = req.headers['x-forwarded-host'] || req.headers.host;
res.setHeader('location', 'https://' + host + req.url);
res.statusCode = 301;
res.end();
});
app.use(require('x-frame-options')());
app.use(require('body-parser').json({ limit: '5mb' }));
app.use(require('cookie-parser')());
app.use(noSniff());
let expressSession = require('express-session');
let MongoStore = require('connect-mongo')(expressSession);
// custom mrepodleware
app.use('/api', require('./middleware/param'));
app.use('/github', require('./middleware/param'));
app.use('/accept', require('./middleware/param'));
app.use('/count', require('./middleware/param'));
// app.use(function (err, req, res, next) {
// var log = require('./services/logger');
// log.info('app error: ', err.stack);
// });
let bootstrap = function (files, callback) {
console.log('bootstrap'.bold, files.bold);
async.eachSeries(config.server[files], function (p, cb) {
glob(p, function (err, file) {
if (err) {
console.log('✖ '.bold.red + err);
}
if (file && file.length) {
file.forEach(function (f) {
try {
if (files === 'api') {
api[path.basename(f, '.js')] = require(f);
} else if (files === 'passport') {
require(f);
} else if (files === 'plugins') {
global.plugins[path.basename(f, '.js')] = require(f);
} else if (files === 'controller') {
app.use('/', require(f));
} else if (files === 'graphQueries') {
require(f);
} else if (files === 'documents') {
global.models = merge(global.models, require(f));
} else if (files === 'webhooks') {
webhooks[path.basename(f, '.js')] = require(f);
}
} catch (ex) {
console.log('✖ '.bold.red + path.relative(process.cwd(), f));
console.log(ex.stack);
return;
}
console.log('✓ '.bold.green + path.relative(process.cwd(), f));
});
}
cb();
});
}, callback);
};
async.series([
function (callback) {
console.log('checking configs'.bold);
function validateProtocol(protocol, msg) {
if (config.server[protocol].protocol !== 'http' && config.server[protocol].protocol !== 'https') {
throw new Error(msg + ' must be "http" or "https"');
}
}
validateProtocol('http', 'PROTOCOL');
validateProtocol('github', 'GITHUB_PROTOCOL');
console.log('✓ '.bold.green + 'configs seem ok');
let url = require('./services/url');
console.log('Host: ' + url.baseUrl);
console.log('GitHub: ' + url.githubBase);
console.log('GitHub-Api: ' + url.githubApiBase);
callback();
},
function (callback) {
console.log('bootstrap static files'.bold);
config.server.static.forEach(function (p) {
app.use(sass_middleware({
src: p,
dest: p,
outputStyle: 'compressed',
force: config.server.always_recompile_sass
}));
app.use(express.static(p));
});
callback();
},
// ////////////////////////////////////////////////////////////////////////////////////////////
// Bootstrap mongoose
// ////////////////////////////////////////////////////////////////////////////////////////////
function (callback) {
retryInitializeMongoose(config.server.mongodb.uri, {
useMongoClient: true,
keepAlive: true
}, () => {
bootstrap('documents', callback);
});
app.use(expressSession({
secret: config.server.security.sessionSecret,
saveUninitialized: true,
resave: false,
cookie: {
maxAge: config.server.security.cookieMaxAge
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
collection: 'cookieSession'
})
}));
app.use(passport.initialize());
app.use(passport.session());
global.models = {};
},
function (callback) {
bootstrap('passport', callback);
},
function (callback) {
bootstrap('controller', callback);
},
function (callback) {
bootstrap('graphQueries', callback);
},
function (callback) {
bootstrap('api', callback);
},
function (callback) {
bootstrap('webhooks', callback);
}
], function (err) {
if (err) {
console.log('! '.yellow + err);
}
let log = require('./services/logger');
console.log('\n✓ '.bold.green + 'bootstrapped, '.bold + 'app listening on ' + config.server.http.host + ':' + config.server.localport);
log.info('✓ bootstrapped !!! App listening on ' + config.server.http.host + ':' + config.server.http.port);
});
// ////////////////////////////////////////////////////////////////////////////////////////////////
// Handle api calls
// ////////////////////////////////////////////////////////////////////////////////////////////////
app.use('/api', require('./middleware/authenticated'));
app.all('/api/:obj/:fun', function (req, res) {
res.set('Content-Type', 'application/json');
api[req.params.obj][req.params.fun](req, function (err, obj) {
if (err && typeof err === 'string') {
return res.status(500).send(err);
} else if (err) {
return res.status(err.code > 0 ? err.code : 500).send(JSON.stringify(err.text || err.message || err));
}
if (obj !== undefined && obj !== null) {
obj = cleanup.cleanObject(obj);
res.send(JSON.stringify(obj));
} else {
res.send();
}
});
});
// ////////////////////////////////////////////////////////////////////////////////////////////////
// Handle webhook calls
// ////////////////////////////////////////////////////////////////////////////////////////////////
app.all('/github/webhook/:repo', function (req, res) {
let event = req.headers['x-github-event'];
try {
if (!webhooks[event]) {
return res.status(400).send('Unsupported event');
}
webhooks[event](req, res);
} catch (err) {
res.status(500).send('Internal Server Error');
}
});
function retryInitializeMongoose(uri, options, callback) {
const defaultInterval = 1000;
mongoose.connect(uri, options, err => {
if (err) {
console.log(err, `Retry initialize mongoose in ${options.retryInitializeInterval || defaultInterval} milliseconds`);
setTimeout(() => {
retryInitializeMongoose(uri, options);
}, options.retryInitializeInterval || defaultInterval);
}
if (typeof callback === 'function') {
callback();
}
});
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// Register email notifications
// ////////////////////////////////////////////////////////////////////////////////////////////////
let _ = require('./services/email').init()
module.exports = app; |
const express = require("express");
const router = express.Router();
const {
createUser,
getUserById,
getAllUsers,
deleteAllCartItems,
getUserCartItems,
removeCartItemById,
addToCart,
userLogin,
getClientSecretKey,
productOrdered,
useReferral,
} = require("../controllers/userController");
router.post("/user/signup", createUser);
router.post("/user/login", userLogin);
router.get("/user/:id", getUserById);
router.get("/users", getAllUsers);
router.delete("/users/deletecart/:id", deleteAllCartItems);
router.post("/users/removeCartItemById", removeCartItemById);
router.get("/users/getUserCartItems/:id", getUserCartItems);
router.post("/users/addToCart", addToCart);
router.post("/user/getClientSecretKey", getClientSecretKey);
router.post("/user/productOrdered", productOrdered);
router.post("/useReferral", useReferral);
module.exports = router;
|
ContinueContractForm = Ext
.extend(
Ext.Window,
{
formPanel : null,
constructor : function(a) {
Ext.applyIf(this, a);
this.initUIComponents();
ContinueContractForm.superclass.constructor
.call(this,
{
id : "ContinueContractFormWin",
layout : {
type : "vbox",
align : "stretch"
},
items : [ this.formPanel,
this.detailPanel ],
region : "center",
modal : true,
height : 520,
width : 650,
autoScroll : false,
title : "合同续约",
buttonAlign : "center",
buttons : this.buttons
});
},
initUIComponents : function() {
this.formPanel = new Ext.FormPanel(
{
region : "north",
layout : "form",
bodyStyle : "padding:10px 10px 10px 10px",
border : false,
url : __ctxPath
+ "/hrm/RenewUserContract.do",
id : "ContinueContractForm",
autoHeight : true,
defaultType : "textfield",
items : [ {
xtype : "fieldset",
title : "合同信息",
layout : "form",
labelWidth : 60,
defaultType : "textfield",
defaults : {
anchor : "98%,98%"
},
items : [
{
name : "userContract.contractId",
id : "contractId",
xtype : "hidden",
value : this.contractId == null ? ""
: this.contractId
},
{
width : 300,
fieldLabel : "合同编号",
name : "userContract.contractNo",
id : "contractNo",
allowBlank : false,
blankText : "合同类型不可为空!"
},
{
xtype : "compositefield",
fieldLabel : "签约人",
items : [
{
xtype : "textfield",
name : "userContract.fullname",
id : "fullname",
allowBlank : false,
blankText : "姓名不能为空!",
width : 420,
readOnly : true
},
{
xtype : "button",
id : "UserContractSelectEmp",
text : "选择员工",
iconCls : "btn-mail_recipient",
handler : function() {
UserSelector
.getView(
function(
e,
d) {
Ext
.getCmp(
"fullname")
.setValue(
d);
Ext
.getCmp(
"userId")
.setValue(
e);
Ext.Ajax
.request( {
url : __ctxPath
+ "/system/getAppUser.do",
params : {
userId : e
},
method : "post"
});
},
true)
.show();
}
} ]
},
{
fieldLabel : "合同类型",
name : "userContract.contractType",
id : "contractType",
allowBlank : false,
blankText : "合同类型不可为空!"
},
{
fieldLabel : "签约职员ID",
name : "userContract.userId",
id : "userId",
xtype : "hidden"
},
{
xtype : "compositefield",
fieldLabel : "续约时间",
items : [
{
width : 200,
name : "userContract.timeLimit",
id : "timeLimit",
xtype : "combo",
mode : "local",
editable : true,
triggerAction : "all",
store : [],
listeners : {
focus : function(
e) {
var d = Ext
.getCmp(
"timeLimit")
.getStore();
if (d
.getCount() <= 0) {
Ext.Ajax
.request( {
url : __ctxPath
+ "/system/loadDictionary.do",
method : "post",
params : {
itemName : "期限形式"
},
success : function(
g) {
var f = Ext.util.JSON
.decode(g.responseText);
d
.loadData(f);
}
});
}
}
}
},
{
xtype : "displayfield",
value : "合同状态:",
width : 64
},
{
width : 200,
hiddenName : "userContract.status",
id : "status",
xtype : "combo",
mode : "local",
editable : true,
triggerAction : "all",
store : [
[ "0",
"草稿" ],
[ "1",
"有效" ],
[ "2",
"终止" ] ]
} ]
},
{
xtype : "compositefield",
fieldLabel : "竞业条款",
items : [
{
width : 200,
hiddenName : "userContract.isCompeted",
id : "isCompeted",
xtype : "combo",
mode : "local",
editable : true,
triggerAction : "all",
store : [
[ "0",
"无" ],
[ "1",
"有" ] ]
},
{
xtype : "displayfield",
value : "保密协议:",
width : 64
},
{
width : 200,
hiddenName : "userContract.isSecret",
id : "isSecret",
xtype : "combo",
mode : "local",
editable : true,
triggerAction : "all",
store : [
[ "0",
"无" ],
[ "1",
"有" ] ]
} ]
},
{
xtype : "compositefield",
fieldLabel : "有效日期",
items : [
{
xtype : "datefield",
width : 200,
format : "Y-m-d",
editable : false,
name : "userContract.startDate",
id : "startDate",
allowBlank : false,
blankText : "合同生效日期不可为空!"
},
{
xtype : "displayfield",
value : "至",
width : 20
},
{
xtype : "datefield",
width : 200,
format : "Y-m-d",
editable : false,
name : "userContract.expireDate",
id : "expireDate",
allowBlank : false,
blankText : "合同满约日期不可为空!"
} ]
},
{
width : 300,
fieldLabel : "违约责任",
name : "userContract.breakBurden",
id : "breakBurden"
},
{
width : 300,
fieldLabel : "其他事宜",
name : "userContract.otherItems",
id : "otherItems"
} ]
} ]
});
this.detailStore = new Ext.data.JsonStore( {
fields : [ {
name : "eventId",
type : "int"
}, "userContract", "eventName", "eventDescp",
"createTime", "creator" ]
});
var c = new Ext.grid.CheckboxSelectionModel();
var a = new Ext.grid.ColumnModel( {
columns : [ c, new Ext.grid.RowNumberer(), {
header : "eventId",
dataIndex : "eventId",
hidden : true
}, {
header : "记录名称",
dataIndex : "eventName",
editor : new Ext.form.TextField( {
allowBlank : false,
blankText : "事件名称不可为空!"
})
}, {
header : "记录理由",
dataIndex : "eventDescp",
editor : new Ext.form.TextField()
} ],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
this.topbar = new Ext.Toolbar( {
items : [ {
xtype : "button",
iconCls : "btn-add",
scope : this,
text : "添加合同记录",
handler : function() {
var e = this.detailPanel.getStore();
var d = e.recordType;
e.add(new d());
this.detailPanel.stopEditing();
}
} ]
});
this.detailPanel = new Ext.grid.EditorGridPanel( {
title : "合同记录信息",
region : "center",
stripeRows : true,
tbar : this.topbar,
clicksToEdit : 1,
store : this.detailStore,
trackMouseOver : true,
loadMask : true,
height : 150,
cm : a,
sm : c
});
var b = this.defaultStatus;
if (this.contractId != null
&& this.contractId != "undefined") {
this.formPanel
.getForm()
.load(
{
deferredRender : false,
url : __ctxPath
+ "/hrm/getUserContract.do?contractId="
+ this.contractId,
waitMsg : "正在载入数据...",
success : function(e, f) {
var d = Ext.util.JSON
.decode(f.response.responseText);
b
.loadDate(d.data.contractEvents);
},
failure : function(d, e) {
}
});
}
this.buttons = [
{
text : "保存",
iconCls : "btn-save",
handler : this.save.createCallback(
this.formPanel, this)
},
{
text : "重置",
iconCls : "btn-reset",
handler : this.reset
.createCallback(this.formPanel)
}, {
text : "取消",
iconCls : "btn-cancel",
handler : this.cancel.createCallback(this)
} ];
},
reset : function(a) {
a.getForm().reset();
},
cancel : function(a) {
a.close();
},
save : function(a, d) {
var c = d.detailPanel.getStore();
var e = [];
if (c.getCount() > 0) {
for (i = 0, cnt = c.getCount(); i < cnt; i++) {
var b = c.getAt(i);
e.push(b.data);
}
} else {
Ext.ux.Toast.msg("提示信息", "请添加合同记录信息!");
return;
}
if (a.getForm().isValid()) {
a.getForm().submit( {
method : "POST",
waitMsg : "正在提交数据...",
params : {
details : Ext.encode(e)
},
success : function(f, h) {
Ext.ux.Toast.msg("操作信息", "成功保存信息!");
var g = Ext.getCmp("UserContractGrid");
if (g != null) {
g.getStore().reload();
}
d.close();
},
failure : function(f, g) {
Ext.MessageBox.show( {
title : "操作信息",
msg : g.result.msg,
buttons : Ext.MessageBox.OK,
icon : Ext.MessageBox.ERROR
});
d.close();
}
});
}
}
}); |
r"""
Symbolic Equations and Inequalities
Sage can solve symbolic equations and inequalities. For
example, we derive the quadratic formula as follows::
sage: a,b,c = var('a,b,c')
sage: qe = (a*x^2 + b*x + c == 0)
sage: qe
a*x^2 + b*x + c == 0
sage: print(solve(qe, x))
[
x == -1/2*(b + sqrt(b^2 - 4*a*c))/a,
x == -1/2*(b - sqrt(b^2 - 4*a*c))/a
]
The operator, left hand side, and right hand side
--------------------------------------------------
Operators::
sage: eqn = x^3 + 2/3 >= x - pi
sage: eqn.operator()
<built-in function ge>
sage: (x^3 + 2/3 < x - pi).operator()
<built-in function lt>
sage: (x^3 + 2/3 == x - pi).operator()
<built-in function eq>
Left hand side::
sage: eqn = x^3 + 2/3 >= x - pi
sage: eqn.lhs()
x^3 + 2/3
sage: eqn.left()
x^3 + 2/3
sage: eqn.left_hand_side()
x^3 + 2/3
Right hand side::
sage: (x + sqrt(2) >= sqrt(3) + 5/2).right()
sqrt(3) + 5/2
sage: (x + sqrt(2) >= sqrt(3) + 5/2).rhs()
sqrt(3) + 5/2
sage: (x + sqrt(2) >= sqrt(3) + 5/2).right_hand_side()
sqrt(3) + 5/2
Arithmetic
----------
Add two symbolic equations::
sage: var('a,b')
(a, b)
sage: m = 144 == -10 * a + b
sage: n = 136 == 10 * a + b
sage: m + n
280 == 2*b
sage: int(-144) + m
0 == -10*a + b - 144
Subtract two symbolic equations::
sage: var('a,b')
(a, b)
sage: m = 144 == 20 * a + b
sage: n = 136 == 10 * a + b
sage: m - n
8 == 10*a
sage: int(144) - m
0 == -20*a - b + 144
Multiply two symbolic equations::
sage: x = var('x')
sage: m = x == 5*x + 1
sage: n = sin(x) == sin(x+2*pi, hold=True)
sage: m * n
x*sin(x) == (5*x + 1)*sin(2*pi + x)
sage: m = 2*x == 3*x^2 - 5
sage: int(-1) * m
-2*x == -3*x^2 + 5
Divide two symbolic equations::
sage: x = var('x')
sage: m = x == 5*x + 1
sage: n = sin(x) == sin(x+2*pi, hold=True)
sage: m/n
x/sin(x) == (5*x + 1)/sin(2*pi + x)
sage: m = x != 5*x + 1
sage: n = sin(x) != sin(x+2*pi, hold=True)
sage: m/n
x/sin(x) != (5*x + 1)/sin(2*pi + x)
Substitution
------------
Substitution into relations::
sage: x, a = var('x, a')
sage: eq = (x^3 + a == sin(x/a)); eq
x^3 + a == sin(x/a)
sage: eq.substitute(x=5*x)
125*x^3 + a == sin(5*x/a)
sage: eq.substitute(a=1)
x^3 + 1 == sin(x)
sage: eq.substitute(a=x)
x^3 + x == sin(1)
sage: eq.substitute(a=x, x=1)
x + 1 == sin(1/x)
sage: eq.substitute({a:x, x:1})
x + 1 == sin(1/x)
You can even substitute multivariable and matrix
expressions::
sage: x,y = var('x, y')
sage: M = Matrix([[x+1,y],[x^2,y^3]]); M
[x + 1 y]
[ x^2 y^3]
sage: M.substitute({x:0,y:1})
[1 1]
[0 1]
Solving
-------
We can solve equations::
sage: x = var('x')
sage: S = solve(x^3 - 1 == 0, x)
sage: S
[x == 1/2*I*sqrt(3) - 1/2, x == -1/2*I*sqrt(3) - 1/2, x == 1]
sage: S[0]
x == 1/2*I*sqrt(3) - 1/2
sage: S[0].right()
1/2*I*sqrt(3) - 1/2
sage: S = solve(x^3 - 1 == 0, x, solution_dict=True)
sage: S
[{x: 1/2*I*sqrt(3) - 1/2}, {x: -1/2*I*sqrt(3) - 1/2}, {x: 1}]
sage: z = 5
sage: solve(z^2 == sqrt(3),z)
Traceback (most recent call last):
...
TypeError: 5 is not a valid variable.
We can also solve equations involving matrices. The following
example defines a multivariable function ``f(x,y)``, then solves
for where the partial derivatives with respect to ``x``
and ``y`` are zero. Then it substitutes one of the solutions
into the Hessian matrix ``H`` for ``f``::
sage: f(x,y) = x^2*y+y^2+y
sage: solutions = solve(list(f.diff()),[x,y],solution_dict=True)
sage: solutions == [{x: -I, y: 0}, {x: I, y: 0}, {x: 0, y: -1/2}]
True
sage: H = f.diff(2) # Hessian matrix
sage: H.subs(solutions[2])
[(x, y) |--> -1 (x, y) |--> 0]
[ (x, y) |--> 0 (x, y) |--> 2]
sage: H(x,y).subs(solutions[2])
[-1 0]
[ 0 2]
We illustrate finding multiplicities of solutions::
sage: f = (x-1)^5*(x^2+1)
sage: solve(f == 0, x)
[x == -I, x == I, x == 1]
sage: solve(f == 0, x, multiplicities=True)
([x == -I, x == I, x == 1], [1, 1, 5])
We can also solve many inequalities::
sage: solve(1/(x-1)<=8,x)
[[x < 1], [x >= (9/8)]]
We can numerically find roots of equations::
sage: (x == sin(x)).find_root(-2,2)
0.0
sage: (x^5 + 3*x + 2 == 0).find_root(-2,2,x)
-0.6328345202421523
sage: (cos(x) == sin(x)).find_root(10,20)
19.634954084936208
We illustrate some valid error conditions::
sage: (cos(x) != sin(x)).find_root(10,20)
Traceback (most recent call last):
...
ValueError: Symbolic equation must be an equality.
sage: (SR(3)==SR(2)).find_root(-1,1)
Traceback (most recent call last):
...
RuntimeError: no zero in the interval, since constant expression is not 0.
There must be at most one variable::
sage: x, y = var('x,y')
sage: (x == y).find_root(-2,2)
Traceback (most recent call last):
...
NotImplementedError: root finding currently only implemented in 1 dimension.
Assumptions
-----------
Forgetting assumptions::
sage: var('x,y')
(x, y)
sage: forget() #Clear assumptions
sage: assume(x>0, y < 2)
sage: assumptions()
[x > 0, y < 2]
sage: (y < 2).forget()
sage: assumptions()
[x > 0]
sage: forget()
sage: assumptions()
[]
Miscellaneous
-------------
Conversion to Maxima::
sage: x = var('x')
sage: eq = (x^(3/5) >= pi^2 + e^i)
sage: eq._maxima_init_()
'(_SAGE_VAR_x)^(3/5) >= ((%pi)^(2))+(exp(0+%i*1))'
sage: e1 = x^3 + x == sin(2*x)
sage: z = e1._maxima_()
sage: z.parent() is sage.calculus.calculus.maxima
True
sage: z = e1._maxima_(maxima)
sage: z.parent() is maxima
True
sage: z = maxima(e1)
sage: z.parent() is maxima
True
Conversion to Maple::
sage: x = var('x')
sage: eq = (x == 2)
sage: eq._maple_init_()
'x = 2'
Comparison::
sage: x = var('x')
sage: (x>0) == (x>0)
True
sage: (x>0) == (x>1)
False
sage: (x>0) != (x>1)
True
Variables appearing in the relation::
sage: var('x,y,z,w')
(x, y, z, w)
sage: f = (x+y+w) == (x^2 - y^2 - z^3); f
w + x + y == -z^3 + x^2 - y^2
sage: f.variables()
(w, x, y, z)
LaTeX output::
sage: latex(x^(3/5) >= pi)
x^{\frac{3}{5}} \geq \pi
When working with the symbolic complex number `I`, notice that comparisons do not
automatically simplify even in trivial situations::
sage: I^2 == -1
-1 == -1
sage: I^2 < 0
-1 < 0
sage: (I+1)^4 > 0
-4 > 0
Nevertheless, if you force the comparison, you get the right answer (:trac:`7160`)::
sage: bool(I^2 == -1)
True
sage: bool(I^2 < 0)
True
sage: bool((I+1)^4 > 0)
False
More Examples
-------------
::
sage: x,y,a = var('x,y,a')
sage: f = x^2 + y^2 == 1
sage: f.solve(x)
[x == -sqrt(-y^2 + 1), x == sqrt(-y^2 + 1)]
::
sage: f = x^5 + a
sage: solve(f==0,x)
[x == 1/4*(-a)^(1/5)*(sqrt(5) + I*sqrt(2*sqrt(5) + 10) - 1), x == -1/4*(-a)^(1/5)*(sqrt(5) - I*sqrt(-2*sqrt(5) + 10) + 1), x == -1/4*(-a)^(1/5)*(sqrt(5) + I*sqrt(-2*sqrt(5) + 10) + 1), x == 1/4*(-a)^(1/5)*(sqrt(5) - I*sqrt(2*sqrt(5) + 10) - 1), x == (-a)^(1/5)]
You can also do arithmetic with inequalities, as illustrated
below::
sage: var('x y')
(x, y)
sage: f = x + 3 == y - 2
sage: f
x + 3 == y - 2
sage: g = f - 3; g
x == y - 5
sage: h = x^3 + sqrt(2) == x*y*sin(x)
sage: h
x^3 + sqrt(2) == x*y*sin(x)
sage: h - sqrt(2)
x^3 == x*y*sin(x) - sqrt(2)
sage: h + f
x^3 + x + sqrt(2) + 3 == x*y*sin(x) + y - 2
sage: f = x + 3 < y - 2
sage: g = 2 < x+10
sage: f - g
x + 1 < -x + y - 12
sage: f + g
x + 5 < x + y + 8
sage: f*(-1)
-x - 3 < -y + 2
TESTS:
We test serializing symbolic equations::
sage: eqn = x^3 + 2/3 >= x
sage: loads(dumps(eqn))
x^3 + 2/3 >= x
sage: loads(dumps(eqn)) == eqn
True
AUTHORS:
- Bobby Moretti: initial version (based on a trick that Robert
Bradshaw suggested).
- William Stein: second version
- William Stein (2007-07-16): added arithmetic with symbolic equations
"""
from __future__ import print_function
from six.moves import range
import operator
def test_relation_maxima(relation):
"""
Return True if this (in)equality is definitely true. Return False
if it is false or the algorithm for testing (in)equality is
inconclusive.
EXAMPLES::
sage: from sage.symbolic.relation import test_relation_maxima
sage: k = var('k')
sage: pol = 1/(k-1) - 1/k -1/k/(k-1);
sage: test_relation_maxima(pol == 0)
True
sage: f = sin(x)^2 + cos(x)^2 - 1
sage: test_relation_maxima(f == 0)
True
sage: test_relation_maxima( x == x )
True
sage: test_relation_maxima( x != x )
False
sage: test_relation_maxima( x > x )
False
sage: test_relation_maxima( x^2 > x )
False
sage: test_relation_maxima( x + 2 > x )
True
sage: test_relation_maxima( x - 2 > x )
False
Here are some examples involving assumptions::
sage: x, y, z = var('x, y, z')
sage: assume(x>=y,y>=z,z>=x)
sage: test_relation_maxima(x==z)
True
sage: test_relation_maxima(z<x)
False
sage: test_relation_maxima(z>y)
False
sage: test_relation_maxima(y==z)
True
sage: forget()
sage: assume(x>=1,x<=1)
sage: test_relation_maxima(x==1)
True
sage: test_relation_maxima(x>1)
False
sage: test_relation_maxima(x>=1)
True
sage: test_relation_maxima(x!=1)
False
sage: forget()
sage: assume(x>0)
sage: test_relation_maxima(x==0)
False
sage: test_relation_maxima(x>-1)
True
sage: test_relation_maxima(x!=0)
True
sage: test_relation_maxima(x!=1)
False
sage: forget()
TESTS:
Ensure that ``canonicalize_radical()`` and ``simplify_log`` are not
used inappropriately, :trac:`17389`. Either one would simplify ``f``
to zero below::
sage: x,y = SR.var('x,y')
sage: assume(y, 'complex')
sage: f = log(x*y) - (log(x) + log(y))
sage: f(x=-1, y=i)
-2*I*pi
sage: test_relation_maxima(f == 0)
False
sage: forget()
Ensure that the ``sqrt(x^2)`` -> ``abs(x)`` simplification is not
performed when testing equality::
sage: assume(x, 'complex')
sage: f = sqrt(x^2) - abs(x)
sage: test_relation_maxima(f == 0)
False
sage: forget()
If assumptions are made, ``simplify_rectform()`` is used::
sage: assume(x, 'real')
sage: f1 = ( e^(I*x) - e^(-I*x) ) / ( I*e^(I*x) + I*e^(-I*x) )
sage: f2 = sin(x)/cos(x)
sage: test_relation_maxima(f1 - f2 == 0)
True
sage: forget()
But not if ``x`` itself is complex::
sage: assume(x, 'complex')
sage: f1 = ( e^(I*x) - e^(-I*x) ) / ( I*e^(I*x) + I*e^(-I*x) )
sage: f2 = sin(x)/cos(x)
sage: test_relation_maxima(f1 - f2 == 0)
False
sage: forget()
If assumptions are made, then ``simplify_factorial()`` is used::
sage: n,k = SR.var('n,k')
sage: assume(n, 'integer')
sage: assume(k, 'integer')
sage: f1 = factorial(n+1)/factorial(n)
sage: f2 = n + 1
sage: test_relation_maxima(f1 - f2 == 0)
True
sage: forget()
In case one of the solutions while solving an equation is a real number::
sage: var('K, d, R')
(K, d, R)
sage: assume(K>0)
sage: assume(K, 'noninteger')
sage: assume(R>0)
sage: assume(R<1)
sage: assume(d<R)
sage: assumptions()
[K > 0, K is noninteger, R > 0, R < 1, d < R]
"""
m = relation._maxima_()
#Handle some basic cases first
if repr(m) in ['0=0']:
return True
elif repr(m) in ['0#0', '1#1']:
return False
if relation.operator() == operator.eq: # operator is equality
try:
s = m.parent()._eval_line('is (equal(%s,%s))'%(repr(m.lhs()),repr(m.rhs())))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))
elif relation.operator() == operator.ne: # operator is not equal
try:
s = m.parent()._eval_line('is (notequal(%s,%s))'%(repr(m.lhs()),repr(m.rhs())))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))
else: # operator is < or > or <= or >=, which Maxima handles fine
try:
s = m.parent()._eval_line('is (%s)'%repr(m))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))
if s == 'true':
return True
elif s == 'false':
return False # if neither of these, s=='unknown' and we try a few other tricks
if relation.operator() != operator.eq:
return False
difference = relation.lhs() - relation.rhs()
if repr(difference) == '0':
return True
# Try to apply some simplifications to see if left - right == 0.
#
# TODO: If simplify_log() is ever removed from simplify_full(), we
# can replace all of these individual simplifications with a
# single call to simplify_full(). That would work in cases where
# two simplifications are needed consecutively; the current
# approach does not.
#
simp_list = [difference.simplify_factorial(),
difference.simplify_rational(),
difference.simplify_rectform(),
difference.simplify_trig()]
for f in simp_list:
try:
if repr( f() ).strip() == "0":
return True
break
except Exception:
pass
return False
def string_to_list_of_solutions(s):
r"""
Used internally by the symbolic solve command to convert the output
of Maxima's solve command to a list of solutions in Sage's symbolic
package.
EXAMPLES:
We derive the (monic) quadratic formula::
sage: var('x,a,b')
(x, a, b)
sage: solve(x^2 + a*x + b == 0, x)
[x == -1/2*a - 1/2*sqrt(a^2 - 4*b), x == -1/2*a + 1/2*sqrt(a^2 - 4*b)]
Behind the scenes when the above is evaluated the function
:func:`string_to_list_of_solutions` is called with input the
string `s` below::
sage: s = '[x=-(sqrt(a^2-4*b)+a)/2,x=(sqrt(a^2-4*b)-a)/2]'
sage: sage.symbolic.relation.string_to_list_of_solutions(s)
[x == -1/2*a - 1/2*sqrt(a^2 - 4*b), x == -1/2*a + 1/2*sqrt(a^2 - 4*b)]
"""
from sage.categories.all import Objects
from sage.structure.sequence import Sequence
from sage.calculus.calculus import symbolic_expression_from_maxima_string
v = symbolic_expression_from_maxima_string(s, equals_sub=True)
return Sequence(v, universe=Objects(), cr_str=True)
###########
# Solving #
###########
def solve(f, *args, **kwds):
r"""
Algebraically solve an equation or system of equations (over the
complex numbers) for given variables. Inequalities and systems
of inequalities are also supported.
INPUT:
- ``f`` - equation or system of equations (given by a
list or tuple)
- ``*args`` - variables to solve for.
- ``solution_dict`` - bool (default: False); if True or non-zero,
return a list of dictionaries containing the solutions. If there
are no solutions, return an empty list (rather than a list containing
an empty dictionary). Likewise, if there's only a single solution,
return a list containing one dictionary with that solution.
There are a few optional keywords if you are trying to solve a single
equation. They may only be used in that context.
- ``multiplicities`` - bool (default: False); if True,
return corresponding multiplicities. This keyword is
incompatible with ``to_poly_solve=True`` and does not make
any sense when solving inequalities.
- ``explicit_solutions`` - bool (default: False); require that
all roots be explicit rather than implicit. Not used
when solving inequalities.
- ``to_poly_solve`` - bool (default: False) or string; use
Maxima's ``to_poly_solver`` package to search for more possible
solutions, but possibly encounter approximate solutions.
This keyword is incompatible with ``multiplicities=True``
and is not used when solving inequalities. Setting ``to_poly_solve``
to 'force' (string) omits Maxima's solve command (useful when
some solutions of trigonometric equations are lost).
EXAMPLES::
sage: x, y = var('x, y')
sage: solve([x+y==6, x-y==4], x, y)
[[x == 5, y == 1]]
sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y)
[[x == -1/2*I*sqrt(3) - 1/2, y == -sqrt(-1/2*I*sqrt(3) + 3/2)],
[x == -1/2*I*sqrt(3) - 1/2, y == sqrt(-1/2*I*sqrt(3) + 3/2)],
[x == 1/2*I*sqrt(3) - 1/2, y == -sqrt(1/2*I*sqrt(3) + 3/2)],
[x == 1/2*I*sqrt(3) - 1/2, y == sqrt(1/2*I*sqrt(3) + 3/2)],
[x == 0, y == -1],
[x == 0, y == 1]]
sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y)
[[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]]
sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True)
sage: for solution in solutions: print("{} , {}".format(solution[x].n(digits=3), solution[y].n(digits=3)))
-0.500 - 0.866*I , -1.27 + 0.341*I
-0.500 - 0.866*I , 1.27 - 0.341*I
-0.500 + 0.866*I , -1.27 - 0.341*I
-0.500 + 0.866*I , 1.27 + 0.341*I
0.000 , -1.00
0.000 , 1.00
Whenever possible, answers will be symbolic, but with systems of
equations, at times approximations will be given by Maxima, due to the
underlying algorithm::
sage: sols = solve([x^3==y,y^2==x], [x,y]); sols[-1], sols[0]
([x == 0, y == 0],
[x == (0.3090169943749475 + 0.9510565162951535*I),
y == (-0.8090169943749475 - 0.5877852522924731*I)])
sage: sols[0][0].rhs().pyobject().parent()
Complex Double Field
sage: solve([y^6==y],y)
[y == 1/4*sqrt(5) + 1/4*I*sqrt(2*sqrt(5) + 10) - 1/4,
y == -1/4*sqrt(5) + 1/4*I*sqrt(-2*sqrt(5) + 10) - 1/4,
y == -1/4*sqrt(5) - 1/4*I*sqrt(-2*sqrt(5) + 10) - 1/4,
y == 1/4*sqrt(5) - 1/4*I*sqrt(2*sqrt(5) + 10) - 1/4,
y == 1,
y == 0]
sage: solve( [y^6 == y], y)==solve( y^6 == y, y)
True
Here we demonstrate very basic use of the optional keywords::
sage: ((x^2-1)^2).solve(x)
[x == -1, x == 1]
sage: ((x^2-1)^2).solve(x,multiplicities=True)
([x == -1, x == 1], [2, 2])
sage: solve(sin(x)==x,x)
[x == sin(x)]
sage: solve(sin(x)==x,x,explicit_solutions=True)
[]
sage: solve(abs(1-abs(1-x)) == 10, x)
[abs(abs(x - 1) - 1) == 10]
sage: solve(abs(1-abs(1-x)) == 10, x, to_poly_solve=True)
[x == -10, x == 12]
sage: from sage.symbolic.expression import Expression
sage: Expression.solve(x^2==1,x)
[x == -1, x == 1]
We must solve with respect to actual variables::
sage: z = 5
sage: solve([8*z + y == 3, -z +7*y == 0],y,z)
Traceback (most recent call last):
...
TypeError: 5 is not a valid variable.
If we ask for dictionaries containing the solutions, we get them::
sage: solve([x^2-1],x,solution_dict=True)
[{x: -1}, {x: 1}]
sage: solve([x^2-4*x+4],x,solution_dict=True)
[{x: 2}]
sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True)
sage: for soln in res: print("x: %s, y: %s" % (soln[x], soln[y]))
x: 2, y: 4
x: -2, y: 4
If there is a parameter in the answer, that will show up as
a new variable. In the following example, ``r1`` is a real free
variable (because of the ``r``)::
sage: forget()
sage: x, y = var('x,y')
sage: solve([x+y == 3, 2*x+2*y == 6],x,y)
[[x == -r1 + 3, y == r1]]
sage: var('b, c')
(b, c)
sage: solve((b-1)*(c-1), [b,c])
[[b == 1, c == r...], [b == r..., c == 1]]
Especially with trigonometric functions, the dummy variable may
be implicitly an integer (hence the ``z``)::
sage: solve( sin(x)==cos(x), x, to_poly_solve=True)
[x == 1/4*pi + pi*z...]
sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y)
[[x == 1/4*pi + pi*z..., y == -1/4*pi - pi*z...]]
Expressions which are not equations are assumed to be set equal
to zero, as with `x` in the following example::
sage: solve([x, y == 2],x,y)
[[x == 0, y == 2]]
If ``True`` appears in the list of equations it is
ignored, and if ``False`` appears in the list then no
solutions are returned. E.g., note that the first
``3==3`` evaluates to ``True``, not to a
symbolic equation.
::
sage: solve([3==3, 1.00000000000000*x^3 == 0], x)
[x == 0]
sage: solve([1.00000000000000*x^3 == 0], x)
[x == 0]
Here, the first equation evaluates to ``False``, so
there are no solutions::
sage: solve([1==3, 1.00000000000000*x^3 == 0], x)
[]
Completely symbolic solutions are supported::
sage: var('s,j,b,m,g')
(s, j, b, m, g)
sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ];
sage: solve(sys,s,j)
[[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]]
sage: solve(sys,(s,j))
[[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]]
sage: solve(sys,[s,j])
[[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]]
sage: z = var('z')
sage: solve((x-z)^2==2, x)
[x == z - sqrt(2), x == z + sqrt(2)]
Inequalities can be also solved::
sage: solve(x^2>8,x)
[[x < -2*sqrt(2)], [x > 2*sqrt(2)]]
sage: x,y=var('x,y'); (ln(x)-ln(y)>0).solve(x)
[[log(x) - log(y) > 0]]
sage: x,y=var('x,y'); (ln(x)>ln(y)).solve(x) # random
[[0 < y, y < x, 0 < x]]
[[y < x, 0 < y]]
A simple example to show the use of the keyword
``multiplicities``::
sage: ((x^2-1)^2).solve(x)
[x == -1, x == 1]
sage: ((x^2-1)^2).solve(x,multiplicities=True)
([x == -1, x == 1], [2, 2])
sage: ((x^2-1)^2).solve(x,multiplicities=True,to_poly_solve=True)
Traceback (most recent call last):
...
NotImplementedError: to_poly_solve does not return multiplicities
Here is how the ``explicit_solutions`` keyword functions::
sage: solve(sin(x)==x,x)
[x == sin(x)]
sage: solve(sin(x)==x,x,explicit_solutions=True)
[]
sage: solve(x*sin(x)==x^2,x)
[x == 0, x == sin(x)]
sage: solve(x*sin(x)==x^2,x,explicit_solutions=True)
[x == 0]
The following examples show the use of the keyword ``to_poly_solve``::
sage: solve(abs(1-abs(1-x)) == 10, x)
[abs(abs(x - 1) - 1) == 10]
sage: solve(abs(1-abs(1-x)) == 10, x, to_poly_solve=True)
[x == -10, x == 12]
sage: var('Q')
Q
sage: solve(Q*sqrt(Q^2 + 2) - 1, Q)
[Q == 1/sqrt(Q^2 + 2)]
The following example is a regression in Maxima 5.39.0.
It used to be possible to get one more solution here,
namely ``1/sqrt(sqrt(2) + 1)``, see
https://sourceforge.net/p/maxima/bugs/3276/::
sage: solve(Q*sqrt(Q^2 + 2) - 1, Q, to_poly_solve=True)
[Q == -sqrt(-sqrt(2) - 1)]
An effort is made to only return solutions that satisfy
the current assumptions::
sage: solve(x^2==4, x)
[x == -2, x == 2]
sage: assume(x<0)
sage: solve(x^2==4, x)
[x == -2]
sage: solve((x^2-4)^2 == 0, x, multiplicities=True)
([x == -2], [2])
sage: solve(x^2==2, x)
[x == -sqrt(2)]
sage: z = var('z')
sage: solve(x^2==2-z, x)
[x == -sqrt(-z + 2)]
sage: assume(x, 'rational')
sage: solve(x^2 == 2, x)
[]
In some cases it may be worthwhile to directly use ``to_poly_solve``
if one suspects some answers are being missed::
sage: forget()
sage: solve(cos(x)==0, x)
[x == 1/2*pi]
sage: solve(cos(x)==0, x, to_poly_solve=True)
[x == 1/2*pi]
sage: solve(cos(x)==0, x, to_poly_solve='force')
[x == 1/2*pi + pi*z...]
The same may also apply if a returned unsolved expression has a
denominator, but the original one did not::
sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve=True)
[sin(x) == 1/2/cos(x)]
sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve=True, explicit_solutions=True)
[x == 1/4*pi + pi*z...]
sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve='force')
[x == 1/4*pi + pi*z...]
We use ``use_grobner`` in Maxima if no solution is obtained from
Maxima's ``to_poly_solve``::
sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9
sage: solve([c1(x,y),c2(x,y)],[x,y])
[[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(55) + 123/68],
[x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(55) + 123/68]]
We use SymPy for Diophantine equations, see
``Expression.solve_diophantine``::
sage: assume(x, 'integer')
sage: assume(z, 'integer')
sage: solve((x-z)^2==2, x)
[]
sage: forget()
TESTS::
sage: solve([sin(x)==x,y^2==x],x,y)
[sin(x) == x, y^2 == x]
sage: solve(0==1,x)
Traceback (most recent call last):
...
TypeError: The first argument must be a symbolic expression or a list of symbolic expressions.
Test if the empty list is returned, too, when (a list of)
dictionaries (is) are requested (:trac:`8553`)::
sage: solve([SR(0)==1],x)
[]
sage: solve([SR(0)==1],x,solution_dict=True)
[]
sage: solve([x==1,x==-1],x)
[]
sage: solve([x==1,x==-1],x,solution_dict=True)
[]
sage: solve((x==1,x==-1),x,solution_dict=0)
[]
Relaxed form, suggested by Mike Hansen (:trac:`8553`)::
sage: solve([x^2-1],x,solution_dict=-1)
[{x: -1}, {x: 1}]
sage: solve([x^2-1],x,solution_dict=1)
[{x: -1}, {x: 1}]
sage: solve((x==1,x==-1),x,solution_dict=-1)
[]
sage: solve((x==1,x==-1),x,solution_dict=1)
[]
This inequality holds for any real ``x`` (:trac:`8078`)::
sage: solve(x^4+2>0,x)
[x < +Infinity]
Test for user friendly input handling :trac:`13645`::
sage: poly.<a,b> = PolynomialRing(RR)
sage: solve([a+b+a*b == 1], a)
Traceback (most recent call last):
...
TypeError: a is not a valid variable.
sage: a,b = var('a,b')
sage: solve([a+b+a*b == 1], a)
[a == -(b - 1)/(b + 1)]
sage: solve([a, b], (1, a))
Traceback (most recent call last):
...
TypeError: 1 is not a valid variable.
sage: solve([x == 1], (1, a))
Traceback (most recent call last):
...
TypeError: 1 is not a valid variable.
sage: x.solve((1,2))
Traceback (most recent call last):
...
TypeError: 1 is not a valid variable.
Test that the original version of a system in the French Sage book
now works (:trac:`14306`)::
sage: var('y,z')
(y, z)
sage: solve([x^2 * y * z == 18, x * y^3 * z == 24, x * y * z^4 == 6], x, y, z)
[[x == 3, y == 2, z == 1],
[x == (1.337215067... - 2.685489874...*I),
y == (-1.700434271... + 1.052864325...*I),
z == (0.9324722294... - 0.3612416661...*I)],
...]
:trac:`13286` fixed::
sage: solve([x-4], [x])
[x == 4]
"""
from sage.symbolic.ring import is_SymbolicVariable
from sage.symbolic.expression import Expression, is_Expression
explicit_solutions = kwds.get('explicit_solutions', None)
multiplicities = kwds.get('multiplicities', None)
to_poly_solve = kwds.get('to_poly_solve', None)
solution_dict = kwds.get('solution_dict', False)
if len(args) > 1:
x = args
else:
x = args[0]
if isinstance(x, (list, tuple)):
for i in x:
if not isinstance(i, Expression):
raise TypeError("%s is not a valid variable." % repr(i))
elif x is None:
vars = f.variables()
if len(vars) == 0:
if multiplicities:
return [], []
else:
return []
x = vars[0]
elif not isinstance(x, Expression):
raise TypeError("%s is not a valid variable." % repr(x))
if isinstance(f, (list, tuple)) and len(f) == 1:
# f is a list with a single element
if is_Expression(f[0]):
f = f[0]
else:
raise TypeError("The first argument to solve() should be a"
"symbolic expression or a list of symbolic expressions, "
"cannot handle %s"%repr(type(f)))
if is_Expression(f): # f is a single expression
return _solve_expression(f, x, explicit_solutions, multiplicities, to_poly_solve, solution_dict)
if not isinstance(f, (list, tuple)):
raise TypeError("The first argument must be a symbolic expression or a list of symbolic expressions.")
# f is a list of such expressions or equations
if not args:
raise TypeError("Please input variables to solve for.")
if is_SymbolicVariable(x):
variables = args
else:
variables = tuple(x)
for v in variables:
if not is_SymbolicVariable(v):
raise TypeError("%s is not a valid variable."%repr(v))
try:
f = [s for s in f if s is not True]
except TypeError:
raise ValueError("Unable to solve %s for %s"%(f, args))
if any(s is False for s in f):
return []
from sage.calculus.calculus import maxima
m = maxima(f)
try:
s = m.solve(variables)
except Exception: # if Maxima gave an error, try its to_poly_solve
try:
s = m.to_poly_solve(variables)
except TypeError as mess: # if that gives an error, raise an error.
if "Error executing code in Maxima" in str(mess):
raise ValueError("Sage is unable to determine whether the system %s can be solved for %s"%(f,args))
else:
raise
if len(s) == 0: # if Maxima's solve gave no solutions, try its to_poly_solve
try:
s = m.to_poly_solve(variables)
except Exception: # if that gives an error, stick with no solutions
s = []
if len(s) == 0: # if to_poly_solve gave no solutions, try use_grobner
try:
s = m.to_poly_solve(variables,'use_grobner=true')
except Exception: # if that gives an error, stick with no solutions
s = []
sol_list = string_to_list_of_solutions(repr(s))
# Relaxed form suggested by Mike Hansen (#8553):
if kwds.get('solution_dict', None):
if not sol_list: # fixes IndexError on empty solution list (#8553)
return []
if isinstance(sol_list[0], list):
sol_dict = [{eq.left(): eq.right() for eq in solution}
for solution in sol_list]
else:
sol_dict = [{eq.left(): eq.right()} for eq in sol_list]
return sol_dict
else:
return sol_list
def _solve_expression(f, x, explicit_solutions, multiplicities,
to_poly_solve, solution_dict):
"""
Solve an expression ``f``. For more information, see :func:`solve`.
.. NOTE::
This is an auxillery function only meant to be called
from :func:`solve`.
TESTS:
:trac:`7325` (solving inequalities)::
sage: (x^2>1).solve(x)
[[x < -1], [x > 1]]
Catch error message from Maxima::
sage: solve(acot(x),x)
[]
::
sage: solve(acot(x),x,to_poly_solve=True)
[]
:trac:`7491` fixed::
sage: y=var('y')
sage: solve(y==y,y)
[y == r1]
sage: solve(y==y,y,multiplicities=True)
([y == r1], [])
sage: from sage.symbolic.assumptions import GenericDeclaration
sage: GenericDeclaration(x, 'rational').assume()
sage: solve(x^2 == 2, x)
[]
sage: forget()
:trac:`8390` fixed::
sage: solve(sin(x)==1/2,x)
[x == 1/6*pi]
::
sage: solve(sin(x)==1/2,x,to_poly_solve=True)
[x == 1/6*pi]
::
sage: solve(sin(x)==1/2, x, to_poly_solve='force')
[x == 5/6*pi + 2*pi*z..., x == 1/6*pi + 2*pi*z...]
:trac:`11618` fixed::
sage: g(x)=0
sage: solve(g(x)==0,x,solution_dict=True)
[{x: r1}]
:trac:`17128`: fixed::
sage: var('x,y')
(x, y)
sage: f = x+y
sage: sol = f.solve([x, y], solution_dict=True)
sage: sol[0].get(x) + sol[0].get(y)
0
:trac:`16651` fixed::
sage: (x^7-x-1).solve(x, to_poly_solve=True) # abs tol 1e-6
[x == 1.11277569705,
x == (-0.363623519329 - 0.952561195261*I),
x == (0.617093477784 - 0.900864951949*I),
x == (-0.809857800594 - 0.262869645851*I),
x == (-0.809857800594 + 0.262869645851*I),
x == (0.617093477784 + 0.900864951949*I),
x == (-0.363623519329 + 0.952561195261*I)]
"""
if f.is_relational():
if f.operator() is not operator.eq:
try:
return(solve_ineq(f)) # trying solve_ineq_univar
except Exception:
pass
try:
return(solve_ineq([f])) # trying solve_ineq_fourier
except Exception:
raise NotImplementedError("solving only implemented for equalities and few special inequalities, see solve_ineq")
ex = f
else:
ex = (f == 0)
if multiplicities and to_poly_solve:
raise NotImplementedError("to_poly_solve does not return multiplicities")
# check if all variables are assumed integer;
# if so, we have a Diophantine
def has_integer_assumption(v):
from sage.symbolic.assumptions import assumptions, GenericDeclaration
alist = assumptions()
return any(isinstance(a, GenericDeclaration) and a.has(v) and
a._assumption in ['even','odd','integer','integervalued']
for a in alist)
if len(ex.variables()) and all(has_integer_assumption(var) for var in ex.variables()):
return f.solve_diophantine(x, solution_dict=solution_dict)
# from here on, maxima is used for solution
m = ex._maxima_()
P = m.parent()
if explicit_solutions:
P.eval('solveexplicit: true') # switches Maxima to looking for only explicit solutions
try:
if to_poly_solve != 'force':
s = m.solve(x).str()
else: # omit Maxima's solve command
s = str([])
except TypeError as mess: # if Maxima's solve has an error, we catch it
if "Error executing code in Maxima" in str(mess):
s = str([])
else:
raise
if explicit_solutions:
P.eval('solveexplicit: false') # switches Maxima back to default
if s == 'all':
if solution_dict:
ans = [ {x: f.parent().var('r1')} ]
else:
ans = [x == f.parent().var('r1')]
if multiplicities:
return ans,[]
else:
return ans
X = string_to_list_of_solutions(s) # our initial list of solutions
if multiplicities: # to_poly_solve does not return multiplicities, so in this case we end here
if len(X) == 0:
return X, []
else:
ret_multiplicities = [int(e) for e in str(P.get('multiplicities'))[1:-1].split(',')]
########################################################
# Maxima's to_poly_solver package converts difficult #
# equations to (quasi)-polynomial systems and uses #
# Maxima's algsys function to try to solve them. #
# This allows a much larger range of solved equations, #
# but also allows for the possibility of approximate #
# solutions being returned. #
########################################################
if to_poly_solve:
if len(X) == 0:
# Maxima's solve gave no solutions
solutions_so_far = [ex]
ignore_exceptions = True
else:
solutions_so_far = X
ignore_exceptions = False
X = []
for eq in solutions_so_far:
if eq.lhs().is_symbol() and (eq.lhs() == x) and (x not in eq.rhs().variables()):
X.append(eq)
continue
try:
m = eq._maxima_()
s = m.to_poly_solve(x, options='algexact:true')
T = string_to_list_of_solutions(repr(s))
X.extend([t[0] for t in T])
except TypeError as mess:
if ignore_exceptions:
continue
elif "Error executing code in Maxima" in str(mess) or \
"unable to make sense of Maxima expression" in \
str(mess):
if not explicit_solutions:
X.append(eq) # we keep this implicit solution
else:
raise
# make sure all the assumptions are satisfied
from sage.symbolic.assumptions import assumptions
to_check = assumptions()
if to_check:
for ix, soln in reversed(list(enumerate(X))):
if soln.lhs().is_symbol():
if any([a.contradicts(soln) for a in to_check]):
del X[ix]
if multiplicities:
del ret_multiplicities[ix]
continue
if solution_dict:
if isinstance(x, (list, tuple)):
X = [{sol.left():sol.right() for sol in b} for b in X]
else:
X = [dict([[sol.left(),sol.right()]]) for sol in X]
if multiplicities:
return X, ret_multiplicities
else:
return X
def solve_mod(eqns, modulus, solution_dict = False):
r"""
Return all solutions to an equation or list of equations modulo the
given integer modulus. Each equation must involve only polynomials
in 1 or many variables.
By default the solutions are returned as `n`-tuples, where `n`
is the number of variables appearing anywhere in the given
equations. The variables are in alphabetical order.
INPUT:
- ``eqns`` - equation or list of equations
- ``modulus`` - an integer
- ``solution_dict`` - bool (default: False); if True or non-zero,
return a list of dictionaries containing the solutions. If there
are no solutions, return an empty list (rather than a list containing
an empty dictionary). Likewise, if there's only a single solution,
return a list containing one dictionary with that solution.
EXAMPLES::
sage: var('x,y')
(x, y)
sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14)
[(4, 2), (4, 6), (4, 9), (4, 13)]
sage: solve_mod([x^2 == 1, 4*x == 11], 15)
[(14,)]
Fermat's equation modulo 3 with exponent 5::
sage: var('x,y,z')
(x, y, z)
sage: solve_mod([x^5 + y^5 == z^5], 3)
[(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)]
We can solve with respect to a bigger modulus if it consists only of small prime factors::
sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True)
sage: d[x]
12915279
sage: d[y]
8610183
For cases where there are relatively few solutions and the prime
factors are small, this can be efficient even if the modulus itself
is large::
sage: sorted(solve_mod([x^2 == 41], 10^20))
[(4538602480526452429,), (11445932736758703821,), (38554067263241296179,),
(45461397519473547571,), (54538602480526452429,), (61445932736758703821,),
(88554067263241296179,), (95461397519473547571,)]
We solve a simple equation modulo 2::
sage: x,y = var('x,y')
sage: solve_mod([x == y], 2)
[(0, 0), (1, 1)]
.. warning::
The current implementation splits the modulus into prime
powers, then naively enumerates all possible solutions
(starting modulo primes and then working up through prime
powers), and finally combines the solution using the Chinese
Remainder Theorem. The interface is good, but the algorithm is
very inefficient if the modulus has some larger prime factors! Sage
*does* have the ability to do something much faster in certain
cases at least by using Groebner basis, linear algebra
techniques, etc. But for a lot of toy problems this function as
is might be useful. At least it establishes an interface.
TESTS:
Make sure that we short-circuit in at least some cases::
sage: solve_mod([2*x==1], 2*next_prime(10^50))
[]
Try multi-equation cases::
sage: x, y, z = var("x y z")
sage: solve_mod([2*x^2 + x*y, -x*y+2*y^2+x-2*y, -2*x^2+2*x*y-y^2-x-y], 12)
[(0, 0), (4, 4), (0, 3), (4, 7)]
sage: eqs = [-y^2+z^2, -x^2+y^2-3*z^2-z-1, -y*z-z^2-x-y+2, -x^2-12*z^2-y+z]
sage: solve_mod(eqs, 11)
[(8, 5, 6)]
Confirm that modulus 1 now behaves as it should::
sage: x, y = var("x y")
sage: solve_mod([x==1], 1)
[(0,)]
sage: solve_mod([2*x^2+x*y, -x*y+2*y^2+x-2*y, -2*x^2+2*x*y-y^2-x-y], 1)
[(0, 0)]
"""
from sage.rings.all import Integer, Integers, crt_basis
from sage.symbolic.expression import is_Expression
from sage.misc.all import cartesian_product_iterator
from sage.modules.all import vector
from sage.matrix.all import matrix
if not isinstance(eqns, (list, tuple)):
eqns = [eqns]
eqns = [eq if is_Expression(eq) else (eq.lhs()-eq.rhs()) for eq in eqns]
modulus = Integer(modulus)
if modulus < 1:
raise ValueError("the modulus must be a positive integer")
vars = list(set(sum([list(e.variables()) for e in eqns], [])))
vars.sort(key=repr)
if modulus == 1: # degenerate case
ans = [tuple(Integers(1)(0) for v in vars)]
return ans
factors = modulus.factor()
crt_basis = vector(Integers(modulus), crt_basis([p**i for p,i in factors]))
solutions = []
has_solution = True
for p,i in factors:
solution =_solve_mod_prime_power(eqns, p, i, vars)
if len(solution) > 0:
solutions.append(solution)
else:
has_solution = False
break
ans = []
if has_solution:
for solution in cartesian_product_iterator(solutions):
solution_mat = matrix(Integers(modulus), solution)
ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns()))
# if solution_dict == True:
# Relaxed form suggested by Mike Hansen (#8553):
if solution_dict:
sol_dict = [dict(zip(vars, solution)) for solution in ans]
return sol_dict
else:
return ans
def _solve_mod_prime_power(eqns, p, m, vars):
r"""
Internal help function for solve_mod, does little checking since it expects
solve_mod to do that
Return all solutions to an equation or list of equations modulo p^m.
Each equation must involve only polynomials
in 1 or many variables.
The solutions are returned as `n`-tuples, where `n`
is the number of variables in vars.
INPUT:
- ``eqns`` - equation or list of equations
- ``p`` - a prime
- ``i`` - an integer > 0
- ``vars`` - a list of variables to solve for
EXAMPLES::
sage: var('x,y')
(x, y)
sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14)
[(4, 2), (4, 6), (4, 9), (4, 13)]
sage: solve_mod([x^2 == 1, 4*x == 11], 15)
[(14,)]
Fermat's equation modulo 3 with exponent 5::
sage: var('x,y,z')
(x, y, z)
sage: solve_mod([x^5 + y^5 == z^5], 3)
[(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)]
We solve a simple equation modulo 2::
sage: x,y = var('x,y')
sage: solve_mod([x == y], 2)
[(0, 0), (1, 1)]
.. warning::
Currently this constructs possible solutions by building up
from the smallest prime factor of the modulus. The interface
is good, but the algorithm is horrible if the modulus isn't the
product of many small primes! Sage *does* have the ability to
do something much faster in certain cases at least by using the
Chinese Remainder Theorem, Groebner basis, linear algebra
techniques, etc. But for a lot of toy problems this function as
is might be useful. At the very least, it establishes an
interface.
TESTS:
Confirm we can reproduce the first few terms of :oeis:`A187719`::
sage: from sage.symbolic.relation import _solve_mod_prime_power
sage: [sorted(_solve_mod_prime_power([x^2==41], 10, i, [x]))[0][0] for i in [1..13]]
[1, 21, 71, 1179, 2429, 47571, 1296179, 8703821, 26452429, 526452429,
13241296179, 19473547571, 2263241296179]
"""
from sage.rings.all import Integers, PolynomialRing
from sage.modules.all import vector
from sage.misc.all import cartesian_product_iterator
mrunning = 1
ans = []
for mi in range(m):
mrunning *= p
R = Integers(mrunning)
S = PolynomialRing(R, len(vars), vars)
eqns_mod = [S(eq) for eq in eqns]
if mi == 0:
possibles = cartesian_product_iterator([range(len(R)) for _ in range(len(vars))])
else:
shifts = cartesian_product_iterator([range(p) for _ in range(len(vars))])
pairs = cartesian_product_iterator([shifts, ans])
possibles = (tuple(vector(t)+vector(shift)*(mrunning//p)) for shift, t in pairs)
ans = list(t for t in possibles if all(e(*t) == 0 for e in eqns_mod))
if not ans: return ans
return ans
def solve_ineq_univar(ineq):
"""
Function solves rational inequality in one variable.
INPUT:
- ``ineq`` - inequality in one variable
OUTPUT:
- ``list`` -- output is list of solutions as a list of simple inequalities
output [A,B,C] means (A or B or C) each A, B, C is again a list and
if A=[a,b], then A means (a and b). The list is empty if there is no
solution.
EXAMPLES::
sage: from sage.symbolic.relation import solve_ineq_univar
sage: solve_ineq_univar(x-1/x>0)
[[x > -1, x < 0], [x > 1]]
sage: solve_ineq_univar(x^2-1/x>0)
[[x < 0], [x > 1]]
sage: solve_ineq_univar((x^3-1)*x<=0)
[[x >= 0, x <= 1]]
ALGORITHM:
Calls Maxima command solve_rat_ineq
AUTHORS:
- Robert Marik (01-2010)
"""
ineqvar = ineq.variables()
if len(ineqvar) != 1:
raise NotImplementedError("The command solve_ineq_univar accepts univariate inequalities only. Your variables are " + ineqvar)
ineq0 = ineq._maxima_()
ineq0.parent().eval("if solve_rat_ineq_loaded#true then (solve_rat_ineq_loaded:true,load(\"solve_rat_ineq.mac\")) ")
sol = ineq0.solve_rat_ineq().sage()
if repr(sol)=="all":
from sage.rings.infinity import Infinity
sol = [ineqvar[0]<Infinity]
return sol
def solve_ineq_fourier(ineq,vars=None):
"""
Solves system of inequalities using Maxima and Fourier elimination
Can be used for system of linear inequalities and for some types
of nonlinear inequalities. For examples see the section EXAMPLES
below and http://maxima.cvs.sourceforge.net/viewvc/maxima/maxima/share/contrib/fourier_elim/rtest_fourier_elim.mac
INPUT:
- ``ineq`` - list with system of inequalities
- ``vars`` - optionally list with variables for Fourier elimination.
OUTPUT:
- ``list`` - output is list of solutions as a list of simple inequalities
output [A,B,C] means (A or B or C) each A, B, C is again a list and
if A=[a,b], then A means (a and b). The list is empty if there is no
solution.
EXAMPLES::
sage: from sage.symbolic.relation import solve_ineq_fourier
sage: y=var('y')
sage: solve_ineq_fourier([x+y<9,x-y>4],[x,y])
[[y + 4 < x, x < -y + 9, y < (5/2)]]
sage: solve_ineq_fourier([x+y<9,x-y>4],[y,x])
[[y < min(x - 4, -x + 9)]]
sage: solve_ineq_fourier([x^2>=0])
[[x < +Infinity]]
sage: solve_ineq_fourier([log(x)>log(y)],[x,y])
[[y < x, 0 < y]]
sage: solve_ineq_fourier([log(x)>log(y)],[y,x])
[[0 < y, y < x, 0 < x]]
Note that different systems will find default variables in different
orders, so the following is not tested::
sage: solve_ineq_fourier([log(x)>log(y)]) # random (one of the following appears)
[[0 < y, y < x, 0 < x]]
[[y < x, 0 < y]]
ALGORITHM:
Calls Maxima command fourier_elim
AUTHORS:
- Robert Marik (01-2010)
"""
if vars is None:
setvars = set([])
for i in (ineq):
setvars = setvars.union(set(i.variables()))
vars =[i for i in setvars]
ineq0 = [i._maxima_() for i in ineq]
ineq0[0].parent().eval("if fourier_elim_loaded#true then (fourier_elim_loaded:true,load(\"fourier_elim\"))")
sol = ineq0[0].parent().fourier_elim(ineq0,vars)
ineq0[0].parent().eval("or_to_list(x):=\
if not atom(x) and op(x)=\"or\" then args(x) \
else [x]")
sol = sol.or_to_list().sage()
if repr(sol) == "[emptyset]":
sol = []
if repr(sol) == "[universalset]":
from sage.rings.infinity import Infinity
sol = [[i<Infinity for i in vars]]
return sol
def solve_ineq(ineq, vars=None):
"""
Solves inequalities and systems of inequalities using Maxima.
Switches between rational inequalities
(sage.symbolic.relation.solve_ineq_rational)
and Fourier elimination (sage.symbolic.relation.solve_ineq_fouried).
See the documentation of these functions for more details.
INPUT:
- ``ineq`` - one inequality or a list of inequalities
Case1: If ``ineq`` is one equality, then it should be rational
expression in one varible. This input is passed to
sage.symbolic.relation.solve_ineq_univar function.
Case2: If ``ineq`` is a list involving one or more
inequalities, than the input is passed to
sage.symbolic.relation.solve_ineq_fourier function. This
function can be used for system of linear inequalities and
for some types of nonlinear inequalities. See
http://maxima.cvs.sourceforge.net/viewvc/maxima/maxima/share/contrib/fourier_elim/rtest_fourier_elim.mac
for a big gallery of problems covered by this algorithm.
- ``vars`` - optional parameter with list of variables. This list
is used only if Fourier elimination is used. If omitted or if
rational inequality is solved, then variables are determined
automatically.
OUTPUT:
- ``list`` -- output is list of solutions as a list of simple inequalities
output [A,B,C] means (A or B or C) each A, B, C is again a list and
if A=[a,b], then A means (a and b).
EXAMPLES::
sage: from sage.symbolic.relation import solve_ineq
Inequalities in one variable. The variable is detected automatically::
sage: solve_ineq(x^2-1>3)
[[x < -2], [x > 2]]
sage: solve_ineq(1/(x-1)<=8)
[[x < 1], [x >= (9/8)]]
System of inequalities with automatically detected inequalities::
sage: y=var('y')
sage: solve_ineq([x-y<0,x+y-3<0],[y,x])
[[x < y, y < -x + 3, x < (3/2)]]
sage: solve_ineq([x-y<0,x+y-3<0],[x,y])
[[x < min(-y + 3, y)]]
Note that although Sage will detect the variables automatically,
the order it puts them in may depend on the system, so the following
command is only guaranteed to give you one of the above answers::
sage: solve_ineq([x-y<0,x+y-3<0]) # random
[[x < y, y < -x + 3, x < (3/2)]]
ALGORITHM:
Calls solve_ineq_fourier if inequalities are list and
solve_ineq_univar of the inequality is symbolic expression. See
the description of these commands for more details related to the
set of inequalities which can be solved. The list is empty if
there is no solution.
AUTHORS:
- Robert Marik (01-2010)
"""
if isinstance(ineq,list):
return(solve_ineq_fourier(ineq, vars))
else:
return(solve_ineq_univar(ineq))
|
"""
This module demonstrates various patterns
for ITERATING through SEQUENCES, including:
-- Beginning to end
-- Other ranges (e.g., backwards and every-3rd-item)
-- The COUNT/SUM/etc pattern
-- The FIND pattern (via LINEAR SEARCH)
-- The MAX/MIN pattern
-- Looking two places in the sequence at once
-- Looking at two sequences in parallel
Of course, these are not the only patterns, and some problems require
combining these patterns, but this is a good base upon which to build.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and Weizhou Liu.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
# ----------------------------------------------------------------------
# DONE: 2. SKIM the program below and RUN it.
#
# Then look more closely at the CODE for:
# -- find_example1
# -- find_example2
# -- find_example3
# -- min_index
# -- min_item
# -- two_places_at_once
# -- two_sequences_in_parallel
#
# When you have read them, asking questions as needed,
# and you feel that you understand (at least mostly)
# the patterns for:
# -- FIND
# -- MIN/MAX
# -- TWO-PLACES-AT-ONCE, and
# -- TWO-SEQUENCES-IN-PARALLEL
# then:
# change the above TODO to DONE.
# ----------------------------------------------------------------------
import math
def main():
""" Demonstrates some patterns for ITERATING through SEQUENCES. """
# ------------------------------------------------------------------
# Demonstrate the BEGINNING-TO-END and COUNTING patterns.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating the BEGINNING-TO-END pattern,')
print(' along with the COUNTING pattern:')
print('-----------------------------------------------------------')
sequence = [88, 232, 8.5, -11, 'Grandmother', 22, 4.3, 9.0, 7.0]
answer = beginning_to_end(sequence)
print('The test sequence is:')
print(' ', sequence)
print('The number of integers in that sequence is', answer)
# ------------------------------------------------------------------
# Demonstrate the OTHER-RANGES pattern.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating the OTHER-RANGES pattern')
print(' (backwards, every 3rd item) in each of THREE FORMS:')
print('-----------------------------------------------------------')
sequence = [88, 232, 8.5, -11, 'Grandmother', 22, 4.3, 9.0, 7.0]
other_ranges(sequence)
# ------------------------------------------------------------------
# Demonstrate the FIND pattern.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating the FIND pattern, in several variations:')
print('-----------------------------------------------------------')
print()
print('Example: FINDING the first STRING in the sequence.')
print()
print(' Case 1: The item ** IS ** in the sequence:')
find([88, 232, 8.5, -11, 'Grandmother', 22, 'mother', 9.0, 7.0])
print()
print(' Case 2: The item ** IS NOT ** in the sequence:')
find([1, 2, 5])
# ------------------------------------------------------------------
# Demonstrate the MAX/MIN pattern.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating the MAX/MIN pattern, in several variations:')
print('-----------------------------------------------------------')
sequence = [4, 66, 33, 90, 93, 3, 3, 3, 2, 15]
max_min(sequence)
# ------------------------------------------------------------------
# Demonstrate the TWO-PLACES-IN-THE-SEQUENCE-AT-ONCE pattern.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating TWO-PLACES-IN-THE-SEQUENCE-AT-ONCE pattern:')
print('-----------------------------------------------------------')
sequence = [4, 66, 33, 90, 93, 3, 3, 3, 2, 15]
print('The sequence is:', sequence)
answer = two_places_at_once(sequence)
print('The sequence increments at', answer, 'places.')
# ------------------------------------------------------------------
# Demonstrate the TWO-SEQUENCES-IN-PARALLEL pattern.
# ------------------------------------------------------------------
print()
print('-----------------------------------------------------------')
print('Demonstrating the TWO-SEQUENCES-IN-PARALLEL pattern:')
print('-----------------------------------------------------------')
seq1 = [11, 22, 10, 44, 33, 12]
seq2 = [55, 10, 30, 30, 30, 30]
print('Sequence 1 is:', seq1)
print('Sequence 2 is:', seq2)
answer = two_sequences_in_parallel(seq1, seq2)
print('The 2nd sequence exceeds the 1st at', answer, 'places.')
# ----------------------------------------------------------------------
# The BEGINNING-TO-END pattern:
# ----------------------------------------------------------------------
def beginning_to_end(sequence):
"""
Demonstrates iterating (looping) through a sequence in the most
typical way: from BEGINNING TO END.
This particular example returns the number of items in the sequence
that are integers. It also prints the index during the looping.
"""
# ------------------------------------------------------------------
# The BEGINNING-TO-END pattern is:
#
# for k in range(len(sequence)):
# ... sequence[k] ...
#
# ------------------------------------------------------------------
count = 0
for k in range(len(sequence)):
if type(sequence[k]) == int:
count = count + 1
print(k)
return count
# ----------------------------------------------------------------------
# The OTHER-RANGES pattern:
# ----------------------------------------------------------------------
def other_ranges(sequence):
"""
Demonstrates iterating (looping) through a sequence in a pattern
OTHER than from beginning to end.
This particular example prints every 3rd item of the sequence,
but starting at the END of the list (and going backwards).
"""
# ------------------------------------------------------------------
# The OTHER-RANGES pattern can be thought of as having
# any of three equivalent forms.
# Choose the form that makes the most sense to you.
#
# FORM 1:
# for k in range( NUMBER ):
# ... sequence[ BLAH ] ...
#
# where NUMBER is the number of items in the sequence to examine
# and BLAH is some formula involving k that is carefully
# crafted to produce exactly the right indices.
#
# FORM 2:
# for k in range( BLAH ):
# ... sequence[k] ...
#
# where BLAH is some range OTHER than one that generates
# 0, 1, 2, 3, ...
# and is carefully crafted to produce exactly the right indices.
#
# FORM 3:
# m = ...
# for k in range( NUMBER ):
# ... sequence[ m ] ...
#
# where NUMBER is the number of items in the sequence to examine
# and m is an auxiliary variable that is carefully
# controlled to produce exactly the right indices.
#
# FORM 1: Puts all the heavy lifting into figuring out BLAH.
# FORM 2: Like FORM 1,
# but uses a more sophisticated RANGE expression
# to simplify figuring out BLAH.
# So BLAH may be simpler, but the RANGE expression is harder.
# FORM 3: Like FORM 1,
# but uses an auxiliary variable to simplify figuring out BLAH.
# ------------------------------------------------------------------
print('Printing backwards, every 3rd item, ONE WAY:')
# ------------------------------------------------------------------
# Solution using FORM 1:
# ------------------------------------------------------------------
last = len(sequence) - 1
for k in range(len(sequence) // 3):
print(sequence[last - (k * 3)])
print('\nANOTHER way:')
# ------------------------------------------------------------------
# Solution using FORM 2:
# ------------------------------------------------------------------
last = len(sequence) - 1
for k in range(last, -1, -3):
print(sequence[k])
print('\nYET ANOTHER way:')
# ------------------------------------------------------------------
# Solution using FORM 3:
# ------------------------------------------------------------------
last = len(sequence) - 1
m = last
for k in range(len(sequence) // 3):
print(sequence[m])
m = m - 3
# ----------------------------------------------------------------------
# The FIND pattern, in its several variations:
# ----------------------------------------------------------------------
def find(sequence):
"""
Demonstrates FINDING an item in a sequence. Its forms include:
1. Finding WHETHER a given item is in the given sequence.
2. Finding whether the sequence contains an item
with a given property, and returning either of:
2a. the INDEX of the first such item found
(or -1 if none was found)
2b. the ITEM that was found (or None if none was found)
This particular example finds the first item in the sequence
that is a string. The three sub-examples return:
-- True or False (per item 1 above)
-- the INDEX of the found item (per 2a above)
-- the ITEM that was found (per 2b above)
"""
# ------------------------------------------------------------------
# The FIND pattern is:
#
# for k in range(len(sequence)):
# if ... seq[k] ...:
# return k
#
# return -1
#
# NOTE the placement of the TWO return statements!
#
# The above returns the INDEX where the item was found,
# or -1 if none was found.
#
# Other problems/variations might return True if the item
# was found and False otherwise, or might return the item itself
# that was found (and perhaps None if the item was not found).
#
# Also, some problems might require you to search through only part
# of the sequence (not all of it) or to search backwards, or ...
# ------------------------------------------------------------------
answer1 = find_example1(sequence)
answer2 = find_example2(sequence)
answer3 = find_example3(sequence)
print(' Test sequence is:', sequence)
print(' -- Found (True or False)?', answer1)
print(' -- Index of found item:', answer2)
print(' -- Item that was found:', answer3)
def find_example1(sequence):
"""
Returns True if the given sequence contains a string,
else returns False.
"""
# Returns True or False
for k in range(len(sequence)):
if type(sequence[k]) == str:
return True
return False
def find_example2(sequence):
"""
Returns the INDEX of the first string in the given sequence,
or -1 if the given sequence contains no strings.
"""
# Returns the index (k) or -1
for k in range(len(sequence)):
if type(sequence[k]) == str:
return k
return -1
def find_example3(sequence):
"""
Returns the FIRST STRING in the given sequence,
or None if the sequence contains no strings.
"""
# Returns the item ( sequence[k] ) or None
for k in range(len(sequence)):
if type(sequence[k]) == str:
return sequence[k]
return None
# ----------------------------------------------------------------------
# The MAX/MIN pattern, in several variations:
# ----------------------------------------------------------------------
def max_min(sequence):
"""
Demonstrates determining the item in a sequence whose BLAH
is SMALLEST (or LARGEST), where BLAH varies from problem to problem.
The sub-examples of this particular example find,
for a sequence of numbers:
-- The index of the smallest number in the sequence
-- The number at that index
(i.e., the smallest number in the sequence)
-- The index of the number in the sequence
whose cosine is smallest
"""
# ------------------------------------------------------------------
# The MIN pattern is as follows (with MAX being similar):
#
# index_of_min = 0
# for k in range(1, len(sequence)):
# if BLAH(sequence[k]) < BLAH(sequence[index_of_min]):
# index_of_min = k
#
# return index_of_min
#
# The property BLAH varies from problem to problem.
# NOTE the distinction between the SMALLEST item
# and the INDEX of that item.
#
# The above returns the INDEX where the item was found.
# Some problems ask for the item itself.
# ------------------------------------------------------------------
print('The sequence is:', sequence)
answer1 = min_index(sequence)
answer2 = min_item(sequence)
answer3 = min_cosine(sequence)
print()
print('The index of the smallest item in the sequence is', answer1)
print()
print('The smallest item in the sequence is', answer2)
print()
print('The index of the item in the sequence')
print(' whose cosine is smallest is', answer3)
print('That item is', sequence[answer3])
print('Its cosine is', math.cos(sequence[answer3]))
def min_index(sequence):
"""
Returns the index of the smallest item in the given sequence.
Precondition: the sequence is a non-empty sequence of numbers.
"""
# ------------------------------------------------------------------
# Return the INDEX of the smallest item in the sequence.
# ------------------------------------------------------------------
index_of_min = 0
for k in range(1, len(sequence)):
if sequence[k] < sequence[index_of_min]:
index_of_min = k
return index_of_min
def min_item(sequence):
"""
Returns the smallest item in the given sequence.
Precondition: the sequence is a non-empty sequence of numbers.
"""
# ------------------------------------------------------------------
# Use the same code as above to find the INDEX of the smallest item.
# But return the item itself, in this variation.
# ------------------------------------------------------------------
index_of_min = min_index(sequence)
return sequence[index_of_min]
def min_cosine(sequence):
"""
Returns the index of the item in the sequence whose cosine
is smallest.
Precondition: the sequence is a non-empty sequence of numbers.
"""
# ------------------------------------------------------------------
# Very similar to min_index above. Just compare the COSINES
# of the numbers instead of the numbers themselves.
# ------------------------------------------------------------------
index_of_min = 0
for k in range(1, len(sequence)):
if math.cos(sequence[k]) < math.cos(sequence[index_of_min]):
index_of_min = k
return index_of_min
# ----------------------------------------------------------------------
# The TWO-PLACES-AT-ONCE pattern:
# ----------------------------------------------------------------------
def two_places_at_once(sequence):
"""
Demonstrates iterating (looping) through a sequence,
but examining TWO places in the sequence on the SAME ITERATION.
This particular example returns the number of items in the sequence
that are bigger than the previous item in the sequence.
For example, if the sequence is [4, 66, 33, 90, 93, 3, 3, 3, 2, 15],
then the function returns 4
since 66 > 4 and 90 > 33 and 93 > 90 and 15 > 2.
"""
# ------------------------------------------------------------------
# The TWO-PLACES-AT-ONCE pattern is:
#
# for k in range( BLAH ):
# ... sequence[ FOO_1 ] ... sequence[ FOO_2 ] ...
#
# where BLAH is some range appropriate to the problem,
# FOO_1 is some function of k that gives ONE
# of the "two places at once" to examine, and
# FOO_2 is another function of k that gives the OTHER
# of the "two places at once" to examine.
# Typically, FOO_1 or FOO_2 (but not both) is simply k.
# ------------------------------------------------------------------
count = 0
for k in range(len(sequence) - 1):
if sequence[k + 1] > sequence[k]:
count = count + 1
return count
# ----------------------------------------------------------------------
# The TWO-SEQUENCES-IN-PARALLEL pattern:
# ----------------------------------------------------------------------
def two_sequences_in_parallel(sequence1, sequence2):
"""
Demonstrates iterating (looping) through TWO sequences in PARALLEL.
This particular example assumes that the two sequences are of equal
length and returns the number of items in sequence2 that are bigger
than their corresponding item in sequence1. For example,
if the sequences are:
[11, 22, 10, 44, 33, 12]
[55, 10, 30, 30, 30, 30]
then this function returns 3, since 55 > 11 and 30 > 10 and 30 > 12.
"""
# ------------------------------------------------------------------
# The TWO-SEQUENCES-IN-PARALLEL pattern is:
#
# for k in range(len(sequence1)):
# ... sequence1[k] ... sequence2[k] ...
#
# The above assumes that the sequences are of equal length
# (or that you just want to do the length of sequence1).
# ------------------------------------------------------------------
count = 0
for k in range(len(sequence1)):
if sequence1[k] > sequence2[k]:
count = count + 1
return count
# ----------------------------------------------------------------------
# Calls main to start the ball rolling.
# ----------------------------------------------------------------------
main()
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{123:function(e,t,n){"use strict";var o=n(1),r=n(188),c=n.n(r);o.a.use(c.a,{space:0})},163:function(e,t,n){var content=n(237);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("13e6c80a",content,!0,{sourceMap:!1})},165:function(e,t,n){var content=n(247);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("3c793469",content,!0,{sourceMap:!1})},166:function(e,t,n){var content=n(249);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("2475ca5e",content,!0,{sourceMap:!1})},167:function(e,t,n){var content=n(251);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("62d68a08",content,!0,{sourceMap:!1})},168:function(e,t,n){var content=n(253);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("bb69d43c",content,!0,{sourceMap:!1})},169:function(e,t,n){var content=n(255);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("6f5e6693",content,!0,{sourceMap:!1})},190:function(e,t,n){"use strict";var o=n(8),r=(n(40),n(15),n(24),n(25),n(16)),c=n(178),l={name:"navigate",components:{"nav-menu":function(){return n.e(1).then(n.bind(null,743))}},data:function(){return{sketchManager:null,animations:{pageValue:0}}},computed:{pageToValue:function(){var e=0;if("/navigate/page-2"===this.$route.path)e=1;return e}},watch:{"$route.path":{handler:"onRouteChange",immediate:!0}},mounted:function(){var e=this;return Object(o.a)(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.$sketch({animate:!0,context:"webgl",attributes:{antialias:!0},canvas:e.$refs.canvas},e.sketch);case 3:e.sketchManager=t.sent,e.$once("hook:beforeDestroy",(function(){return e.sketchManager.unload()})),t.next=10;break;case 7:t.prev=7,t.t0=t.catch(0),console.error(t.t0);case 10:case"end":return t.stop()}}),t,null,[[0,7]])})))()},methods:{createSphere:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,t=arguments.length>2?arguments[2]:void 0;u*=-Math.PI,e*=2*Math.PI;var n=Math.sin(u)*Math.cos(e),o=Math.sin(u)*Math.sin(e),r=Math.cos(u);t.set(n,o,r)},createGrayKlein:function(){var u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,t=arguments.length>2?arguments[2]:void 0;u*=-4*Math.PI,e*=2*Math.PI;var a=3,n=3,o=1,r=(a+Math.cos(n*u/2)*Math.sin(e)-Math.sin(n*u/2)*Math.sin(2*e))*Math.cos(o*u/2),c=(a+Math.cos(n*u/2)*Math.sin(e)-Math.sin(n*u/2)*Math.sin(2*e))*Math.sin(o*u/2),l=Math.sin(n*u/2)*Math.sin(e)+Math.cos(n*u/2)*Math.sin(2*e);t.set(r,c,l)},onRouteChange:function(){c.a.to(this.animations,{duration:2,ease:"sine.inOut",pageValue:this.pageToValue})},sketch:function(e){var t=this;return Object(o.a)(regeneratorRuntime.mark((function o(){var c,canvas,l,d,f,h,v,m,x,w,y,M,_,k,z,C,P;return regeneratorRuntime.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:return c=e.context,canvas=e.canvas,l=e.width,d=e.height,f=e.pixelRatio,o.next=3,n.e(0).then(n.bind(null,741));case 3:return h=o.sent,v=h.OrbitControls,m=l/d,x=f,w=new r.H({context:c}),y=new r.r(70,m,.001,1e3),M=new v(y,canvas),_=new r.q(t.createGrayKlein,100,100),k=new r.q(t.createSphere,100,100),z=new r.y({vertexShader:"#pragma vscode_glsllint_stage : vert\n\nprecision mediump float;\n#define GLSLIFY 1\n\nuniform float page;\n\nvarying vec3 vNormal;\n\nattribute vec3 positionSphere;\n\nvoid main() {\n\n vNormal = normal;\n\n vec3 final = mix(\n position,\n positionSphere,\n page\n );\n\n vec4 mvPosition = modelViewMatrix * vec4( final, 1.0 );\n\n gl_Position = projectionMatrix * mvPosition;\n\n}\n",fragmentShader:"#pragma vscode_glsllint_stage : frag\n\nprecision mediump float;\n#define GLSLIFY 1\n\nuniform float page;\n\nvarying vec3 vNormal;\n\nvec3 palette( in float t, in vec3 a, in vec3 b, in vec3 c, in vec3 d ) {\n\n return a + b * cos( 6.28318 * ( c * t + d ) );\n\n}\n\nvoid main () {\n\n float diff = dot(\n normalize(\n vec3(\n 1.,\n 1.,\n 0.5\n )\n ),\n mix(\n vNormal,\n vec3(\n 0.6,\n 0.,\n 0.1\n ),\n page\n )\n );\n\n // Colors\n // https://iquilezles.org/www/articles/palettes/palettes.htm\n vec3 a = vec3( 0.1, 0., 0.1 );\n vec3 b = vec3( 0.6, 0.5, 0.5 );\n vec3 c = vec3( 0.5, 0.5, 0.5 );\n vec3 d = vec3( 0.6, 0.5, 0.5 );\n\n vec3 color = palette( diff, a, b, c, d );\n\n gl_FragColor = vec4(\n color,\n 1.\n );\n\n}\n",extensions:{derivatives:"#extension GL_OES_standard_derivatives : enable"},side:r.i,uniforms:{time:{type:"f",value:0},page:{type:"f",value:t.animations.pageValue},resolution:{type:"v2",value:new r.D(l,d)},uvRate1:{value:new r.D(1,1)}}}),C=new r.o(_,z),P=new r.x,w.setPixelRatio(x),w.setSize(l,d),w.setClearColor(new r.f("#111"),1),_.setAttribute("positionSphere",new r.d(k.attributes.position.array,3)),y.position.set(0,0,9),_.center(),P.add(C),o.abrupt("return",{resize:function(e){var t=e.pixelRatio,n=e.viewportWidth,o=e.viewportHeight;w.setPixelRatio(t),w.setSize(n,o),z.uniforms.resolution.value.x=n,z.uniforms.resolution.value.y=o,y.aspect=n/o,y.updateProjectionMatrix()},render:function(e){var time=e.time;z.uniforms.time.value=time,z.uniforms.page.value=t.animations.pageValue,C.rotateX(.001),C.rotateY(.001),M.update(),w.render(P,y)},unload:function(){M.dispose(),w.dispose()}});case 23:case"end":return o.stop()}}),o)})))()}}},d=l,f=(n(248),n(250),n(23)),component=Object(f.a)(d,(function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"layout"},[n("canvas",{ref:"canvas",staticClass:"absolute z-index--minus-1"}),n("nav-menu",{key:e.$route.fullPath}),e._m(0),n("nuxt")],1)}),[function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"main-title"},[n("h1",[e._v("Navigate through pages")]),n("h2",[n("em",[e._v("enhance your creative 3D / UX / Visual art while browsing")])])])}],!1,null,"c35ded26",null);t.a=component.exports},191:function(e,t,n){"use strict";n(15),n(24),n(25);var o={name:"default",components:{"nav-menu":function(){return n.e(1).then(n.bind(null,743))}}},r=(n(246),n(23)),component=Object(r.a)(o,(function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"layout"},[n("nav-menu",{key:"menu-"+e.$route.fullPath}),n("nuxt",{key:e.$route.fullPath})],1)}),[],!1,null,"762d7a2a",null);t.a=component.exports},192:function(e,t,n){"use strict";n(15),n(24),n(25);var o={name:"readme",components:{"nav-menu":function(){return n.e(1).then(n.bind(null,743))}}},r=(n(252),n(254),n(23)),component=Object(r.a)(o,(function(){var e=this.$createElement,t=this._self._c||e;return t("div",{staticClass:"layout layout-readme"},[t("nav-menu"),t("nuxt")],1)}),[],!1,null,"3b20ccbf",null);t.a=component.exports},198:function(e,t,n){e.exports=n(199)},236:function(e,t,n){"use strict";n(163)},237:function(e,t,n){var o=n(27)(!1);o.push([e.i,".layout-error[data-v-214a2248]{display:flex;flex:1 1 100%;flex-direction:column;align-items:center;justify-content:center;min-height:100vh}",""]),e.exports=o},242:function(e,t,n){var content=n(243);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("19dcf68c",content,!0,{sourceMap:!1})},243:function(e,t,n){var o=n(27)(!1);o.push([e.i,":root{font-size:16px}*{min-width:0}body,html{margin:0;padding:0;overflow-x:hidden}body{position:relative;color:#333;line-height:1.5}.container{display:flex;flex:1 1 100%;flex-direction:column;align-items:center;justify-content:center;width:100%;max-width:100%;margin-right:auto;margin-left:auto}img{width:auto;max-width:100%;height:auto}main{min-height:100vh}h1{font-size:2em}video{display:block;margin:0;padding:0}label{display:block}button,label{width:100%;cursor:pointer}button{max-width:354px;margin:16px auto;padding:8px;color:#f05;font-weight:700;line-height:1.36;text-align:center;background-color:#f3f0f1;border:0;border-radius:6px;opacity:.9;transition:all .27s ease-in-out;-webkit-appearance:none;-moz-appearance:none;appearance:none}button:active,button:focus,button:hover{opacity:1}.opacity-90{opacity:.9!important}.w-full{width:100%}.w-screen{width:100vw}.h-screen{height:100vh}.absolute{position:absolute}.font-bold{font-weight:700}.z-index--minus-1{z-index:-1}.z-index--1{z-index:1}.z-index--2{z-index:2}a{color:#00bfff}.text--center{text-align:center}.text--red{color:#ff1e00}.no-pointer-event{pointer-events:none}.cursor--pointer{cursor:pointer}.pin{top:0;right:0;bottom:0;left:0}.pin-r{right:16px}.pin-b{bottom:100px}@media and screen (min-width:600px){.pin-b{bottom:16px}}",""]),e.exports=o},244:function(e,t,n){var content=n(245);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[e.i,content,""]]),content.locals&&(e.exports=content.locals);(0,n(28).default)("2bdd7b28",content,!0,{sourceMap:!1})},245:function(e,t,n){var o=n(27)(!1);o.push([e.i,".canvas-container{overflow:hidden}canvas{top:0;right:0;bottom:0;left:0;z-index:0;display:block;width:100%;height:100%;margin:0 auto;transform:translateZ(0);opacity:1;transition:opacity .3s ease-out;will-change:opacity}",""]),e.exports=o},246:function(e,t,n){"use strict";n(165)},247:function(e,t,n){var o=n(27)(!1);o.push([e.i,'.layout[data-v-762d7a2a]:before{position:fixed;top:0;left:0;z-index:-1;display:block;width:100%;height:100%;background-color:#333;content:""}.layout[data-v-762d7a2a]{position:relative;min-height:100vh;color:#fff}',""]),e.exports=o},248:function(e,t,n){"use strict";n(166)},249:function(e,t,n){var o=n(27)(!1);o.push([e.i,'.layout[data-v-c35ded26]:before{position:fixed;top:0;left:0;z-index:-1;display:block;width:100%;height:100%;background-color:#333;content:""}.layout[data-v-c35ded26]{position:relative;min-height:100vh;color:#fff}',""]),e.exports=o},250:function(e,t,n){"use strict";n(167)},251:function(e,t,n){var o=n(27)(!1);o.push([e.i,".layout .main-title[data-v-c35ded26]{position:absolute;bottom:2.5%;width:100%;text-align:center}",""]),e.exports=o},252:function(e,t,n){"use strict";n(168)},253:function(e,t,n){var o=n(27)(!1);o.push([e.i,'.layout[data-v-3b20ccbf]:before{position:fixed;top:0;left:0;z-index:-1;display:block;width:100%;height:100%;background-color:#333;content:""}.layout[data-v-3b20ccbf]{position:relative;min-height:100vh;color:#fff}',""]),e.exports=o},254:function(e,t,n){"use strict";n(169)},255:function(e,t,n){var o=n(27)(!1);o.push([e.i,".layout-readme[data-v-3b20ccbf] .nav-menu{position:sticky}@media screen and (min-width:600px){.layout-readme[data-v-3b20ccbf] .nav-menu{top:0;left:0;max-width:100%}}",""]),e.exports=o},39:function(e,t,n){"use strict";var o={name:"error",props:{error:{type:Object,required:!0}},head:function(){if(this.is404)return{title:"404 Pagina non trovata - NuxtJs || ThreeJs",meta:[{hid:"referrer",name:"referrer",content:"unsafe-url"}]}},computed:{is404:function(){return this.error&&404===this.error.statusCode}}},r=(n(236),n(23)),component=Object(r.a)(o,(function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"layout-error container text-center"},[n("h1",{attrs:{align:"center"}},[e._v(" C'è stato un errore imprevisto: "),n("strong",{domProps:{textContent:e._s(e.error.statusCode)}}),e._v(". ")]),e.error.message?n("p",{domProps:{textContent:e._s(e.error.message)}}):e._e(),n("nuxt-link",{attrs:{to:"/",title:"go back to the homepage"}},[n("strong",[e._v("< go back to the homepage")])])],1)}),[],!1,null,"214a2248",null);t.a=component.exports}},[[198,23,5,24]]]); |
/*
* Copyright 2019 Verapi 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 agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
|
const webpack = require('webpack')
const merge = require('webpack-merge')
const base = require('./webpack.base.config')
const HTMLPlugin = require('html-webpack-plugin')
const SWPrecachePlugin = require('sw-precache-webpack-plugin')
const config = merge(base, {
plugins: [
// 全局变量
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.VUE_ENV': '"client"'
}),
// 提取公共库
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
}),
// html模板
new HTMLPlugin({
template: 'src/index.html'
})
]
})
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
// 生产环境下 - 压缩js
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
// 用于使用service worker来缓存外部项目依赖项。
new SWPrecachePlugin({
cacheId: 'vue-hn',
filename: 'service-worker.js',
dontCacheBustUrlsMatching: /./,
staticFileGlobsIgnorePatterns: [/index\.html$/, /\.map$/]
})
)
}
module.exports = config
|
/*
Massively by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
(function($) {
var $window = $(window),
$body = $('body'),
$wrapper = $('#wrapper'),
$header = $('#header'),
$nav = $('#nav'),
$main = $('#main'),
$navPanelToggle, $navPanel, $navPanelInner;
// Breakpoints.
breakpoints({
default: ['1681px', null ],
xlarge: ['1281px', '1680px' ],
large: ['981px', '1280px' ],
medium: ['737px', '980px' ],
small: ['481px', '736px' ],
xsmall: ['361px', '480px' ],
xxsmall: [null, '360px' ]
});
/**
* Applies parallax scrolling to an element's background image.
* @return {jQuery} jQuery object.
*/
$.fn._parallax = function(intensity) {
var $window = $(window),
$this = $(this);
if (this.length == 0 || intensity === 0)
return $this;
if (this.length > 1) {
for (var i=0; i < this.length; i++)
$(this[i])._parallax(intensity);
return $this;
}
if (!intensity)
intensity = 0.25;
$this.each(function() {
var $t = $(this),
$bg = $('<div class="bg"></div>').appendTo($t),
on, off;
on = function() {
$bg
.removeClass('fixed')
.css('transform', 'matrix(1,0,0,1,0,0)');
$window
.on('scroll._parallax', function() {
var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);
$bg.css('transform', 'matrix(1,0,0,1,0,' + (pos * intensity) + ')');
});
};
off = function() {
$bg
.addClass('fixed')
.css('transform', 'none');
$window
.off('scroll._parallax');
};
// Disable parallax on ..
if (browser.name == 'ie' // IE
|| browser.name == 'edge' // Edge
|| window.devicePixelRatio > 1 // Retina/HiDPI (= poor performance)
|| browser.mobile) // Mobile devices
off();
// Enable everywhere else.
else {
breakpoints.on('>large', on);
breakpoints.on('<=large', off);
}
});
$window
.off('load._parallax resize._parallax')
.on('load._parallax resize._parallax', function() {
$window.trigger('scroll');
});
return $(this);
};
// Play initial animations on page load.
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-preload');
}, 100);
});
// Scrolly.
$('.scrolly').scrolly();
// Background.
$wrapper._parallax(0.925);
// Nav Panel.
// Toggle.
$navPanelToggle = $(
'<a href="#navPanel" id="navPanelToggle" style="color: #000000;">Menu</a>'
)
.appendTo($wrapper);
// Change toggle styling once we've scrolled past the header.
$header.scrollex({
bottom: '5vh',
enter: function() {
$navPanelToggle.removeClass('alt');
},
leave: function() {
$navPanelToggle.addClass('alt');
}
});
// Panel.
$navPanel = $(
'<div id="navPanel">' +
'<nav>' +
'</nav>' +
'<a href="#navPanel" class="close"></a>' +
'</div>'
)
.appendTo($body)
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'right',
target: $body,
visibleClass: 'is-navPanel-visible'
});
// Get inner.
$navPanelInner = $navPanel.children('nav');
// Move nav content on breakpoint change.
var $navContent = $nav.children();
breakpoints.on('>medium', function() {
// NavPanel -> Nav.
$navContent.appendTo($nav);
// Flip icon classes.
$nav.find('.icons, .icon')
.removeClass('alt');
});
breakpoints.on('<=medium', function() {
// Nav -> NavPanel.
$navContent.appendTo($navPanelInner);
// Flip icon classes.
$navPanelInner.find('.icons, .icon')
.addClass('alt');
});
// Hack: Disable transitions on WP.
if (browser.os == 'wp'
&& browser.osVersion < 10)
$navPanel
.css('transition', 'none');
// Intro.
var $intro = $('#intro');
if ($intro.length > 0) {
// Hack: Fix flex min-height on IE.
if (browser.name == 'ie') {
$window.on('resize.ie-intro-fix', function() {
var h = $intro.height();
if (h > $window.height())
$intro.css('height', 'auto');
else
$intro.css('height', h);
}).trigger('resize.ie-intro-fix');
}
// Hide intro on scroll (> small).
breakpoints.on('>small', function() {
$main.unscrollex();
$main.scrollex({
mode: 'bottom',
top: '25vh',
bottom: '-50vh',
enter: function() {
$intro.addClass('hidden');
},
leave: function() {
$intro.removeClass('hidden');
}
});
});
// Hide intro on scroll (<= small).
breakpoints.on('<=small', function() {
$main.unscrollex();
$main.scrollex({
mode: 'middle',
top: '15vh',
bottom: '-15vh',
enter: function() {
$intro.addClass('hidden');
},
leave: function() {
$intro.removeClass('hidden');
}
});
});
}
})(jQuery); |
try:
import influxdb
INFLUXDB_SUPPORTED = True
except ImportError:
INFLUXDB_SUPPORTED = False
class Database(object):
def Close(self):
raise NotImplementedError
def Initialize(self):
raise NotImplementedError
def Write(self, metrics):
raise NotImplementedError
class InfluxDatabase(Database):
def __init__(self, config, precision='ms', logger=None):
"""
InfluxDB database constructor.
This class will throw a RuntimeError if InfluxDB is not supported in the
current environment.
:param config: Database configuration from the main configuration object.
:param precision: Timestamp precision. Defaults to ms.
:param logger: Logger instance to use otherwise logging will be ignored.
"""
if not INFLUXDB_SUPPORTED:
raise RuntimeError('InfluxDB is not installed')
self.config = config
self.precision = precision
self.logger = logger
self.handle = None
def Close(self):
"""
Close the InfluxDB connection if one is open.
This function will only throw in the event that InfluxDB is not supported
otherwise it is safe to call during shutdown.
:return: None
"""
if not INFLUXDB_SUPPORTED:
raise RuntimeError('InfluxDB is not installed')
if self.handle:
try:
self.handle.close()
except Exception as e:
if self.logger:
self.logger.warning('Failed to close influx db connection: {}'.format(e))
def Initialize(self):
"""
Initialize the InfluxDB connection.
This class will throw a RuntimeError if InfluxDB is not supported in the
current environment.
:return: True on success or False if the connection fails.
"""
if not INFLUXDB_SUPPORTED:
raise RuntimeError('InfluxDB is not installed')
try:
self.handle = influxdb.InfluxDBClient(
host=self.config['server'],
port=self.config['port'],
ssl=self.config['ssl'],
verify_ssl=self.config['verify'],
database=self.config['database'])
except KeyError as e:
# If any of the configuration options are missing we need to trigger a fatal
# error because we cannot recover from this.
raise RuntimeError("Missing configuration option '{}'".format(e.args[0]))
except Exception as e:
if self.logger:
self.logger.error('Failed to initiate influx db connection: {}'.format(e))
self.handle = None
return False
return True
def Write(self, metrics):
"""
Write metrics to the InfluxDB database.
This class will throw a RuntimeError if InfluxDB is not supported in the
current environment.
:param metrics: metrics object generated that should be sent to InfluxDB.
:return: True on success or False on failure.
"""
if not INFLUXDB_SUPPORTED:
raise RuntimeError('InfluxDB is not installed')
if not self.handle and not self.Initialize():
return False
self.handle.write_points(metrics, time_precision=self.precision)
return True
|
import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import joblib
import yaml
import shap
with open("./artifacts.yaml", "r") as stream:
try:
data = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
@st.cache()
def load_data(data_type):
index_column = str(data["model"]["index"])
if data_type == "Train":
X = pd.read_csv(
str('../' + data["model"]["X_train"]), low_memory=False, index_col=index_column
)
y = pd.read_csv(
'../' + data["model"]["y_train"], low_memory=False, index_col=index_column
)
X = pd.read_csv('../' +data["model"]["X_test"], low_memory=False, index_col=index_column)
y = pd.read_csv('../' +data["model"]["y_test"], low_memory=False, index_col=index_column)
return X, y
def check_path(path_dict):
for path in path_dict:
if not isinstance(path, (str, type(None))):
raise AttributeError("Data Path Must be String and Not NONE in .csv format")
return
@st.cache(allow_output_mutation=True)
def load_model():
path = '../' + data["model"]["model_path"]
check_path(path)
# pip install dill imbalanced-learn
model = joblib.load(path)
return model
@st.cache(allow_output_mutation=True, suppress_st_warning=True)
def plot_confusion_matrix(data_type="Test", threshold=0.5):
from sklearn.metrics import (
confusion_matrix,
f1_score,
roc_curve,
precision_recall_curve,
classification_report,
)
from numpy import sqrt, argmax, arange
c1, c2, c3 = st.columns((1, 6, 1))
# Load Model
model = load_model()
# Load Data
X, y = load_data(data_type)
# preds = model.predict(X)
preds = (model.predict_proba(X)[:, 1] >= float(threshold)).astype(bool)
cm = confusion_matrix(y, preds)
fig, axs = plt.subplots(1, 2, figsize=(15, 5))
fig.tight_layout(pad=5.0, w_pad=5.0)
sns.heatmap(cm, fmt="", annot=True, cmap="Blues", ax=axs[0])
c2.markdown(
"<h2 style='text-align: center;'>Confusion Matrix and Classification Report</h2>",
unsafe_allow_html=True,
)
report = classification_report(y, preds, output_dict=True)
sns.heatmap(
pd.DataFrame(report).iloc[:-1, :].T, annot=True, ax=axs[1], cmap="Blues"
)
c2.pyplot(fig)
# RCO and PR plot
fig, axs = plt.subplots(1, 2, figsize=(15, 5))
fig.tight_layout(pad=5.0, w_pad=5.0)
c2.markdown(
"<h2 style='text-align: center;'>ROC Curve and P-R Curve</h2>",
unsafe_allow_html=True,
)
# Roc Curve
# predict probabilities
yhat = model.predict_proba(X)
# keep probabilities for the positive outcome only
yhat = yhat[:, 1]
# calculate roc curves
fpr, tpr, thresholds = roc_curve(y, yhat)
# calculate the g-mean for each threshold
gmeans = sqrt(tpr * (1 - fpr))
# locate the index of the largest g-mean
ix = argmax(gmeans)
st.sidebar.info(
"ROC Curve Best Threshold=%f, G-Mean=%.3f" % (thresholds[ix], gmeans[ix])
)
# plot the roc curve for the model
plt.clf()
fig, axs = plt.subplots(1, 2, figsize=(15, 5))
fig.tight_layout(pad=5.0, w_pad=5.0)
axs[0].plot([0, 1], [0, 1], linestyle="--", label="base")
axs[0].plot(fpr, tpr, marker=".", label="Current Model")
axs[0].scatter(fpr[ix], tpr[ix], marker="o", color="black", label="Best")
# axis labels
axs[0].set_xlabel("False Positive Rate")
axs[0].set_ylabel("True Positive Rate")
axs[0].legend()
# PR Curve Plot
precision, recall, thresholds = precision_recall_curve(y, yhat)
# convert to f score
fscore = (2 * precision * recall) / (precision + recall)
# locate the index of the largest f score
ix = argmax(fscore)
st.sidebar.info(
"PR Curve Best Threshold=%f, F-Score=%.3f" % (thresholds[ix], fscore[ix])
)
# plot the roc curve for the model
no_skill = len(y[y == 1]) / len(y)
axs[1].plot([0, 1], [no_skill, no_skill], linestyle="--", label="base")
axs[1].plot(recall, precision, marker=".", label="Current Model")
axs[1].scatter(recall[ix], precision[ix], marker="o", color="black", label="Best")
# axis labels
axs[1].set_xlabel("Recall")
axs[1].set_ylabel("Precision")
axs[1].legend()
c2.pyplot(fig)
# plot_roc_curve(model, X, y, ax=axs[0])
# plot_precision_recall_curve(model, X, y, ax=axs[1])
# c2.pyplot(fig)
with st.expander("See explanation"):
st.write("ROC Thresholding")
st.write(
"'Youden's J statistic (also called Youden's index) is a single statistic that captures the performance of a dichotomous diagnostic test. Informedness is its generalization to the multiclass case and estimates the probability of an informed decision.'"
)
# apply threshold to positive probabilities to create labels
def to_labels(pos_probs, threshold):
return (pos_probs >= threshold).astype("int")
# define thresholds
thresholds = arange(0, 1, 0.001)
# evaluate each threshold
scores = [f1_score(y, to_labels(yhat, t)) for t in thresholds]
# get best threshold
ix = argmax(scores)
st.sidebar.info(
"Overall Best Threshold=%.3f, F-Score=%.5f" % (thresholds[ix], scores[ix])
)
def create_map():
# Load an empty map
from keplergl import KeplerGl
data_type = st.sidebar.selectbox(
"Select Test or train to see the metrics", ["Test", "Train"], index=0
)
threshold = st.sidebar.slider(
label="Prediction threshold",
min_value=0.0,
max_value=1.0,
value=0.5,
step=0.05,
format="%f",
)
X, y = load_data(data_type)
model = load_model()
preds = (model.predict_proba(X)[:, 1] >= float(threshold)).astype(bool)
index_col = str(data['model']['index'])
df = pd.concat([X, y],axis=1).reset_index()
map_1 = KeplerGl(height=800, data={'Data': df,
'Predictions': pd.DataFrame({index_col: df[index_col],
'predictions': preds})},
)
return map_1._repr_html_()
@st.cache()
def load_map():
if data["map"]["map_path"] is not None:
HtmlFile = open('../' + data["map"]["map_path"], "r", encoding="utf-8")
source_code = HtmlFile.read()
return source_code
else:
return
@st.cache(allow_output_mutation=True, suppress_st_warning=True)
def create_explainer(X_sampled):
model = load_model()
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_sampled)
return explainer, shap_values
@st.cache(allow_output_mutation=True, suppress_st_warning=True)
def st_shap(plot, height=None):
shap_html = f"<head>{shap.getjs()}</head><body>{plot.html()}</body>"
components.html(shap_html, height=height)
def plot_SHAP(data_type="Test"):
# Load Data
X, y = load_data(data_type)
sample_size = int(data["shap"]["sample_size"])
X_sampled = X.sample(n=sample_size)
hid = st.sidebar.selectbox(
label="Select Index to see its SHAP", options=X_sampled.index
)
explainer, shap_values = create_explainer(X_sampled)
st.header("SHAP Force Plot (Stacked)")
st_shap(
shap.force_plot(explainer.expected_value[1], shap_values[1], X_sampled), 400
)
idx = X_sampled.loc[[hid]].reset_index().index.tolist()[0]
st.header("SHAP Force Plot (Individual)")
st_shap(
shap.force_plot(
explainer.expected_value[1], shap_values[1][idx, :], X_sampled.loc[hid]
),
200,
)
st.header("SHAP Summary Plot")
st.pyplot(shap.summary_plot(shap_values, X_sampled, plot_size=(5, 5)))
|
#!/usr/bin/env python3
from .variational_elbo import VariationalELBO
class VariationalMarginalLogLikelihood(VariationalELBO):
def __init__(self, likelihood, model, num_data, combine_terms=True):
"""
A special MLL designed for variational inference
Args:
- likelihood: (Likelihood) - the likelihood for the model
- model: (Module) - the variational GP model
- num_data: (int) - the total number of training data points (necessary for SGD)
- combine_terms: (bool) - whether or not to sum the expected NLL with the KL terms (default True)
"""
super(VariationalMarginalLogLikelihood, self).__init__(likelihood, model, num_data, combine_terms)
|
import React from "react";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import PageRoute from "./page-route";
const PageRouter = ({
children,
config = [],
isUserSignedIn = false,
defaultPath = "/",
}) => {
return (
<Router>
{children}
<Switch>
{config &&
config.map(({ redirectPath, ...routeConfig }) => {
return (
<PageRoute
defaultPath={redirectPath || defaultPath}
isUserSignedIn={isUserSignedIn}
key={routeConfig.path}
{...routeConfig}
/>
);
})}
</Switch>
</Router>
);
};
export default PageRouter;
|
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _isEqual = require('is-equal');
var _isEqual2 = _interopRequireDefault(_isEqual);
var _isRegex = require('is-regex');
var _isRegex2 = _interopRequireDefault(_isRegex);
var _assert = require('./assert');
var _assert2 = _interopRequireDefault(_assert);
var _SpyUtils = require('./SpyUtils');
var _TestUtils = require('./TestUtils');
/**
* An Expectation is a wrapper around an assertion that allows it to be written
* in a more natural style, without the need to remember the order of arguments.
* This helps prevent you from making mistakes when writing tests.
*/
var Expectation = (function () {
function Expectation(actual) {
_classCallCheck(this, Expectation);
this.actual = actual;
if (_TestUtils.isFunction(actual)) {
this.context = null;
this.args = [];
}
}
Expectation.prototype.toExist = function toExist(message) {
_assert2['default'](this.actual, message || 'Expected %s to exist', this.actual);
return this;
};
Expectation.prototype.toNotExist = function toNotExist(message) {
_assert2['default'](!this.actual, message || 'Expected %s to not exist', this.actual);
return this;
};
Expectation.prototype.toBe = function toBe(value, message) {
_assert2['default'](this.actual === value, message || 'Expected %s to be %s', this.actual, value);
return this;
};
Expectation.prototype.toNotBe = function toNotBe(value, message) {
_assert2['default'](this.actual !== value, message || 'Expected %s to not be %s', this.actual, value);
return this;
};
Expectation.prototype.toEqual = function toEqual(value, message) {
try {
_assert2['default'](_isEqual2['default'](this.actual, value), message || 'Expected %s to equal %s', this.actual, value);
} catch (e) {
// These attributes are consumed by Mocha to produce a diff output.
e.showDiff = true;
e.actual = this.actual;
e.expected = value;
throw e;
}
return this;
};
Expectation.prototype.toNotEqual = function toNotEqual(value, message) {
_assert2['default'](!_isEqual2['default'](this.actual, value), message || 'Expected %s to not equal %s', this.actual, value);
return this;
};
Expectation.prototype.toThrow = function toThrow(value, message) {
_assert2['default'](_TestUtils.isFunction(this.actual), 'The "actual" argument in expect(actual).toThrow() must be a function, %s was given', this.actual);
_assert2['default'](_TestUtils.functionThrows(this.actual, this.context, this.args, value), message || 'Expected %s to throw %s', this.actual, value || 'an error');
return this;
};
Expectation.prototype.toNotThrow = function toNotThrow(value, message) {
_assert2['default'](_TestUtils.isFunction(this.actual), 'The "actual" argument in expect(actual).toNotThrow() must be a function, %s was given', this.actual);
_assert2['default'](!_TestUtils.functionThrows(this.actual, this.context, this.args, value), message || 'Expected %s to not throw %s', this.actual, value || 'an error');
return this;
};
Expectation.prototype.toBeA = function toBeA(value, message) {
_assert2['default'](_TestUtils.isFunction(value) || typeof value === 'string', 'The "value" argument in toBeA(value) must be a function or a string');
_assert2['default'](_TestUtils.isA(this.actual, value), message || 'Expected %s to be a %s', this.actual, value);
return this;
};
Expectation.prototype.toNotBeA = function toNotBeA(value, message) {
_assert2['default'](_TestUtils.isFunction(value) || typeof value === 'string', 'The "value" argument in toNotBeA(value) must be a function or a string');
_assert2['default'](!_TestUtils.isA(this.actual, value), message || 'Expected %s to be a %s', this.actual, value);
return this;
};
Expectation.prototype.toMatch = function toMatch(pattern, message) {
_assert2['default'](typeof this.actual === 'string', 'The "actual" argument in expect(actual).toMatch() must be a string');
_assert2['default'](_isRegex2['default'](pattern), 'The "value" argument in toMatch(value) must be a RegExp');
_assert2['default'](pattern.test(this.actual), message || 'Expected %s to match %s', this.actual, pattern);
return this;
};
Expectation.prototype.toNotMatch = function toNotMatch(pattern, message) {
_assert2['default'](typeof this.actual === 'string', 'The "actual" argument in expect(actual).toNotMatch() must be a string');
_assert2['default'](_isRegex2['default'](pattern), 'The "value" argument in toNotMatch(value) must be a RegExp');
_assert2['default'](!pattern.test(this.actual), message || 'Expected %s to not match %s', this.actual, pattern);
return this;
};
Expectation.prototype.toBeLessThan = function toBeLessThan(value, message) {
_assert2['default'](typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeLessThan() must be a number');
_assert2['default'](typeof value === 'number', 'The "value" argument in toBeLessThan(value) must be a number');
_assert2['default'](this.actual < value, message || 'Expected %s to be less than %s', this.actual, value);
return this;
};
Expectation.prototype.toBeGreaterThan = function toBeGreaterThan(value, message) {
_assert2['default'](typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeGreaterThan() must be a number');
_assert2['default'](typeof value === 'number', 'The "value" argument in toBeGreaterThan(value) must be a number');
_assert2['default'](this.actual > value, message || 'Expected %s to be greater than %s', this.actual, value);
return this;
};
Expectation.prototype.toInclude = function toInclude(value, compareValues, message) {
_assert2['default'](_TestUtils.isArray(this.actual) || typeof this.actual === 'string', 'The "actual" argument in expect(actual).toInclude() must be an array or a string');
if (typeof compareValues === 'string') {
message = compareValues;
compareValues = null;
}
message = message || 'Expected %s to include %s';
if (_TestUtils.isArray(this.actual)) {
_assert2['default'](_TestUtils.arrayContains(this.actual, value, compareValues), message, this.actual, value);
} else {
_assert2['default'](_TestUtils.stringContains(this.actual, value), message, this.actual, value);
}
return this;
};
Expectation.prototype.toExclude = function toExclude(value, compareValues, message) {
_assert2['default'](_TestUtils.isArray(this.actual) || typeof this.actual === 'string', 'The "actual" argument in expect(actual).toExclude() must be an array or a string');
if (typeof compareValues === 'string') {
message = compareValues;
compareValues = null;
}
message = message || 'Expected %s to exclude %s';
if (_TestUtils.isArray(this.actual)) {
_assert2['default'](!_TestUtils.arrayContains(this.actual, value, compareValues), message, this.actual, value);
} else {
_assert2['default'](!_TestUtils.stringContains(this.actual, value), message, this.actual, value);
}
return this;
};
Expectation.prototype.toHaveBeenCalled = function toHaveBeenCalled(message) {
var spy = this.actual;
_assert2['default'](_SpyUtils.isSpy(spy), 'The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy');
_assert2['default'](spy.calls.length > 0, message || 'spy was not called');
return this;
};
Expectation.prototype.toHaveBeenCalledWith = function toHaveBeenCalledWith() {
var spy = this.actual;
_assert2['default'](_SpyUtils.isSpy(spy), 'The "actual" argument in expect(actual).toHaveBeenCalledWith() must be a spy');
var expectedArgs = Array.prototype.slice.call(arguments, 0);
_assert2['default'](spy.calls.some(function (call) {
return _isEqual2['default'](call.arguments, expectedArgs);
}), 'spy was never called with %s', expectedArgs);
return this;
};
Expectation.prototype.toNotHaveBeenCalled = function toNotHaveBeenCalled(message) {
var spy = this.actual;
_assert2['default'](_SpyUtils.isSpy(spy), 'The "actual" argument in expect(actual).toNotHaveBeenCalled() must be a spy');
_assert2['default'](spy.calls.length === 0, message || 'spy was not supposed to be called');
return this;
};
Expectation.prototype.withContext = function withContext(context) {
_assert2['default'](_TestUtils.isFunction(this.actual), 'The "actual" argument in expect(actual).withContext() must be a function');
this.context = context;
return this;
};
Expectation.prototype.withArgs = function withArgs() {
_assert2['default'](_TestUtils.isFunction(this.actual), 'The "actual" argument in expect(actual).withArgs() must be a function');
if (arguments.length) this.args = this.args.concat(Array.prototype.slice.call(arguments, 0));
return this;
};
return Expectation;
})();
var aliases = {
toBeAn: 'toBeA',
toNotBeAn: 'toNotBeA',
toBeTruthy: 'toExist',
toBeFalsy: 'toNotExist',
toBeFewerThan: 'toBeLessThan',
toBeMoreThan: 'toBeGreaterThan',
toContain: 'toInclude',
toNotContain: 'toExclude'
};
for (var alias in aliases) {
Expectation.prototype[alias] = Expectation.prototype[aliases[alias]];
}exports['default'] = Expectation;
module.exports = exports['default']; |
webpackHotUpdate(1,{
/***/ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/arrayWithHoles.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/construct.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/esm/extends.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/interopRequireWildcard.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/nonIterableRest.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/slicedToArray.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/typeof.js":
false,
/***/ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
false,
/***/ "./node_modules/@babel/runtime/regenerator/index.js":
false,
/***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js":
false,
/***/ "./node_modules/native-url/dist/index.js":
false,
/***/ "./node_modules/next/dist/client/router.js":
false,
/***/ "./node_modules/next/dist/client/with-router.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/mitt.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/router-context.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/router/router.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/router/utils/is-dynamic.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/router/utils/route-matcher.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/router/utils/route-regex.js":
false,
/***/ "./node_modules/next/dist/next-server/lib/utils.js":
false,
/***/ "./node_modules/prop-types/checkPropTypes.js":
false,
/***/ "./node_modules/prop-types/factoryWithTypeCheckers.js":
false,
/***/ "./node_modules/prop-types/index.js":
false,
/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js":
false,
/***/ "./node_modules/querystring-es3/decode.js":
false,
/***/ "./node_modules/querystring-es3/encode.js":
false,
/***/ "./node_modules/querystring-es3/index.js":
false,
/***/ "./node_modules/react-is/cjs/react-is.development.js":
false,
/***/ "./node_modules/react-is/index.js":
false,
/***/ "./node_modules/regenerator-runtime/runtime.js":
false
})
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzdGF0aWMvd2VicGFjay8xLmViOTVjNzYxOTI5OThjMzQ4Y2YxLmhvdC11cGRhdGUuanMiLCJzb3VyY2VSb290IjoiIn0= |
import argparse
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from tools.text import clean_text
def parse_arguments(parser):
parser.add_argument('--data_dir', type=str, default='C:/data/niosh_ifund/')
parser.add_argument('--test_file', type=str, default='test.csv')
parser.add_argument('--train_file', type=str, default='train.csv')
args = parser.parse_args()
return args
if __name__ == '__main__':
parser = argparse.ArgumentParser()
args = parse_arguments(parser)
# Importing the raw data
train = pd.read_csv(args.data_dir + args.train_file,
usecols=['text', 'event'])
test = pd.read_csv(args.data_dir + args.test_file,
usecols=['text'])
# Adding a random identifier for the BERT scripts
num_train = train.shape[0]
num_test = test.shape[0]
num_records = num_train + num_test
ids = np.array([''.join(['record', str(num)])
for num in list(range(num_records))])
np.random.shuffle(ids)
train['id'] = ids[0:num_train]
test['id'] = ids[num_train:]
# Lowercasing and adding spaces around common abbreviations;
# only fixes a few things
train.text = pd.Series(clean_text(train.text))
test.text = pd.Series(clean_text(test.text))
# Clipping the docs to the max length
train_lengths = np.array([len(doc.split()) for doc in
pd.concat([train.text, test.text])])
test_lengths = np.array([len(doc.split()) for doc in
pd.concat([train.text, test.text])])
clip_to = np.min([np.max(train_lengths), np.max(test_lengths)])
train.text = pd.Series([' '.join(doc.split()[:clip_to])
for doc in train.text])
test.text = pd.Series([' '.join(doc.split()[:clip_to])
for doc in test.text])
pd.Series(clip_to).to_csv(args.data_dir + 'clip_to.csv',
header=False, index=False)
# Making a lookup dictionary for the event codes
code_df = pd.read_csv(args.data_dir + 'code_descriptions.csv')
codes = code_df.event.values
code_dict = dict(zip(codes, np.arange(len(codes))))
train.event = [code_dict[code] for code in train.event]
# Saving the code dict to disk
code_df = pd.DataFrame.from_dict(code_dict, orient='index')
code_df['event_code'] = code_df.index
code_df.columns = ['value', 'event_code']
code_df.to_csv(args.data_dir + 'code_dict.csv', index=False)
# Rearranging the columns for BERT
train['filler'] = np.repeat('a', train.shape[0])
test['filler'] = np.repeat('a', test.shape[0])
train = train[['id', 'event', 'filler', 'text']]
test = test[['id', 'text']]
# Shuffling the rows
train = train.sample(frac=1)
# Writing the regular splits to disk
train.to_csv(args.data_dir + 'train.tsv', sep='\t',
index=False, header=False)
test.to_csv(args.data_dir + 'test.tsv', sep='\t',
index=False, header=True)
|
import React from "react";
import _ from "lodash";
import moment from "moment";
import Link from "gatsby-link";
import Helmet from "react-helmet";
import { Page, Row, Column } from "hedron";
import Thumbnail from "../components/Thumbnail";
import Breadcrumb from "../components/Breadcrumb";
import SectionTitle from "../components/SectionTitle";
import PostExcerpt from "../components/PostExcerpt";
import QuestionForm from "../components/QuestionForm";
import Icon from "../components/Icon";
import styled, { css, ThemeProvider } from "styled-components";
import colors, { rubriqueColor } from "../utils/colors";
import globals from "../utils/globals";
import { noBullet, rowMargin, position, link } from "../utils/mixins";
import "moment/locale/fr";
moment.locale("fr");
import mascotte from "../assets/images/mascotte.png";
const ArticleHeader = styled.header`
margin-bottom: 65px;
time {
color: ${rubriqueColor};
font-size: ${globals.sizes.small};
text-transform: uppercase;
}
h1 {
font-size: ${globals.sizes.large};
margin-bottom: 8px;
line-height: 1.3;
}
h2 {
color: ${colors.grey.base};
font-size: ${globals.sizes.medium};
line-height: 1.3;
}
`;
const Speech = styled.div`
position: relative;
@media (min-width: 1024px) {
&:after {
display: block;
content: "";
width: 113px;
height: 181px;
background-image: url(${mascotte});
${position(0, "-150px")};
}
}
`;
const Blockquote = styled.blockquote`
margin: 1.5em 10px;
position: relative;
font-style: italic;
font-weight: 300;
&:before,
&:after {
color: ${rubriqueColor};
font-size: ${globals.sizes.xlarge};
font-weight: bold;
font-style: normal;
line-height: 1;
font-family: Merriweather;
opacity: 0.1;
position: absolute;
top: 0;
}
&:before {
content: "“";
left: -3rem;
}
&:after {
content: "”";
right: -2rem;
}
`;
const includeListStyle = css`
ul {
${noBullet("0 0 0 16px")};
li {
position: relative;
&:before {
display: inline-block;
content: "";
width: 8px;
height: 8px;
background-color: ${rubriqueColor};
margin-left: -16px;
margin-right: 8px;
}
}
}
`;
const Summary = styled.section`
font-size: ${globals.sizes.small};
h1,
h2,
h3 {
font-size: 1.2em;
line-height: 1.3;
}
a {
${link};
}
${includeListStyle};
`;
const numberPrint = number => css`
&:nth-child(${number}) {
&:before {
content: "1";
}
}
`;
const itemLoop = () => {
const nbre = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
nbre.map(element => numberPrint(element));
};
const Main = styled.main`
font-weight: 300;
h2,
h3 {
line-height: 1.3;
}
${includeListStyle};
a {
${link};
}
ol {
${noBullet(0)};
li {
padding-top: 3.5rem;
position: relative;
> strong:first-child {
color: ${rubriqueColor};
display: block;
font-weight: 400;
text-transform: uppercase;
}
&:before {
color: ${rubriqueColor};
display: block;
line-height: 1;
font-size: ${globals.sizes.xlarge};
font-family: ${globals.fonts.default};
font-weight: 300;
opacity: 0.2;
position: absolute;
top: 0;
left: 0;
}
&:nth-child(1) {
&:before {
content: "1";
}
}
&:nth-child(2) {
&:before {
content: "2";
}
}
&:nth-child(3) {
&:before {
content: "3";
}
}
&:nth-child(4) {
&:before {
content: "4";
}
}
&:nth-child(5) {
&:before {
content: "5";
}
}
&:nth-child(6) {
&:before {
content: "6";
}
}
&:nth-child(7) {
&:before {
content: "7";
}
}
&:nth-child(8) {
&:before {
content: "8";
}
}
&:nth-child(9) {
&:before {
content: "9";
}
}
&:nth-child(10) {
&:before {
content: "10";
}
}
}
}
`;
const FileLink = styled.div`
margin: ${globals.spaces.base};
margin-left: 0;
`;
const RowWrapper = styled.div`
${rowMargin};
margin-top: 0;
`;
const Navigation = styled.nav`
border-top: solid 1px ${colors.grey.light};
padding: ${globals.sizes.base} 0;
margin-top: ${globals.sizes.medium};
`;
const NavigationItem = styled.div`
text-align: ${props => (props.next ? "right" : "left")};
position: relative;
a {
color: inherit;
display: block;
text-decoration: none;
font-family: ${globals.fonts.alt};
font-weight: 300;
span {
color: ${rubriqueColor};
display: block;
font-size: ${globals.sizes.small};
font-family: ${globals.fonts.default};
font-weight: bold;
}
.icon {
${props =>
props.next
? css`
transform: rotate(180deg);
${position("5px", "-32px", "auto", "auto")};
`
: css`
${position("5px", "auto", "auto", "-32px")};
`};
}
}
`;
const Aside = styled.aside`
margin-top: ${globals.spaces.large};
`;
const PostTemplate = ({ data }) => {
const {
createdAt,
title,
subtitle,
rubrique,
tag,
id,
thumbnail,
thumbAlt,
document,
summary,
main,
speech,
moreInfoUrl
} = data.contentfulArticle;
const onTheme = _.filter(
rubrique.article,
post => post.rubrique.slug === rubrique.slug && post.id !== id
);
const postIndex = _.find(
data.allContentfulArticle.edges,
({ node: post }) => post.id === id
);
return (
<ThemeProvider theme={{ rubrique: rubrique.slug }}>
<div>
<Helmet title={`${title} - ${data.site.siteMetadata.title}`} />
<Page fluid>
<article>
<Row divisions={24}>
<Column lg={17} lgShift={3} md={22} mdShift={1}>
<Breadcrumb rubrique={rubrique} title={title} tag={tag} />
</Column>
<Column lg={5} lgShift={3} md={6} mdShift={1}>
{thumbnail && (
<Thumbnail
img={thumbnail.responsiveResolution}
alt={thumbAlt}
caption={thumbnail.description}
/>
)}
{summary && (
<Summary>
<SectionTitle>en bref</SectionTitle>
<div
dangerouslySetInnerHTML={{
__html: summary.childMarkdownRemark.html
}}
/>
<a href={moreInfoUrl}>En savoir plus</a>
</Summary>
)}
</Column>
<Column lg={12} mdShift={1} md={15}>
<ArticleHeader>
<time dateTime={createdAt}>
le {moment(createdAt).format("ll")}
</time>
<h1>{title}</h1>
<h2>{subtitle}</h2>
</ArticleHeader>
{main && (
<Main>
<SectionTitle>in concreto</SectionTitle>
<div
dangerouslySetInnerHTML={{
__html: main.childMarkdownRemark.html
}}
/>
{document && (
<FileLink>
<a
href={document.file.url}
title={document.description}
target="_blank"
>
<Icon icon="download" /> Télécharger la pièce jointe
</a>
</FileLink>
)}
</Main>
)}
{speech && (
<Speech>
<SectionTitle>Discours</SectionTitle>
<Blockquote
dangerouslySetInnerHTML={{
__html: speech.childMarkdownRemark.html
}}
/>
</Speech>
)}
<QuestionForm light title={`Depuis l'article "${title}"`} />
{onTheme.length > 0 && (
<Aside>
<SectionTitle>Sur le même thème</SectionTitle>
<RowWrapper>
<Row divisions={2}>
{onTheme.map((post, index) => {
return (
<Column md={1} key={index}>
<PostExcerpt post={post} />
</Column>
);
})}
</Row>
</RowWrapper>
</Aside>
)}
</Column>
</Row>
<Navigation>
<Row divisions={24}>
<Column lg={9} lgShift={3} md={11} mdShift={1}>
{postIndex.previous && (
<NavigationItem>
<Link
to={`/${postIndex.previous.rubrique.slug}/${postIndex
.previous.slug}`}
>
<Icon icon="chevron" />
<span>Article Précédent :</span>
{postIndex.previous.title}
</Link>
</NavigationItem>
)}
</Column>
<Column lg={9} md={11}>
{postIndex.next && (
<NavigationItem next>
<Link
to={`/${postIndex.next.rubrique.slug}/${postIndex.next
.slug}`}
>
<Icon icon="chevron" />
<span>Article Suivant :</span>
{postIndex.next.title}
</Link>
</NavigationItem>
)}
</Column>
</Row>
</Navigation>
</article>
</Page>
</div>
</ThemeProvider>
);
};
export default PostTemplate;
export const query = graphql`
query PostQuery($id: String) {
site {
siteMetadata {
title
}
}
contentfulArticle(id: { eq: $id }) {
id
createdAt
title
subtitle
thumbnail {
description
responsiveResolution(width: 400, height: 400) {
width
height
src
srcSet
}
}
thumbAlt
document {
description
file {
url
}
}
summary {
childMarkdownRemark {
html
}
}
main {
childMarkdownRemark {
html
}
}
speech {
childMarkdownRemark {
html
}
}
moreInfoUrl
rubrique {
slug
title
article {
id
slug
title
rubrique {
slug
}
tag {
slug
title
categorie {
slug
}
}
thumbnail {
responsiveResolution(width: 400, height: 400) {
width
height
src
srcSet
}
}
}
}
tag {
slug
title
}
}
allContentfulArticle {
edges {
previous {
slug
title
subtitle
rubrique {
slug
}
}
node {
id
}
next {
slug
title
subtitle
rubrique {
slug
}
}
}
}
}
`;
|
/**
* Taken from Material UI [https://github.com/mui-org/material-ui]
*/
/* eslint-disable no-use-before-define */
import warning from 'warning';
/**
* Returns a number whose value is limited to the given range.
*
* @param {number} value The value to be clamped
* @param {number} min The lower boundary of the output range
* @param {number} max The upper boundary of the output range
* @returns {number} A number in the range [min, max]
*/
function clamp(value, min = 0, max = 1) {
warning(
value >= min && value <= max,
`Material-UI: the value provided ${value} is out of range [${min}, ${max}].`,
);
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
/**
* Converts a color from CSS hex format to CSS rgb format.
*
* @param {string} color - Hex color, i.e. #nnn or #nnnnnn
* @returns {string} A CSS rgb color string
*/
export function hexToRGB(color) {
color = color.substr(1);
const re = new RegExp(`.{1,${color.length / 3}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map(n => n + n);
}
return colors ? `${colors.map(n => parseInt(n, 16)).join(', ')}` : '';
}
/**
* Converts a color from CSS rgb format to CSS hex format.
*
* @param {string} color - RGB color, i.e. rgb(n, n, n)
* @returns {string} A CSS rgb color string, i.e. #nnnnnn
*/
export function rgbToHex(color) {
// Pass hex straight through
if (color.indexOf('#') === 0) {
return color;
}
function intToHex(c) {
const hex = c.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
let { values } = decomposeColor(color);
values = values.map(n => intToHex(n));
return `#${values.join('')}`;
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {object} - A MUI color object: {type: string, values: number[]}
*/
export function decomposeColor(color) {
if (color.charAt(0) === '#') {
return decomposeColor(`rgb(${hexToRGB(color)})`);
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
let values = color.substring(marker + 1, color.length - 1).split(',');
values = values.map(value => parseFloat(value));
if (process.env.NODE_ENV !== 'production') {
if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {
throw new Error(
[
`Material-UI: unsupported \`${color}\` color.`,
'We support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().',
].join('\n'),
);
}
}
return { type, values };
}
/**
* Converts a color object with type and values to a string.
*
* @param {object} color - Decomposed color
* @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns {string} A CSS color string
*/
export function recomposeColor(color) {
const { type } = color;
let { values } = color;
if (type.indexOf('rgb') !== -1) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n, i) => (i < 3 ? parseInt(n, 10) : n));
}
if (type.indexOf('hsl') !== -1) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
return `${color.type}(${values.join(', ')})`;
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
*
* @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {number} A contrast ratio value in the range 0 - 21.
*/
export function getContrastRatio(foreground, background) {
warning(
foreground,
`Material-UI: missing foreground argument in getContrastRatio(${foreground}, ${background}).`,
);
warning(
background,
`Material-UI: missing background argument in getContrastRatio(${foreground}, ${background}).`,
);
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
export function getContrastText(background) {
warning(
background,
`Material-UI: missing background argument in getContrastText(${background}).`,
);
const contrastText =
getContrastRatio(background, '#FFFFFF') >= 3
? '#FFFFFF'
: '#000000';
if (process.env.NODE_ENV !== 'production') {
const contrast = getContrastRatio(background, contrastText);
warning(
contrast >= 3,
[
`Material-UI: the contrast ratio of ${contrast}:1 for ${contrastText} on ${background}`,
'falls below the WACG recommended absolute minimum contrast ratio of 3:1.',
'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast',
].join('\n'),
);
}
return contrastText;
}
/**
* The relative brightness of any point in a color space,
* normalized to 0 for darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @returns {number} The relative brightness of the color in the range 0 - 1
*/
export function getLuminance(color) {
warning(color, `Material-UI: missing color argument in getLuminance(${color}).`);
const decomposedColor = decomposeColor(color);
if (decomposedColor.type.indexOf('rgb') !== -1) {
const rgb = decomposedColor.values.map(val => {
val /= 255; // normalized
return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;
});
// Truncate at 3 digits
return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));
}
// else if (decomposedColor.type.indexOf('hsl') !== -1)
return decomposedColor.values[2] / 100;
}
/**
* Darken or lighten a colour, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient=0.15 - multiplier in the range 0 - 1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
export function emphasize(color, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} value - value to set the alpha channel to in the range 0 -1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
export function fade(color, value) {
warning(color, `Material-UI: missing color argument in fade(${color}, ${value}).`);
if (!color) return color;
color = decomposeColor(color);
value = clamp(value);
if (color.type === 'rgb' || color.type === 'hsl') {
color.type += 'a';
}
color.values[3] = value;
return recomposeColor(color);
}
/**
* Darkens a color.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient - multiplier in the range 0 - 1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
export function darken(color, coefficient) {
warning(color, `Material-UI: missing color argument in darken(${color}, ${coefficient}).`);
if (!color) return color;
color = decomposeColor(color);
coefficient = clamp(coefficient);
if (color.type.indexOf('hsl') !== -1) {
color.values[2] *= 1 - coefficient;
} else if (color.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
color.values[i] *= 1 - coefficient;
}
}
return recomposeColor(color);
}
/**
* Lightens a color.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient - multiplier in the range 0 - 1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
export function lighten(color, coefficient) {
warning(color, `Material-UI: missing color argument in lighten(${color}, ${coefficient}).`);
if (!color) return color;
color = decomposeColor(color);
coefficient = clamp(coefficient);
if (color.type.indexOf('hsl') !== -1) {
color.values[2] += (100 - color.values[2]) * coefficient;
} else if (color.type.indexOf('rgb') !== -1) {
for (let i = 0; i < 3; i += 1) {
color.values[i] += (255 - color.values[i]) * coefficient;
}
}
return recomposeColor(color);
} |
/**
* @param {number} n
* @return {string[]}
* Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”.
For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
*/
var fizzBuzz = function (n) {
var arr = [];
for(var i = 1; i <= n; ++i) {
var isMultipleOfThree = i % 3 === 0;
var isMultipleOfFive = i % 5 === 0;
var isMultipleOfThreeAndFive = isMultipleOfThree && isMultipleOfFive;
//注意条件的顺序
if(isMultipleOfThreeAndFive) {
arr.push('FizzBuzz');
} else if(isMultipleOfThree) {
arr.push('Fizz');
} else if(isMultipleOfFive) {
arr.push('Buzz');
} else {
arr.push(i + '');
}
}
return arr;
};
console.log(fizzBuzz(15)) |
# MenuTitle: Scribble
# -*- coding: utf-8 -*-
__doc__ = """
Scribble
"""
import GlyphsApp
from NaNGFGraphikshared import *
from NaNGFAngularizzle import *
from NaNGFSpacePartition import *
from NaNGFNoise import *
from NaNFilter import NaNFilter
from NaNGlyphsEnvironment import glyphsEnvironment as G
import random
class Scribble(NaNFilter):
params = {
"S": {"offset": -13, "iterations": 2, "walklen": 100},
"M": {"offset": -15, "iterations": 3, "walklen": 800},
"L": {"offset": -18, "iterations": 3, "walklen": 900},
}
pen = 8
def processLayer(self, thislayer, params):
G.remove_overlap(thislayer)
outlinedata = setGlyphCoords(ConvertPathsToSkeleton(thislayer.paths, 20))
ClearPaths(thislayer)
noisepaths = NoiseOutline(thislayer, outlinedata, noisevars=[0.05, 0, 35])
noiseoutline = self.expandMonolineFromPathlist(noisepaths, self.pen)
outlinedata2 = setGlyphCoords(ConvertPathsToSkeleton(noisepaths, 4))
allscribbles = []
for n in range(0, params["iterations"]):
scribble = self.ScribblePath(thislayer, outlinedata2, params["walklen"])
if scribble is not None:
scribble = drawSimplePath(scribble, False, False)
scribblemono = self.expandMonolineFromPathlist([scribble], self.pen)
AddAllPathsToLayer(scribblemono, thislayer)
retractHandles(thislayer)
AddAllPathsToLayer(noiseoutline, thislayer)
G.remove_overlap(thislayer)
self.CleanOutlines(thislayer, remSmallPaths=True, remSmallSegments=True, remStrayPoints=True, remOpenPaths=True, keepshape=False)
def ScribblePath(self, thislayer, outlinedata, walklen):
start = defineStartXY(thislayer, outlinedata)
if start is None:
return None
else:
sx, sy = start[0], start[1]
noisescale = 0.05
seedx, seedy = random.randrange(0,100000), random.randrange(0,100000)
minsize, maxsize = 0, 80
walkpath = []
for n in range(0, walklen):
x_noiz = pnoise1( (n+seedx)*noisescale, 3)
rx = noiseMap( x_noiz, minsize, maxsize )
y_noiz = pnoise1( ((1000+n)+seedy)*noisescale, 3)
ry = noiseMap( y_noiz, minsize, maxsize )
nx = sx + rx
ny = sy + ry
if withinGlyphBlack(nx, ny, outlinedata):
sx = nx
sy = ny
walkpath.append([sx, sy])
return walkpath
Scribble()
|
const path = require('path');
module.exports = {
entry: {
app: './search//index.js'
},
output: {
path: path.join(__dirname, 'src/static/js/'),
filename: 'bundle.js',
},
module: {
loaders: [{
// Test for js or jsx files
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
// Convert ES6 syntax to ES5 for browser compatibility
presets: ['es2015', 'react'],
},
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
},
}; |
var mongodb = require("../../lib/mongodb"),
ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager;
var options = {
auto_reconnect: true,
poolSize: 4,
socketOptions: { keepAlive: 100, timeout:30000 }
};
var userObjects = [];
var counter = 0;
var counter2 = 0;
// Build user array
for(var i = 0; i < 122; i++) {
userObjects.push({a:true, b:true});
}
RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1});
RS.startSet(true, function(err, result) {
// Replica configuration
var replSet = new mongodb.ReplSetServers( [
new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ),
new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } )
],
{rs_name:RS.name}
);
var collA;
var collB;
var db = new mongodb.Db("data", replSet);
db.open(function(err, client){
console.log("Connected");
client.collection("collA", function(err, coll){
collA = coll;
coll.insert(userObjects, {w:1}, function(err, result) {
client.collection("collB", function(err, coll){
collB = coll;
coll.insert(userObjects, {w:1}, function(err, result) {
var timeoutFunc = function() {
lookup(function(err, result) {
console.log("-------------------------------------------- lookedup")
process.nextTick(timeoutFunc, 1);
})
}
process.nextTick(timeoutFunc, 1);
});
});
});
});
});
function lookup(cb){
var a, b;
var waiting = 2;
collA.findOne({ a: true }, function(err, result){
a = result;
waiting--;
if(waiting === 0){
console.log("---------------------------------------------------------------------- collA :: " + counter);
counter = counter + 1;
cb(null, [a, b]);
}
});
collB.findOne({ b: true }, function(err, result){
b = result;
waiting--;
if(waiting === 0){
console.log("---------------------------------------------------------------------- collB :: " + counter);
counter = counter + 1;
cb(null, [a, b]);
}
});
}
}); |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums = nums1+nums2
nums.sort()
length = len(nums)
if length%2 == 0 :
return (nums[int(length/2)-1]+nums[int(length/2)])/2
else :
return nums[int(length/2)]
if __name__ == "__main__":
solution = Solution()
print(solution.findMedianSortedArrays([1, 3], [2])) |
//= require jquery
//= require jquery_ujs
//= require back/plugins/bootstrap/bootstrap.min
//= require back/plugins/bootstrap-tagsinput/bootstrap-tagsinput.min
//= require back/plugins/datatables/jquery.dataTables.min
//= require back/plugins/datatables/dataTables.bootstrap.min
//= require ckeditor/init
//= require back/app
$(document).ready(function() {
var table = $('.dataTable').DataTable();
// Get sidebar state from localStorage and add the proper class to body
$('body').addClass(localStorage.getItem('sidebar-state'));
var activePage = stripTrailingSlash(window.location.pathname);
$('.sidebar-menu li a').each(function(){
var currentPage = stripTrailingSlash($(this).attr('href'));
if (activePage == currentPage) {
$(this).closest('.treeview').addClass('active');
$(this).parent().addClass('active');
}
});
function stripTrailingSlash(str) {
if(str.substr(-1) == '/') { return str.substr(0, str.length - 1); }
return str;
}
// Save sidebar state in localStorage browser
$('.sidebar-toggle').on('click', function(){
if($('body').attr('class').indexOf('sidebar-collapse') != -1) {
localStorage.setItem('sidebar-state', '');
} else {
localStorage.setItem('sidebar-state', 'sidebar-collapse');
}
});
});
|
"""A library to evaluate MDM on a single GPU.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
from pathlib import Path
import data_provider
import menpo
import matplotlib
import matplotlib.pyplot as plt
import mdm_model
import numpy as np
import tensorflow as tf
import time
import utils
import menpo.io as mio
from menpo.shape.pointcloud import PointCloud
import json
# Do not use a gui toolkit for matlotlib.
matplotlib.use('Agg')
tf.flags.DEFINE_string('c', 'config.json', """Model config file""")
with open(tf.flags.FLAGS.c, 'r') as g_config:
g_config = json.load(g_config)
for k in g_config:
print(k, type(g_config[k]), g_config[k])
input('OK?(Y/N): ')
def plot_ced(errors, method_names=['MDM']):
from menpofit.visualize import plot_cumulative_error_distribution
# plot the ced and store it at the root.
fig = plt.figure()
fig.add_subplot(111)
plot_cumulative_error_distribution(errors, legend_entries=method_names,
error_range=(0, 0.09, 0.005))
# shift the main graph to make room for the legend
ax = plt.gca()
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
plt.clf()
return data
def flip_predictions(predictions, shapes):
flipped_preds = []
for pred, shape in zip(predictions, shapes):
pred = menpo.shape.PointCloud(pred)
if pred.points.shape[0] == 68:
pred = utils.mirror_landmarks_68(pred, shape)
elif pred.points.shape[0] == 73:
pred = utils.mirror_landmarks_73(pred, shape)
flipped_preds.append(pred.points)
return np.array(flipped_preds, np.float32)
def evaluate():
with tf.Graph().as_default(), tf.device('/cpu:0'):
path_base = Path(g_config['eval_dataset']).parent.parent
_mean_shape = mio.import_pickle(path_base / 'reference_shape.pkl')
_mean_shape = data_provider.align_reference_shape_to_112(_mean_shape)
def decode_feature(serialized):
feature = {
'test/image': tf.FixedLenFeature([], tf.string),
'test/shape': tf.VarLenFeature(tf.float32),
'test/init': tf.VarLenFeature(tf.float32),
}
features = tf.parse_single_example(serialized, features=feature)
decoded_image = tf.decode_raw(features['test/image'], tf.float32)
decoded_image = tf.reshape(decoded_image, (256, 256, 3))
decoded_shape = tf.sparse.to_dense(features['test/shape'])
decoded_shape = tf.reshape(decoded_shape, (g_config['num_patches'], 2))
decoded_init = tf.sparse.to_dense(features['test/init'])
decoded_init = tf.reshape(decoded_init, (g_config['num_patches'], 2))
return decoded_image, decoded_shape, decoded_init
def scale_image(image, shape):
mp_image = menpo.image.Image(image.transpose((2, 0, 1)))
mp_image.landmarks['PTS'] = PointCloud(shape)
bb = mp_image.landmarks['PTS'].bounding_box().points
miny, minx = np.min(bb, 0)
maxy, maxx = np.max(bb, 0)
bbsize = max(maxx - minx, maxy - miny)
center = [(miny + maxy) / 2., (minx + maxx) / 2.]
mp_image.landmarks['bb'] = PointCloud(
[
[center[0] - bbsize * 0.5, center[1] - bbsize * 0.5],
[center[0] + bbsize * 0.5, center[1] + bbsize * 0.5],
]
).bounding_box()
mp_image = mp_image.crop_to_landmarks_proportion(1. / 6., group='bb')
mp_image = mp_image.resize((112, 112))
image = (mp_image.pixels.transpose((1, 2, 0)) - 0.5) * 2.
shape = mp_image.landmarks['PTS'].points
init = _mean_shape
return image.astype(np.float32), shape.astype(np.float32), init.astype(np.float32)
with tf.name_scope('DataProvider', values=[]):
tf_dataset = tf.data.TFRecordDataset([str(path_base / 'test.bin')])
tf_dataset = tf_dataset.map(decode_feature)
tf_dataset = tf_dataset.map(
lambda x, y, _: tf.py_func(
scale_image, [x, y], [tf.float32, tf.float32, tf.float32],
stateful=False,
name='scale'
)
)
tf_dataset = tf_dataset.batch(1)
tf_dataset = tf_dataset.prefetch(5000)
tf_iterator = tf_dataset.make_one_shot_iterator()
tf_images, tf_shapes, tf_inits = tf_iterator.get_next(name='batch')
tf_images.set_shape((1, 112, 112, 3))
tf_inits.set_shape((1, 73, 2))
tf_shapes.set_shape((1, 73, 2))
print('Loading model...')
with tf.device(g_config['eval_device']):
model = mdm_model.MDMModel(
tf_images,
tf_shapes,
tf_inits,
batch_size=1,
num_iterations=g_config['num_iterations'],
num_patches=g_config['num_patches'],
patch_shape=(g_config['patch_size'], g_config['patch_size']),
num_channels=3,
is_training=False
)
tf_predictions = model.prediction
# Calculate predictions.
# tf_nme = model.normalized_rmse(tf_predictions, tf_shapes)
tf_ne = model.normalized_error(tf_predictions, tf_shapes)
tf_nme = model.normalized_mean_error(tf_ne)
# Restore the moving average version of the learned variables for eval.
variable_averages = tf.train.ExponentialMovingAverage(g_config['MOVING_AVERAGE_DECAY'])
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
graph_def = tf.get_default_graph().as_graph_def()
summary_writer = tf.summary.FileWriter(g_config['eval_dir'], graph_def=graph_def)
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
ckpt = tf.train.get_checkpoint_state(g_config['train_dir'])
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
# Assuming model_checkpoint_path looks something like:
# /ckpt/train/model.ckpt-0,
# extract global_step from it.
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
print('Successfully loaded model from {} at step={}.'.format(ckpt.model_checkpoint_path, global_step))
else:
print('No checkpoint file found')
return
eval_base = Path('Evaluate')
for i in range(10):
eval_path = eval_base / 'err{}'.format(i)
if not eval_path.exists():
eval_path.mkdir(parents=True)
num_iter = g_config['num_examples']
# Counts the number of correct predictions.
errors = []
mean_errors = []
print('%s: starting evaluation on (%s).' % (datetime.now(), g_config['eval_dataset']))
start_time = time.time()
for step in range(num_iter):
rmse, rse, img = sess.run([tf_nme, tf_ne, model.out_images])
error_level = min(9, int(rmse[0] * 100))
plt.imsave('Evaluate/err{}/step{}.png'.format(error_level, step), img[0])
errors.append(rse)
mean_errors.append(rmse)
step += 1
if step % 20 == 0:
duration = time.time() - start_time
sec_per_batch = duration / 20.0
examples_per_sec = 1. / sec_per_batch
log_str = '{}: [{:d} batches out of {:d}] ({:.1f} examples/sec; {:.3f} sec/batch)'
print(log_str.format(datetime.now(), step, num_iter, examples_per_sec, sec_per_batch))
start_time = time.time()
errors = np.array(errors)
errors = np.reshape(errors, (-1, g_config['num_patches']))
print(errors.shape)
mean_errors = np.vstack(mean_errors).ravel()
mean_rse = np.mean(errors, 0)
mean_rmse = mean_errors.mean()
with open('Evaluate/errors.txt', 'w') as ofs:
for row, avg in zip(errors, mean_errors):
for col in row:
ofs.write('%.4f, ' % col)
ofs.write('%.4f' % avg)
ofs.write('\n')
for col in mean_rse:
ofs.write('%.4f, ' % col)
ofs.write('%.4f' % mean_rmse)
ofs.write('\n')
auc_at_08 = (mean_errors < .08).mean()
auc_at_05 = (mean_errors < .05).mean()
ced_image = plot_ced([mean_errors.tolist()])
ced_plot = sess.run(tf.summary.merge([tf.summary.image('ced_plot', ced_image[None, ...])]))
print('Errors', mean_errors.shape)
print(
'%s: mean_rmse = %.4f, auc @ 0.05 = %.4f, auc @ 0.08 = %.4f [%d examples]' %
(datetime.now(), mean_errors.mean(), auc_at_05, auc_at_08, num_iter)
)
summary_writer.add_summary(ced_plot, global_step)
if __name__ == '__main__':
evaluate()
|
Roblox = Roblox || {};
if (typeof Roblox.CancelSubscriptionModal === 'undefined') {
Roblox.CancelSubscriptionModal = (function () {
var open = function () {
var options = {
titleText: Roblox.CancelSubscriptionModal.Resources.title,
bodyContent: Roblox.CancelSubscriptionModal.Resources.body,
allowHtmlContentInBody: true,
footerText: '',
overlayClose: true,
escClose: true,
acceptText: Roblox.CancelSubscriptionModal.Resources.cancel,
declineText: Roblox.CancelSubscriptionModal.Resources.dontCancel,
acceptColor: Roblox.GenericConfirmation.gray,
declineColor: Roblox.GenericConfirmation.green,
onAccept: function () {
$('#Message').hide();
Roblox.CancelSubscriptionModal.process();
},
onDecline: function () {
window.location.href = '/home';
},
opacity: 80,
overlayCss: { backgroundColor: '#000' },
};
Roblox.GenericConfirmation.open(options);
if (Roblox.FormEvents) {
Roblox.FormEvents.SendInteractionClick('confirmCancelRenewal', {
pid: Roblox.CancelSubscriptionModal.Resources.premiumFeatureId,
});
}
};
var process = function () {
var url = Roblox.CancelSubscriptionModal.Resources.URL;
var goHome = function () {
window.location.href = '/my/account#!/billing';
};
$.post(url, function (data) {
if (data.success) {
var options = {
titleText: Roblox.CancelSubscriptionModal.Resources.cancelSuccessfulTitle,
bodyContent: Roblox.CancelSubscriptionModal.Resources.cancelSuccessfulBody,
acceptText: Roblox.CancelSubscriptionModal.Resources.ok,
acceptColor: Roblox.GenericConfirmation.blue,
declineColor: Roblox.GenericConfirmation.none,
onAccept: goHome,
allowHtmlContentInBody: true,
dismissable: false,
};
} else {
options = {
titleText: Roblox.CancelSubscriptionModal.Resources.cancelFailedTitle,
bodyContent: '<p class="CancelModalBody">' + data.message + '</p>',
acceptText: Roblox.CancelSubscriptionModal.Resources.ok,
acceptColor: Roblox.GenericConfirmation.blue,
declineColor: Roblox.GenericConfirmation.none,
onAccept: goHome,
allowHtmlContentInBody: true,
dismissable: false,
};
}
Roblox.GenericConfirmation.open(options);
});
if (Roblox.EventStream) {
Roblox.EventStream.SendEventWithTarget(
'modalAction',
'confirmCancelRenewal',
{ pid: Roblox.CancelSubscriptionModal.Resources.premiumFeatureId },
Roblox.EventStream.TargetTypes.WWW,
);
}
};
return {
open: open,
process: process,
};
})();
}
$(function () {
$('a.CancelSubscriptionButton').click(function () {
Roblox.CancelSubscriptionModal.open();
return false;
});
});
|
#!/usr/bin/python
import sys
import os
import re
import fnmatch
import string
workload_dir = "/Users/xiyuexiang/GoogleDrive/NOCulator/hring/src/bin/"
workload = "mix_app"
insns_count = 1000000
ipc_alone = [2.16, 2.75, 2.08, 1.91, 2.16, 2.75, 2.08, 1.91, 2.16, 2.75, 2.08, 1.91, 2.16, 2.75, 2.08, 1.91]
ipc_share = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
out_dir = "/Users/xiyuexiang/GoogleDrive/NOCulator/hring/src/bin/sweep_batch/"
filename = '../bin/sweep_batch_period.txt'
filename_out = str(filename)
if os.path.exists(filename_out) == True:
os.remove(filename_out)
fo_out = open(filename_out, "a")
fo_out.write('\n\n' + 'sweep packet batching period (epoch = 100000)' + '\n\n')
fo_out.write('period'.ljust(15) + 'w_speedup'.ljust(15) + 'h_speedup'.ljust(15))
fo_out.write('\n')
for sim_index in range(100, 5100, 100):
out_file = "sim_" + str(sim_index) + ".out"
command_line = "mono ../bin/sim.exe -config " + workload_dir + "config_0.txt -output " + out_dir + out_file + " -workload " + workload_dir + workload + ' 3 ' + "-STC_batchPeriod " + str(sim_index)
os.system (command_line)
# collect result
result_file = open (out_dir + out_file, 'r')
result = result_file.read()
result_file.close()
searchObj = re.search(r'(?:"active_cycles":\[(.*?)])',result)
splitObj = re.split('\W+',searchObj.group(1))
active_cycles = splitObj
weighted_speedup = 0
temp0 = 0
for i in range (0, 16, 1):
ipc_share [i] = float(insns_count) / int(active_cycles[i])
weighted_speedup = ipc_share[i] / ipc_alone[i] + weighted_speedup
temp0 = ipc_alone[i] / ipc_share[i] + temp0
harmonic_speedup = 16 / temp0
print str(sim_index) + " " + str("%.2f" % weighted_speedup) + " " + str("%.2f" % harmonic_speedup)
fo_out.write('\n')
fo_out.write(str(sim_index).ljust(15) + str(weighted_speedup).ljust(15) + str(harmonic_speedup).ljust(15))
fo_out.write('\n')
fo_out.close()
|
import React,{Component} from 'react';
import {Tile,Button} from 'tinper-bee';
import style from './index.css';
import errorPoolImg from '../../assets/img/error-pool.png';
class SuccessOne extends Component {
constructor(props) {
super(props);
this.apply=this.apply.bind(this);
}
componentDidMount(){
}
apply(){
window.location.hash='#/';
}
render() {
let msg=this.props.params.msg||'请稍后再试';
return (
<Tile className="u-container pool-error" border={false}>
<div className="left">
<img src={errorPoolImg} style={{width:130,height:130}}/>
</div>
<div className="right">
<h3>很抱歉,资源池申请失败</h3>
<h6>{msg}</h6>
<Button onClick={this.apply}>重新创建</Button>
</div>
</Tile>
)
}
}
export default SuccessOne;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[10],{247:function(r,t,o){var content=o(256);content.__esModule&&(content=content.default),"string"==typeof content&&(content=[[r.i,content,""]]),content.locals&&(r.exports=content.locals);(0,o(25).default)("01a13bf0",content,!0,{sourceMap:!1})},255:function(r,t,o){"use strict";o(247)},256:function(r,t,o){var e=o(24)(!1);e.push([r.i,"._sign_all_r8_all_top li a[data-v-7dbb584a],._sign_all_r8_all_top li a[data-v-7dbb584a]:hover{color:#fff}",""]),r.exports=e},284:function(r,t,o){"use strict";o.r(t);var e=o(0),n=o(8),l=(o(101),o(4),{middleware:"guest",data:function(){var r;return r={isLoading:!1,form:{email:"",password:""},error:{email:"",password:""},errorMsg:"",showPassword:!1},Object(n.a)(r,"errorMsg",""),Object(n.a)(r,"idd",""),Object(n.a)(r,"fromMarketing",""),Object(n.a)(r,"fromhome",""),Object(n.a)(r,"cookieForm",{_fprom_tid:"",ref_id:""}),r},created:function(){this.$route.query&&this.$route.query.idd&&(this.idd=this.$route.query.idd,this.$store.commit("setQueryUrl",this.idd)),this.$route.query&&this.$route.query.fromhome&&(this.fromhome=this.$route.query.fromhome),this.$route.query&&this.$route.query.fromMarketing&&(this.fromMarketing="".concat(this.$route.query.fromMarketing,"&isPattern=").concat(this.$route.query.isPattern,"&product_id=").concat(this.$route.query.product_id,"&modalOpen=").concat(this.$route.query.modalOpen),this.$store.commit("setQueryUrl",this.fromMarketing)),this.getCookie()},methods:{eyeClick:function(){this.showPassword=!this.showPassword},login:function(){var r=this;return Object(e.a)(regeneratorRuntime.mark((function t(){var o,e;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r.clearData(),o=1,r.form.email&&""!=r.form.email.trim()&&null!=r.form.email||(r.error.email="Email is required!",o=0),r.form.password&&""!=r.form.password.trim()&&null!=r.form.password||(r.error.password="Password is required!",o=0),0!=o){t.next=6;break}return t.abrupt("return");case 6:return r.isLoading=!0,t.next=9,r.callApi("post","/login",r.form);case 9:200==(e=t.sent).status?(r.s("You're successfully logged in"),r.$store.commit("setQueryUrl",!1),r.clearData2(),r.idd&&(window.location="/"+r.idd),"home"==r.fromhome?(location.reload(),window.location="/?tohome=plan?#subs"):r.fromMarketing?window.location=r.fromMarketing:window.location="/market"):401==e.status?r.errorMsg="Invalid login credentials.":r.swr(),r.isLoading=!1;case 12:case"end":return t.stop()}}),t)})))()},clearData:function(){this.error={email:"",password:""}},clearData2:function(){this.error={email:"",password:""},this.form={email:"",password:""}},getCookie:function(){var r=this;return Object(e.a)(regeneratorRuntime.mark((function t(){var o,i,e;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:for(o=document.cookie.split(";"),i=0;i<o.length;i++)"_fprom_ref"==(e=o[i].split("="))[0].trim()&&(r.cookieForm.ref_id=decodeURIComponent(e[1])),"_fprom_tid"==e[0].trim()&&(r.cookieForm._fprom_tid=decodeURIComponent(e[1]));return t.abrupt("return",0);case 3:case"end":return t.stop()}}),t)})))()}}}),c=(o(255),o(3)),component=Object(c.a)(l,(function(){var r=this,t=r.$createElement,o=r._self._c||t;return o("div",[o("div",{staticClass:"_sign_all"},[o("div",{staticClass:"row"},[o("div",{staticClass:"col-12 col-md-5 col-lg-5 _pad_r_0"},[o("div",{staticClass:"_sign_all_lft"},[o("div",{staticClass:"_sign_all_lft_logo"},[o("nuxt-link",{attrs:{to:"/"}},[o("img",{attrs:{src:"/../img/Logo.svg",alt:"image"}})])],1),r._v(" "),r._m(0)])]),r._v(" "),o("div",{staticClass:"col-12 col-md-7 col-lg-7 _pad_l_0"},[o("div",{staticClass:"_sign_all_r8"},[o("div",{staticClass:"_sign_all_r8_top_crnr"},[o("nuxt-link",{attrs:{to:"/register"}},[r._v("Sign Up")])],1),r._v(" "),o("div",{staticClass:"_sign_all_r8_all"},[o("div",{staticClass:"_sign_all_r8_all_top"},[o("h1",[r._v("Welcome to Uihut")]),r._v(" "),o("p",{staticClass:"_sign_p1"},[r._v("Let’s sign up first for enter into Uihut website. Uh She Up!")]),r._v(" "),o("ul",[o("li",{staticClass:"_sign_gogl"},[o("a",{attrs:{href:r.BASE_URL+"googleLogin?reqParams="+this.fromhome+"&ref_id="+this.cookieForm.ref_id+"&_fprom_tid="+this.cookieForm._fprom_tid}},[o("img",{attrs:{src:"/../img/google.png",alt:"image"}}),r._v("\n Continue with Google\n ")])]),r._v(" "),o("li",{staticClass:"_sign_fb"},[o("a",{attrs:{href:r.BASE_URL+"login/facebook?reqParams="+this.fromhome+"&ref_id="+this.cookieForm.ref_id+"&_fprom_tid="+this.cookieForm._fprom_tid}},[r._m(1)])])])]),r._v(" "),o("div",{staticClass:"_sign_all_r8_all_info"},[o("div",{staticClass:"row"},[o("div",{staticClass:"col-12 col-md-12 col-lg-12"},[""!=r.errorMsg?o("div",{staticClass:"_invalid_login _dis_flex",staticStyle:{"margin-bottom":"15px"}},[r._m(2),r._v(" "),o("p",[r._v(r._s(r.errorMsg))])]):r._e()]),r._v(" "),o("div",{staticClass:"col-12 col-md-12 col-lg-12"},[o("div",{staticClass:"_sign_inpt _inpt1",class:""!=r.error.email?"_inpt1_eror _prfl_modal_inpt2":""},[o("p",{staticClass:"_inpt1_text"},[r._v("Please put your mail")]),r._v(" "),o("input",{directives:[{name:"model",rawName:"v-model",value:r.form.email,expression:"form.email"}],attrs:{type:"email",placeholder:"Enter your email",autocomplete:"new-password"},domProps:{value:r.form.email},on:{input:function(t){t.target.composing||r.$set(r.form,"email",t.target.value)}}}),r._v(" "),""!=r.error.email?o("p",{staticClass:"_inpt1_eror_p"},[r._v(r._s(r.error.email))]):r._e()])]),r._v(" "),o("div",{staticClass:"col-12 col-md-12 col-lg-12"},[o("div",{staticClass:"_sign_inpt _inpt1",class:""!=r.error.password?"_inpt1_eror _prfl_modal_inpt2":""},[o("p",{staticClass:"_inpt1_text"},[r._v("Password")]),r._v(" "),"checkbox"==(r.showPassword?"text":"password")?o("input",{directives:[{name:"model",rawName:"v-model",value:r.form.password,expression:"form.password"}],attrs:{placeholder:"Enter your password",autocomplete:"new-password",type:"checkbox"},domProps:{checked:Array.isArray(r.form.password)?r._i(r.form.password,null)>-1:r.form.password},on:{change:function(t){var o=r.form.password,e=t.target,n=!!e.checked;if(Array.isArray(o)){var l=r._i(o,null);e.checked?l<0&&r.$set(r.form,"password",o.concat([null])):l>-1&&r.$set(r.form,"password",o.slice(0,l).concat(o.slice(l+1)))}else r.$set(r.form,"password",n)}}}):"radio"==(r.showPassword?"text":"password")?o("input",{directives:[{name:"model",rawName:"v-model",value:r.form.password,expression:"form.password"}],attrs:{placeholder:"Enter your password",autocomplete:"new-password",type:"radio"},domProps:{checked:r._q(r.form.password,null)},on:{change:function(t){return r.$set(r.form,"password",null)}}}):o("input",{directives:[{name:"model",rawName:"v-model",value:r.form.password,expression:"form.password"}],attrs:{placeholder:"Enter your password",autocomplete:"new-password",type:r.showPassword?"text":"password"},domProps:{value:r.form.password},on:{input:function(t){t.target.composing||r.$set(r.form,"password",t.target.value)}}}),r._v(" "),o("span",{on:{click:function(t){return r.eyeClick()}}},[o("i",{staticClass:"fas",class:0==r.showPassword?"fa-eye":"fa-eye-slash"})]),r._v(" "),""!=r.error.password?o("p",{staticClass:"_inpt1_eror_p"},[r._v(r._s(r.error.password))]):r._e()])])]),r._v(" "),o("div",{staticClass:"_sign_btm _dis_flex"},[o("div",{staticClass:"_sign_btm_lft _dis_flex"}),r._v(" "),o("div",{staticClass:"_sign_btm_r8"},[o("nuxt-link",{attrs:{to:"/forgot-password"}},[r._v("\n Forgot Password?\n ")])],1)]),r._v(" "),o("div",{staticClass:"_sign_btm_btn _mar_t30"},[o("Button",{attrs:{loading:r.isLoading,disabled:r.isLoading},on:{click:function(t){return r.login()}}},[r._v("Sign In")])],1)])])])])])])])}),[function(){var r=this.$createElement,t=this._self._c||r;return t("div",{staticClass:"_sign_all_img"},[t("img",{attrs:{src:"/../img/sign2.png"}})])},function(){var r=this.$createElement,t=this._self._c||r;return t("span",[t("i",{staticClass:"fab fa-facebook-square"})])},function(){var r=this.$createElement,t=this._self._c||r;return t("span",[t("i",{staticClass:"fas fa-exclamation"})])}],!1,null,"7dbb584a",null);t.default=component.exports}}]); |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "StaticDatePicker", {
enumerable: true,
get: function () {
return _StaticDatePicker.StaticDatePicker;
}
});
var _StaticDatePicker = require("./StaticDatePicker"); |
const log = new (require('./logger'))('Roleypoly')
const Sequelize = require('sequelize')
const fetchModels = require('./models')
const fetchApis = require('./api')
class Roleypoly {
constructor(router, io, app) {
this.router = router
this.io = io
this.ctx = {}
this.ctx.config = {
appUrl: process.env.APP_URL,
}
this.ctx.io = io
this.__app = app
if (log.debugOn) log.warn('debug mode is on')
this.__initialized = this._mountServices()
}
async awaitServices() {
await this.__initialized
}
async _mountServices() {
const sequelize = new Sequelize(process.env.DB_URL, {
logging: log.sql.bind(log, log),
})
this.ctx.sql = sequelize
this.M = fetchModels(sequelize)
this.ctx.M = this.M
await sequelize.sync()
// this.ctx.redis = new (require('ioredis'))({
// port: process.env.REDIS_PORT || '6379',
// host: process.env.REDIS_HOST || 'localhost',
// parser: 'hiredis',
// dropBufferSupport: true,
// enableReadyCheck: true,
// enableOfflineQueue: true
// })
this.ctx.server = new (require('./services/server'))(this.ctx)
this.ctx.discord = new (require('./services/discord'))(this.ctx)
this.ctx.sessions = new (require('./services/sessions'))(this.ctx)
this.ctx.P = new (require('./services/presentation'))(this.ctx)
}
async mountRoutes() {
fetchApis(this.router, this.ctx)
this.__app.use(this.router.middleware())
}
}
module.exports = Roleypoly
|
# Generated by Django 3.1.7 on 2021-02-27 10:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grapesjs', '0003_auto_20210227_1050'),
]
operations = [
migrations.AddField(
model_name='user_content',
name='active',
field=models.BooleanField(default=False),
),
]
|
import React from "react";
import swal from 'sweetalert';
// reactstrap components
import {
Button,
Card,
CardHeader,
CardBody,
FormGroup,
Form,
Input,
InputGroupAddon,
InputGroupText,
InputGroup,
Container,
Row,
Col,
UncontrolledAlert
} from "reactstrap";
// core components
import DemoNavbar from "components/Navbars/DemoNavbar.js";
import SimpleFooter from "components/Footers/SimpleFooter.js";
import moment from "moment";
class Detail extends React.Component {
constructor(props) {
super(props);
const {match} = this.props;
const productId = match.params.productId;
this.state = { arrayTemp:[] , NumRows:0, productId : productId, product : '', comentarios: [], comentario:''};
this.handleChange = this.handleChange.bind(this);
this.getProduct = this.getProduct.bind(this);
this.getComentaries = this.getComentaries.bind(this);
this.comentar = this.comentar.bind(this);
this._addProductToShoppingCart = this._addProductToShoppingCart.bind(this);
}
handleChange(event) {
const target = event.target;
let nam = target.name;
let val = target.value;
this.setState({[nam]: val});
}
_addProductToShoppingCart(event){
event.preventDefault();
let userSession = localStorage.getItem('user');
console.log(userSession);
if(userSession !== null){
const _id = event.currentTarget.id;
//busco en eel arreglo el item
let product = this.state.product;
let shoppingCart = localStorage.getItem('shoppingCart'); //primero verficamos si hay algo en session.
if(shoppingCart == ""){ //<--------- carrito inicial.
let shoppingCart_temp = [];
shoppingCart_temp.push(product);
localStorage.shoppingCart = JSON.stringify(shoppingCart_temp);
//alert('El manual ha sido agregado al carrido con exito!.'); //<------------------ cambiarlo a modal
swal("Exito!", "El manual ha sido agregado al carrido con exito!", "success");
}else{
let shoppingCart_temp = JSON.parse(localStorage.shoppingCart); //<-- recupero los items agregados
//---- comprobamos si existe un item
let existInShoppingCart = false;
shoppingCart_temp.forEach(itemInShoppingCart => {
if(product.ID == itemInShoppingCart.ID){
existInShoppingCart = true;
}
});
//----
if(existInShoppingCart == true){
//alert('no puedes agregarlo, ya esta agregado en el carrito!. '); //<------------------ cambiarlo a modal
swal("Advertencia!", "No puedes agregarlo, ya esta agregado en el carrito", "warning");
}else{
shoppingCart_temp.push(product);
localStorage.shoppingCart = JSON.stringify(shoppingCart_temp);
//alert('El manual ha sido agregado al carrido con exito!.'); //<------------------ cambiarlo a modal
swal("Exito!", "El manual ha sido agregado al carrido con exito!", "success");
}
}
this.state.arrayTemp = this._getDataToShoppingCart();
this.setState({NumRows:this._getNumberOfItemsInTheShoppingCart()});
}else{
window.location.href = "/login-page";
}
}
_getDataToShoppingCart(){
try {
if(localStorage["user"]){
let shoppingCart = localStorage.getItem('shoppingCart');
if(shoppingCart !== ""){
let shoppingCart_temp = JSON.parse(localStorage.shoppingCart);
return shoppingCart_temp;
}else{
return [];
}
}else{
localStorage.setItem('shoppingCart', []);
}
} catch (error) {
console.log(error);
}
}
_getNumberOfItemsInTheShoppingCart(){
try {
if(localStorage["user"]){
let shoppingCart = localStorage.getItem('shoppingCart');
if(shoppingCart !== ""){
let shoppingCart_temp = JSON.parse(localStorage.shoppingCart);
return shoppingCart_temp.length;
}else{
return 0;
}
}else{
localStorage.setItem('shoppingCart', []);
}
} catch (error) {
console.log(error);
}
}
async getProduct(){
let productId = this.state.productId;
console.log('productId :'+productId)
await fetch('https://dev-loopers.herokuapp.com/api/producto/'+ productId, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
})
})
.then(response => {
return response.json()
})
.then((data) => {
//console.log(result[0]);
this.setState({product: data[0]});
})
}
async getComentaries(){
let productId = this.state.productId;
await fetch('https://dev-loopers.herokuapp.com/api/comentarios/'+ productId, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
})
})
.then(response => {
return response.json()
})
.then((data) => {
//console.log(data.length);
//let fechaParse = Date.parse(data[0].created_at);
//let fechaParse = moment(data[0].created_at).format('DD-MM-YYYY');
//let fechaNumber = Number(fechaParse);
//data[0].created_at = new Date(data[0].created_at);
//data[0].created_at = fechaParse;
//data[0].created_at = new Date(fecha);
//new Date(Date.parse(item.created_at))
this.setState({comentarios: data});
})
}
async comentar(event) {
event.preventDefault();
let user = JSON.parse(localStorage.user);
let productId = this.state.productId;
await fetch('https://dev-loopers.herokuapp.com/api/comentarios', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}),
body: new URLSearchParams({
'usuarioId': JSON.parse(user.userId),
'productoId': productId,
'comentario': this.state.comentario
}),
})
.then(response => {
/*if(response.status >= 400 && response.status < 600) {
//alert('400');
}*/
return response.json()
})
.then((data) => {
console.log(data);
window.location.href = window.location.href;
})
}
componentDidMount() {
this.setState({arrayTemp:this._getDataToShoppingCart()});
this.setState({NumRows:this._getNumberOfItemsInTheShoppingCart()});
this.getProduct();
this.getComentaries();
document.documentElement.scrollTop = 0;
document.scrollingElement.scrollTop = 0;
this.refs.main.scrollTop = 0;
}
render() {
return (
<>
<DemoNavbar carrito={this.state.arrayTemp} items={this.state.NumRows}/>
<main ref="main">
<section className="section section-shaped section-lg">
<div className="shape shape-style-1 bg-gradient-default">
<span />
<span />
<span />
<span />
<span />
<span />
<span />
<span />
</div>
<Container className="pt-lg-7">
<Row className="justify-content-center">
<Col lg="12">
<Card className="bg-secondary shadow border-0">
<CardHeader className="bg-white">
<div className="text-muted text-center mb-3">
<h3>{this.state.product.titulo}</h3>
</div>
</CardHeader>
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<img
alt="..."
className="img-fluid"
src={"https://dev-loopers.herokuapp.com/assets/images/portadas/"+this.state.product.imagen}
style={{ width: "450px" }}
/>
</div>
<Form role="form">
<FormGroup className="mb-3">
<p className="text-center">
<strong>Descripción :</strong> {this.state.product.descripcion}
</p>
</FormGroup>
<FormGroup className="mb-3">
<p className="text-center">
<strong>Precio :</strong> ${this.state.product.precio} MXN
</p>
</FormGroup>
<FormGroup className="mb-3">
<p className="text-center">
<strong>Autor :</strong> {this.state.product.autor}
</p>
</FormGroup>
<FormGroup className="mb-3">
<p className="text-center">
<strong>Tecnología :</strong> {this.state.product.tecnologia}
</p>
</FormGroup>
<FormGroup className="mb-3">
<p className="text-center">
<strong>Estado : </strong>{this.state.product.estatus}
</p>
</FormGroup>
</Form>
<div className="text-center">
<Button
className="my-4"
color="info"
type="button"
href = {this.state.product.preview}
>
Vista Previa
</Button>
<Button
className="my-4"
color="info"
type="button"
onClick={this._addProductToShoppingCart}
>
Agregar a carrito
</Button>
</div>
<br></br>
<div className="mt-5 py-5 border-top text-center">
<Row className="justify-content-center">
<Col lg="12">
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<strong>Comentario :</strong>
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Comentario"
value={this.state.comentario}
name="comentario"
onChange={this.handleChange}
type="textarea" />
</InputGroup>
</FormGroup>
</Col>
<Button
className="my-4"
color="success"
type="button"
onClick={this.comentar}
>
Comentar
</Button>
</Row>
</div>
<div className="mt-5 py-5 border-top text-center">
{this.state.comentarios.map(
(item, i) =>
<Row className="justify-content-center">
<Col lg="12">
<UncontrolledAlert color="success" toggle={false}>
<span className="alert-inner--text ml-1">
<strong>{item.username} : </strong> " {item.comentario} " : {moment(item.created_at).format('DD-MM-YYYY')}
</span>
</UncontrolledAlert>
</Col>
</Row>
)}
</div>
</CardBody>
</Card>
</Col>
</Row>
</Container>
</section>
</main>
<SimpleFooter />
</>
);
}
}
export default Detail; |
// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');
const getClient = () => {
// Your Google Cloud Platform project ID
const projectId = 'bac76e25e74d770f7bcb42110d91af6d25f37125';
// Instantiates a client
const translate = new Translate({
projectId: projectId,
});
return translate;
}
// Translates some text into the Language of choice
const translate = async (translateClient, text, target) => {
let translation;
return await new Promise(resolve => {
translateClient.translate(text, target)
.then(results => {
translation = results[0][0];
// console.log(`Target: ${target}`)
// console.log(`Text: ${text}`);
// console.log(`Translation: ${translation}`);
resolve();
})
.catch(err => {
console.error('ERROR:', err);
});
}).then(() => {
return translation;
}).catch(error => {
console.log('ERROR: ', error.message, error);
});
}
module.exports = {
translate,
getClient
}
|
/**
* @author [email protected]
*/
(function($){
$.fn.extend({
checkboxCtrl: function(parent){
return this.each(function(){
var $trigger = $(this);
$trigger.click(function(){
var group = $trigger.attr("group");
if ($trigger.is(":checkbox")) {
var type = $trigger.is(":checked") ? "all" : "none";
if (group) $.checkbox.select(group, type, parent);
} else {
if (group) $.checkbox.select(group, $trigger.attr("selectType") || "all", parent);
}
});
});
}
});
$.checkbox = {
selectAll: function(_name, _parent){
this.select(_name, "all", _parent);
},
unSelectAll: function(_name, _parent){
this.select(_name, "none", _parent);
},
selectInvert: function(_name, _parent){
this.select(_name, "invert", _parent);
},
select: function(_name, _type, _parent){
$parent = $(_parent || document);
$checkboxLi = $parent.find(":checkbox[name='"+_name+"']");
switch(_type){
case "invert":
$checkboxLi.each(function(){
$checkbox = $(this);
$checkbox.attr('checked', !$checkbox.is(":checked"));
});
break;
case "none":
$checkboxLi.attr('checked', false);
break;
default:
$checkboxLi.attr('checked', true);
break;
}
}
};
})(jQuery);
|
'use strict';
// const adminLogin = 'admin';
// const adminPassword = 'm4ng0h4ckz';
// const cansel = 'Отменено пользователем!';
// const wrongLogin = 'Доступ запрещен, неверный логин!';
// const wrongPassword = 'Доступ запрещен, неверный пароль!';
// const welcome = 'Добро пожаловать!';
// const inputLogin = prompt('Введите логин');
// let inputPassword;
// if (!inputLogin) {
// alert(cansel);
// } else if (inputLogin !== adminLogin) {
// alert(wrongLogin);
// } else {
// inputPassword = prompt('Введите пароль');
// if (!inputPassword) {
// alert(cansel);
// } else if (inputPassword !== adminPassword) {
// alert(wrongPassword);
// } else {
// alert(welcome);
// }
// }
// Дополнительное задание
const sharm = 15;
const hurgada = 25;
const taba = 6;
let max = Math.max(sharm, hurgada, taba);
const userInput = prompt('Введите число необходимых мест');
const cansel = 'Нам очень жаль, приходите еще!';
let userConfirm;
if (!userInput) {
alert(cansel);
}
if (userInput % 1 === 0 && userInput > 0) {
if (userInput <= sharm) {
userConfirm = confirm('Есть места в группе Sharm, хотите присоединиться?');
if (userConfirm === true) {
alert('Приятного путешествия в группе Sharm');
} else {
alert(cansel);
}
}
if (userInput <= hurgada && userConfirm === false) {
userConfirm = confirm(
'Есть места в группе Hurgada, хотите присоединиться?',
);
if (userConfirm === true) {
alert('Приятного путешествия в группе Hurgada');
} else {
alert(cansel);
}
}
if (userInput <= taba && userConfirm === false) {
userConfirm = confirm('Есть места в группе Taba, хотите присоединиться?');
if (userConfirm === true) {
alert('Приятного путешествия в группе Taba');
} else {
alert(cansel);
}
} else if (userInput > max) {
alert('Извините, столько мест нет ни в одной группе!');
}
} else {
alert('Ошибка ввода!');
}
|
# -*- coding: utf-8 -*-
"""
Multi-GPU Examples
==================
Data Parallelism is when we split the mini-batch of samples into
multiple smaller mini-batches and run the computation for each of the
smaller mini-batches in parallel.
Data Parallelism is implemented using ``torch.nn.DataParallel``.
One can wrap a Module in ``DataParallel`` and it will be parallelized
over multiple GPUs in the batch dimension.
DataParallel
-------------
"""
import torch
import torch.nn as nn
class DataParallelModel(nn.Module):
def __init__(self):
super().__init__()
self.block1 = nn.Linear(10, 20)
# wrap block2 in DataParallel
self.block2 = nn.Linear(20, 20)
self.block2 = nn.DataParallel(self.block2)
self.block3 = nn.Linear(20, 20)
def forward(self, x):
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
return x
########################################################################
# The code does not need to be changed in CPU-mode.
#
# The documentation for DataParallel can be found
# `here <https://pytorch.org/docs/stable/nn.html#dataparallel-layers-multi-gpu-distributed>`_.
#
# **Attributes of the wrapped module**
#
# After wrapping a Module with ``DataParallel``, the attributes of the module
# (e.g. custom methods) became inaccessible. This is because ``DataParallel``
# defines a few new members, and allowing other attributes might lead to
# clashes in their names. For those who still want to access the attributes,
# a workaround is to use a subclass of ``DataParallel`` as below.
class MyDataParallel(nn.DataParallel):
def __getattr__(self, name):
return getattr(self.module, name)
########################################################################
# **Primitives on which DataParallel is implemented upon:**
#
#
# In general, pytorch’s `nn.parallel` primitives can be used independently.
# We have implemented simple MPI-like primitives:
#
# - replicate: replicate a Module on multiple devices
# - scatter: distribute the input in the first-dimension
# - gather: gather and concatenate the input in the first-dimension
# - parallel\_apply: apply a set of already-distributed inputs to a set of
# already-distributed models.
#
# To give a better clarity, here function ``data_parallel`` composed using
# these collectives
def data_parallel(module, input, device_ids, output_device=None):
if not device_ids:
return module(input)
if output_device is None:
output_device = device_ids[0]
replicas = nn.parallel.replicate(module, device_ids)
inputs = nn.parallel.scatter(input, device_ids)
replicas = replicas[:len(inputs)]
outputs = nn.parallel.parallel_apply(replicas, inputs)
return nn.parallel.gather(outputs, output_device)
########################################################################
# Part of the model on CPU and part on the GPU
# --------------------------------------------
#
# Let’s look at a small example of implementing a network where part of it
# is on the CPU and part on the GPU
device = torch.device("cuda:0")
class DistributedModel(nn.Module):
def __init__(self):
super().__init__(
embedding=nn.Embedding(1000, 10),
rnn=nn.Linear(10, 10).to(device),
)
def forward(self, x):
# Compute embedding on CPU
x = self.embedding(x)
# Transfer to GPU
x = x.to(device)
# Compute RNN on GPU
x = self.rnn(x)
return x
########################################################################
#
# This was a small introduction to PyTorch for former Torch users.
# There’s a lot more to learn.
#
# Look at our more comprehensive introductory tutorial which introduces
# the ``optim`` package, data loaders etc.: :doc:`/beginner/deep_learning_60min_blitz`.
#
# Also look at
#
# - :doc:`Train neural nets to play video games </intermediate/reinforcement_q_learning>`
# - `Train a state-of-the-art ResNet network on imagenet`_
# - `Train an face generator using Generative Adversarial Networks`_
# - `Train a word-level language model using Recurrent LSTM networks`_
# - `More examples`_
# - `More tutorials`_
# - `Discuss PyTorch on the Forums`_
# - `Chat with other users on Slack`_
#
# .. _`Deep Learning with PyTorch: a 60-minute blitz`: https://github.com/pytorch/tutorials/blob/master/Deep%20Learning%20with%20PyTorch.ipynb
# .. _Train a state-of-the-art ResNet network on imagenet: https://github.com/pytorch/examples/tree/master/imagenet
# .. _Train an face generator using Generative Adversarial Networks: https://github.com/pytorch/examples/tree/master/dcgan
# .. _Train a word-level language model using Recurrent LSTM networks: https://github.com/pytorch/examples/tree/master/word_language_model
# .. _More examples: https://github.com/pytorch/examples
# .. _More tutorials: https://github.com/pytorch/tutorials
# .. _Discuss PyTorch on the Forums: https://discuss.pytorch.org/
# .. _Chat with other users on Slack: https://pytorch.slack.com/messages/beginner/
|
export default {
props: {
canaryDeploymentFeatureId: {
type: String,
required: false,
default: '',
},
showCanaryDeploymentCallout: {
type: Boolean,
required: false,
default: false,
},
userCalloutsPath: {
type: String,
required: false,
default: '',
},
lockPromotionSvgPath: {
type: String,
required: false,
default: '',
},
helpCanaryDeploymentsPath: {
type: String,
required: false,
default: '',
},
},
};
|
// #region DRB.Logic
/**
* Logic - Console To Results Editor
* @param {any} message Message
*/
DRB.Logic.ConsoleToResultsEditor = function (message) {
console.log(message);
var indentedMessage = message;
try { indentedMessage = JSON.parse(indentedMessage); } catch { }
indentedMessage = JSON.stringify(indentedMessage, null, 2);
var resultsValue = DRB.Settings.Editors[DRB.Settings.TabResults].session.getValue();
if (!DRB.Utilities.HasValue(resultsValue)) { resultsValue = indentedMessage; }
else { resultsValue += "\n" + indentedMessage; }
if (resultsValue === undefined) { resultsValue = ""; }
DRB.Settings.Editors[DRB.Settings.TabResults].session.setValue(resultsValue);
}
/**
* Logic - Execute Code From Editor
*/
DRB.Logic.ExecuteCodeFromEditor = function () {
DRB.Settings.Editors[DRB.Settings.TabResults].session.setValue("");
var now = new Date();
DRB.Logic.ConsoleToResultsEditor("Execution Start: " + now.toLocaleString("sv"));
var codeValue = DRB.Settings.Editors[DRB.Settings.TabExecute].session.getValue();
var preCode = [];
if (DRB.Xrm.IsInstanceMode()) { preCode.push('let Xrm = parent.Xrm;'); }
preCode.push('let webapi = {};');
preCode.push('webapi.safeAjax = function(ajaxOptions) {');
preCode.push('\tlet ajaxUrl = ajaxOptions.url;');
preCode.push('\tif (ajaxUrl.indexOf("/_api/") === 0) {');
preCode.push('\t\tajaxOptions.url = ajaxUrl.replace("/_api/", DRB.Xrm.GetClientUrl() + "/api/data/v9.0/");');
preCode.push('\t\tajaxOptions.beforeSend = function (req) {');
preCode.push('\t\t\treq.setRequestHeader("OData-MaxVersion", "4.0");');
preCode.push('\t\t\treq.setRequestHeader("OData-Version", "4.0");');
preCode.push('\t\t\treq.setRequestHeader("Content-Type", "application/json; charset=utf-8");');
preCode.push('\t\t\treq.setRequestHeader("Accept", "application/json");');
var token = DRB.Xrm.GetCurrentAccessToken();
if (DRB.Utilities.HasValue(token)) {
preCode.push('\t\t\treq.setRequestHeader("Authorization", "Bearer ' + token + '");');
}
preCode.push('\t\t};');
preCode.push('\t}');
preCode.push('\t$.ajax(ajaxOptions);');
preCode.push('}');
preCode.push('');
codeValue = preCode.join('\n') + codeValue;
// Portals replace for portalUri + "/_api" syntax (association)
var replacePortalUri = 'Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.0/';
if (DRB.Xrm.IsXTBMode() || DRB.Xrm.IsJWTMode() || DRB.Xrm.IsDVDTMode()) { replacePortalUri = 'DRB.Xrm.GetClientUrl() + "/api/data/v9.0/'; }
codeValue = codeValue.replace(/portalUri \+\ "\/_api\//gi, replacePortalUri);
codeValue = codeValue.replace(/portalUri\+\ "\/_api\//gi, replacePortalUri);
codeValue = codeValue.replace(/portalUri \+\"\/_api\//gi, replacePortalUri);
codeValue = codeValue.replace(/portalUri\+\"\/_api\//gi, replacePortalUri);
codeValue = codeValue.replace(/console.log/gi, "DRB.Logic.ConsoleToResultsEditor");
if (DRB.Xrm.IsXTBMode() || DRB.Xrm.IsJWTMode() || DRB.Xrm.IsDVDTMode()) {
codeValue = codeValue.replace(/Xrm.Utility.getGlobalContext\(\).getClientUrl\(\)/gi, "DRB.Xrm.GetClientUrl()");
if (DRB.Utilities.HasValue(token)) {
codeValue = codeValue.replace(/headers: {/gi, 'headers: { "Authorization": "Bearer ' + token + '",');
codeValue = codeValue.replace(/req.setRequestHeader\("OData-MaxVersion", "4.0"\);/gi, 'req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("Authorization", "Bearer ' + token + '");');
}
}
DRB.UI.ShowLoading("Executing code...");
setTimeout(function () {
try {
// console.log(codeValue);
eval(codeValue);
$("#a_" + DRB.Settings.TabResults).click();
DRB.UI.HideLoading();
} catch (ex) {
DRB.UI.ShowError("Execute Code Error", ex.message);
}
}, DRB.Settings.TimeoutDelay);
}
/**
* Logic - Move Code To Main Editor
* @param {string} sectionName Section Name
*/
DRB.Logic.MoveCodeToMainEditor = function (sectionName) {
var codeValue = "";
var checkTab = DRB.Utilities.GetRecordById(DRB.Settings.Tabs, sectionName);
if (DRB.Utilities.HasValue(checkTab)) {
if (checkTab.MoveToEditor === true) { codeValue = DRB.Settings.Editors[checkTab.Id].session.getValue(); }
}
DRB.Settings.Editors[DRB.Settings.TabExecute].session.setValue(codeValue);
$("#a_" + DRB.Settings.TabExecute).click();
}
/**
* Logic - Copy Code To Clipboard
* @param {string} codeValue Code Value
*/
DRB.Logic.CopyCodeToClipboard = function (codeValue) {
// copy to clipboard
if (DRB.Utilities.HasValue(navigator.clipboard)) {
// modern browser code
navigator.clipboard.writeText(codeValue);
} else {
// old code for IE
var $temp = $("<textarea>");
$("body").append($temp);
$temp.val(codeValue).select();
document.execCommand("copy");
$temp.remove();
}
}
/**
* Logic - Copy Code From Editor
* @param {string} sectionName Section Name
*/
DRB.Logic.CopyCodeFromEditor = function (sectionName) {
var codeValue = "";
var contentText = "Code";
var checkTab = DRB.Utilities.GetRecordById(DRB.Settings.Tabs, sectionName);
if (DRB.Utilities.HasValue(checkTab)) {
if (checkTab.CopyCode === true) {
codeValue = DRB.Settings.Editors[checkTab.Id].session.getValue();
}
if (checkTab.Results === true) { contentText = "Results"; }
}
DRB.Logic.CopyCodeToClipboard(codeValue);
// show message to the user
DRB.UI.ShowMessage(contentText + " copied to Clipboard");
setTimeout(function () { DRB.UI.HideLoading(); }, DRB.Settings.TimeoutDelay * 1.5);
}
/**
* Logic - Copy Code From Editor
* @param {string} sectionName Section Name
*/
DRB.Logic.CopyCodeFromEditorByTabName = function (tabName) {
var codeValue = DRB.Settings.Editors[tabName].session.getValue();
DRB.Logic.CopyCodeToClipboard(codeValue);
// show message to the user
DRB.UI.ShowMessage("Code copied to Clipboard");
setTimeout(function () { DRB.UI.HideLoading(); }, DRB.Settings.TimeoutDelay * 1.5);
}
/**
* Logic - Send Code To FetchXML Builder
* @param {string} sectionName Section Name
*/
DRB.Logic.SendCodeToFetchXMLBuilder = function (sectionName) {
if (DRB.Xrm.IsXTBMode()) {
var checkTab = DRB.Utilities.GetRecordById(DRB.Settings.Tabs, sectionName);
if (DRB.Utilities.HasValue(checkTab)) {
if (checkTab.SendFetchXML === true) {
codeValue = DRB.Settings.Editors[checkTab.Id].session.getValue();
}
}
if (DRB.Utilities.HasValue(chrome) && DRB.Utilities.HasValue(chrome.webview)) {
var message = { action: "sendtofxb", data: codeValue };
chrome.webview.postMessage(JSON.stringify(message));
}
}
}
DRB.Logic.CopyCodeForPowerAutomate = function (id, name) {
var codeValue = $("#" + DRB.DOM.PowerAutomate[id + "Input"].Id).val();
DRB.Logic.CopyCodeToClipboard(codeValue);
// show message to the user
DRB.UI.ShowMessage(name + " copied to Clipboard");
setTimeout(function () { DRB.UI.HideLoading(); }, DRB.Settings.TimeoutDelay * 1.5);
}
DRB.Logic.CopyCodeForPowerQuery = function (id, name) {
var codeValue = $("#" + DRB.DOM.PowerQuery[id + "Input"].Id).val();
DRB.Logic.CopyCodeToClipboard(codeValue);
// show message to the user
DRB.UI.ShowMessage(name + " copied to Clipboard");
setTimeout(function () { DRB.UI.HideLoading(); }, DRB.Settings.TimeoutDelay * 1.5);
}
// #region DRB.Logic Grid
/**
* Logic - Grid Collapse All Tables
*/
DRB.Logic.GridExpandCollapseAllTables = function (operation) {
let visibleCheck = ":hidden";
if (operation === false) { visibleCheck = ":visible"; }
let buttons = $("table#gridresults button");
for (let count = 0; count < buttons.length; count++) {
button = buttons[count];
let itemId = button.id.substring(2);
if ($("#" + itemId).is(visibleCheck)) { button.click(); }
}
}
/**
* Logic - Grid Collapse All Tables
*/
DRB.Logic.GridCollapseAllTables = function () {
DRB.Logic.GridExpandCollapseAllTables(false);
}
/**
* Logic - Grid Expand All Tables
*/
DRB.Logic.GridExpandAllTables = function () {
DRB.Logic.GridExpandCollapseAllTables(true);
}
/**
* Logic - Grid Toggle Table
*/
DRB.Logic.GridToggleTable = function (id) {
let item = $("#" + id);
let button = $("#b_" + id);
if (item.is(":hidden")) { item.show(); button.text("[-]"); }
else { item.hide(); button.text("[+]"); }
}
/**
* Logic - Grid Download CSV
*/
DRB.Logic.GridDownloadCSV = function () {
if (!DRB.Utilities.HasValue(DRB.Metadata.GridResults)) { return; }
let tableName = DRB.Metadata.GridResults.EntitySetName;
let saveDate = DRB.Metadata.GridResults.SaveDate;
let jsonObject = DRB.Metadata.GridResults.Values;
let currentJson = null;
if (Array.isArray(jsonObject)) { currentJson = jsonObject; } else { currentJson = [jsonObject]; }
let headerColumns = [];
currentJson.forEach(function (row) {
var rowHeaders = Object.keys(row);
rowHeaders.forEach(function (rowHeader, rowHeaderIndex) {
if (headerColumns.indexOf(rowHeader) === -1) {
headerColumns.splice(rowHeaderIndex, 0, rowHeader);
}
});
});
let csvHeaders = [];
headerColumns.forEach(function (headerColumn) {
csvHeaders.push(headerColumn.replace(/"/g, '""'));
});
let fileContent = '"' + csvHeaders.join('","') + '"';
currentJson.forEach(function (row) {
let csvItems = [];
headerColumns.forEach(function (column) {
let item = row[column];
if (item === undefined) { item = ''; }
if (item === null) { item = 'null'; }
if (Array.isArray(item)) { item = "[Array]"; } else { if (typeof item === "object" && item !== null) { item = "{Object}"; } }
item = "" + item;
csvItems.push(item.replace(/"/g, '""'));
});
fileContent += '\n"' + csvItems.join('","') + '"';
});
let fileDate = saveDate.toLocaleString("sv").replace(/ /g, "_").replace(/-/g, "").replace(/:/g, "");
let fileName = tableName + "_" + fileDate + ".csv";
let saveFile = new Blob([fileContent], { type: "text/csv" });
let customLink = document.createElement("a");
customLink.href = URL.createObjectURL(saveFile);
customLink.download = fileName;
customLink.click();
}
/**
* Logic - Grid Create Table
*/
DRB.Logic.GridCreateTable = function (jsonObject, hidden, id) {
let currentJson = null;
if (Array.isArray(jsonObject)) { currentJson = jsonObject; } else { currentJson = [jsonObject]; }
let table = '';
let currentHeader = '';
let headerColumns = [];
currentJson.forEach(function (row) {
var rowHeaders = Object.keys(row);
rowHeaders.forEach(function (rowHeader, rowHeaderIndex) {
if (headerColumns.indexOf(rowHeader) === -1) {
headerColumns.splice(rowHeaderIndex, 0, rowHeader);
}
});
});
let header = headerColumns.join();
currentJson.forEach(function (row, rowIndex) {
// OLD CODE
// let headerColumns = Object.keys(row);
// let header = headerColumns.join();
// END OLD CODE
if (header !== currentHeader) {
if (rowIndex > 1) { table += '</table>'; }
let hiddenStyle = '';
if (hidden === true) { hiddenStyle += ' style="display: none;"'; }
table += '<table id="' + id + '" class="grid"' + hiddenStyle + '><tr><th class="gridindex">#</th><th class="grid">';
table += headerColumns.join('</th><th class="grid">');
table += '</th></tr>';
currentHeader = header;
}
table += '<tr><td class="gridindex">' + (rowIndex + 1) + '</td>';
headerColumns.forEach(function (column) {
let item = row[column];
if (item === undefined) { item = ""; }
table += '<td class="grid">';
let addExpand = false;
if (Array.isArray(item)) { addExpand = true; } else { if (typeof item === "object" && item !== null) { addExpand = true; } }
if (addExpand === false) { table += item; }
else {
id += '_' + rowIndex;
let onClickEvent = "DRB.Logic.GridToggleTable('" + id + "');";
let onClickButton = '<button id="b_' + id + '" type="button" class="gridexpand" onclick="' + onClickEvent + '">[+]</button> ';
let onClickText = 'Object { }';
if (Array.isArray(item)) {
if (item.length === 0) { onClickButton = ''; }
onClickText = 'Array [' + item.length + ']';
}
table += '<b>' + onClickButton + '</b><i>' + onClickText + '</i>';
table += DRB.Logic.GridCreateTable(item, true, id);
}
table += '</td>';
});
table += '</tr>';
});
if (currentJson.length > 0) { table += '</table>'; }
return table;
}
/**
* Logic - Refresh Grid
*/
DRB.Logic.RefreshGrid = function () {
$('#' + DRB.DOM.Grid.Div.Id).empty();
let gridHeader = DRB.UI.CreateEmptyDiv(DRB.DOM.Grid.DivHeader.Id);
let gridDetails = DRB.UI.CreateEmptyDiv(DRB.DOM.Grid.DivDetails.Id, DRB.DOM.Grid.DivDetails.Class);
$('#' + DRB.DOM.Grid.Div.Id).append(DRB.UI.CreateSpacer());
$('#' + DRB.DOM.Grid.Div.Id).append(DRB.UI.CreateSpacer());
$('#' + DRB.DOM.Grid.Div.Id).append(gridHeader);
$('#' + DRB.DOM.Grid.Div.Id).append(gridDetails);
var requestType = $("#" + DRB.DOM.RequestType.Dropdown.Id).val();
try { DRB.GenerateCode.Grid(requestType); } catch { }
}
// #endregion
/**
* Logic - Complete Initialize
*/
DRB.Logic.CompleteInitialize = function () {
DRB.Metadata = {}; // Empty DRB.Metadata
DRB.Metadata.CurrentNode = null; // set CurrentNode as null
DRB.Metadata.DataverseCustomAPIsLoaded = false; // set DataverseCustomAPILoaded as false
DRB.Metadata.DataverseCustomActionsLoaded = false; // set DataverseCustomActionLoaded as false
DRB.Metadata.DataverseMetadataLoaded = false; // set DataverseMetadataLoaded as false
// hide the main content because CurrentNode is now null
$("#" + DRB.DOM.MainContent.Id).hide();
// set URL to be visible
$("#" + DRB.DOM.ContextSpan.Id).html(DRB.Xrm.GetContext());
// retrieve tables
DRB.UI.ShowLoading("Retrieving Tables and Users...");
setTimeout(function () {
DRB.Common.RetrieveTables()
.done(function (data) {
DRB.Metadata.Tables = DRB.Common.MapTables(data, "Name");
DRB.Common.RetrieveUsers()
.done(function (data2) {
DRB.Metadata.Users = DRB.Common.MapUsers(data2, "Name");
// create an empty data structure
var currentNodes = [];
// Check localStorage
if (DRB.Settings.LocalStorageAvailable === true) {
var storedJson = localStorage.getItem("DRB_" + DRB.Xrm.GetClientUrl());
if (storedJson !== null) {
try {
var parsedContent = JSON.parse(storedJson);
// version check
if (parsedContent.version > 1) {
// version not compatible, remove the localStorage item
localStorage.removeItem("DRB_" + DRB.Xrm.GetClientUrl());
} else {
currentNodes = [{}];
// import jsTree nodes to the new data structure
DRB.Collection.ImportNodes(parsedContent, currentNodes[0]);
}
} catch (e) {
// something went wrong when parsing the file, remove the localStorage item
localStorage.removeItem("DRB_" + DRB.Xrm.GetClientUrl());
}
}
}
// load nodes
DRB.Collection.LoadNodes(currentNodes);
// Set Tabs Warnings
var warningXrmWebApi = "";
var warningClientUrl = "";
var warningPortals = "NOTE: Inside DRB, Portals endpoint (<i>/_api/</i>) is routed to the default Web API endpoint";
var warningEditor = "NOTE: console.log messages will appear inside the Results tab";
var warningResults = "NOTE: Due to asynchronous calls the output can appear later";
var warningFetchXML = "NOTE: Inside DRB for XrmToolBox you can send the code to <a target='_blank' href='https://fetchxmlbuilder.com'>FetchXML Builder</a>";
// warnings when DRB is running outside a managed solution
if (DRB.Xrm.IsXTBMode() || DRB.Xrm.IsJWTMode() || DRB.Xrm.IsDVDTMode()) {
if (DRB.Xrm.IsXTBMode()) {
warningXrmWebApi = "NOTE: Xrm.WebApi is not available when DRB is executed inside XrmToolBox";
warningClientUrl = "NOTE: Inside DRB for XrmToolBox, Xrm.Utility.getGlobalContext().getClientUrl() is routed to the Instance URL";
}
if (DRB.Xrm.IsJWTMode()) {
warningXrmWebApi = "NOTE: Xrm.WebApi is not available when DRB is in JWT Mode";
warningClientUrl = "NOTE: Inside DRB JWT Mode, Xrm.Utility.getGlobalContext().getClientUrl() is routed to the Instance URL";
}
if (DRB.Xrm.IsDVDTMode()) {
warningXrmWebApi = "NOTE: Xrm.WebApi is not available when DRB is executed inside DVDT";
warningClientUrl = "NOTE: Inside DRB for DVDT, Xrm.Utility.getGlobalContext().getClientUrl() is routed to the Instance URL";
}
}
DRB.Settings.Tabs.forEach(function (tab) {
if (DRB.Utilities.HasValue(tab.ShowWarning) && tab.ShowWarning === true) {
if (DRB.Utilities.HasValue(tab.WarningXrmWebApi) && tab.WarningXrmWebApi === true) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningXrmWebApi);
}
if (DRB.Utilities.HasValue(tab.WarningClientUrl) && tab.WarningClientUrl === true) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningClientUrl);
}
if (DRB.Utilities.HasValue(tab.WarningPortals) && tab.WarningPortals === true) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningPortals);
}
if (DRB.Utilities.HasValue(tab.WarningEditor) && tab.WarningEditor === true) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningEditor);
}
if (DRB.Utilities.HasValue(tab.WarningResults) && tab.WarningResults === true) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningResults);
}
if (DRB.Utilities.HasValue(tab.WarningFetchXML) && tab.WarningFetchXML === true) {
if (!DRB.Xrm.IsXTBMode()) {
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).html(warningFetchXML);
} else {
if (DRB.Utilities.HasValue(tab.SendFetchXML) && tab.SendFetchXML === true) {
var btn_copyFetchXML = DRB.UI.CreateButton("btn_" + tab.Id + "_copyfetchxml", "Open in FetchXML Builder", "btn-secondary", DRB.Logic.SendCodeToFetchXMLBuilder, tab.Id);
$("#" + DRB.DOM.TabsWarning.Id + tab.Id).append(btn_copyFetchXML);
}
}
}
}
});
DRB.UI.HideLoading();
})
.fail(function (xhr) { DRB.UI.ShowError("DRB.Common.RetrieveUsers Error", DRB.Common.GetErrorMessage(xhr)); });
})
.fail(function (xhr) { DRB.UI.ShowError("DRB.Common.RetrieveTables Error", DRB.Common.GetErrorMessage(xhr)); });
}, DRB.Settings.TimeoutDelay);
}
/**
* Logic - Edit Request
* @param {any} node Node
*/
DRB.Logic.EditRequest = function (node) {
if (node.type === "request") {
DRB.Metadata.CurrentNode = node;
// check if the Metadata CurrentNode has all the correct generic properties (endpoint, requestType, configuration)
if (!DRB.Utilities.HasValue(DRB.Metadata.CurrentNode.data)) { DRB.Metadata.CurrentNode.data = { endpoint: "webapi", requestType: "", configuration: {} }; }
if (!DRB.Utilities.HasValue(DRB.Metadata.CurrentNode.data.requestType)) { DRB.Metadata.CurrentNode.data.requestType = ""; DRB.Metadata.CurrentNode.data.configuration = {}; }
if (!DRB.Utilities.HasValue(DRB.Metadata.CurrentNode.data.configuration)) { DRB.Metadata.CurrentNode.data.configuration = {}; }
$("#" + DRB.DOM.RequestType.Div.Id).text(DRB.Metadata.CurrentNode.text); // Set the request name inside the main content
$("#" + DRB.DOM.RequestType.Dropdown.Id).val(DRB.Metadata.CurrentNode.data.requestType).change(); // trigger the Request Type dropdown
$("#" + DRB.DOM.MainContent.Id).show(); // Show the main content
}
}
/**
* Logic - Set Configuration Properties
* @param {any} nodeConfiguration Node Configuration
* @param {string[]} properties Properties
*/
DRB.Logic.SetNodeConfigurationProperties = function (nodeConfiguration, properties) {
var updatedNodeConfiguration = {};
properties.forEach(function (property) {
updatedNodeConfiguration[property] = JSON.parse(JSON.stringify(nodeConfiguration[property]));
});
return updatedNodeConfiguration;
}
/**
* Logic - Bind Request Type
* @param {string} id Id
*/
DRB.Logic.BindRequestType = function (id) {
$("#" + id).on("change", function (e) {
var requestTypeValue = $(this).val();
var showTabs = false;
if (DRB.Utilities.HasValue(requestTypeValue)) { showTabs = true; }
$("#" + DRB.DOM.ConfigureContent.Id).empty();
$("#a_" + DRB.Settings.Tabs[0].Id).click();
DRB.Settings.Tabs.forEach(function (tab) {
var showDefaultTab = true;
if (DRB.Utilities.HasValue(tab.EnabledRequests) && tab.EnabledRequests.length > 0) {
showDefaultTab = false;
if (tab.EnabledRequests.indexOf(requestTypeValue) > -1) { $("#a_" + tab.Id).show(); } else { $("#a_" + tab.Id).hide(); }
}
if (DRB.Utilities.HasValue(tab.DisabledRequests) && tab.DisabledRequests.length > 0) {
showDefaultTab = false;
if (tab.DisabledRequests.indexOf(requestTypeValue) > -1) { $("#a_" + tab.Id).hide(); } else { $("#a_" + tab.Id).show(); }
}
if (showDefaultTab === true) { $("#a_" + tab.Id).show(); }
});
// Set the Metadata CurrentNode generic values
DRB.Metadata.CurrentNode.data.requestType = requestTypeValue;
// reset all the values to the default if missing
var nodeConfiguration = DRB.Metadata.CurrentNode.data.configuration;
// set default values if a property is missing
if (!DRB.Utilities.HasValue(nodeConfiguration.version)) { nodeConfiguration.version = DRB.Settings.Versions[DRB.Settings.Versions.length - 1].Id; } // All except Retrieve NextLink
if (!DRB.Utilities.HasValue(nodeConfiguration.async)) { nodeConfiguration.async = true; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.tokenHeader)) { nodeConfiguration.tokenHeader = false; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.impersonate)) { nodeConfiguration.impersonate = false; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.impersonateType)) { nodeConfiguration.impersonateType = "mscrmcallerid"; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.impersonateId)) { nodeConfiguration.impersonateId = ""; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.formattedValues)) { nodeConfiguration.formattedValues = true; }
if (!DRB.Utilities.HasValue(nodeConfiguration.returnRecord)) { nodeConfiguration.returnRecord = false; } // Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.detectDuplicates)) { nodeConfiguration.detectDuplicates = false; } // Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.detectChanges)) { nodeConfiguration.detectChanges = false; } // Retrieve Single, Retrieve NextLink
if (!DRB.Utilities.HasValue(nodeConfiguration.retrieveCount)) { nodeConfiguration.retrieveCount = false; } // Retrieve Multiple, Retrieve NextLink, Predefined Query
if (!DRB.Utilities.HasValue(nodeConfiguration.prevent)) { nodeConfiguration.prevent = "none"; } // Update
if (!DRB.Utilities.HasValue(nodeConfiguration.topCount)) { nodeConfiguration.topCount = ""; } // Retrieve Multiple
if (!DRB.Utilities.HasValue(nodeConfiguration.primaryEntity)) { nodeConfiguration.primaryEntity = null; } // All
if (!DRB.Utilities.HasValue(nodeConfiguration.primaryIdField)) { nodeConfiguration.primaryIdField = ""; }
if (!DRB.Utilities.HasValue(nodeConfiguration.useAlternateKey)) { nodeConfiguration.useAlternateKey = false; }
if (!DRB.Utilities.HasValue(nodeConfiguration.primaryId)) { nodeConfiguration.primaryId = ""; }
if (!DRB.Utilities.HasValue(nodeConfiguration.alternateKeyName)) { nodeConfiguration.alternateKeyName = ""; }
if (!DRB.Utilities.HasValue(nodeConfiguration.alternateKeyFields)) { nodeConfiguration.alternateKeyFields = []; }
if (!DRB.Utilities.HasValue(nodeConfiguration.fields)) { nodeConfiguration.fields = []; } // Retrieve Single, Retrieve Multiple, Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.setFields)) { nodeConfiguration.setFields = []; } // Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.oneToMany)) { nodeConfiguration.oneToMany = []; } // Retrieve Single, Retrieve Multiple, Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.manyToOne)) { nodeConfiguration.manyToOne = []; } // Retrieve Single, Retrieve Multiple, Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.manyToMany)) { nodeConfiguration.manyToMany = []; } // Retrieve Single, Retrieve Multiple, Create, Update
if (!DRB.Utilities.HasValue(nodeConfiguration.filterCriteria)) { nodeConfiguration.filterCriteria = {}; } // Retrieve Multiple
if (!DRB.Utilities.HasValue(nodeConfiguration.orderFields)) { nodeConfiguration.orderFields = []; } // Retrieve Multiple
if (!DRB.Utilities.HasValue(nodeConfiguration.secondaryEntity)) { nodeConfiguration.secondaryEntity = null; } // Association
if (!Array.isArray(nodeConfiguration.secondaryIds)) { nodeConfiguration.secondaryIds = [""]; } // Association
if (!DRB.Utilities.HasValue(nodeConfiguration.relationship)) { nodeConfiguration.relationship = ""; } // Association
if (!DRB.Utilities.HasValue(nodeConfiguration.nextLink)) { nodeConfiguration.nextLink = ""; } // Retrieve NextLink
if (!DRB.Utilities.HasValue(nodeConfiguration.queryType)) { nodeConfiguration.queryType = ""; } // Predefined Query
if (!DRB.Utilities.HasValue(nodeConfiguration.systemViewId)) { nodeConfiguration.systemViewId = ""; } // Predefined Query
if (!DRB.Utilities.HasValue(nodeConfiguration.personalViewId)) { nodeConfiguration.personalViewId = ""; } // Predefined Query
if (!DRB.Utilities.HasValue(nodeConfiguration.fetchXML)) { nodeConfiguration.fetchXML = ""; } // Predefined Query
if (!DRB.Utilities.HasValue(nodeConfiguration.workflowId)) { nodeConfiguration.workflowId = ""; } // Execute Workflow
if (!DRB.Utilities.HasValue(nodeConfiguration.dataverseExecute)) { nodeConfiguration.dataverseExecute = ""; } // Dataverse Execute
if (!DRB.Utilities.HasValue(nodeConfiguration.dataverseOperationType)) { nodeConfiguration.dataverseOperationType = 0; } // Dataverse Execute
if (!DRB.Utilities.HasValue(nodeConfiguration.dataverseParameters)) { nodeConfiguration.dataverseParameters = []; } // Dataverse Execute
if (!DRB.Utilities.HasValue(nodeConfiguration.fileField)) { nodeConfiguration.fileField = null; } // Manage File Data, Manage Image Data
if (!DRB.Utilities.HasValue(nodeConfiguration.fileOperation)) { nodeConfiguration.fileOperation = ""; } // Manage File Data, Manage Image Data
if (!DRB.Utilities.HasValue(nodeConfiguration.fileName)) { nodeConfiguration.fileName = ""; } // Manage File Data, Manage Image Data
if (!DRB.Utilities.HasValue(nodeConfiguration.fileContent)) { nodeConfiguration.fileContent = null; } // Manage File Data, Manage Image Data
if (!DRB.Utilities.HasValue(nodeConfiguration.fileFullSize)) { nodeConfiguration.fileFullSize = false; } // Manage Image Data
if (!DRB.Utilities.HasValue(nodeConfiguration.fileBase64)) { nodeConfiguration.fileBase64 = false; } // Manage File Data, Manage Image Data
// Check the selected Request Type
switch (requestTypeValue) {
case "retrievesingle": // Retrieve Single
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"detectChanges", "primaryEntity", "useAlternateKey", "alternateKeyName", "alternateKeyFields",
"primaryId", "primaryIdField", "fields", "oneToMany", "manyToOne", "manyToMany"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.RetrieveSingle.Start();
break;
case "retrievemultiple": // Retrieve Multiple
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"retrieveCount", "topCount", "primaryEntity", "primaryIdField", "fields", "oneToMany", "manyToOne", "manyToMany",
"filterCriteria", "orderFields"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.RetrieveMultiple.Start();
break;
case "create": // Create
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"returnRecord", "detectDuplicates", "primaryEntity", "primaryIdField", "fields", "setFields", "oneToMany", "manyToOne", "manyToMany"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.Create.Start();
break;
case "update": // Update
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"returnRecord", "detectDuplicates", "prevent", "primaryEntity", "useAlternateKey", "alternateKeyName", "alternateKeyFields",
"primaryId", "primaryIdField", "fields", "setFields", "oneToMany", "manyToOne", "manyToMany"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.Update.Start();
break;
case "delete": // Delete
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "useAlternateKey", "alternateKeyName", "alternateKeyFields", "primaryId"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.Delete.Start();
break;
// Associate and Disassociate have the same configuration
case "associate": // Associate
case "disassociate": // Disassociate
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "primaryId", "secondaryEntity", "secondaryIds", "relationship"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.Association.Start();
break;
case "retrievenextlink": // Retrieve NextLink
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"detectChanges", "primaryEntity", "retrieveCount", "nextLink"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Metadata.CurrentNode.data.configuration.primaryEntity = null; // primaryEntity starts always empty as we parse the NextLink
DRB.Logic.RetrieveNextLink.Start();
break;
case "predefinedquery": // Predefined Query
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId", "formattedValues",
"retrieveCount", "primaryEntity", "queryType", "systemViewId", "personalViewId", "fetchXML"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.PredefinedQuery.Start();
break;
// Custom API, Custom Action, Action and Function have the same configuration
case "executecustomapi": // Execute Custom API
case "executecustomaction": // Execute Custom Action
case "executeaction": // Execute Action
case "executefunction": // Execute Function
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "dataverseExecute", "dataverseOperationType", "dataverseParameters"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.DataverseExecute.Start(requestTypeValue);
break;
case "executeworkflow": // Execute Workflow
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "primaryId", "workflowId"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.ExecuteWorkflow.Start();
break;
case "managefiledata": // Manage File Data
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "primaryId", "fileField", "fileOperation", "fileName", "fileContent", "fileBase64"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.ManageFileImageData.Start(requestTypeValue);
break;
case "manageimagedata": // Manage Image Data
var properties = ["version", "async", "tokenHeader", "impersonate", "impersonateType", "impersonateId",
"primaryEntity", "primaryId", "fileField", "fileOperation", "fileName", "fileContent", "fileFullSize", "fileBase64"];
DRB.Metadata.CurrentNode.data.configuration = DRB.Logic.SetNodeConfigurationProperties(nodeConfiguration, properties);
DRB.Logic.ManageFileImageData.Start(requestTypeValue);
break;
}
if (showTabs) { $("#" + DRB.DOM.TabsRequest.Id).show(); } else { $("#" + DRB.DOM.TabsRequest.Id).hide(); }
DRB.Settings.Editors.forEach(function (editor) { editor.session.setValue(""); });
});
}
/**
* Logic - Export Relationships
* @param {any[]} values Values (from a dropdown)
* @param {any[]} relationshipMetadata Metadata relationship array
*/
DRB.Logic.ExportRelationships = function (values, relationshipMetadata) {
// array containing the result
var relationshipExports = [];
// first extract all relationships
var relationships = [];
values.forEach(function (value) { relationships.push(value.split('|')[0]); });
relationships = DRB.Utilities.RemoveDuplicatesFromArray(relationships);
// Create the list of fields for each relationship
relationships.forEach(function (relationship) {
var relationshipExport = { schemaName: relationship, fields: [] };
values.forEach(function (selectedRelationshipColumn) {
var splitted = selectedRelationshipColumn.split('|');
if (splitted[0] === relationship) { relationshipExport.fields.push({ logicalName: splitted[1] }); }
});
relationshipExports.push(relationshipExport);
});
// fill the other properties from the Metadata
relationshipExports.forEach(function (relationshipExport) {
var relationship = DRB.Utilities.GetRecordById(relationshipMetadata, relationshipExport.schemaName);
if (DRB.Utilities.HasValue(relationship)) {
relationshipExport.navigationProperty = relationship.NavigationProperty;
relationshipExport.navigationAttribute = relationship.NavigationAttribute;
var relationshipTable = DRB.Utilities.GetRecordById(DRB.Metadata.Tables, relationship.TargetTable);
if (DRB.Utilities.HasValue(relationshipTable)) {
relationshipExport.targetEntity = relationshipTable.LogicalName;
relationshipExport.targetEntityLabel = relationshipTable.Name;
relationshipExport.targetEntityPrimaryIdField = relationshipTable.PrimaryIdAttribute;
relationshipExport.fields.forEach(function (relationshipExportField) {
var relationshipTableColumn = DRB.Utilities.GetRecordById(relationshipTable.Columns, relationshipExportField.logicalName);
relationshipExportField.schemaName = relationshipTableColumn.SchemaName;
relationshipExportField.label = relationshipTableColumn.Name;
relationshipExportField.type = relationshipTableColumn.AttributeType;
relationshipExportField.oDataName = relationshipTableColumn.ODataName;
});
}
}
});
return relationshipExports;
}
/**
* Logic - Fill Current Metadata
* @param {DRB.Models.Table} table Table
*/
DRB.Logic.FillCurrentMetadata = function (table) {
// when a table is selected, fill Current Metadata with table properties (Columns, Relationships, Alternate Keys)
DRB.Metadata.CurrentColumns = table.Columns;
DRB.Metadata.CurrentOneToMany = table.OneToManyRelationships;
DRB.Metadata.CurrentManyToOne = table.ManyToOneRelationships;
DRB.Metadata.CurrentManyToMany = table.ManyToManyRelationships;
DRB.Metadata.CurrentAlternateKeys = table.AlternateKeys;
}
/**
* Logic - Fill Columns
*/
DRB.Logic.FillColumns = function () {
if (DRB.Metadata.CurrentColumns.length === 0) {
DRB.UI.ResetDropdown(DRB.DOM.Columns.Dropdown.Id, DRB.DOM.Columns.Dropdown.Name);
} else {
var readColumns = [];
DRB.Metadata.CurrentColumns.forEach(function (currentColumn) {
if (currentColumn.IsValidForRead === true) { readColumns.push(currentColumn); }
});
DRB.UI.FillDropdown(DRB.DOM.Columns.Dropdown.Id, DRB.DOM.Columns.Dropdown.Name, new DRB.Models.Records(readColumns).ToDropdown());
var columnsValues = [];
DRB.Metadata.CurrentNode.data.configuration.fields.forEach(function (field) { columnsValues.push(field.logicalName); });
if (columnsValues.length > 0) { $("#" + DRB.DOM.Columns.Dropdown.Id).val(columnsValues).change(); }
}
}
/**
* Logic - Fill Relationships Columns
*/
DRB.Logic.FillRelationshipsColumns = function () {
var currentRelationships = ["CurrentOneToMany", "CurrentManyToOne", "CurrentManyToMany"];
currentRelationships.forEach(function (currentRelationship) {
DRB.Metadata[currentRelationship].forEach(function (relationship) {
var targetTable = DRB.Utilities.GetRecordById(DRB.Metadata.Tables, relationship.TargetTable);
if (DRB.Utilities.HasValue(targetTable)) {
relationship.TargetTableName = targetTable.Name;
relationship.Columns = [];
// take NavigationAttributeName from the related table columns
if (DRB.Utilities.HasValue(relationship.NavigationAttribute)) {
if (currentRelationship === "CurrentOneToMany") {
var relColumn = DRB.Utilities.GetRecordById(targetTable.Columns, relationship.NavigationAttribute);
if (DRB.Utilities.HasValue(relColumn)) { relationship.NavigationAttributeName = relColumn.Name; }
}
if (currentRelationship === "CurrentManyToOne") {
var sourceTable = DRB.Utilities.GetRecordById(DRB.Metadata.Tables, relationship.SourceTable);
if (DRB.Utilities.HasValue(sourceTable)) {
var relColumn = DRB.Utilities.GetRecordById(sourceTable.Columns, relationship.NavigationAttribute);
if (DRB.Utilities.HasValue(relColumn)) { relationship.NavigationAttributeName = relColumn.Name; }
}
}
}
targetTable.Columns.forEach(function (targetColumn) {
relationship.Columns.push(new DRB.Models.RelationshipColumn(relationship.SchemaName, relationship.Type, relationship.NavigationProperty, relationship.NavigationAttribute, relationship.NavigationAttributeName, relationship.TargetTable, targetTable.Name, targetColumn.LogicalName, targetColumn.Name, targetColumn.SchemaName, targetColumn.AttributeType, targetColumn.IsPrimaryIdAttribute, targetColumn.IsPrimaryNameAttribute, targetColumn.RequiredLevel, targetColumn.IsValidForRead, targetColumn.IsValidForCreate, targetColumn.IsValidForUpdate, targetColumn.AdditionalProperties));
});
}
});
});
}
/**
* Logic - Fill Relationships
*/
DRB.Logic.FillRelationships = function () {
var currentRelationships = ["CurrentOneToMany", "CurrentManyToOne", "CurrentManyToMany"];
currentRelationships.forEach(function (currentRelationship) {
var shortRel = currentRelationship.replace("Current", "");
var configRel = shortRel.charAt(0).toLowerCase() + shortRel.substring(1);
if (DRB.Metadata[currentRelationship].length === 0) {
$("#" + DRB.DOM.Relationship[shortRel].Button.Id).hide();
DRB.UI.ResetDropdown(DRB.DOM.Relationship[shortRel].Dropdown.Id, DRB.DOM.Relationship[shortRel].Dropdown.Name);
DRB.Metadata.CurrentNode.data.configuration[configRel] = [];
} else {
$("#" + DRB.DOM.Relationship[shortRel].Button.Id).show();
var relRecords = [];
var configurationRelRecords = [];
DRB.Metadata.CurrentNode.data.configuration[configRel].forEach(function (relationship) {
var checkRelationship = DRB.Utilities.GetRecordById(DRB.Metadata[currentRelationship], relationship.schemaName);
if (DRB.Utilities.HasValue(checkRelationship)) {
relationship.fields.forEach(function (relationshipField) {
var checkColumn = DRB.Utilities.GetRecordByProperty(checkRelationship.Columns, "ColumnLogicalName", relationshipField.logicalName);
if (DRB.Utilities.HasValue(checkColumn)) { relRecords.push(checkColumn); configurationRelRecords.push(checkColumn.Id); }
});
}
});
DRB.Metadata.CurrentNode.data.configuration[configRel] = DRB.Logic.ExportRelationships(configurationRelRecords, DRB.Metadata[currentRelationship]);
DRB.UI.FillDropdownWithGroups(DRB.DOM.Relationship[shortRel].Dropdown.Id, DRB.DOM.Relationship[shortRel].Dropdown.Name, new DRB.Models.Records(relRecords).ToDropdown(), false);
}
});
}
/**
* Logic - Fill Alternate Keys
*/
DRB.Logic.FillAlternateKeys = function () {
// Fill Alternate Keys
if (DRB.Metadata.CurrentAlternateKeys.length === 0) {
// this table has no Alternate Keys, "Use Alternate Key" is No
DRB.UI.LockDropdown(DRB.DOM.UseAlternateKey.Dropdown.Id);
DRB.UI.ResetDropdown(DRB.DOM.AlternateKey.Dropdown.Id, DRB.DOM.AlternateKey.Dropdown.Name);
$("#" + DRB.DOM.UseAlternateKey.Dropdown.Id).val("no").change();
} else {
// this table has Alternate Keys
DRB.UI.UnlockDropdown(DRB.DOM.UseAlternateKey.Dropdown.Id);
DRB.UI.FillDropdown(DRB.DOM.AlternateKey.Dropdown.Id, DRB.DOM.AlternateKey.Dropdown.Name, new DRB.Models.Records(DRB.Metadata.CurrentAlternateKeys).ToDropdown());
if (DRB.Metadata.CurrentNode.data.configuration.useAlternateKey === true) { $("#" + DRB.DOM.UseAlternateKey.Dropdown.Id).val("yes").change(); }
}
}
/**
* Logic - Parse Image
* @param {event} e Event
*/
DRB.Logic.ParseImage = function (e) {
var file = e.target.files[0];
if (!file) {
DRB.UI.ShowError("Load Image Error", "Error loading the selected file");
} else {
if (/\.(jpe?g|png|gif|bmp)$/i.test(file.name)) {
var reader = new FileReader();
reader.onload = function (e) {
try {
var fileContent = e.target.result;
if (DRB.Utilities.HasValue(DRB.Metadata.CurrentImageIndex)) {
// get full Metadata and configuration path
var refMetadata = DRB.Metadata;
var refConfiguration = DRB.Metadata.CurrentNode.data.configuration;
// get full Metadata and configuration path
DRB.Metadata.CurrentMetadataPath.split("_").forEach(function (path) {
if (isNaN(parseInt(path))) {
if (refMetadata.hasOwnProperty(path)) { refMetadata = refMetadata[path]; }
if (refConfiguration.hasOwnProperty(path)) { refConfiguration = refConfiguration[path]; }
} else {
// is a position number
var metadataIndex = parseInt(path);
refMetadata.forEach(function (refItem, refItemIndex) {
if (refItem.Id === metadataIndex) {
// this is the correct path to follow
refMetadata = refMetadata[refItemIndex];
refConfiguration = refConfiguration[refItemIndex];
}
});
}
});
refMetadata.forEach(function (column, columnIndex) {
if (column.Id === DRB.Metadata.CurrentImageIndex) {
var currentField = JSON.parse(JSON.stringify(column.Value));
currentField.value = fileContent.split(",")[1];
column.Value = currentField;
refConfiguration[columnIndex] = currentField;
$("#" + DRB.DOM.Image.ShowButton.Id + DRB.DOM[DRB.Metadata.CurrentDomObject].ControlValue.Id + DRB.Metadata.CurrentMetadataPath + "_" + DRB.Metadata.CurrentImageIndex).show();
$("#" + DRB.DOM.Image.RemoveButton.Id + DRB.DOM[DRB.Metadata.CurrentDomObject].ControlValue.Id + DRB.Metadata.CurrentMetadataPath + "_" + DRB.Metadata.CurrentImageIndex).show();
}
});
}
} catch (e) { DRB.UI.ShowError("Load Image Error", "Failed to parse the selected file"); }
};
reader.readAsDataURL(file);
} else {
DRB.UI.ShowError("Load Image Error", "Supported file extensions: gif, png, bmp, jpg, jpeg");
}
}
// reset the File Input (necessary if we load the same file again)
$(e.target).val("");
}
/**
* Logic - Load Image
* @param {string} domObject DOM Object
* @param {string} metadataPath Metadata Path
* @param {number} elementIndex Element Index
*/
DRB.Logic.LoadImage = function (domObject, metadataPath, elementIndex) {
DRB.Metadata.CurrentDomObject = domObject;
DRB.Metadata.CurrentMetadataPath = metadataPath;
DRB.Metadata.CurrentImageIndex = elementIndex;
$("#" + DRB.DOM.Image.LoadInput.Id + DRB.DOM[domObject].ControlValue.Id + metadataPath + "_" + elementIndex).trigger("click");
}
/**
* Logic - Show Image
* @param {string} metadataPath Metadata Path
* @param {number} elementIndex Element Index
*/
DRB.Logic.ShowImage = function (metadataPath, elementIndex) {
try {
var refMetadata = DRB.Metadata;
// get full Metadata and configuration path
metadataPath.split("_").forEach(function (path) {
if (isNaN(parseInt(path))) {
if (refMetadata.hasOwnProperty(path)) { refMetadata = refMetadata[path]; }
} else {
// is a position number
var metadataIndex = parseInt(path);
refMetadata.forEach(function (refItem, refItemIndex) {
if (refItem.Id === metadataIndex) {
// this is the correct path to follow
refMetadata = refMetadata[refItemIndex];
}
});
}
});
var imageContent = null;
refMetadata.forEach(function (column) {
if (column.Id === elementIndex) {
var field = JSON.parse(JSON.stringify(column.Value));
imageContent = field.value;
}
});
var base64Prefix = "data:image/jpeg;base64,";
var finalImage = base64Prefix + imageContent;
var showContent = DRB.UI.CreateEmptyDiv("div_showimage", "centercontent");
showContent.append(DRB.UI.CreateImage("preview", finalImage));
DRB.UI.Show("Show Image", showContent, "large");
} catch (e) {
DRB.UI.ShowError("Image Error", "Unable to show the image");
}
}
/**
* Logic - Remove Image
* @param {string} domObject DOM Object
* @param {string} metadataPath Metadata Path
* @param {number} elementIndex Element Index
*/
DRB.Logic.RemoveImage = function (domObject, metadataPath, elementIndex) {
// get full Metadata and configuration path
var refMetadata = DRB.Metadata;
var refConfiguration = DRB.Metadata.CurrentNode.data.configuration;
// get full Metadata and configuration path
metadataPath.split("_").forEach(function (path) {
if (isNaN(parseInt(path))) {
if (refMetadata.hasOwnProperty(path)) { refMetadata = refMetadata[path]; }
if (refConfiguration.hasOwnProperty(path)) { refConfiguration = refConfiguration[path]; }
} else {
// is a position number
var metadataIndex = parseInt(path);
refMetadata.forEach(function (refItem, refItemIndex) {
if (refItem.Id === metadataIndex) {
// this is the correct path to follow
refMetadata = refMetadata[refItemIndex];
refConfiguration = refConfiguration[refItemIndex];
}
});
}
});
refMetadata.forEach(function (column, columnIndex) {
if (column.Id === elementIndex) {
var field = JSON.parse(JSON.stringify(column.Value));
field.value = null;
column.Value = field;
refConfiguration[columnIndex] = field;
$("#" + DRB.DOM.Image.ShowButton.Id + DRB.DOM[domObject].ControlValue.Id + metadataPath + "_" + elementIndex).hide();
$("#" + DRB.DOM.Image.RemoveButton.Id + DRB.DOM[domObject].ControlValue.Id + metadataPath + "_" + elementIndex).hide();
}
});
}
// #endregion |
const db = require('quick.db')
const Discord = require('discord.js')
const colors = require('../../../Storage/json/colors.json')
module.exports = {
name: "HelpFight",
run: async(client, interaction) => {
var prefix = db.get(`prefix_${interaction.guild.id}`) || 'u!'
let lang = client.langs.get(db.get(`lang_${interaction.guild.id}`) || 'en')
try {
interaction.user.send({
embeds: [
new Discord.MessageEmbed()
.setColor(colors.PERSO)
.setTitle(lang.commands.help.helpFight[1].replace('{PREFIX}', prefix))
.setDescription(lang.commands.helpa[4])
.addFields({
name: lang.commands.helpa[5],
value: lang.commands.help.helpFight[2]
}, {
name: lang.commands.helpa[6],
value: lang.commands.help.helpFight[3].replace('{PREFIX}', prefix),
inline: true
}, {
name: lang.commands.helpa[7],
value: lang.commands.helpa[8],
inline: true
}, {
name: lang.commands.helpa[2],
value: lang.commands.helpa[1]
}, {
name: lang.commands.helpa[9],
value: "`Fun`"
}, {
name: "Cooldown",
value: "10s"
}, {
name: lang.commands.helpa[10],
value: lang.commands.helpa[11] + `\n\n[${lang.commandsa[0]}](https://nepust.fr/)`
})
.setFooter({text: `© ${client.user.username}`, iconURL: client.user.displayAvatarURL()})
.setTimestamp()
]
}).then(() => {
interaction.reply({
content: lang.commands.help.success[0],
ephemeral: true
})
})
} catch {
interaction.reply(`Please active your DMs.`)
}
}
}
|
/* jshint esversion: 6 */
module.exports = class Controller {
constructor (
roomOptionsService,
newroomDefaults
) {
"ngInject";
Object.assign(this, {
roomOptionsService,
newroomDefaults
});
({placesOptions: this.placesOptions, timeOptions: this.timeOptions} = this.newroomDefaults);
}
get time () {
return this.roomOptionsService.time;
}
set time (time) {
this.roomOptionsService.time = time;
}
get numberPlaces () {
return this.roomOptionsService.numberPlaces;
}
set numberPlaces (number) {
this.roomOptionsService.numberPlaces = number;
}
};
|
// COPYRIGHT © 201 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: [email protected]
//
// See http://js.arcgis.com/3.34/esri/copyright.txt for details.
define(["require","exports","dojo/Deferred"],(function(e,r,n){Object.defineProperty(r,"__esModule",{value:!0}),r.when=function e(r,t){if(Array.isArray(t)){var i=new n;return r(t,(function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];i.resolve(e)})),i.promise}return e(r,[t]).then((function(e){return e[0]}))},r.getAbsMid=function(e,r,n){return r.toAbsMid?r.toAbsMid(e):n.id.replace(/\/[^\/]*$/gi,"/")+e}})); |
angular
.module('app', [
'ui.router',
'app.directives.contactCard'
])
.config(['$urlRouterProvider', '$stateProvider','$httpProvider', function($urlRouterProvider, $stateProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html',
controller: 'homeCtrl'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'aboutCtrl'
})
}]) |
class FacebookQuickReplyItemTypeText {
constructor (title = '', payload = '') {
this.title = title;
this.payload = payload;
}
get response () {
return {
content_type: 'text',
title: this.title,
payload: (this.payload !== '' ? this.payload : this.title)
};
}
static fromSimpleStringArray (messages = []) {
return messages.map(message => new FacebookQuickReplyItemTypeText(message));
}
static from2DimensionsStringArray (messages = []) {
return messages.map(message => new FacebookQuickReplyItemTypeText(message[0], message[1]));
}
}
class FacebookQuickReplyTypeText {
constructor (titleMessage = '', quickReplyMessages = []) {
this.titleMessage = titleMessage;
this.quickReplyMessages = quickReplyMessages;
}
get response () {
let quickReplies = this.quickReplyMessages.map(quickReplyItem => quickReplyItem.response);
let response = {
text: this.titleMessage,
quick_replies: quickReplies
};
return response;
}
}
class FacebookQuickReplyTypeUserPhoneNumber {
constructor (titleMessage = '') {
this.titleMessage = titleMessage;
}
get response () {
const response = {
text: this.titleMessage,
quick_replies: [
{
'content_type': 'user_phone_number'
}
]
};
return response;
}
}
class FacebookQuickReplyTypeUserEmail {
constructor (titleMessage = '') {
this.titleMessage = titleMessage;
}
get response () {
const response = {
text: this.titleMessage,
quick_replies: [
{
'content_type': 'user_email'
}
]
};
return response;
}
}
class FacebookGenericTemplate {
constructor (elements, {imageAspectRatio=FacebookImageAspectRatio.HORIZONTAL}={}) {
if (!Array.isArray(elements)) {
throw new Error('elements must be array');
}
this.elements = elements;
this.imageAspectRatio = imageAspectRatio;
}
get response () {
return {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
image_aspect_ratio: this.imageAspectRatio,
elements: this.elements
}
}
};
}
static fromMssqlPremiumPlanResult (result, config, userData) {
let cards = result.recordset.map(data => {
let defaultActionOption = {
url: 'https://www.generali.co.th',
webviewHeightRatio: FacebookWebViewHeight.TALL,
messengerExtensions: true
};
let defaultAction = new FacebookDefaultActionItem(FacebookActionType.WEB_URL, defaultActionOption);
let btnOption1 = {
url: `${config.getAppUrl(userData.Item.id.S)}/web/leads-form/products?facebook_id=${userData.Item.id.S}`,
webviewHeightRatio: FacebookWebViewHeight.TALL,
messengerExtensions: true
};
let btn1 = new FacebookButtonItem(FacebookActionType.WEB_URL, 'สนใจแผนนี้', btnOption1);
let btnOption2 = {
url: `${config.s3_base_url}/compare-plan-images/GENHealthLumpSumCompare.png`,
webviewHeightRatio: FacebookWebViewHeight.TALL,
messengerExtensions: true
};
let btn2 = new FacebookButtonItem(FacebookActionType.WEB_URL, 'เปรียบเทียบแผน', btnOption2);
let btnOption3 = {
payload: 'PremiumCal.Health.F1.Recal'
};
let btn3 = new FacebookButtonItem(FacebookActionType.POSTBACK, 'ยังไม่ถูกใจ', btnOption3);
let buttons = [
btn1.response,
btn2.response,
btn3.response
];
let element = new FacebookGenericTemplateElement(
data.Header,
`${config.s3_base_url}/plan-images/images/exported/${data.imageName}.png`,
`${data.productName} ${data.productPlan}`,
defaultAction.response,
buttons);
return element.response;
});
// console.log(JSON.stringify(new FacebookGenericTemplate(cards, {imageAspectRatio:FacebookImageAspectRatio.SQUARE}).response));
return new FacebookGenericTemplate(cards, {imageAspectRatio: FacebookImageAspectRatio.SQUARE});
}
}
class FacebookGenericTemplateElement {
constructor (title = '', imageUrl = '', subtitle = '', defaultAction = {}, buttons = []) {
if (title === '') {
throw new Error('title can NOT be empty');
}
if (imageUrl === '') {
throw new Error('imageUrl can NOT be empty');
}
if (subtitle === '') {
throw new Error('subtitle can NOT be empty');
}
if (typeof defaultAction !== 'object') {
throw new Error('title can NOT be empty');
}
if (!Array.isArray(buttons)) {
throw new Error('buttons must be array');
}
this.title = title;
this.imageUrl = imageUrl;
this.subtitle = subtitle;
this.defaultAction = defaultAction;
this.buttons = buttons;
}
get response () {
return {
title: this.title,
image_url: this.imageUrl,
subtitle: this.subtitle,
default_action: this.defaultAction,
buttons: this.buttons
};
}
}
class FacebookDefaultActionItem {
constructor (type, {url='', webviewHeightRatio=FacebookWebViewHeight.TALL, messengerExtensions=false, payload=''}={}) {
if (!type || (typeof type !== 'string')) {
throw new Error('type can NOT be empty');
}
this.type = type;
this.url = url;
this.webviewHeightRatio = webviewHeightRatio;
this.messengerExtensions = messengerExtensions;
this.payload = payload;
}
get response () {
switch (this.type) {
case FacebookActionType.POSTBACK:
return {
type: 'postback',
payload: this.payload
};
case FacebookActionType.WEB_URL:
return {
type: 'web_url',
url: this.url,
webview_height_ratio: this.webviewHeightRatio,
messenger_extensions: this.messengerExtensions,
};
default:
throw new Error('Button is error');
}
}
}
class FacebookButtonTemplate {
constructor (text, buttons) {
if (!text || (typeof text !== 'string')) {
throw new Error('type can NOT be empty');
}
if (!Array.isArray(buttons)) {
throw new Error('elements must be array');
}
this.text = text;
this.buttons = buttons;
}
get response () {
return {
attachment: {
type: 'template',
payload: {
template_type: 'button',
text: this.text,
buttons: this.buttons
}
}
};
}
}
class FacebookListTemplate {
constructor (topElementStyle, elements, buttons) {
if (!Array.isArray(elements)) {
throw new Error('elements must be array');
}
if (!Array.isArray(buttons)) {
throw new Error('buttons must be array');
}
this.topElementStyle = topElementStyle;
this.elements = elements;
this.buttons = buttons;
}
get response () {
const response = {
attachment: {
type: 'template',
payload: {
template_type: 'list',
top_element_style: this.topElementStyle,
elements: []
}
}
};
for (const element of this.elements) {
response.attachment.payload.elements.push(element);
}
if (this.buttons.length == 1) {
response.attachment.buttons = this.buttons[0];
}
return response;
}
}
class FacebookButtonItem {
constructor (
type,
title,
{
url = '',
webviewHeightRatio = FacebookWebViewHeight.TALL,
messengerExtensions = false,
payload = ''
} = {}
) {
if (!type || (typeof type !== 'string')) {
throw new Error('type can NOT be empty');
}
if (!title || (typeof title !== 'string')) {
throw new Error('title can NOT be empty');
}
this.type = type;
this.title = title;
this.url = url;
this.webviewHeightRatio = webviewHeightRatio;
this.messengerExtensions = messengerExtensions;
this.payload = payload;
}
get response () {
switch (this.type) {
case FacebookActionType.POSTBACK:
return {
type: 'postback',
title: this.title,
payload: this.payload
};
case FacebookActionType.WEB_URL:
return {
type: 'web_url',
url: this.url,
title: this.title,
webview_height_ratio: this.webviewHeightRatio,
messenger_extensions: this.messengerExtensions,
};
case FacebookActionType.PHONE_NUMBER:
return {
type: 'phone_number',
title: this.title,
payload: this.payload
};
default:
throw new Error('Button is error');
}
}
}
class FacebookElementItem {
constructor (title, subtitle, imageUrl = '', buttons = [], defaultAction = {}) {
if (!title || (typeof title !== 'string')) {
throw new Error('title can NOT be empty');
}
if (!subtitle || (typeof subtitle !== 'string')) {
throw new Error('subtitle can NOT be empty');
}
if (typeof imageUrl !== 'string') {
throw new Error('imageUrl can NOT be empty');
}
this.title = title;
this.subtitle = subtitle;
this.imageUrl = imageUrl;
this.buttons = buttons;
this.defaultAction = defaultAction;
}
get response () {
const response = {
title: this.title,
subtitle: this.subtitle
};
if (this.imageUrl !== '') {
response.image_url = this.imageUrl;
}
if (this.buttons.length > 0) {
response.buttons = [];
for (const button of this.buttons) {
response.buttons.push(button);
}
}
// ECMA 5+
if (!(Object.keys(this.defaultAction).length === 0 && this.defaultAction.constructor === Object)) {
response.default_action = this.defaultAction;
}
return response;
}
}
const FacebookActionType = {
WEB_URL: 'url',
POSTBACK: 'postback',
PHONE_NUMBER: 'phone_number'
};
const FacebookWebViewHeight = {
COMPACT: 'compact',
TALL: 'tall',
FULL: 'full'
};
const FacebookImageAspectRatio = {
HORIZONTAL: 'horizontal', // 1.91:1
SQUARE: 'square' // 1:1
};
const FacebookTopElementStyle = {
LARGE: 'large',
COMPACT: 'compact',
};
module.exports = {
FacebookQuickReplyTypeText,
FacebookQuickReplyItemTypeText,
FacebookQuickReplyTypeUserPhoneNumber,
FacebookQuickReplyTypeUserEmail,
FacebookButtonItem,
FacebookDefaultActionItem,
FacebookActionType,
FacebookWebViewHeight,
FacebookImageAspectRatio,
FacebookGenericTemplate,
FacebookGenericTemplateElement,
FacebookButtonTemplate,
FacebookTopElementStyle,
FacebookListTemplate,
FacebookElementItem
}; |
""" Module to access the Search endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Dict, Union
from ...models import FileInfoList, SearchFilesMultipartData
from ..base import ApiBaseClass
class SearchApi(ApiBaseClass):
""" """
async def search_files(
self,
team_id: str,
*,
multipart_data: Union[SearchFilesMultipartData, Dict],
) -> FileInfoList:
"""Search files in a team
Search for files in a team based on file name, extention and file
content (if file content extraction is enabled and supported for the
files).
Permissions:
Must be authenticated and have the `view_team` permission.
Minimum Server Version:
5.34
Api Reference:
`SearchFiles <https://api.mattermost.com/#operation/SearchFiles>`_
"""
url = f"/teams/{team_id}/files/search"
multipart_body_data = SearchFilesMultipartData.parse_obj(multipart_data)
request_kwargs = {
"url": url,
"data": multipart_body_data.get_data(),
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.post(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = FileInfoList.parse_obj(response.json())
return response200
return response
|
class Kid:
def __init__(self, name=None, age=-1):
self.name = name
self.age = age
class Family:
def __init__(self, parents=[]):
self.parents = parents
self.kids = []
def __str__(self):
return_str = "Family:\n"
return_str += " Parents:\n"
for parent in self.parents:
return_str += " "+parent+"\n"
return_str += " Kids:\n"
for kid in self.kids:
return_str += " " + kid.name + ", " + str(kid.age) + "\n"
return return_str
def add_kid(self, kid=None):
self.kids.append(kid)
|
//@flow
const watchPathIgnorePatterns = [
'<rootDir>/node_modules/',
'<rootDir>/tools/',
'<rootDir>/npm/',
'<rootDir>/packages/',
'<rootDir>/flow/',
'<rootDir>/flow-typed/',
'<rootDir>/examples/',
]
const createDefaultConfig = () => ({
automock: false,
browser: false,
testEnvironment: 'node',
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
// moduleNameMapper: {},
modulePathIgnorePatterns: watchPathIgnorePatterns,
testPathIgnorePatterns: watchPathIgnorePatterns,
transformIgnorePatterns: [
...watchPathIgnorePatterns,
'node_modules/(?!(bs-platform)/)',
],
watchPathIgnorePatterns,
// roots: ['<rootDir>/src/'],
})
module.exports = {
collectCoverage: boolean(process.env.COVERAGE, false),
collectCoverageFrom: [
'<rootDir>/src/**/*.js',
'!**/node_modules/**',
'!**/__tests__/**',
'!**/*.test.js',
'!**/*.spec.js',
'!<rootDir>/src/babel/**',
'!<rootDir>/src/fixtures/**',
'!<rootDir>/src/redux/**',
],
// watchPlugins: ['jest-runner-eslint/watch-fix'],
watchPathIgnorePatterns,
projects: createProjectList([
{
effector: {
testMatch: [`<rootDir>/src/effector/__tests__/**/*.test.js`],
},
},
'effector/kernel',
'static-land',
'forms',
'babel',
// 'redux',
{
react: {
testEnvironment: 'jsdom',
testMatch: [
`<rootDir>/src/react/**/*.test.js`,
`<rootDir>/src/react/**/*.spec.js`,
],
// setupFiles: ['<rootDir>/src/fixtures/performance.mock.js'],
// watchPathIgnorePatterns,
},
},
{
reason: {
testMatch: [`<rootDir>/src/reason/**/*_test.bs.js`],
},
},
!boolean(process.env.NO_TYPE_TESTS, false) && {
types: {
testMatch: [
`<rootDir>/src/types/__tests__/**/*.test.js`,
`<rootDir>/src/types/__tests__/**/*.spec.js`,
`<rootDir>/src/types/__tests__/**/*.test.ts`,
`<rootDir>/src/types/__tests__/**/*.spec.ts`,
`<rootDir>/src/types/__tests__/**/*.test.tsx`,
`<rootDir>/src/types/__tests__/**/*.spec.tsx`,
],
browser: false,
globalSetup: './src/types/src/globalSetup.js',
globalTeardown: './src/types/src/globalTeardown.js',
maxConcurrency: 25,
transform: {
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.tsx?$': 'babel-jest',
},
},
},
]),
}
// if (boolean(process.env.LINT, false)) {
// module.exports.projects.push({
// runner: 'jest-runner-eslint',
// displayName: 'lint',
// testMatch: ['<rootDir>/src/**/*.js', '!**/redux/**'],
// // watchPathIgnorePatterns,
// })
// }
function createProjectList(items) {
items = items.filter(Boolean)
const list = []
for (const item of items) {
if (typeof item === 'string') {
const project = Object.assign(
{},
createDefaultConfig(),
{
testMatch: [
`<rootDir>/src/${item}/**/*.test.js`,
`<rootDir>/src/${item}/**/*.spec.js`,
],
},
{
displayName: item,
},
)
list.push(project)
} else {
for (const key in item) {
const val = item[key]
const project = Object.assign(
{},
createDefaultConfig(),
{
testMatch: [
`<rootDir>/src/${key}/**/*.test.js`,
`<rootDir>/src/${key}/**/*.spec.js`,
],
},
val,
{displayName: key},
)
list.push(project)
}
}
}
return list
}
function boolean(
value /*: string | boolean | null | void*/,
defaults /*: boolean*/,
) /*: boolean*/ {
switch (value) {
case 'no':
case 'false':
case false:
return false
case 'yes':
case 'true':
case true:
return true
case null:
case undefined:
default:
return defaults
}
}
|
import Projection from '../../../../src/ol/proj/Projection.js';
import WMTS, {optionsFromCapabilities} from '../../../../src/ol/source/WMTS.js';
import WMTSCapabilities from '../../../../src/ol/format/WMTSCapabilities.js';
import WMTSTileGrid from '../../../../src/ol/tilegrid/WMTS.js';
import {getBottomLeft, getTopRight} from '../../../../src/ol/extent.js';
import {get as getProjection} from '../../../../src/ol/proj.js';
describe('ol.source.WMTS', function () {
describe('when creating options from capabilities', function () {
const parser = new WMTSCapabilities();
let capabilities, content;
before(function (done) {
afterLoadText('spec/ol/format/wmts/ogcsample.xml', function (xml) {
try {
content = xml;
capabilities = parser.read(xml);
} catch (e) {
done(e);
}
done();
});
});
it('returns null if the layer was not found in the capabilities', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'invalid',
});
expect(options).to.be(null);
});
it('passes the crossOrigin option', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857',
crossOrigin: '',
});
expect(options.crossOrigin).to.be.eql('');
});
it('can create KVP options from spec/ol/format/wmts/ogcsample.xml', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'http://www.maps.bob/cgi-bin/MiraMon5_0.cgi?'
);
expect(options.layer).to.be.eql('BlueMarbleNextGeneration');
expect(options.matrixSet).to.be.eql('google3857');
expect(options.format).to.be.eql('image/jpeg');
expect(options.projection).to.be.a(Projection);
expect(options.projection).to.be.eql(getProjection('EPSG:3857'));
expect(options.requestEncoding).to.be.eql('KVP');
expect(options.tileGrid).to.be.a(WMTSTileGrid);
expect(options.style).to.be.eql('DarkBlue');
expect(options.dimensions).to.eql({Time: '20110805'});
expect(options.crossOrigin).to.be(undefined);
});
it('can create REST options from spec/ol/format/wmts/ogcsample.xml', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857',
requestEncoding: 'REST',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'http://www.example.com/wmts/coastlines/{TileMatrix}/{TileRow}/{TileCol}.png'
);
expect(options.layer).to.be.eql('BlueMarbleNextGeneration');
expect(options.matrixSet).to.be.eql('google3857');
expect(options.format).to.be.eql('image/png');
expect(options.projection).to.be.a(Projection);
expect(options.projection).to.be.eql(getProjection('EPSG:3857'));
expect(options.requestEncoding).to.be.eql('REST');
expect(options.tileGrid).to.be.a(WMTSTileGrid);
expect(options.style).to.be.eql('DarkBlue');
expect(options.dimensions).to.eql({Time: '20110805'});
});
it('can find a MatrixSet by SRS identifier', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
projection: 'EPSG:3857',
requestEncoding: 'REST',
});
expect(options.matrixSet).to.be.eql('google3857');
expect(options.projection.getCode()).to.be.eql('EPSG:3857');
});
it('can find a MatrixSet by equivalent SRS identifier', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
projection: 'EPSG:900913',
requestEncoding: 'REST',
});
expect(options.matrixSet).to.be.eql('google3857');
expect(options.projection.getCode()).to.be.eql('EPSG:900913');
});
it('can find the default MatrixSet', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
requestEncoding: 'REST',
});
expect(options.matrixSet).to.be.eql('BigWorldPixel');
expect(options.projection.getCode()).to.be.eql(
'urn:ogc:def:crs:OGC:1.3:CRS84'
);
});
it("uses the projection of the default MatrixSet if the config's projection is not supported", function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
projection: new Projection({
code: 'EPSG:2056',
units: 'm',
}),
});
expect(options.matrixSet).to.be.eql('BigWorldPixel');
expect(options.projection.getCode()).to.be.eql(
'urn:ogc:def:crs:OGC:1.3:CRS84'
);
});
it('uses extent of tile matrix instead of projection extent', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857subset',
});
// Since google3857subset defines subset of space defined by the google3857 matrix set:
// - top left corner: -10000000, 10000000
// - calculated grid extent: [-10000000, 9999694.25188686, -9999694.25188686, 10000000]
// then the tile grid extent is only a part of the full projection extent.
const gridExtent = options.tileGrid.getExtent();
const gridBottomLeft = getBottomLeft(gridExtent);
const gridTopRight = getTopRight(gridExtent);
expect(Math.round(gridBottomLeft[0])).to.be.eql(-10000000);
expect(Math.round(gridBottomLeft[1])).to.be.eql(9999847);
expect(Math.round(gridTopRight[0])).to.be.eql(-9999847);
expect(Math.round(gridTopRight[1])).to.be.eql(10000000);
const projExtent = options.projection.getExtent();
const projBottomLeft = getBottomLeft(projExtent);
const projTopRight = getTopRight(projExtent);
expect(Math.round(projBottomLeft[0])).to.be.eql(-20037508);
expect(Math.round(projBottomLeft[1])).to.be.eql(-20037508);
expect(Math.round(projTopRight[0])).to.be.eql(20037508);
expect(Math.round(projTopRight[1])).to.be.eql(20037508);
});
it("doesn't fail if the GetCap doesn't contains Constraint tags", function () {
const tmpXml = content.replace(
/<ows:Constraint[\s\S]*?<\/ows:Constraint>/g,
''
);
const tmpCapabilities = parser.read(tmpXml);
expect(
tmpCapabilities['OperationsMetadata']['GetTile']['DCP']['HTTP'][
'Get'
][0]['Constraint']
).to.be(undefined);
const options = optionsFromCapabilities(tmpCapabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857',
});
expect(options.layer).to.be.eql('BlueMarbleNextGeneration');
expect(options.matrixSet).to.be.eql('google3857');
});
it("set KVP as default request encoding if the GetCap doesn't contains Constraint and ResourceUrl tags", function () {
let tmpXml = content.replace(
/<ows:Constraint[\s\S]*?<\/ows:Constraint>/g,
''
);
tmpXml = tmpXml.replace(/<ResourceURL[\s\S]*?"\/>/g, '');
const tmpCapabilities = parser.read(tmpXml);
expect(
tmpCapabilities['OperationsMetadata']['GetTile']['DCP']['HTTP'][
'Get'
][0]['Constraint']
).to.be(undefined);
expect(tmpCapabilities['Contents']['Layer'][0]['ResourceURL']).to.be(
undefined
);
const options = optionsFromCapabilities(tmpCapabilities, {
layer: 'BlueMarbleNextGeneration',
matrixSet: 'google3857',
});
expect(options.layer).to.be.eql('BlueMarbleNextGeneration');
expect(options.matrixSet).to.be.eql('google3857');
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'http://www.maps.bob/cgi-bin/MiraMon5_0.cgi?'
);
});
});
describe('when creating tileUrlFunction', function () {
const defaultTileGrid = new WMTSTileGrid({
origin: [-20037508.342789244, 20037508.342789244],
resolutions: [
559082264.029 * 0.28e-3,
279541132.015 * 0.28e-3,
139770566.007 * 0.28e-3,
],
matrixIds: [0, 1, 2],
});
it('can replace lowercase REST parameters', function () {
const source = new WMTS({
layer: 'layer',
style: 'default',
urls: [
'http://host/{layer}/{style}/{tilematrixset}/{TileMatrix}/{TileCol}/{TileRow}.jpg',
],
matrixSet: 'EPSG:3857',
requestEncoding: 'REST',
tileGrid: defaultTileGrid,
});
const projection = getProjection('EPSG:3857');
const url = source.tileUrlFunction(
source.getTileCoordForTileUrlFunction([1, 1, 1]),
1,
projection
);
expect(url).to.be.eql('http://host/layer/default/EPSG:3857/1/1/1.jpg');
});
it('can replace camelcase REST parameters', function () {
const source = new WMTS({
layer: 'layer',
style: 'default',
urls: [
'http://host/{Layer}/{Style}/{tilematrixset}/{TileMatrix}/{TileCol}/{TileRow}.jpg',
],
matrixSet: 'EPSG:3857',
requestEncoding: 'REST',
tileGrid: defaultTileGrid,
});
const projection = getProjection('EPSG:3857');
const url = source.tileUrlFunction(
source.getTileCoordForTileUrlFunction([1, 1, 1]),
1,
projection
);
expect(url).to.be.eql('http://host/layer/default/EPSG:3857/1/1/1.jpg');
});
it('can replace dimensions', function () {
const source = new WMTS({
layer: 'layer',
style: 'default',
dimensions: {'Time': 42},
urls: [
'http://host/{Layer}/{Style}/{Time}/{tilematrixset}/{TileMatrix}/{TileCol}/{TileRow}.jpg',
],
matrixSet: 'EPSG:3857',
requestEncoding: 'REST',
tileGrid: defaultTileGrid,
});
const projection = getProjection('EPSG:3857');
const url = source.tileUrlFunction(
source.getTileCoordForTileUrlFunction([1, 1, 1]),
1,
projection
);
expect(url).to.be.eql('http://host/layer/default/42/EPSG:3857/1/1/1.jpg');
});
});
describe('when creating options from Esri capabilities', function () {
const parser = new WMTSCapabilities();
let capabilities;
before(function (done) {
afterLoadText('spec/ol/format/wmts/arcgis.xml', function (xml) {
try {
capabilities = parser.read(xml);
} catch (e) {
done(e);
}
done();
});
});
it('can create KVP options from spec/ol/format/wmts/arcgis.xml', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'Demographics_USA_Population_Density',
requestEncoding: 'KVP',
matrixSet: 'default028mm',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'https://services.arcgisonline.com/arcgis/rest/services/' +
'Demographics/USA_Population_Density/MapServer/WMTS?'
);
});
it('can create REST options from spec/ol/format/wmts/arcgis.xml', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'Demographics_USA_Population_Density',
matrixSet: 'default028mm',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'https://services.arcgisonline.com/arcgis/rest/services/' +
'Demographics/USA_Population_Density/MapServer/WMTS/' +
'tile/1.0.0/Demographics_USA_Population_Density/' +
'{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png'
);
});
});
describe('when creating options from wgs84 capabilities', function () {
const parser = new WMTSCapabilities();
let capabilities;
before(function (done) {
afterLoadText(
'spec/ol/format/wmts/capabilities_wgs84.xml',
function (xml) {
try {
capabilities = parser.read(xml);
} catch (e) {
done(e);
}
done();
}
);
});
it('returns correct bounding box', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'baselayer',
matrixSet: 'inspire_quad',
requestEncoding: 'REST',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'https://example.com/wmts/baselayer/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.png'
);
expect(options.layer).to.be.eql('baselayer');
expect(options.matrixSet).to.be.eql('inspire_quad');
expect(options.format).to.be.eql('image/png');
expect(options.projection).to.be.a(Projection);
expect(options.projection).to.be.eql(getProjection('EPSG:4326'));
expect(options.requestEncoding).to.be.eql('REST');
expect(options.tileGrid).to.be.a(WMTSTileGrid);
expect(options.style).to.be.eql('default');
const extent = options.tileGrid.getExtent();
// compare with delta, due to rounding not the exact bounding box is returned...
const expectDelta = (value, expected) =>
expect(Math.abs(value - expected)).to.below(1e-10);
expectDelta(extent[0], -180);
expectDelta(extent[1], -90);
expectDelta(extent[2], 180);
expectDelta(extent[3], 90);
});
});
describe('when creating options from capabilities with TileMatrixSetLink', function () {
const parser = new WMTSCapabilities();
let capabilities;
before(function (done) {
afterLoadText(
'spec/ol/format/wmts/capabilities_with_tilematrixsetlink.xml',
function (xml) {
try {
capabilities = parser.read(xml);
} catch (e) {
done(e);
}
done();
}
);
});
it('returns correct bounding box for a layer', function () {
const options = optionsFromCapabilities(capabilities, {
layer: 'mean_atlas_land',
matrixSet: 'inspire_quad',
requestEncoding: 'REST',
});
expect(options.urls).to.be.an('array');
expect(options.urls).to.have.length(1);
expect(options.urls[0]).to.be.eql(
'https://example.com/wmts/mean_atlas_land/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.png'
);
expect(options.layer).to.be.eql('mean_atlas_land');
expect(options.matrixSet).to.be.eql('inspire_quad');
expect(options.format).to.be.eql('image/png');
expect(options.projection).to.be.a(Projection);
expect(options.projection).to.be.eql(getProjection('EPSG:4326'));
expect(options.requestEncoding).to.be.eql('REST');
expect(options.tileGrid).to.be.a(WMTSTileGrid);
expect(options.style).to.be.eql('default');
const extent = options.tileGrid.getExtent();
// calculate with of one tile, this will be used as tolerance for result extent
const tile_width =
((68247.34668319306 * 0.00028) /
getProjection('EPSG:4326').getMetersPerUnit()) *
256;
// compare with delta, due to rounding not the exact bounding box is returned...
const expectDelta = (value, expected) =>
expect(Math.abs(value - expected)).to.below(tile_width + 1e-10);
expectDelta(extent[0], -36);
expectDelta(extent[1], 15);
expectDelta(extent[2], 43);
expectDelta(extent[3], 90);
});
});
describe('#setUrls()', function () {
it('sets the URL for the source', function () {
const source = new WMTS({});
const urls = [
'https://a.example.com/',
'https://b.example.com/',
'https://c.example.com/',
];
source.setUrls(urls);
expect(source.getUrls()).to.eql(urls);
});
it('updates the key for the source', function () {
const source = new WMTS({});
const urls = [
'https://a.example.com/',
'https://b.example.com/',
'https://c.example.com/',
];
source.setUrls(urls);
expect(source.getKey()).to.eql(urls.join('\n'));
});
it('generates the correct tileUrlFunction during application of setUrl()', function () {
const projection = getProjection('EPSG:3857');
const source = new WMTS({
projection: projection,
requestEncoding: 'REST',
urls: [
'http://1.example.com/{TileMatrix}/{TileRow}/{TileCol}.jpeg',
'http://2.example.com/{TileMatrix}/{TileRow}/{TileCol}.jpeg',
],
tileGrid: new WMTSTileGrid({
matrixIds: [0, 1, 2, 3, 4, 5, 6, 7],
origin: [2690000, 1285000],
resolutions: [4000, 3750, 3500, 3250, 3000, 2750, 2500, 2250],
}),
});
const urls = [
'https://a.example.com/{TileMatrix}/{TileRow}/{TileCol}.jpg',
'https://b.example.com/{TileMatrix}/{TileRow}/{TileCol}.jpg',
];
source.setUrls(urls);
const tileUrl1 = source.tileUrlFunction([2, 9, -5], 1, projection);
expect(tileUrl1).to.match(/https\:\/\/[ab]\.example\.com\/2\/-5\/9\.jpg/);
});
});
describe('url option', function () {
it('expands url template', function () {
const tileSource = new WMTS({
url: '{1-3}',
});
const urls = tileSource.getUrls();
expect(urls).to.eql(['1', '2', '3']);
});
});
describe('#getUrls', function () {
let sourceOptions;
let source;
beforeEach(function () {
sourceOptions = {
layer: 'layer',
style: 'default',
matrixSet: 'foo',
requestEncoding: 'REST',
tileGrid: new WMTSTileGrid({
origin: [0, 0],
resolutions: [],
matrixIds: [],
}),
};
});
describe('using a "url" option', function () {
beforeEach(function () {
sourceOptions.url = 'some_wmts_url';
source = new WMTS(sourceOptions);
});
it('returns the WMTS URLs', function () {
const urls = source.getUrls();
expect(urls).to.be.eql(['some_wmts_url']);
});
});
describe('using a "urls" option', function () {
beforeEach(function () {
sourceOptions.urls = ['some_wmts_url1', 'some_wmts_url2'];
source = new WMTS(sourceOptions);
});
it('returns the WMTS URLs', function () {
const urls = source.getUrls();
expect(urls).to.be.eql(['some_wmts_url1', 'some_wmts_url2']);
});
});
});
describe('#getRequestEncoding', function () {
let source;
beforeEach(function () {
source = new WMTS({
layer: 'layer',
style: 'default',
matrixSet: 'foo',
requestEncoding: 'REST',
tileGrid: new WMTSTileGrid({
origin: [0, 0],
resolutions: [],
matrixIds: [],
}),
});
});
it('returns the request encoding', function () {
const requestEncoding = source.getRequestEncoding();
expect(requestEncoding).to.be.eql('REST');
});
});
});
|
import * as React from 'react';
import {PureComponent} from 'react';
const eventNames = ['onDragStart', 'onDrag', 'onDragEnd'];
function round5(value) {
return (Math.round(value * 1e5) / 1e5).toFixed(5);
}
export default class ControlPanel extends PureComponent {
renderEvent = eventName => {
const {events = {}} = this.props;
const lngLat = events[eventName];
return (
<div key={eventName}>
<strong>{eventName}:</strong> {lngLat ? lngLat.map(round5).join(', ') : <em>null</em>}
</div>
);
};
render() {
return (
<div className="control-panel">
<h3>Draggable Marker</h3>
<p>Try dragging the marker to another location.</p>
<div>{eventNames.map(this.renderEvent)}</div>
<div className="source-link">
<a
href="https://github.com/visgl/react-map-gl/tree/5.2-release/examples/draggable-markers"
target="_new"
>
View Code ↗
</a>
</div>
</div>
);
}
}
|
"""Fonduer learning utils' unit tests."""
from fonduer.candidates.models import Candidate
from fonduer.learning.utils import confusion_matrix
def test_confusion_matrix():
"""Test the confusion matrix."""
# Synthesize candidates
cand1 = Candidate(id=1, type="type")
cand2 = Candidate(id=2, type="type")
cand3 = Candidate(id=3, type="type")
cand4 = Candidate(id=4, type="type")
# pred and gold as set
pred = {cand1, cand2, cand3}
gold = {cand1, cand2, cand4}
(TP, FP, FN) = confusion_matrix(pred, gold)
assert TP == {cand1, cand2}
assert FP == {cand3}
assert FN == {cand4}
# pred as list
pred = [cand1, cand2, cand3]
(TP, FP, FN) = confusion_matrix(pred, gold)
assert TP == {cand1, cand2}
assert FP == {cand3}
assert FN == {cand4}
# test if the order of elements does not affect the output
pred = [cand3, cand2, cand1]
(TP, FP, FN) = confusion_matrix(pred, gold)
assert TP == {cand1, cand2}
assert FP == {cand3}
assert FN == {cand4}
# Assume the followings are entities
pred = {"1", "2", "3"}
gold = {"1", "2", "4"}
(TP, FP, FN) = confusion_matrix(pred, gold)
assert TP == {"1", "2"}
assert FP == {"3"}
assert FN == {"4"}
|
'use strict'
const semver = require('semver')
const harness = require('./harness')
const H = harness
async function startWorker(workerData) {
/* eslint-disable-next-line node/no-unsupported-features/node-builtins */
const worker = require('worker_threads')
return await new Promise((resolve, reject) => {
let has_resolved = false
const work = new worker.Worker('./test/workerthread.worker.js', {
workerData,
})
work.on('message', (data) => {
// we need to force terminate the worker so it doesn't stay running, but
// we mark the handler as resolved so we don't send an error for the terminate
has_resolved = true
work.terminate().then(() => {
resolve(data)
})
})
work.on('error', (err) => {
if (!has_resolved) {
has_resolved = true
reject(err)
}
})
work.on('exit', (code) => {
if (!has_resolved) {
if (code !== 0) {
has_resolved = true
reject(new Error(`Worker stopped with exit code ${code}`))
}
}
})
})
}
describe('#worker-threads', function () {
it('should start a worker and complete an operation', async function () {
if (semver.lt(process.version, '12.11.0')) {
return this.skip()
}
const res = await startWorker({
connStr: H.connStr,
connOpts: H.connOpts,
bucketName: H.bucketName,
testKey: H.genTestKey(),
})
if (!res.success) {
throw res.error
}
}).timeout(30000)
})
|
/**
*
* FormOperacion
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import {
Box,
Container,
Title,
} from 'bloomer';
import { FormattedMessage } from 'react-intl';
import Button from 'components/Button';
import DropList from 'components/DropField';
import Input from 'components/FieldInput';
import Item from './ItemDrop';
import {
styles,
ContainerTitle,
ContainerButtons,
} from './StyledComponents';
import messages from './messages';
function FormOperacion({
SubmitAction,
backToList,
dataCustomers,
loading,
changeFunc,
changeMonto,
actual,
montoActual,
validateDrop,
validateMonto,
}) {
return (
<form onSubmit={SubmitAction} style={styles.containerFlex} >
<Box style={styles.containerBox}>
<Container style={styles.container}>
<ContainerTitle>
<Title isSize={4}>
<strong>
<FormattedMessage {...messages.title} />
</strong>
</Title>
</ContainerTitle>
<DropList
dropName={'Selecciona un customer:'}
data={dataCustomers}
item={Item}
placeholder={'Seleccione un customer:'}
validate={validateDrop}
filter={false}
textField={'name'}
valueField={'name'}
changeFunc={(selected) => { changeFunc(selected); }}
busy={loading}
defaultValue={actual[1]}
/>
<Input
fieldName={'Monto a Transferir: '}
ChangeFunc={(monto) => { changeMonto(monto); }}
placeholder={'Monto'}
validate={validateMonto}
valueDefault={montoActual}
typeField={'number'}
/>
<ContainerButtons>
<Button
color={'success'}
text={'Transferir'}
loading={loading}
typeButton={'submit'}
/>
<Button
color={'warning'}
text={' Volver '}
loading={false}
action={backToList}
/>
</ContainerButtons>
</Container>
</Box>
</form>
);
}
FormOperacion.propTypes = {
SubmitAction: PropTypes.func,
backToList: PropTypes.func,
dataCustomers: PropTypes.array,
loading: PropTypes.bool,
changeFunc: PropTypes.func,
actual: PropTypes.array,
changeMonto: PropTypes.func,
montoActual: PropTypes.number,
validateDrop: PropTypes.bool,
validateMonto: PropTypes.bool,
};
export default FormOperacion;
|
import pygame
import os
pygame.init()
pygame.display.set_caption("TEST")
w = 700
h = 600
screensize = (w,h)
screen = pygame.display.set_mode(screensize)
black = (0, 0, 0)
xa = 0
ya = 0
while True:
player = pygame.image.load(os.path.join("Images", "run", "run0.gif"))
playern = pygame.transform.flip(player, xa, ya)
screen.fill(black)
pressed = pygame.key.get_pressed()
if pressed[pygame.K_a]:
xa += 1
if pressed[pygame.K_d]:
xa -= 1
if xa > 1:
xa = 1
if xa < 0:
xa = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
Exit = True
pygame.display.quit()
screen.blit(playern, (0,0))
pygame.display.update() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.