Not sure how LoadItems work in the React-Native-Calendars example - react-native

I'm trying to use the react-native-calendars library in my code.
I'm trying to understand this snipped of the code here
loadItems = (day: DateData) => {
const items = this.state.items || {};
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = this.timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: 'Item for ' + strTime + ' #' + j,
height: Math.max(50, Math.floor(Math.random() * 150)),
day: strTime
});
}
}
}
const newItems: AgendaSchedule = {};
Object.keys(items).forEach(key => {
newItems[key] = items[key];
});
this.setState({
items: newItems
});
}, 1000);
}
The entire code snip can be found here: https://gist.github.com/jonasgroendahl/f5e938cdf0a77c2e1509ded22630ba7d
Currently I know this part of the code generates an item for everyday. I'm looking to change this up but I'm not sure what happening line by line. If anyone can please break this down and explain it to me would be great. Thanks.

Related

getDisplayMedia force "Stop Sharing" [duplicate]

This question already has answers here:
MediaRecorder.stop() doesn't clear the recording icon in the tab
(2 answers)
Closed 4 months ago.
This has been racking my brain for a week.
I have getDisplayMedia working just fine, however I want to turn off the "sharing permission" after recording has been stopped.
I've seen this work here:
https://www.webrtc-experiment.com/RecordRTC/
Set the form to record the Full Screen
Start recording
Stop recording
You will see the "permission dialog" disappear.
How can I programmatically do this?
Current Code:
recBtn.onclick = () => {
stopBtn.disabled = false;
recBtn.disabled = true;
limRange.disabled = true;
navigator.mediaDevices
.getDisplayMedia ({
audio: {
sampleRate: 44100,
echoCancellation: false,
noiseSuppression: false
},
video: { mediaSource: "screen" },
})
.then ( ( stream ) =>
{
mediaRecorder = new MediaRecorder( stream );
//music.play();
mediaRecorder.addEventListener("dataavailable", (e) =>
{
// manage timer
if ( seconds >= 60 ) {
seconds = 0;
minutes += 1;
}
seconds += 1;
if ( minutes > 9 && seconds > 9 )
{
p.innerHTML = minutes + ":" + seconds;
}
else if ( minutes > 9 )
{
p.innerHTML = minutes + ":0" + seconds;
}
else if ( seconds > 9 )
{
p.innerHTML = "0" + minutes + ":" + seconds;
}
else {
p.innerHTML = "0" + minutes + ":0" + seconds;
}
// push data
chunks.push(e.data);
});
mediaRecorder.onstop = ( e ) =>
{
//console.log( chunks );
const blob = new Blob( chunks , { type: "audio/mp3" });
//console.log( minutes, seconds );
var offlineAudioContext = new OfflineAudioContext (
2,
44100 * ((minutes * 60) + seconds),
44100
);
var soundSource = offlineAudioContext.createBufferSource();
var audioContext = new window.AudioContext();
var reader = new FileReader();
var buff;
reader.readAsArrayBuffer(blob); // video file
reader.onload = function ()
{
var videoFileAsBuffer = reader.result; // arraybuffer
audioContext
.decodeAudioData(videoFileAsBuffer)
.then( function ( decodedAudioData )
{
myBuffer = decodedAudioData;
soundSource.buffer = myBuffer;
soundSource.connect(offlineAudioContext.destination);
soundSource.start();
offlineAudioContext
.startRendering()
.then( function ( renderedBuffer )
{
console.log(renderedBuffer); // outputs audiobuffer
buff = renderedBuffer;
let wav = audioBufferToWav(buff);
console.log(wav);
let bblob = new window.Blob([new DataView(wav)], {
type: "audio/mp3",
});
const audioURL = URL.createObjectURL(bblob);
audioRecorded.src = audioURL;
/*const fileName =
"recording-" +
recs +
"-" +
minutes +
"_" +
seconds +
".mp3";*/
var fileName = "Block " + block_letter.toUpperCase() + " - " + block_filename + '.mp3';
let elm = document.createElement("a");
elm.id = 'download-mp3'
elm.setAttribute("href", audioRecorded.src);
elm.setAttribute("download", fileName);
//elm.click();
//elm.remove();
$('.download-link').html( elm );
$('#download-mp3').html( fileName ).addClass('text-4 text-primary font-weight-semi-bold');
$('.recording-link').show();
$('.recording-info').hide();
minutes = 0;
seconds = 0;
})
.catch(function (err) {
console.log("Rendering failed: " + err);
});
})
.catch(function (err) {
console.log("audioContext failed: " + err);
});
};
console.log("recorder stopped");
chunks = [];
p.innerHTML = "00:00";
if (recs == 0)
{
document.body.appendChild(audioRecorded);
}
recs += 1;
$('#btn-record, .btn-block-stop, .modal-btn-right').show();
$('#btn-record-stop, .recording-inprogress').hide();
$('.btn-block-stop').click();
};
mediaRecorder.start(1000);
$('.ajax-modal-btn-right').click();
$('#btn-record, .btn-block-stop, .modal-btn-right').hide();
$('#btn-record-stop, .recording-inprogress').show();
//console.log(mediaRecorder.state);
//console.log("recorder started");
})
.catch ( (error) =>
{
console.log ('error');
});
};
stopBtn.onclick = () =>
{
recBtn.disabled = false;
limRange.disabled = false;
stopBtn.disabled = true;
mediaRecorder.stop( 5000 );
console.log("recording stopped");
$('#btn-record, .btn-block-stop, .modal-btn-right').show();
$('#btn-record-stop, .recording-inprogress').hide();
$('.btn-block-stop').click();
};
The media permissions settings are not accessible from Javascript code. They just aren't, so it's no wonder you can't find them. Because cybercreeps could trick our users into revealing sensitive information.
It's a real pain in the neck, but it works the same for everybody from Google Meet on down.

