data= pandas.read_csv(data_file_name,header=6, encoding= 'unicode_escape')
data\['Time (s)'\] = data\['Time (s)'\].replace('$', '')
time= data.iloc\[:,1\] #s
comm_T=data.iloc\[:,2\] #degC
hand_T=data.iloc\[:,3\] #degC
pyplot.plot(time,comm_T,label='Commerical Thermocouple',marker='o',linestyle='')
pyplot.plot(time,hand_T,label='Handmade Thermocouple',marker='s',linestyle='')
pyplot.xlabel('Time(s)')
pyplot.ylabel('Temperature($^\\circ$C)')
comm_T_mean=np.mean(comm_T)
comm_T_std=np.std(comm_T)
print(comm_T_mean)
print(comm_T_std)
lin_reg=scipy.stats.linregress(time.astype('float'),comm_T.astype('float'))
print (lin_reg)"
"ValueError: could not convert string to float: '00:00.0'"
The error is the time variable since is:
0 00:00.0
1 00:00.1
2 00:00.2
3 00:00.3
4 00:00.4
599 00:59.9
600 01:00.0
601 01:00.1
602 01:00.2
603 01:00.3
Name: Time (s), Length: 604, dtype: object
when I try using it in
"lin_reg=scipy.stats.linregress(time.astype('float'),comm_T.astype('float'))
I would get:
ValueError: could not convert string to float: '00:00.0'
I tried using float(time), the astype(float) I even tried to use:
data\['Time (s)'\] = data\['Time (s)'\].replace('$', '')
which supposed to allow the float, I assumed but didnt.
Pls help help me on what can be done to fix this
Related
On javascript (not using node), I am facing different results when CBOR encoding using library (https://github.com/paroga/cbor-js) and when using CBOR online (https://cbor.me/). Note that even using a more recent CBOR library, result is identical.
For instance setting an object such as :
const initial = { 1: "John", "-2": 456 };
Encoding using CBOR online gives : a201644a6f686e622d321901c8. Details are :
A2 # map(2)
01 # unsigned(1)
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
Now encoding using CBOR library on javascript gives a different result : a26131644a6f686e622d321901c8
When decoding this above Hexadecimal on CBOR online, I got : {"1": "John", "-2": 456}. Result is almost identical than the constant 'initial' except that key 1 now appears with a quote (").
CBOR online re-formats my hexadecimal value to a more 'readable' view :
A2 # map(2)
61 # text(1)
31 # "1"
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
See below my Javascript code :
//convert an array of bytes (as 8 bits) to string of Hex. ensure that Hex value are not return with 1 digit but 2 digits. ie '01' instead of '1'
function toHexString(byteArray) {
var s = '';
byteArray.forEach(function(byte) {
s += ('0' + (byte & 0xFF).toString(16)).slice(-2);
});
return s;
}
const initial = { 1: "John", "-2": 456 };
var encoded = CBOR.encode(initial);
var encodedHex = toHexString(Array.from(new Uint8Array(encoded)));
console.log ( encodedHex );
I could manually replace specific hexadecimal values such as :
'61 31 64' replaced by '01 64'
But not fancy doing it as list could be important to cover all possible options.
Does someone have a workaround as I need my result to be 'a201644a6f686e622d321901c8' and not 'a26131644a6f686e622d321901c8' ?
Object keys in Javascript
The CBOR specification, section 5.6 says:
In applications that need to interwork with JSON-based applications, conversion is simplified by limiting keys to text strings only
And indeed, the cbor-js package uses the Object.keys method here, which returns all keys as strings. Javascript does not distinguish between numbers and their string values and treats {'1':1, 1:2} as {'1':2} (whereas cbor.me treats this as a map with two entries).
Solution with a modified cbor-js
Your example suggests that you want non-negative numeric keys treated as numeric by CBOR. This can be achieved with the following patch on the cbor-js source code:
diff --git a/cbor.js b/cbor.js
--- a/cbor.js
+++ b/cbor.js
## -164,7 +164,10 ## function encode(value) {
writeTypeAndLength(5, length);
for (i = 0; i < length; ++i) {
var key = keys[i];
- encodeItem(key);
+ if (isNaN(key) || Number(key) < 0)
+ encodeItem(key);
+ else
+ encodeItem(Number(key));
encodeItem(value[key]);
}
}
With this change, Node.js gives me
> Buffer.from(cbor.encode({1:'John','-2':456})).toString('hex'))
'a201644a6f686e622d321901c8'
Or you could even treat negative numeric keys as numeric by leaving out the || Number(key) < 0 in the patch above. This gives
> Buffer.from(cbor.encode({1:'John','-2':456})).toString('hex'))
'a201644a6f686e211901c8'
A2 # map(2)
01 # unsigned(1)
64 # text(4)
4A6F686E # "John"
21 # negative(1)
19 01C8 # unsigned(456)
Solution with cbor
Unlike cbor-js, the cbor package allows you to encode a Javascript Map, which distinguishes numeric from string keys:
> Buffer.from(cbor.encode(new Map().set(1,'John').set(-2,456))).toString('hex')
'a201644a6f686e211901c8'
const id = 46919;
const string = id.toString(36); // output: "107b"
console.log(string.padStart(3, '0'));
The expected output of the console.log() would be 107 since the targetLength of method padStart() is equal to 3, but the actual output is 107b which is a total of 4 characters.
Would you know why this happens please?
Edit: I misunderstood the use of this method, I thought it would cut the extra characters like slice()
Maybe you can use parseInt() in the end of code
const id = 46919;
const string = id.toString(36);
console.log(parseInt(string.padStart(3, '0')));
//output 107
the toString(36) converts the number to base 36 from base 10, 46919 is 107b in base 36. padStart will add characters until the length is equal to the first parameter. Since 107b is already 4 characters it doesn't do anything.
I have a Number in French: a='20 000 000'. I want to to add 1 to this number and put again it in French: a='20 000 001'`
I am using in JavaScript
a=Intl.NumberFormat('fr-FR').format(parseInt(document.getElementById('lblndescargas').innerText.replaceAll(' ',''))+1)
The first time it pass through it it gives 20 000 001. But the second time it gives 21. It seems like the space is not valid as separator.
Why? One year later I make the same question.
And replaceAll( / |\s/g, '' ) doesn't work. It is strange.
Now the number is
1 136
Internally it is
1 136
I do
alert(document.getElementById(gvdeglse').innerHTML.replaceAll(/\ \;|\s/g,''))
But it doesn't work, doesn't change. Can u try it and tell me, please? Maybe it is my browser.
Thanks in advance
Something like that?
var a = '20 000 000';
// Remove all spaces and parse Int
var b = parseInt(a.replace(/\s/g,''))+1;
var c = Intl.NumberFormat('fr-FR').format(b);
console.log(c); // 200 000 001
The straightforward approach would be to convert the French string number to an integer, increment it, and then convert back:
a = '20 000 000';
console.log(a); // 20 000 000
a = parseInt(a.replace(/\s+/g, ''), 10) + 1; // 20000000 => 20000001
a = a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' '); // 20 000 001
console.log(a);
But the best practice here would be to always maintain the amount internally in your JavaScript code as an integer. Only when you want to display it using French formatting, then use the latter part of my answer (or the formatting options given in the other answers).
You could use numeral.js library in this way:
numeral.register('locale', 'fr', {
delimiters: {
thousands: ' ',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});
numeral.locale('fr');
let myNumeral = numeral("20 000 000").add(1);
console.log(myNumeral.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
I have a string in JavaScript and at some places corresponding to a regex (lower case followed by upper case), I would like to insert between upper and lower case the backspace character.
This is an example:
Manufacturer: SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels
It should become:
Manufacturer: Samsung
Warranty: 12 months
Unlocking: Any operator
Iris scanner: No
Screen size: 5.7 inches
Display resolution: 2560 x 1440 pixels
You can match on /([a-z])([A-Z])/g and replace with "$1\n\n$2", then prepend "Manufacturer: " to the beginning of the string.
const s = "SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels";
const res = "Manufacturer: " + s.replace(/([a-z])([A-Z])/g, "$1\n\n$2");
console.log(res);
I was just solving random problems on bitwise operators and trying various other combination for making personal notes. And somehow I just cannot figure out the solution.
Say I wanted to check bitwise AND between two integers or on a ~number and -negative number(~num1 & -num2) and various other combo's. Then I can see the answer but I haven't been able to establish how this happened?
Console:
console.log(25 & 3); outputs 1 (I can solve this easily).
console.log(-25 & -3); outputs-27.
Similarly
console.log(~25 & ~3); outputs -28.
console.log(25 & ~3); outputs -24.
console.log(~25 & 3); outputs -2.
console.log(~25 & -3); outputs --28.
console.log(-25 & ~3); outputs --28.
I know the logic behind "console.log(25 & -3)".
25 is 11001
-3 is 11101(3=00011 The minus sign is like 2s compliment+1)
AND-11001 = 25.
But I cannot make it work the same way when both the numbers are negative or with the other cases mentioned above. I have tried various combinations of numbers too, not just these two. But I cannot solve the problem. Can somebody explain the binary logic used in the problems I cannot solve.
(I've spend about 2 hrs here on SO to find the answer and another 1 hr+ on google, but I still haven't found the answer).
Thanks and Regards.
JavaScript specifies that bitwise operations on integers are performed as though they were stored in two's-complement notation. Fortunately, most computer hardware nowadays uses this notation natively anyway.
For brevity's sake I'm going to show the following numbers as 8-bit binary. They're actually 32-bit in JavaScript, but for the numbers in the original question, this doesn't change the outcome. It does, however, let us drop a whole lot of leading bits.
console.log(-25 & -3); //outputs -27. How?
If we write the integers in binary, we get (11100111 & 11111101) respectively. AND those together and you get 11100101, which is -27.
In your later examples, you seem to be using the NOT operator (~) and negation (-) interchangeably. You can't do that in two's complement: ~ and - are not the same thing. ~25 is 11100110, which is -26, not -25. Similarly, ~3 is 11111100, which is -4, not -3.
But when we put these together, we can work out the examples you gave.
console.log(~25 & ~3); //outputs-28. How?
11100110 & 11111100 = 11100100, which is -28 (not 28, as you wrote)
console.log(25 & ~3);//outputs-24. How?
00011001 & 11111100 = 00011000, which is 24
console.log(~25 & 3);//outputs-2. How?
11100110 & 00000011 = 00000001, which is 2
console.log(~25 & -3);//outputs--28. How?
11100110 & 11111101 = 11100100, which is -28
console.log(-25 & ~3);//outputs--28. How?
11100111 & 11111100 = 11100100, which is -28
The real key to understanding this is that you don't really use bitwise operations on integers. You use them on bags of bits of a certain size, and these bags of bits happen to be conveniently representable as integers. This is key to understanding what's going on here, because you've stumbled across a case where the difference matters.
There are specific circumstances in computer science where you can manipulate bags of bits in ways that, by coincidence, give the same results as if you'd done particular mathematical operations on numbers. But this only works in specific circumstances, and they require you to assume certain things about the numbers you're working on, and if your numbers don't fit those assumptions, things break down.
This is one of the reasons Donald Knuth said "premature optimization is the root of all evil". If you want to use bitwise operations in place of actual integer math, you have to be absolutely certain that your inputs will actually follow the assumptions required for that trick to work. Otherwise, the results will start looking strange when you start using inputs outside of those assumptions.
25 = 16+8+1 = 0b011001, I've added another 0 digit as the sign digit. Practically you'll have at least 8 binary digits
but the two's complement math is the same. To get -25 in 6-bits two's complement, you'd do -25 = ~25 + 1=0b100111
3=2+1=0b000011; -3 = ~3+1 = 0b111101
When you & the two, you get:
-25 = ~25 + 1=0b100111
&
-3 = ~3 + 1 = 0b111101
0b100101
The leftmost bit (sign bit) is set so it's a negative number. To find what it's a negative of, you reverse the process and first subtract 1 and then do ~.
~(0b100101-1) = 0b011011
thats 1+2+0*4+8+16 = 27 so -25&-3=-27.
For 25 & ~3, it's:
25 = 16+8+1 = 0b011001
& ~3 = 0b111100
______________________
0b011000 = 24
For ~25 & 3, it's:
~25 = 0b100110
& ~3 = 0b000011
______________________
0b000010 = 2
For ~25 & -3, it's:
~25 = 0b100110
& ~3+1 = 0b111101
______________________
0b100100 #negative
#find what it's a negative of:
~(0b100100-1) =~0b100011 = 0b011100 = 4+8+16 = 28
0b100100 = -28
-27 has 6 binary digits in it so you should be using numbers with at least that many digits. With 8-bit numbers then we have:
00011001 = 25
00000011 = 3
00011011 = 27
and:
11100111 = -25
11111101 = -3
11100101 = -27
Now -25 & -3 = -27 because 11100111 & 11111101 = 11100101
The binary string representation of a 32 bit integer can be found with:
(i >>> 0).toString(2).padStart(32, '0')
The bitwise anding of two binary strings is straightforward
The integer value of a signed, 32 bit binary string is either
parseInt(bitwiseAndString, 2)
if the string starts with a '0', or
-~parseInt(bitwiseAndString, 2) - 1
if it starts with a '1'
Putting all that together:
const tests = [
['-25', '-3'],
['~25', '-3'],
['25', '~3'],
['~25', '3'],
['~25', '~3'],
['-25', '~3']
]
const output = (s,t) => { console.log(`${`${s}:`.padEnd(20, ' ')}${t}`); }
const bitwiseAnd = (i, j) => {
console.log(`Calculating ${i} & ${j}`);
const bitStringI = (eval(i) >>> 0).toString(2).padStart(32, '0');
const bitStringJ = (eval(j) >>> 0).toString(2).padStart(32, '0');
output(`bit string for ${i}`, bitStringI);
output(`bit string for ${j}`, bitStringJ);
const bitArrayI = bitStringI.split('');
const bitArrayJ = bitStringJ.split('');
const bitwiseAndString = bitArrayI.map((s, idx) => s === '1' && bitArrayJ[idx] === '1' ? '1' : '0').join('');
output('bitwise and string', bitwiseAndString);
const intValue = bitwiseAndString[0] === '1' ? -~parseInt(bitwiseAndString, 2) - 1 : parseInt(bitwiseAndString, 2);
if (intValue === (eval(i) & eval(j))) {
console.log(`integer value: ${intValue} ✓`);
} else {
console.error(`calculation failed: ${intValue} !== ${i & j}`);
}
}
tests.forEach(([i, j]) => { bitwiseAnd(i, j); })