Changing the values of a dictionary Python - arrays

In the code below I create a dictionary 3 times and then attempt to change the value of Ontrade from True to False on Strategy 2 with the alteration function. However it does not work as expected and turns all the Ontrade values into True. How would i be able to fix that?
import numpy as np
import pprint
listrange = 5
data = {}
dict_integrity = {"Array": np.array([]), "last_timestamp": 0, "last_Trades": 0, "Order_id_list": 0, "Ontrade": False, "TakeProfits": 0, "StopLoss": 0}
for x in range(listrange):
data["Strategy " + str(x)] = dict_integrity
alteration = data["Strategy " + str(2)]["Ontrade"] = True
Output:
{'Strategy 0': {'Array': array([], dtype=float64),
'Ontrade': True,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0},
'Strategy 1': {'Array': array([], dtype=float64),
'Ontrade': True,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0},
'Strategy 2': {'Array': array([], dtype=float64),
'Ontrade': True,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0}}
Expected Output:
{'Strategy 0': {'Array': array([], dtype=float64),
'Ontrade': False,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0},
'Strategy 1': {'Array': array([], dtype=float64),
'Ontrade': False,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0},
'Strategy 2': {'Array': array([], dtype=float64),
'Ontrade': True,
'Order_id_list': 0,
'StopLoss': 0,
'TakeProfits': 0,
'last_Trades': 0,
'last_timestamp': 0}}

Related

how to sort the json array by keys in descending order using angular

var arr = {
'2021-07-20-21:10': {
sends: 1,
recvs: 1,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 0,
appErrors: 0,
responseTimeAvg: 172,
responseTimeMax: 172,
when: '21:10',
hostCount: 1,
},
'2021-07-20-21:22': {
sends: 1,
recvs: 0,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 0,
responseTimeMax: 0,
when: '21:22',
hostCount: 1,
},
'2021-07-20-21:13': {
sends: 2,
recvs: 1,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 89,
responseTimeMax: 177,
when: '21:13',
hostCount: 2,
},
'2021-07-20-21:14': {
sends: 1,
recvs: 0,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 0,
responseTimeMax: 0,
when: '21:14',
hostCount: 1,
}}
and it has to be sorted based on keys in desc order
var arr = {
'2021-07-20-21:22': {
sends: 1,
recvs: 1,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 0,
appErrors: 0,
responseTimeAvg: 172,
responseTimeMax: 172,
when: '21:22',
hostCount: 1,
},
'2021-07-20-21:14': {
sends: 1,
recvs: 0,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 0,
responseTimeMax: 0,
when: '21:14',
hostCount: 1,
},
'2021-07-20-21:13': {
sends: 2,
recvs: 1,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 89,
responseTimeMax: 177,
when: '21:13',
hostCount: 2,
},
'2021-07-20-21:10': {
sends: 1,
recvs: 0,
notSents: 0,
rejects: 0,
xptSkips: 0,
timeouts: 1,
appErrors: 0,
responseTimeAvg: 0,
responseTimeMax: 0,
when: '21:10',
hostCount: 1,
}}
You can extract the "keys" of your array using the Object.keys() function, then use the sort function to sort that array of keys, and generate a new object iterating over each keys there... Code would be (keeping arr as the name of your array):
// Get the keys of your "array"
let arrayOfKeys = Object.keys(arr)
// We sort it out...
let sortedArray = arrayOfKeys.sort()
// We will create the "final" array
let resultingArray = {}
// Now we iterate over each element, in order:
sortedArray.forEach((element) => {
resultingArray[element] = arr[element]
})
...of course this can be shortened wildly, for example:
var resultingArr = {}
Object.keys(arr).sort().forEach(e -> { resultingArr[e] = arr[e] })
EDIT: I see that you need to sort the array in descending order. This can be done using a custom sort function, or using the function reverse(). Just correct the sorting step:
// We sort it out...
let sortedArray = arrayOfKeys.sort().reverse()

Transformation of an array yields an empty placeholder