Expand Text of Compact Data

I am stuck with some data manipulation.
This is a small portion of the input data (df):
site=c("C000-C002","C420-C421,C424")
histology=c("9835-9836","9811-9812,9837")
category=c("Leukemia","Leukemia")
df=data.frame(site,histology,category)
And this is what I want the processed data to look like:
You may assume Site and Histology are both 4-digit after text splitting.
In case anyone is interested, the full data table is here
Please help with the text processing, or if anyone knows an existing processed package or database in a similar format as the image, that would be great too.
Thank you very much.
I don't know R language. So I tried with Javascript as following.
function mapStartEnd(start, end) {
let list = [];
let info = {};
const siteStart = start.match(/([A-Z])(\d{3})/);
if (siteStart) {
const siteEnd = end.match(/([A-Z])(\d{3})/);
info = {
type: "site",
prefix: siteStart[1],
numLength: 3,
from: parseInt(siteStart[2], 10),
to: parseInt(siteEnd[2], 10),
};
}
const histologyStart = start.match(/\d{4}/);
if (histologyStart) {
const histologyEnd = end.match(/\d{4}/);
info = {
type: "histology",
prefix: "",
numLength: 4,
from: parseInt(histologyStart[0], 10),
to: parseInt(histologyEnd[0], 10),
};
}
const categoryStart = start.match(/[A-Z][a-z]+/);
if (categoryStart) {
const categoryEnd = end.match(/[A-Z][a-z]+/);
info = {
type: "category",
prefix: "",
numLength: 0,
from: categoryStart[0],
to: categoryEnd[0],
};
}
if (!info.numLength) {
list = [info.from, info.to];
} else {
for (let i = info.from; i <= info.to; i++) {
list.push(info.prefix + i.toString().padStart(info.numLength, "0"));
}
}
return list;
}
function c(list) {
return list.map((list2) => {
return list2.split(",").reduce((prev, cur) => {
const [start, end] = cur.split("-");
if (!end) prev.push(start);
else prev = [...prev, ...mapStartEnd(start, end)];
return prev;
}, []);
});
}
function map3(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
for (let j = 0; j < histologys.length; j++) {
const histology = histologys[j];
for (let k = 0; k < categorys.length; k++) {
const category = categorys[k];
// JSON format
// list.push({ site, histology, category });
// CSV format
list.push(`${site},${histology},${category}`);
}
}
}
return list;
}
function frame(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
const histology = histologys[i];
const category = categorys[i];
list = [...list, ...map3(site, histology, category)];
}
return list;
}
const site = c(["C000-C002", "C420-C421,C424"]);
const histology = c(["9835-9836", "9811-9812,9837"]);
const category = c(["Leukemia", "Leukemia"]);
const df = frame(site, histology, category);
console.log(df);
Result:
[
"C000,9835,Leukemia",
"C000,9836,Leukemia",
"C001,9835,Leukemia",
"C001,9836,Leukemia",
"C002,9835,Leukemia",
"C002,9836,Leukemia",
"C420,9811,Leukemia",
"C420,9812,Leukemia",
"C420,9837,Leukemia",
"C421,9811,Leukemia",
"C421,9812,Leukemia",
"C421,9837,Leukemia",
"C424,9811,Leukemia",
"C424,9812,Leukemia",
"C424,9837,Leukemia"
]
https://jsfiddle.net/dnu2g0vr/

