traver | Test data generation framework | Testing library
kandi X-RAY | traver Summary
Support
Quality
Security
License
Reuse
- Creates an array of objects that are nested array of objects .
- Sets the given attribute value .
- Convert a key to the graph
- Sets a nested object .
- Parses the parent_options and sets parent_options
- The settings of the object .
- Creates a new graph
- Create a list
- Creates a new graph .
- Returns the parent attributes from the parent object .
traver Key Features
traver Examples and Code Snippets
Trending Discussions on traver
Trending Discussions on traver
QUESTION
I'm trying to travers a Binary Tree and print out the Node Values with a matching number in front of each Node. For better understanding: I'm printing out following lines while Calling my Method:
- 11 , 2. 33 , 3. 10 , 4. 14 , 5. 27 , 3. 31 , 4. 32
Where as my Goal with the Method ist, to print out the exact same order of the Nodes but with having an increasing Number infront of it, which should indicate the order. Like so:
- 11
- 33
- 10
- 14
- 27
- 31
- 32
Till know my Method looks like this:
public int mNr(Node k, int Nr) {
//If the current Node is null, return 0 (currently not making any use of the return)
if(k == null) {
return 0;
} else {
//If the left Side is not null print out the Left Node with Value
if(k.left != null) {
//increment Nr each time priniting
System.out.println("Nr: " + ++Nr + " " + k.left.number);
}
if(k.right != null) {
//Same as left Side
System.out.println("Nr: " + ++Nr + " " + k.right.number);
}
//Calling the Method and not incrementing the Nr Parameter because
//already incrementing it in the print Statements
return mNr(k.left, Nr) + mNr(k.right, Nr);
}
}
I'm also not quite sure how to use the int -return, even till know I'm not making any use of it. Any Advice for getting the Correct Output would be helpful.
ANSWER
Answered 2022-Jan-18 at 21:41Returns are used to make the result of a method available for further evaluation within the program. In this case, the method calling mNr
could used the return of 0 to know that the node is empty and therefore produce a more adequate output for this situation.
QUESTION
I tried to run this Ant Colony algorithm code (ant_colony.py
) in Python:
from threading import Thread
class ant_colony:
class ant(Thread):
def __init__(self, init_location, possible_locations, pheromone_map, distance_callback, alpha, beta, first_pass=False):
Thread.__init__(self)
self.init_location = init_location
self.possible_locations = possible_locations
self.route = []
self.distance_traveled = 0.0
self.location = init_location
self.pheromone_map = pheromone_map
self.distance_callback = distance_callback
self.alpha = alpha
self.beta = beta
self.first_pass = first_pass
self._update_route(init_location)
self.tour_complete = False
def run(self):
while self.possible_locations:
next = self._pick_path()
self._traverse(self.location, next)
self.tour_complete = True
def _pick_path(self):
if self.first_pass:
import random
return random.choice(self.possible_locations)
attractiveness = dict()
sum_total = 0.0
for possible_next_location in self.possible_locations:
pheromone_amount = float(self.pheromone_map[self.location][possible_next_location])
distance = float(self.distance_callback(self.location, possible_next_location))
attractiveness[possible_next_location] = pow(pheromone_amount, self.alpha)*pow(1/distance, self.beta)
sum_total += attractiveness[possible_next_location]
if sum_total == 0.0:
def next_up(x):
import math
import struct
if math.isnan(x) or (math.isinf(x) and x > 0):
return x
if x == 0.0:
x = 0.0
n = struct.unpack('= 0:
n += 1
else:
n -= 1
return struct.unpack('= 1")
self.ant_count = ant_count
if (type(alpha) is not int) and type(alpha) is not float:
raise TypeError("alpha must be int or float")
if alpha < 0:
raise ValueError("alpha must be >= 0")
self.alpha = float(alpha)
if (type(beta) is not int) and type(beta) is not float:
raise TypeError("beta must be int or float")
if beta < 1:
raise ValueError("beta must be >= 1")
self.beta = float(beta)
if (type(pheromone_evaporation_coefficient) is not int) and type(pheromone_evaporation_coefficient) is not float:
raise TypeError("pheromone_evaporation_coefficient must be int or float")
self.pheromone_evaporation_coefficient = float(pheromone_evaporation_coefficient)
#pheromone_constant
if (type(pheromone_constant) is not int) and type(pheromone_constant) is not float:
raise TypeError("pheromone_constant must be int or float")
self.pheromone_constant = float(pheromone_constant)
#iterations
if (type(iterations) is not int):
raise TypeError("iterations must be int")
if iterations < 0:
raise ValueError("iterations must be >= 0")
self.iterations = iterations
#other internal variable init
self.first_pass = True
self.ants = self._init_ants(self.start)
self.shortest_distance = None
self.shortest_path_seen = None
def _get_distance(self, start, end):
if not self.distance_matrix[start][end]:
distance = self.distance_callback(self.nodes[start], self.nodes[end])
if (type(distance) is not int) and (type(distance) is not float):
raise TypeError("distance_callback should return either int or float, saw: "+ str(type(distance)))
self.distance_matrix[start][end] = float(distance)
return distance
return self.distance_matrix[start][end]
def _init_nodes(self, nodes):
id_to_key = dict()
id_to_values = dict()
id = 0
for key in sorted(nodes.keys()):
id_to_key[id] = key
id_to_values[id] = nodes[key]
id += 1
return id_to_key, id_to_values
def _init_matrix(self, size, value=0.0):
ret = []
for row in range(size):
ret.append([float(value) for x in range(size)])
return ret
def _init_ants(self, start):
#allocate new ants on the first pass
if self.first_pass:
return [self.ant(start, self.nodes.keys(), self.pheromone_map, self._get_distance,
self.alpha, self.beta, first_pass=True) for x in range(self.ant_count)]
#else, just reset them to use on another pass
for ant in self.ants:
ant.__init__(start, self.nodes.keys(), self.pheromone_map, self._get_distance, self.alpha, self.beta)
def _update_pheromone_map(self):
#always a square matrix
for start in range(len(self.pheromone_map)):
for end in range(len(self.pheromone_map)):
#decay the pheromone value at this location
#tau_xy <- (1-rho)*tau_xy (ACO)
self.pheromone_map[start][end] = (1-self.pheromone_evaporation_coefficient)*self.pheromone_map[start][end]
#then add all contributions to this location for each ant that travered it
#(ACO)
#tau_xy <- tau_xy + delta tau_xy_k
# delta tau_xy_k = Q / L_k
self.pheromone_map[start][end] += self.ant_updated_pheromone_map[start][end]
def _populate_ant_updated_pheromone_map(self, ant):
route = ant.get_route()
for i in range(len(route)-1):
#find the pheromone over the route the ant traversed
current_pheromone_value = float(self.ant_updated_pheromone_map[route[i]][route[i+1]])
#update the pheromone along that section of the route
#(ACO)
# delta tau_xy_k = Q / L_k
new_pheromone_value = self.pheromone_constant/ant.get_distance_traveled()
self.ant_updated_pheromone_map[route[i]][route[i+1]] = current_pheromone_value + new_pheromone_value
self.ant_updated_pheromone_map[route[i+1]][route[i]] = current_pheromone_value + new_pheromone_value
def mainloop(self):
for _ in range(self.iterations):
#start the multi-threaded ants, calls ant.run() in a new thread
for ant in self.ants:
ant.start()
#source: http://stackoverflow.com/a/11968818/5343977
#wait until the ants are finished, before moving on to modifying shared resources
for ant in self.ants:
ant.join()
for ant in self.ants:
#update ant_updated_pheromone_map with this ant's constribution of pheromones along its route
self._populate_ant_updated_pheromone_map(ant)
#if we haven't seen any paths yet, then populate for comparisons later
if not self.shortest_distance:
self.shortest_distance = ant.get_distance_traveled()
if not self.shortest_path_seen:
self.shortest_path_seen = ant.get_route()
#if we see a shorter path, then save for return
if ant.get_distance_traveled() < self.shortest_distance:
self.shortest_distance = ant.get_distance_traveled()
self.shortest_path_seen = ant.get_route()
#decay current pheromone values and add all pheromone values we saw during traversal (from ant_updated_pheromone_map)
self._update_pheromone_map()
#flag that we finished the first pass of the ants traversal
if self.first_pass:
self.first_pass = False
#reset all ants to default for the next iteration
self._init_ants(self.start)
#reset ant_updated_pheromone_map to record pheromones for ants on next pass
self.ant_updated_pheromone_map = self._init_matrix(len(self.nodes), value=0)
#translate shortest path back into callers node id's
ret = []
for id in self.shortest_path_seen:
ret.append(self.id_to_key[id])
return ret
and my module-test file is:
import ant_colony
import math
test_nodes = {0: (0, 7), 1: (3, 9), 2: (12, 4), 3: (14, 11), 4: (8, 11) ,5: (15, 6), 6: (6, 15), 7: (15, 9), 8: (12, 10), 9: (10, 7)}
def distance(start, end):
x_distance = abs(start[0] - end[0])
y_distance = abs(start[1] - end[1])
return math.sqrt(pow(x_distance, 2) + pow(y_distance, 2))
colony = ant_colony(test_nodes, distance)
answer = colony.mainloop()
print(answer)
but when it runs, this error appears:
TypeError: 'module' object is not callable
I tried a lot of ways but they didn't work at all. I tried to test two coordinates instead of distance
, I tried to test using arguments and so on, but they did not work. How can I fix it?
ANSWER
Answered 2021-Jul-11 at 18:07You are importing module but not a class. Replace this line of code:
import ant_colony
with this line of code:
from ant_colony import ant_colony
What's the difference? In my example you are importing class called ant_colony
from file called ant_colony
. The first thing is path to file and the second thing is the name of class, function etc.
QUESTION
I have an interest in AI and start learning about it. I try to implement a MLP class based on vectors only but it does not work properly.
The feed forward function seems to be OK, but apparently I have a lack of understanding regarding the back propagation algorithm. The Train function is a dummy one in order to test the XOR cases, the network always returns the same result (~0.625915 in my case), setting the error from 0.264518 when the inputs are 1 and 0 (1 is expected as output) to 0.442609 when the inputs are 1 and 1 (0 is expected as output).
I am wondering what I am doing wrong with the backpropagation and descent gradients stuffs. Below is the full code of this class and the main function. Thank you for your help and your highlights !
#include
#include
#include
#include
#include
using namespace std;
typedef function func;
typedef vector < vector < vector > > Matrix3d;
class Net {
public:
Net(const vector &topology, vector &fns) {
learning_rate = 0.1;
alpha = 0.5;
global_error = 1.0;
activationFns = fns;
nbLayers = topology.size();
lastLayerId = nbLayers - 1;
gradients.resize(nbLayers);
neuron_errors.resize(nbLayers);
layers.resize(nbLayers);
weights.resize(nbLayers);
wdeltas.resize(nbLayers);
for (unsigned layerNum = 0; layerNum < nbLayers; layerNum++) {
bool isLastLayer = layerNum == lastLayerId;
unsigned nbNeuronsInLayer = isLastLayer ? topology[layerNum] : topology[layerNum] + 1;
unsigned nbWeights = isLastLayer ? 0 : topology[layerNum + 1] + 1;
gradients[layerNum].resize(nbNeuronsInLayer, 0.0);
layers[layerNum].resize(nbNeuronsInLayer);
weights[layerNum].resize(nbNeuronsInLayer);
wdeltas[layerNum].resize(nbNeuronsInLayer);
neuron_errors[layerNum].resize(nbNeuronsInLayer, 0.0);
if (! isLastLayer) {
layers[layerNum][nbNeuronsInLayer-1] = 1.0; // initialisation du bias
}
for (unsigned n = 0; n < weights[layerNum].size(); n++) {
weights[layerNum][n].resize(nbWeights); // On affecte le nombre de neurones du layer suivant : nombre de weights de ce neurone
wdeltas[layerNum][n].resize(nbWeights, 0.0);
InitialiseWeights(weights[layerNum][n]); // on randomise les weights des neurones de ce layer
}
}
};
~Net() {
gradients.clear();
layers.clear();
weights.clear();
wdeltas.clear();
neuron_errors.clear();
};
// on propage à travers le réseau
// lors du feed forward, output vaut = activationFn(somme des entrées des neurones * leurs poids)
// pour chaque neurone du layer précédent :
// on prend sa sortie : prevLayer[n] qu'on multiplie par le poids vers le neurone i du layer actuel
void FeedForward(const vector &inputs) {
assert(inputs.size() == layers[0].size() - 1);
// on assigne les entrées aux sorties des neurones du layer INPUT
for (unsigned i = 0; i < inputs.size(); i++) {
layers[0][i] = inputs[i];
}
for (unsigned layerNum = 1; layerNum < nbLayers; layerNum++) {
vector &prevLayer = layers[layerNum - 1];
const bool isLastLayer = layerNum == lastLayerId;
const unsigned forcap = isLastLayer ? layers[layerNum].size() : layers[layerNum].size() - 1;
for (unsigned i = 0; i < forcap; i++) {
const double bias = prevLayer[prevLayer.size()-1] * weights[layerNum-1][weights[layerNum-1].size()-1][i];
double output = 0.0;
for (unsigned n = 0; n < prevLayer.size() - 1; n++) {
output += prevLayer[n] * weights[layerNum - 1][n][i];
}
output += bias;
layers[layerNum][i] = activationFns[layerNum - 1](output, false);
}
}
//Print();
};
void BackPropagate(const vector &targets) {
vector &guessed = layers[lastLayerId];
func &outputActivationFn = activationFns[lastLayerId];
assert(targets.size() == guessed.size());
global_error = 0.0;
// Calcul des erreurs de la couche OUTPUT //
for (unsigned t = 0; t < targets.size(); t++) {
double diff_ = targets[t] - guessed[t];
global_error += (diff_ * diff_);
neuron_errors[lastLayerId][t] = targets[t] - guessed[t]; // l'erreur du neurone de sortie
gradients[lastLayerId][t] = diff_ * outputActivationFn(guessed[t], true);
}
if (guessed.size() > 1)
global_error /= guessed.size()-1;
else
global_error *= 0.5;
global_error = sqrt(global_error);
// Calcul des erreurs des neurones des autres couches
for (unsigned l = nbLayers - 2; l < nbLayers; --l) {
// récupérer les weights reliant la couche hidden à la couche output
for (unsigned n = 0; n < layers[l].size(); n++) { // pour chaque neurone de cette couche
neuron_errors[l][n] = 0.0;
for (unsigned m = 0; m < layers[l+1].size(); m++) { // on target le neurone m de la couche supérieure
double &weight = weights[l][n][m];
// là on peut calculer l'erreur du neurone n
neuron_errors[l][n] += weight * gradients[l+1][m];
}
gradients[l][n] = neuron_errors[l][n] * activationFns[l](layers[l][n], true); // ?
}
}
// Mise à jour des weights (?)
for (unsigned l = nbLayers - 2; l < nbLayers; --l) {
for (unsigned n = 0; n < layers[l].size(); n++) {
for (unsigned m = 0; m < layers[l + 1].size(); m++) {
weights[l][n][m] -= (learning_rate * gradients[l][n] * layers[l][n]) + (wdeltas[l][n][m] * alpha);
wdeltas[l][n][m] = (learning_rate * gradients[l][n] * layers[l][n]) + (wdeltas[l][n][m] * alpha);
}
}
}
};
void GetResults(vector &results) {
results.clear();
for (unsigned i = 0; i < layers[lastLayerId].size(); i++) {
results[i] = layers[lastLayerId][i];
}
};
void Train() {
vector < vector > ins = {
{ 1.0, 0.0 },
{ 0.0, 1.0 },
{ 0.0, 0.0 },
{ 1.0, 1.0 }
};
vector < vector > outs = {
{ 1.0 },
{ 1.0 },
{ 0.0 },
{ 0.0 }
};
for (unsigned i = 0; i < 1000; i++) {
unsigned r = rand() % ins.size();
vector k = ins[r];
vector o = outs[r];
FeedForward(k);
BackPropagate(o);
cout << "[" << i << "] " << k[0] << " & " << k[1] << " -> " << o[0] << "\tresult : " << layers[lastLayerId][0] << "\terror = " << global_error << endl;
}
cout << endl << "Test: [ 1 , 0 ]" << endl;
FeedForward({ 1.0, 0.0 });
BackPropagate({ 1.0 });
cout << "Result : " << layers[lastLayerId][0] << "\t(error = " << global_error << endl;
cout << "Test: [ 1 , 1 ]" << endl;
FeedForward({ 0.85, 0.99 });
BackPropagate({ 0.0 });
cout << "Result : " << layers[lastLayerId][0] << "\t(error = " << global_error << endl;
};
double Getglobal_error(void) const {
return global_error;
};
void Print(void) {
for (unsigned l = 0; l < nbLayers; l++) {
cout << "Layer " << l << " : " << endl;
for (unsigned n = 0; n < layers[l].size(); n++) {
cout << "\t" << "Neuron " << l << "-" << n << " : ";
cout << "(" << layers[l][n] << ")" << endl;
for (unsigned w = 0; w < weights[l][n].size(); w++) {
cout << "\t\t" << l << "-" << n << " -> " << (l+1) << "-" << w << " | weight=" << weights[l][n][w] << endl;
}
}
}
}
private:
void InitialiseWeights(vector &weights_) {
for (unsigned w = 0; w < weights_.size(); w++) {
weights_[w] = ((double) rand() / (RAND_MAX));
}
}
double global_error;
double learning_rate;
double alpha;
unsigned nbLayers;
unsigned lastLayerId;
vector activationFns;
vector< vector > gradients; // [layerNum][neuronNum] gradients des erreurs des neurones
vector< vector > layers; // [layerNum][neuronNum]
vector< vector > neuron_errors; // [layerNum][neuronNum] // erreur des neurones
Matrix3d weights; // [layer][neuron][outputWeight]
Matrix3d wdeltas; // [layer][neuron][outputWeight]
};
double transfer_tanh(double x, bool isDerivative) {
if (isDerivative) {
return 1.0 - (tanh(x) * tanh(x));
}
return tanh(x);
}
double transfer_sigmoid(double x, bool isDerivative) {
if (isDerivative) {
return x * (1.0 - x);
}
return 1.0 / (1.0 + exp(-x));
}
int main () {
vector topo = { 2, 2, 1 };
vector funcs = { transfer_sigmoid, transfer_sigmoid, transfer_sigmoid };
Net mynet(topo, funcs);
/*
mynet.FeedForward({ 1.0, 0.0 });
mynet.BackPropagate({ 1.0 });
mynet.Print();
mynet.FeedForward({ 1.0, 0.0 });
mynet.BackPropagate({ 1.0 });
mynet.Print();
*/
mynet.Train();
}
ANSWER
Answered 2021-Feb-03 at 09:12I had a lack of understanding with the maths around the backprop thing. Thanks to this resource : https://pabloinsente.github.io/the-multilayer-perceptron, I figured out with this BackPropagate method :
void BackPropagate(const vector &targets) {
assert(targets.size() == layers[lastLayerId].size());
global_error = 0.0;
for (unsigned l = lastLayerId; l < nbLayers; --l) {
for (unsigned n = 0; n < layers[l].size(); n++) {
neuron_errors[l][n] = 0.0;
if (l == lastLayerId) { // couche output
global_error += (targets[n] - layers[lastLayerId][n]) * (targets[n] - layers[lastLayerId][n]);
neuron_errors[lastLayerId][n] = (targets[n] - layers[lastLayerId][n]) * activationFns[lastLayerId](layers[lastLayerId][n], true);
continue;
}
for (unsigned m = 0; m < layers[l + 1].size(); m++) {
double neuron_output = (l == 0) ? inputs[n] : layers[l][n];
double delta = learning_rate * (neuron_errors[l + 1][m] * neuron_output);
neuron_errors[l][n] += (neuron_errors[l + 1][m] * weights[l][n][m])
* activationFns[l](layers[l][n], true);
weights[l][n][m] += delta + (wdeltas[l][n][m] * alpha);
wdeltas[l][n][m] = delta;
}
}
}
}
QUESTION
Question: Given a generic tree and an integer n. Find and return the node with next larger element in the tree i.e. find a node with value just greater than n.
Although i was able to solve it is O(n) by removing the later for loop and doing comparisons while calling recursion. I am bit curious about time complexity of following version of code.
I came up with recurrence relation as T(n) = T(n-1) + (n-1) = O(n^2). Where T(n-1) is for time taken by children and + (n-1) for finding the next larger (second for loop). Have i done it right? or am i missing something?
def nextLargestHelper(root, n):
"""
root => reference to root node
n => integer
Returns node and value of node which is just larger not first larger than n.
"""
# Special case
if root is None:
return None, None
# list to store all values > n
largers = list()
# Induction step
if root.data > n:
largers.append([root, root.data])
# Induction step and Base case; if no children do not call recursion
for child in root.children:
# Induction hypothesis; my function returns me node and value just larger than 'n'
node, value = nextLargestHelper(child, n)
# If larger found in subtree
if node:
largers.append([node, value])
# Initialize node to none, and value as +infinity
node = None
value = sys.maxsize
# travers through all larger values and return the smallest value greater than n
for item in largers: # structure if item is [Node, value]
# this is why value is initialized to +infinity; so as it is true for first time
if item[1] < value:
node = item[0]
value = item[1]
return node, value
ANSWER
Answered 2020-Dec-11 at 13:05At first: please use different chacters for O-Notation and inputvalues.
You "touch" every node exactly once, so the result should be O(n)
. A bit special is your algorithm finding the minimum afterwards. You could include this in your go-though-all-children loop for an easier recurrence estimation. As it is, you have do a recurrence estimation for the minimum of the list as well.
Your recurrence equation should look more like T(n) = a*T(n/a) + c = O(n)
since in each step you have a
children forming a
subtrees with size (n-1)/a
. In each step you have next to some constant factors also the computation of the minimum of a list with at most a
elements. You could write it as a*T(n/a) + a*c1 +c2
which is the same as a*T(n/a) + c
. The actual formula would look more like this: T(n) = a*T((n-1)/a) + c
but the n-1
makes it harder to apply the master theorem.
QUESTION
As of now, my code only prints out an in-order traveral. However, I would like it to return one.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node):
if(node==None):
return
else:
inorder(node.left)
print(node.data)
inorder(node.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
P.S I know this tree is not a binary search tree.
ANSWER
Answered 2020-Dec-05 at 05:04You can use generators. yield from
the recursive calls and yield
the data value.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node):
if node:
yield from inorder(node.left)
yield node.data
yield from inorder(node.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(list(inorder(root)))
result
[4, 2, 5, 1, 3]
If you wanted it to use a list and not generators.
def inorder_list(node):
accum = []
inorder_list_impl(node, accum.append)
return accum
def inorder_list_impl(node, accumulator):
if node:
inorder_list_impl(node.left, accumulator)
accumulator(node.data)
inorder_list_impl(node.right, accumulator)
You could also use
inorder_list_impl(root, print)
To just print the values.
QUESTION
I have Wordpress site with a page of posts. For each post, I want to run javascript. I essentially want to insert HTML in the output div, conditionally for each. What am I doing wrong?
En travers
A l’unité de produit
En bloc
ANSWER
Answered 2020-Dec-03 at 14:27Answer: Replace the commas in your for loop declaration with semicolons!
i.e., the following:
for (var i=0, i < labels.length, i++) {
should be:
for (var i=0; i < labels.length; i++) {
More info: The comma operator often shows up in minified javascript code, but it is rarely used by us humans. At first glance, the comma operator may appear to work similarly to a semicolon, but in this case they are very different: Your for loop expects 3 input statements, but your use of the comma operator produces just one. See this SO answer for more
var labels = document.querySelectorAll("#uniteLabel"),
unitOutputs = document.querySelectorAll("#uniteOutput");
for (var i=0; i < labels.length; i++) {
if (labels[i].innerHTML == "En travers") {
unitOutputs[i].innerHTML = "Stère";
} else if (labels[i].innerHTML == "A l’unité de produit") {
unitOutputs[i].innerHTML = "Stère";
} else if (labels[i].innerHTML == "En bloc") {
unitOutputs[i].innerHTML = "m3";
}
}
En travers
A l’unité de produit
En bloc
QUESTION
I m working on multi-columns pdfs. I have converted the multi columns into one column with the package tabulazer . Here the result :
text <- "La voiture que conduit Annie suit, à tra-
vers neige et brouillard, la série de lacets
qui conduit de Corenc - non loin de
Grenoble - où les Schaerer demeurent
dans une maison faisant face à la chaîne
de Beldonne, à Mens - au sud de l'Isère,
en pleine Trièves - où René passa son
enfance. Entre deux tournants, la con-
ductrice apporte une précision que n'a
pas formulée son mari, et qui lui appa-
raît capitale : "
What I want :
"La voiture que conduit Annie suit, à travers neige et brouillard, la série de lacets
qui conduit de Corenc - non loin de Grenoble - où les Schaerer demeurent dans une maison faisant face à la chaîne de Beldonne, à Mens - au sud de l'Isère, en pleine Trièves - où René passa son enfance. Entre deux tournants, la conductrice apporte une précision que n'a pas formulée son mari, et qui lui apparaît capitale : "
ANSWER
Answered 2020-Oct-31 at 16:40This should be solvable with some simple substitition. R reads your input as
> text
[1] "La voiture que conduit Annie suit, à tra-\nvers neige et brouillard, la série de lacets\nqui conduit de Corenc - non loin de\nGrenoble - où les Schaerer demeurent\ndans une maison faisant face à la chaîne\nde Beldonne, à Mens - au sud de l'Isère,\nen pleine Trièves - où René passa son\nenfance. Entre deux tournants, la con-\nductrice apporte une précision que n'a\npas formulée son mari, et qui lui appa-\nraît capitale : "
Let us first remove the "-\n"
with
> text2 <- gsub("-\n","",text)
[1] "La voiture que conduit Annie suit, à travers neige et brouillard, la série de lacets\nqui conduit de Corenc - non loin de\nGrenoble - où les Schaerer demeurent\ndans une maison faisant face à la chaîne\nde Beldonne, à Mens - au sud de l'Isère,\nen pleine Trièves - où René passa son\nenfance. Entre deux tournants, la conductrice apporte une précision que n'a\npas formulée son mari, et qui lui apparaît capitale : "
And finally remove the remaining \n
with
> gsub("\n"," ",text2)
[1] "La voiture que conduit Annie suit, à travers neige et brouillard, la série de lacets qui conduit de Corenc - non loin de Grenoble - où les Schaerer demeurent dans une maison faisant face à la chaîne de Beldonne, à Mens - au sud de l'Isère, en pleine Trièves - où René passa son enfance. Entre deux tournants, la conductrice apporte une précision que n'a pas formulée son mari, et qui lui apparaît capitale : "
Leaving us with
La voiture que conduit Annie suit, à travers neige et brouillard, la série de lacets qui conduit de Corenc - non loin de Grenoble - où les Schaerer demeurent dans une maison faisant face à la chaîne de Beldonne, à Mens - au sud de l'Isère, en pleine Trièves - où René passa son enfance. Entre deux tournants, la conductrice apporte une précision que n'a pas formulée son mari, et qui lui apparaît capitale :
To summarise, perform the following replacements:
"-\n"
->""
"\n"
->" "
If you want this in one step, use the following command gsub("\n"," ",(gsub("-\n","",text)))
QUESTION
i wrote as beginner xslt for version 2.0 and it is work
....
this template is for displaying of conditions and it is recursive calling. i would like to generate html over python and lxml, so i switched to version 1.0, because it is nessesary for lxml
xsl:when : could not compile test expression '../name()='or''
i can use in test expression syntax like name()
or ../Atribute
but combination ../name()
is impossible for XSLT 1.0. can you advice me to resolving this situation, i would like to travers level up for name()
3rd party of dll for generating html over python like Saxon work, but is for me impossible thank you
ANSWER
Answered 2020-Jun-19 at 11:52Use name(..) = 'or'
or ../self::or
. Also for Python there is a now a module to use Saxon 9.9 C with Python.
QUESTION
I would like,if possible, to enhance the code in way that it indicates on the column F when the email has been sent. Like this line:
Latest update: Mail sent @Wed Jun 03 2020 23:05:18 GMT-0400
Also, I'd appreciate if an option is added to uncheck the box once the email is sent.
function EnvoiIDCourriel() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var LR = SS.getLastRow()
var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
//Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template
//Logger.log(NomCandidat);
//Cette ligne permet de passer à travers de toutes les lignes inscrites
var fileId = "1uLc_a5t2w1DFsDujpdMYTS7wYi5RtK8N"; // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob(); // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = CorpsMessage.replace(/\n/g, '
').replace('{LOGO}', ''); // Added
try{
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}}); // Modified
SS.getRange("F5").setFontColor("#228B22");
SS.getRange("F5").setValue("Latest update: Mail sent @" + new Date());
}catch(err){
SS.getRange("F5").setFontColor("#FF0000")
SS.getRange("F5").setValue("Alert! Error: " + " " + new Date() + " " + e.message)
}
}
});
}
ANSWER
Answered 2020-Jun-04 at 03:42I believe your goal as follows.
- You want to send an email, when the checkbox of the column "A" has the checked checkbox.
- You want to put
"Latest update: Mail sent @" + new Date()
to the column "F" of the same row when the email is sent. - You want to put
"Alert! Error: " + " " + new Date() + " " + e.message
to the column "F" of the same row when the email is NOT sent. - You want to uncheck the checkbox of the row.
For this, how about this answer?
Modification points:- In
forEach()
, whenvalues.forEach(([check, NomCandidat, ID, CurrentEmail, Processus], i))
is used, the ranges for the same row of the columns "A" and "F" areSS.getRange("F" + (i + 2))
andSS.getRange("A" + (i + 2))
, respectively. I think that your goal can be achieved using this. - I think that in your script,
e.message
iserr.message
.
When your script is modified, it becomes as follows.
Modified script: From: values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = CorpsMessage.replace(/\n/g, '
').replace('{LOGO}', ''); // Added
try{
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}}); // Modified
SS.getRange("F5").setFontColor("#228B22");
SS.getRange("F5").setValue("Latest update: Mail sent @" + new Date());
}catch(err){
SS.getRange("F5").setFontColor("#FF0000")
SS.getRange("F5").setValue("Alert! Error: " + " " + new Date() + " " + e.message)
}
}
});
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus], i) => { // Modified
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = CorpsMessage.replace(/\n/g, '
').replace('{LOGO}', '');
var range = SS.getRange("F" + (i + 2)); // Added
try {
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}});
range.setFontColor("#228B22"); // Modified
range.setValue("Latest update: Mail sent @" + new Date()); // Modified
SS.getRange("A" + (i + 2)).uncheck(); // Added
} catch(err) {
range.setFontColor("#FF0000") // Modified
range.setValue("Alert! Error: " + " " + new Date() + " " + err.message) // Modified
}
}
});
QUESTION
I'm wondering how can I embed a logo into email. The logo is saved on Google Drive. Also, I know the reference inlineimage and blob need to be used but I don't know how.
I tried this code, but no success
var Img = DriveApp.getFileById(1pRBZ....cKMFll1OouC..er2V97e8...).getBlob();
The line below retreive the message template. So, I want to include the image into the message as a signature.
var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
function EnvoiIDCourriel() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var LR = SS.getLastRow()
var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
//Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template
//Logger.log(NomCandidat);
//Cette ligne permet de passer à travers de toutes les lignes inscrites
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
}
});
}
ANSWER
Answered 2020-Jun-03 at 22:19I believe your goal as follows.
- You want to add a logo image to the email using the inlineimage.
- The logo image file is put in your Google Drive.
For this, how about this answer?
Modification points:- In order to add the logo image to the email, it is required to use the HTML body.
- In this case,
options
ofsendEmail(recipient, subject, body, options)
is used.
When your script is modified, it becomes as follows.
From: var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
}
});
var fileId = "###"; // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob(); // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = CorpsMessage + '
'; // Added
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}}); // Modified
}
});
or
To:As other modification, this is the method for using the HTML template. By this, you can prepare the HTML body of the email as a file.
var fileId = "###"; // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob(); // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = HtmlService.createTemplateFromFile("index"); // Added
html.text = CorpsMessage; // Added
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html.evaluate().getContent(), inlineImages: {logo: blob}}); // Added
}
});
And, please create a HTML file at the script editor as the filename of index.html
and copy&paste the following HTML.
- In this modified script,
CorpsMessage + '
is used as the HTML body. So if you want to modify for your actual situation, please modify this.
'logo
ofcid:logo
is corresponding tologo
ofinlineImages: {logo: blob}
.
- If the email client cannot read the HTML email, the logo is not shown. Please be careful this.
From your replying, you want to use the email template as follows.
Bonjour {Nom},
Ceci est vorte code d'identification : {ID}
Ce code devra être utillisé lors de votre examen en Iigne pour le processus : {Processus}.
Bon succés !
---
Equipe des tests en ligne
Service des Ressources Humaines
For this, how about the following modification? In this case, please modify above template as follows.
From:Equipe des tests en ligne
{LOGO}
In this modification, {LOGO}
is replaced with the logo image.
Please modify your script as follows.
From: var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
}
});
var fileId = "###"; // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob(); // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
if (check === true) {
var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
var html = CorpsMessage.replace(/\n/g, '
').replace('{LOGO}', ''); // Added
GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}}); // Modified
}
});
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install traver
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page