I have a numpy array called new_input_processed. The code below transforms it into a one hot array of type float32 (cf byte_list). But when I type byte_list to see the values of this array, I get an empty tensor. I would like to have a non-empty tensor instead. Is it possible ?
In [30]: new_input_processed
Out[30]:
array([[ 83, 111, 109, 101, 32, 83, 101, 113, 117, 101, 110, 99, 101,
32, 111, 102, 32, 99, 104, 97, 114, 97, 99, 116, 101, 114,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
In [31]: byte_list = tf.cast(tf.one_hot(new_input_processed, 256, 1, 0), dtype=tf.float32)
In [32]: byte_list
Out[32]: <tf.Tensor 'Cast_2:0' shape=(1, 100, 256) dtype=float32>
You are not getting an empty tensor. The Tensor object info is returned properly with:
<tf.Tensor 'Cast_2:0' shape=(1, 100, 256) dtype=float32>
Look at the shape, it is just as expected.
Nevertheless, if you want to see the content (i.e. the actual value of the byte_list Tensor object), one way is to call eval().
Something like this should do:
import numpy as np
import tensorflow as tf
new_input_processed = np.array([[ 83, 111, 109, 101, 32, 83, 101, 113, 117, 101, 110, 99, 101,
32, 111, 102, 32, 99, 104, 97, 114, 97, 99, 116, 101, 114,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
byte_list = tf.cast(tf.one_hot(new_input_processed, 256, 1, 0), dtype=tf.float32)
with tf.Session() as sess: print(byte_list.eval()) # here
Output:
[[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[1. 0. 0. ... 0. 0. 0.]
[1. 0. 0. ... 0. 0. 0.]
[1. 0. 0. ... 0. 0. 0.]]]

numpy logical.xor on a 2D array

I have a 2D numpy array with only 0 and 255 values (created from a black and white image) that i'd like to XOR with another similar 2D array.
The dtype of these arrays is uint8 and their shapes are identical.
The only information and examples i've been able to find, so far, deal with 1D arrays.
Do I need to 'flatten' these 2D arrays before XOR'ing? If so, how is that done?
numpy.logical_xor and numpy.bitwise_xor will work for 2-D arrays, as will the operators != and ^ (essentially logical and bitwise XOR, respectively).
edit: I just noticed in your title you are looking for logical XOR, but I will leave the bitwise info there for reference in case it's helpful.
Setup:
a = np.random.choice([0,255], (5,5))
b = np.random.choice([0,255], (5,5))
>>> a
array([[255, 255, 0, 255, 255],
[255, 255, 0, 255, 0],
[255, 0, 0, 0, 0],
[ 0, 255, 255, 255, 255],
[ 0, 0, 255, 0, 0]])
>>> b
array([[ 0, 255, 255, 255, 255],
[255, 0, 0, 255, 0],
[255, 0, 255, 0, 255],
[ 0, 0, 0, 0, 0],
[255, 0, 0, 0, 255]])
Logical XOR:
>>> np.logical_xor(a,b)
array([[ True, False, True, False, False],
[False, True, False, False, False],
[False, False, True, False, True],
[False, True, True, True, True],
[ True, False, True, False, True]])
# equivalently:
>>> a!=b
array([[ True, False, True, False, False],
[False, True, False, False, False],
[False, False, True, False, True],
[False, True, True, True, True],
[ True, False, True, False, True]])
Bitwise XOR:
>>> np.bitwise_xor(a,b)
array([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])
# equivalently:
>>> a^b
array([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])

NumPy Array: Minesweeper - substituting random items

I am at the beginning of an attempt to make a "minesweeper" game. I have an 8 x 8 array of 0's. I would like to substitute 8 random 0's within the array with the value 1 (to represent "mines"). I have no clue where to begin. Here is my code:
import numpy as np
import sys
import random
a = np.array([(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0)])
for random.item in a:
item.replace(1)
print(a)
row = int(input("row "))
column = int(input("column "))
print(a[row - 1, column - 1])
How do I replace 8 random 0's within the array with 1's?
Use np.random.choice without replacement option -
In [3]: a # input array of all zeros
Out[3]:
array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
# Generate unique flattened indices and on a flattened view of
# input array assign those as 1s
In [8]: a.flat[np.random.choice(a.size,8,replace=False)] = 1
# Verify results
In [9]: a
Out[9]:
array([[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])

How can I avoid duplicates in ScriptDb?

I have some objects to save in the database, but they must be unique every time the script is executed. These objects are just going to change values every instance of the application. The problem is that when I create the first object, more copies are also created every time the script is executed after that. I try to use the same object again, but when I do the query, I get objects from previous executions giving me the wrong values. I just want to be able to reset the same objects to their default values and not have many unnecessary copies in the ScriptDb.
Here is some code:
// Get a database instance
var database = getDb();
// Create a new employee instance
var myEmployee = {
element: "currentEmployee",
firstName: "",
lastName: "",
ID: 0,
manager: "",
managerEmail: "",
department: "1 - University Store",
startDate: "",
endDate: "",
regularHours: 0,
vacationHours: 0,
sickHours: 0,
personalHours: 0,
H2Hours: 0,
overtimeHours: 0,
totalHours: 0,
rowLocation: 0,
salaryType: "H",
};
var week1 = {
// Identify the week and for query purposes
element: "Week1",
// User entries
HW: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
VH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
SH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
PH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
TH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
// Calculated totals
TotalHW:0, TotalVH: 0, TotalSH: 0, TotalPH: 0, TotalHours: 0,
// Week totals
Vacation: 0, Sick: 0, Personal: 0, H2: 0, OT: 0, Regular: 0,
}
var week2 = {
// Identify the week and for query purposes
element: "Week2",
// User entries
HW: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
VH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
SH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
PH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
TH: {THUR: 0, FRI: 0, SAT: 0, SUN: 0, MON: 0, TUES: 0, WED: 0},
// Calculated totals
TotalHW:0, TotalVH: 0, TotalSH: 0, TotalPH: 0, TotalHours: 0,
// Week totals
Vacation: 0, Sick: 0, Personal: 0, H2: 0, OT: 0, Regular: 0,
}
// Save these to the database
database.save(myEmployee);
database.save(week1);
database.save(week2);
Then, I would use the statement ScriptDb.getMyDb.query({element: element}).next() to retrieve the object. The string element containing "currentEmployee", "Week1", or "Week2".
To avoid re-creating uniquely-keyed objects in ScriptDb, you must first check whether the object you're thinking of saving is already there. If it is, then you need to get the handle of the stored object to use for updates. If it's not there, you will save() your new object, and the return value will be the handle of the copy in the database.
The general pattern is this:
// Get a database instance
var db = getDb();
var result = db.query( {key:keyval, ...} );
if (result.hasNext()) {
// The object already exists in ScriptDb
var obj = result.next()
}
else {
// The object doesn't exist in ScriptDb, so create it
// This example would start by creating only the key values,
// expanding the object during the update stage below.
// Alternatively, you could create the entire object with all
// its properties.
obj = db.save({key:keyval, ...})
}
// Can now update the obj that is in ScriptDb
obj.prop1 = value1;
obj.prop2 = value2;
...
// Save updated object
db.save(obj);
Here's an example of how that pattern could apply to your code. You'll see here that the alternative approach to creating new objects is being used, in which the new object is created in ScriptDb with all its properties at once.
// Get a database instance
var database = getDb();
// Find or create employee instance
var result = database.query({element: "currentEmployee"});
if (result.hasNext()) {
var myEmployee = result.next();
} else {
myEmployee = database.save({
element: "currentEmployee",
firstName: "",
lastName: "",
ID: 0,
manager: "",
managerEmail: "",
department: "1 - University Store",
startDate: "",
endDate: "",
regularHours: 0,
vacationHours: 0,
sickHours: 0,
personalHours: 0,
H2Hours: 0,
overtimeHours: 0,
totalHours: 0,
rowLocation: 0,
salaryType: "H"
});
};
// Find or create Week1 instance
result = database.query({element: "Week1"});
if (result.hasNext()) {
var week1 = result.next();
} else {
week1 = database.save({
// Identify the week and for query purposes
element: "Week1",
// User entries
HW: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
VH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
SH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
PH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
TH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
// Calculated totals
TotalHW: 0, TotalVH: 0, TotalSH: 0, TotalPH: 0, TotalHours: 0,
// Week totals
Vacation: 0, Sick: 0, Personal: 0, H2: 0, OT: 0, Regular: 0,
});
}
// Find or create Week2 instance
result = database.query({element: "Week2"});
if (result.hasNext()) {
var week2 = result.next();
} else {
week2 = database.save({
// Identify the week and for query purposes
element: "Week2",
// User entries
HW: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
VH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
SH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
PH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
TH: {THUR: 0,FRI: 0,SAT: 0,SUN: 0,MON: 0,TUES: 0,WED: 0},
// Calculated totals
TotalHW: 0, TotalVH: 0, TotalSH: 0, TotalPH: 0, TotalHours: 0,
// Week totals
Vacation: 0, Sick: 0, Personal: 0, H2: 0, OT: 0, Regular: 0,
});
}
// At this point, myEmployee, week1 and week2 refer to the ScriptDb objects.
// While we can use them as any javascript object, they also contain information
// relevant to their state as ScriptDb objects.
...

Resources