How could I change the value of this.buttonState in this scenary?

I'm having issues in this process . First is that I have a button in disabled state(true) and I need to change that value to false when the video is uploaded . I have this scenary and I think I got a windows object inside the changing method . Any idea, help please . I'm getting undefined value for the variable.
data: () => ({
buttonState: true} }),
changeBehavior() {
let self
(function () {
const input = document.getElementById('uploader')
self = this
console.log(this)
const changing = ({ target: { files } }) => {
if (input.files.length > 0) {
// self.buttonState = false
const video = document.getElementById('output-video')
video.src = URL.createObjectURL(files[0])
}
}
input.addEventListener('change', changing)
})()
const au = document.getElementById('output-video')
au.onloadedmetadata = () => {
const hidden = document.getElementById('hiddenSlider')
hidden.removeAttribute('hidden')
const muteHidden = document.getElementById('muteHidden')
muteHidden.removeAttribute('hidden')
self = this
self.range = [0, au.duration]
this.max = au.duration
const secNum = parseInt(au.duration, 10)
let hours = Math.floor(secNum / 3600)
let minutes = Math.floor((secNum - (hours * 3600)) / 60)
let seconds = secNum - (hours * 3600) - (minutes * 60)
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
if (seconds < 10) {
seconds = '0' + seconds
}
document.getElementById('renderizado').innerHTML =
hours + ':' + minutes + ':' + seconds
}
},
<v-btn
id="run"
class="accent-3 blue ml-15"
dark
#click="$refs.inputUpload.click()"
>
<input
v-show="false"
id="uploader"
ref="inputUpload"
accept=".mkv,video/*"
type="file"
#click="changeBehavior"
>
Select to Upload Video
</v-btn>
<v-btn
id="doTrimming"
block
class="accent-3 blue mt-5"
dark
:disabled="buttonState"
#click="cutIt"
>
Trim Video Now
</v-btn>
Where you define self you need to assign this to it then.
changeBehavior() {
const self = this;
const callback = function() {
// now you can access the vue instance when in another functions scope
self.buttonState = true;
}
}

how to execute a function after end another in react native?

I have a query that I have a function which response to a server, so it takes a while and when it tries to execute the other function, an error occurs. Since the function responds an array from which comes from the server and when the other function requests that, even It does not have. Have to solve this. example :
responseServer(tarea) {
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ refresh: false })
global.refresh = false
let data = [];
let Milestone = [];
Object.values(responseJson.summary).forEach(item => {
data = data.concat(item);
});
const result = ["Milestone"]
.reduce((total, category) => ({
...total,
[category]: data.filter(line => line.includes(category))
}), {})
Object.values(result.Milestone).forEach(item => {
Milestone = Milestone.concat(item)
});
this.setState({
Milestone: Milestone
})
})
}
and another function
sacarPorcentaje(item) {
this.responseServer(item)
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
You should update sacarPorcentaje() to async function. then await the function call, will resolve your issue
async sacarPorcentaje (item) {
await this.responseServer(item)
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
There is also one more solution for this issue. please search how to use Promise in JS
I think you need to use then when you call responseServer function in sacarPorcentaje function.
sacarPorcentaje(item) {
this.responseServer(item).then(() => {
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
}

Ripple exchanges websocket equivalent for ripple data apiv2

I'm trying to get the exchanges in ripple and I found this data API and its working. But I want to use the ripple websocket tool for some reasons. Is there any websocket equivalent for this data API?
I think there is equivalent if you use "tx_history" command in the socket but Sorry to tell you that the json result are not equal to your specific data result.
ripple data apiv2 is being played by ajax. see the result json formatter in ripple for exchange:
} else if (resp.rows.length) {
resp.rows[0] = {
base_currency: resp.rows[0].base_currency,
base_issuer: resp.rows[0].base_issuer,
base_amount: resp.rows[0].base_amount,
counter_amount: resp.rows[0].counter_amount,
counter_currency: resp.rows[0].counter_currency,
counter_issuer: resp.rows[0].counter_issuer,
rate: resp.rows[0].rate,
executed_time: resp.rows[0].executed_time,
ledger_index: resp.rows[0].ledger_index,
buyer: resp.rows[0].buyer,
seller: resp.rows[0].seller,
taker: resp.rows[0].taker,
provider: resp.rows[0].provider,
autobridged_currency: resp.rows[0].autobridged_currency,
autobridged_issuer: resp.rows[0].autobridged_issuer,
offer_sequence: resp.rows[0].offer_sequence,
tx_type: resp.rows[0].tx_type,
tx_index: resp.rows[0].tx_index,
node_index: resp.rows[0].node_index,
tx_hash: resp.rows[0].tx_hash
};
}
res.csv(resp.rows, filename);
} else {
res.json({
result: 'success',
count: resp.rows.length,
marker: resp.marker,
exchanges: resp.rows
});
} }
and it can be only access by get url :
route: '/v2/exchanges/{:base}/{:counter}'
that is bind in there server.js:
app.get('/v2/exchanges/:base/:counter', routes.getExchanges);
and last hint this is their database query using hbase:
HbaseClient.getExchanges = function (options, callback) {
var base = options.base.currency + '|' + (options.base.issuer || '');
var counter = options.counter.currency + '|' + (options.counter.issuer
||''); var table;
var keyBase;
var startRow;
var endRow;
var descending;
var columns;
if (counter.toLowerCase() > base.toLowerCase()) {
keyBase = base + '|' + counter;
} else {
keyBase = counter + '|' + base;
options.invert = true; }
if (!options.interval) {
table = 'exchanges';
descending = options.descending ? true : false;
options.unreduced = true;
//only need certain columns
if (options.reduce) {
columns = [
'd:base_amount',
'd:counter_amount',
'd:rate',
'f:executed_time',
'f:buyer',
'f:seller',
'f:taker'
];
}
} else if (exchangeIntervals.indexOf(options.interval) !== -1) {
keyBase = options.interval + '|' + keyBase;
descending = options.descending ? true : false;
table = 'agg_exchanges';
} else {
callback('invalid interval: ' + options.interval);
return; }
startRow = keyBase + '|' + options.start.hbaseFormatStartRow();
endRow = keyBase + '|' + options.end.hbaseFormatStopRow();
if (options.autobridged) {
options.filterstring = "DependentColumnFilter('f', 'autobridged_currency')";
if (columns) {
columns.push('f:autobridged_currency');
} }
this.getScanWithMarker(this, {
table: table,
startRow: startRow,
stopRow: endRow,
marker: options.marker,
limit: options.limit,
descending: descending,
columns: columns,
filterString: options.filterstring }, function (err, resp) {
if (!resp) {
resp = {rows: []};
}
if (!resp.rows) {
resp.rows = [];
}
if (options.reduce && options.unreduced) {
if (descending) {
resp.rows.reverse();
}
resp.reduced = reduce(resp.rows);
} else if (table === 'exchanges') {
resp.rows = formatExchanges(resp.rows);
} else {
resp.rows = formatAggregates(resp.rows);
}
callback(err, resp); });
/** * formatExchanges */
function formatExchanges (rows) {
rows.forEach(function(row) {
var key = row.rowkey.split('|');
delete row.base_issuer;
delete row.base_currency;
delete row.counter_issuer;
delete row.counter_currency;
row.base_amount = parseFloat(row.base_amount);
row.counter_amount = parseFloat(row.counter_amount);
row.rate = parseFloat(row.rate);
row.offer_sequence = Number(row.offer_sequence || 0);
row.ledger_index = Number(row.ledger_index);
row.tx_index = Number(key[6]);
row.node_index = Number(key[7]);
row.time = utils.unformatTime(key[4]).unix();
});
if (options.invert) {
rows = invertPair(rows);
}
return rows; }
/** * formatAggregates */
function formatAggregates (rows) {
rows.forEach(function(row) {
var key = row.rowkey.split('|');
row.base_volume = parseFloat(row.base_volume),
row.counter_volume = parseFloat(row.counter_volume),
row.buy_volume = parseFloat(row.buy_volume),
row.count = Number(row.count);
row.open = parseFloat(row.open);
row.high = parseFloat(row.high);
row.low = parseFloat(row.low);
row.close = parseFloat(row.close);
row.vwap = parseFloat(row.vwap);
row.close_time = Number(row.close_time);
row.open_time = Number(row.open_time);
});
if (options.invert) {
rows = invertPair(rows);
}
return rows; }
/** * if the base/counter key was inverted, we need to swap * some of the values in the results */
function invertPair (rows) {
var swap;
var i;
if (options.unreduced) {
for (i=0; i<rows.length; i++) {
rows[i].rate = 1/rows[i].rate;
//swap base and counter vol
swap = rows[i].base_amount;
rows[i].base_amount = rows[i].counter_amount;
rows[i].counter_amount = swap;
//swap buyer and seller
swap = rows[i].buyer;
rows[i].buyer = rows[i].seller;
rows[i].seller = swap;
}
} else {
for (i=0; i<rows.length; i++) {
//swap base and counter vol
swap = rows[i].base_volume;
rows[i].base_volume = rows[i].counter_volume;
rows[i].counter_volume = swap;
//swap high and low
swap = 1/rows[i].high;
rows[i].high = 1/rows[i].low;
rows[i].low = swap;
//invert open, close, vwap
rows[i].open = 1/rows[i].open;
rows[i].close = 1/rows[i].close;
rows[i].vwap = 1/rows[i].vwap;
//invert buy_volume
rows[i].buy_volume /= rows[i].vwap;
}
}
return rows; }
/** * reduce * reduce all rows */
function reduce (rows) {
var buyVolume = 0;
var reduced = {
open: 0,
high: 0,
low: Infinity,
close: 0,
base_volume: 0,
counter_volume: 0,
buy_volume: 0,
count: 0,
open_time: 0,
close_time: 0
};
rows = formatExchanges(rows);
// filter out small XRP amounts
rows = rows.filter(function(row) {
if (options.base.currency === 'XRP' && row.base_amount < 0.0005) {
return false;
} else if (options.counter.currency === 'XRP' && row.counter_amount < 0.0005) {
return false;
} else {
return true;
}
});
if (rows.length) {
reduced.open_time = moment.unix(rows[0].time).utc().format();
reduced.close_time = moment.unix(rows[rows.length-1].time).utc().format();
reduced.open = rows[0].rate;
reduced.close = rows[rows.length -1].rate;
reduced.count = rows.length;
} else {
reduced.low = 0;
return reduced;
}
rows.forEach(function(row) {
reduced.base_volume += row.base_amount;
reduced.counter_volume += row.counter_amount;
if (row.rate < reduced.low) reduced.low = row.rate;
if (row.rate > reduced.high) reduced.high = row.rate;
if (row.buyer === row.taker) {
reduced.buy_volume += row.base_amount;
}
});
reduced.vwap = reduced.counter_volume / reduced.base_volume;
return reduced; } };
Maybe you should make a custom websocket that make your RPC call upgrade to 1.1 http protocol (ws).
In nodejs you can simply
// for http
var http = require('http');
// for websocket
var ws = require("nodejs-websocket")
var options = {
host: 'URL-RPC-HERE',
port: '80',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var req = http.request(options, function(res) {
// after getting the response wich is the <res>
// we can upgrade it to ws
upToWebsocket(res);
});
//Upgrade to websocket
var upToWebsocket = function(json) {
var server = ws.createServer(function (conn) {
conn.on("json", function (str) {
conn.sendText(str.toUpperCase()+"!!!")
})
conn.on("close", function (code, reason) {
console.log("Connection closed")
})
}).listen(8001)
}
And also if you have Rippled running on a server this does not help because there's no RPC or WS that supports exchange API.