Related
I wanted to modify the response for array of object.
I have below result.
And i wanted to change the response to specific response.
let result = [
{
team_id: 1,
team_name: 'Avengers',
participant1: 98,
participant2: 99,
participant3: 100,
participant4: 101,
phase1: 0,
phase2: 0,
phase3: 0,
phase4: 0,
phase5: 0,
participant1_name: 'test 1003',
participant2_name: 'test 1002',
participant3_name: 'test 1004',
participant4_name: 'test 1005'
}
]
And wanted to convert to below.
[
{
"team_id": 1,
"team_name": "Avengers",
"phase1": 0,
"phase2": 0,
"phase3": 0,
"phase4": 0,
"phase5": 0,
"participantDetails": [
{
"participant1": 98,
"participant1_name": "test 1003"
},
{
"participant2": 99,
"participant2_name": "test 1002"
},
{
"participant3": 100,
"participant3_name": "test 1004"
},
{
"participant4": 101,
"participant4_name": "test 1005"
}
]
}
]
I have tried below: -
const data = result.map((elem) => {
const participantDetails = [];
for (let keys in elem) {
if (keys.startsWith('participant')) {
console.log('elem:-',elem);
participantDetails.push({
[keys]: elem[keys]
})
delete elem[keys]
}
}
return {
...elem,
participantDetails: participantDetails
}
});
I have filter participant but not sure how to filter names also.
And they are having different positions for that.
Please help thanks in advance.
You're already in the right direction. You don't have to filter for participant names since you can easily derive them once you filtered the participant.
Here's my approach:
let result = [
{
team_id: 1,
team_name: 'Avengers',
participant1: 98,
participant2: 99,
participant3: 100,
participant4: 101,
phase1: 0,
phase2: 0,
phase3: 0,
phase4: 0,
phase5: 0,
participant1_name: 'test 1003',
participant2_name: 'test 1002',
participant3_name: 'test 1004',
participant4_name: 'test 1005',
},
];
for (let obj of result) {
let participantDetails = [];
Object.keys(obj)
.filter((key) => /^participant\d+$/.test(key))
.forEach((key) => {
participantDetails.push({
[key]: obj[key],
[`${key}_name`]: obj[`${key}_name`],
});
delete obj[key];
delete obj[`${key}_name`];
});
obj.participantDetails = participantDetails;
}
console.log(JSON.stringify(result, null, 4));
Notice that I used regex to filter strictly on participant. From there, I can derive the values for participant_names and push them into the participantDetails array.
It is also important to note that you are modifying the values of the result array. If you want to keep those values, you can use map instead to create a new instance of the array.
Can any one have solution for this, i want there should be api data in this manner ??
I wanted api data in for similar state comes in one hood rather than seprate, different state data can be different obj,
data = [{
state_name:New_jersi, data:{
category:Phishing,
sub_cat_data:[{
name:SubCat1,
count:20
},
{
name:SubCat2,
count:30
}]
}
category: malware,
sub_cat_data:[{
name:SubCat1,
count:20
},
{
name:SubCat2,
count:30
}]
},
{
state_name:Washinton, data:{
category:Phishing,
data:[{
name:SubCat1,
count:20
},
{
name:SubCat2,
count:30
}]
}
}]
But may api response be:
{
"state": "South Carolina",
"state_count": 2,
"Website Compromise/Intrusion": {
"sub_category": {
"Insecure Direct Object Reference": 2,
"Memory Corruption": 2,
"SQLI": 1,
"Stack Overflow": 1,
"XSRF": 1,
"Heap Overflow": 1,
"Security Misconfiguration": 1
}
}
},
{
"state": "South Carolina",
"state_count": 1,
"Phishing": {
"sub_category": {
"Spear Phishing Attacks": 2,
"Fast Flux": 2,
"Rock fish": 2,
"Identify Theft/Social Engineering": 1,
"Phishing Redirector": 1,
"Pharming": 1,
"Exploitation of Hardware Vulnerability": 1
}
}
},
i wanted same state data be in same object buut in my case state data comes in seprate object because of data comes through category, rather that seprate.
My logic are below
cat_count = incnum.values('incident_category__cat_name','incident_category__cat_id').annotate(count=Count('incident_category__cat_id'))
subcat_count = incnum.values('incident_sub_category__sub_cat_name','incident_sub_category__cat_id','incident_sub_category__id').annotate(count=Count('incident_sub_category__cat_id'))
reporter_state_count1 = incnum.values('incident_category__cat_id','reporter__comp_individual_state','reporter__comp_individual_state__name').annotate(count=Count('incident_category__cat_id'))
for x, state_ in enumerate(reporter_state_count1):
for i, cat_ in enumerate(cat_count):
if state_['incident_category__cat_id'] == cat_['incident_category__cat_id']:
for i, cat_ in enumerate(cat_count):
if state_['incident_category__cat_id'] == cat_['incident_category__cat_id']:
arr16.append({'state':state_['reporter__comp_individual_state__name'], 'state_count':state_['count'], cat_['incident_category__cat_name']:{'sub_category':{}}})
for sub_ in subcat_count:
if cat_['incident_category__cat_id'] == sub_['incident_sub_category__cat_id']:
arr16[i][cat_['incident_category__cat_name']]['sub_category'].update({sub_['incident_sub_category__sub_cat_name']:sub_['count']})
cat_count = incnum.values('incident_category__cat_name', 'incident_category__cat_id').annotate(
count=Count('incident_category__cat_id'))
subcat_count = incnum.values('incident_sub_category__sub_cat_name', 'incident_sub_category__cat_id',
'incident_sub_category__id').annotate(count=Count('incident_sub_category__cat_id'))
reporter_state_count1 = incnum.values('incident_category__cat_id', 'reporter__comp_individual_state',
'reporter__comp_individual_state__name').annotate(
count=Count('incident_category__cat_id'))
arr16 = []
for state_ in reporter_state_count1:
state_data = {"state_name" : state_['reporter__comp_individual_state__name'], "data":[]}
for cat_ in cat_count:
if state_['incident_category__cat_id'] == cat_['incident_category__cat_id']:
sub_cat_data = [{sub_['incident_sub_category__sub_cat_name']: sub_['count']} for sub_ in subcat_count if cat_['incident_category__cat_id'] == sub_['incident_sub_category__cat_id']]
category_data = {"category": cat_['incident_category__cat_name'], "sub_cat_data": sub_cat_data}
state_data["data"].append(category_data)
arr16.append(state_data)
1 State might have multiple category, the way you are trying to make your api, it won't be able to show multiple category for a state. This is why i modify a little bit. you will find all the category in state object
Edit
Creating a dictionary which will store category_id as key and all the subcategory of that category as value
cat_to_subcat_list = {}
for cat_ in cat_count:
sub_cat_data = [{"name":sub_['incident_sub_category__sub_cat_name'],"count": sub_['count']} for sub_ in subcat_count if
cat_['incident_category__cat_id'] == sub_['incident_sub_category__cat_id']]
cat_to_subcat_list[cat_['incident_category__cat_id']] = {"category": cat_['incident_category__cat_name'], "sub_cat_data": sub_cat_data}
Createing a dictionary which will store state__name as key and a list of category object will save as value
state_data = {}
for state_ in reporter_state_count1:
if state_['reporter__comp_individual_state__name'] not in state_data:
'''This if statement is checking whether state_name exit or not.
if state_name does not exist in dictionary it'll create a empty list as it's value'''
state_data[state_['reporter__comp_individual_state__name']] = []
state_data[state_['reporter__comp_individual_state__name']].append(cat_to_subcat_list[state_['incident_category__cat_id']])
Re-formatting json as api needed
arr16 = [
{
"state_name": state_name,
"data": state_data
}for state_name, state_data in state_data.items()
]
I'm in the middle of developing an app using node.js. my database is PostgreSQL. I tried to create a temporary table and then update my main table with that temporary table. the reason is that i have many records and data that must update every second. i know that one of the must efficient way is that first create a temp table by your data and then update main table with temporary table.
i create temp table successfully but when i try to update my main table i catch "No operator matches the given name and argument types. You might need to add explicit type casts" error.
anybody can help me or hint me how i can solve this problem?
my temporary creation sql is :
CREATE TEMP TABLE temp_binance_tradika_signals
(id, thpars_dati, thpars_vise, thpars_aipi, thpars_code, thpars_site, thpars_owne, thpars_list, thpars_prio, signal_state, signal_date, signal_account, signal_exchange, signal_abbrev, signal_id, signal_uid, signal_andis, signal_coin, signal_base, signal_symbol, signal_side, signal_step_log, signal_step_update, signal_lotstep, signal_lotint_step, signal_pricetick, signal_priceint_tick, signal_time_init, signal_date_alive, signal_dca_buy, signal_dca_sell, signal_amount_type, signal_score, open_percent, open_price, open_amount, open_date, open_trigger, open_prv_abbrev, open_prv_title, open_prv_code, close_percent, close_price, close_amount, close_date, close_trigger, close_period, close_result, close_prv_abbrev, close_prv_title, close_prv_code, price_latest_percent, price_latest_price, price_higest_percent, price_higest_price, price_lowest_percent, price_lowest_price, point_buy_percent, point_buy_price, point_buy_amount, point_buy_date, point_buy_lifelong, point_buy_lifetime, point_buy_bool, point_sell_percent, point_sell_price, point_sell_amount, point_sell_date, point_sell_lifelong, point_sell_lifetime, point_sell_bool, point_place_percent, point_place_price, point_eject_percent, point_eject_price, point_stoploss_percent, point_stoploss_price, point_stoploss_bool, point_expire_percent, point_expire_price, point_expire_bool, point_expire_date, point_expire_duration) AS
VALUES
('100100104895', '2021-07-08 22:59:15', null, null, null, null, null, null, null, 'ALIVE', '2021-07-08 22:59:08', 'Tradika.net', 'Binance', 'SL', 'JIMP_20210708225908_KEYUSDT', 'JIMP_20210708225908_KEYUSDT_SL', 'KEYUSDT_SL', 'KEY', 'USDT', 'KEYUSDT', 'Buy', 0.5, 0.1, 1, 0, 0.000001, 6, 60, '2021-07-08 23:00:15', 0.6, 0.6, null, 1, 0, 0.007369, null, '2021-07-08 22:59:15', 'SIGNAL', 'JIMP', 'Jim Panda Signals', 441, null, null, null, null, null, null, null, null, null, null, 0, 0.007369, 0, 0.007369, 0, 0.007369, -2.5, 0.007185, '1795', null, 600, null, null, -1, 0.007296, null, null, 43200, null, null, -2.3, 0.0072, -2.1, 0.007215, -6, 0.006927, null, 0.25, 0.007388, null, null, 345600),
('100100104896', '2021-07-08 22:59:15', null, null, null, null, null, null, null, 'ALIVE', '2021-07-08 22:59:08', 'Parsika.net', 'Binance', 'MP', 'JIMP_20210708225908_KEYUSDT', 'JIMP_20210708225908_KEYUSDT_MP', 'KEYUSDT_MP', 'KEY', 'USDT', 'KEYUSDT', 'Buy', 1, 0.2, 1, 0, 0.000001, 6, 100, '2021-07-08 23:00:55', 1, 1, null, 1, 0, 0.007369, null, '2021-07-08 22:59:15', 'SIGNAL', 'JIMP', 'Jim Panda Signals', 441, null, null, null, null, null, null, null, null, null, null, 0, 0.007369, 0, 0.007369, 0, 0.007369, -10, 0.006633, '1944', null, 600, null, null, -4, 0.007075, null, null, 86400, null, null, -9, 0.006706, -8.5, 0.006743, -15, 0.006264, null, 0.25, 0.007388, null, null, 345600)
;
and my update SQL from temporary table is :
UPDATE binance_tradika_signals
SET
signal_state = t.signal_state,
price_latest_price = t.price_latest_price
FROM temp_binance_tradika_signals t
WHERE t.id = binance_tradika_signals.id;
any help will be really appreciated.
The solution is :
id must present as integer not string.
the first row data of insert into temp table specify the datatype. so for example if you insert signal_step_log into temp table as JSON datatype, if you define this row as Varchar, int, Bool etc .... you will get an error.
Hope this will be useful.
Is there any approach to use Fabric.js and Redux together? Fabric.js state should be used as part of store, but it isn't immutable and can mutate itself by user canvas interaction. Any idea? Thanks.
I have extracted small example from my implementation of React-Redux and Fabric.js.
It works by simply getting whole fabric object by fabric.toObject(), saving it into state and revoking by fabric.loadFromJSON(). You can play around by using Redux DevTools and traveling through the state.
For any case, there is also jsfiddle available: https://jsfiddle.net/radomeer/74t5y1r0/
// don't be scared, just some initial objects to play with (fabric's serialized JSON)
const initialState = {
canvasObject: {
"objects": [{
"type": "circle",
"originX": "center",
"originY": "center",
"left": 50,
"top": 50,
"width": 100,
"height": 100,
"fill": "#FF00FF",
"stroke": null,
"strokeWidth": 1,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeLineJoin": "miter",
"strokeMiterLimit": 10,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"clipTo": null,
"backgroundColor": "",
"fillRule": "nonzero",
"globalCompositeOperation": "source-over",
"transformMatrix": null,
"radius": 50,
"startAngle": 0,
"endAngle": 6.283185307179586
}, {
"type": "rect",
"originX": "center",
"originY": "center",
"left": 126,
"top": 210,
"width": 100,
"height": 100,
"fill": "#FF0000",
"stroke": null,
"strokeWidth": 1,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeLineJoin": "miter",
"strokeMiterLimit": 10,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"clipTo": null,
"backgroundColor": "",
"fillRule": "nonzero",
"globalCompositeOperation": "source-over",
"transformMatrix": null,
"radius": 50,
"startAngle": 0,
"endAngle": 6.283185307179586
}, {
"type": "triangle",
"originX": "center",
"originY": "center",
"left": 250,
"top": 100,
"width": 100,
"height": 100,
"fill": "#00F00F",
"stroke": null,
"strokeWidth": 1,
"strokeDashArray": null,
"strokeLineCap": "butt",
"strokeLineJoin": "miter",
"strokeMiterLimit": 10,
"scaleX": 1,
"scaleY": 1,
"angle": 0,
"flipX": false,
"flipY": false,
"opacity": 1,
"shadow": null,
"visible": true,
"clipTo": null,
"backgroundColor": "",
"fillRule": "nonzero",
"globalCompositeOperation": "source-over",
"transformMatrix": null,
"radius": 50,
"startAngle": 0,
"endAngle": 6.283185307179586
}],
"background": ""
}
};
// Redux part
const canvasObjectReducer = function(state = initialState, action) {
switch (action.type) {
case "OBJECTS_CANVAS_CHANGE":
return Object.assign({}, state, {
canvasObject: action.payload.canvasObject,
selectedObject: action.payload.selectedObject
});
default:
return state
}
return state;
}
// standard react-redux boilerplate
const reducers = Redux.combineReducers({
canvasObjectState: canvasObjectReducer
});
const { createStore } = Redux;
const store = createStore(reducers, window.devToolsExtension && window.devToolsExtension());
const { Provider } = ReactRedux;
const { Component } = React;
const MyProvider = React.createClass({
render: function() {
return (
<div>
<Provider store={store}>
<FabricCanvasReduxed/>
</Provider>
</div>
);
}
});
// Fabric part
var fabricCanvas = new fabric.Canvas();
// class which takes care about instantiating fabric and passing state to component with actual canvas
const FabricCanvas = React.createClass({
componentDidMount() {
// we need to get canvas element by ref to initialize fabric
var el = this.refs.canvasContainer.refs.objectsCanvas;
fabricCanvas.initialize(el, {
height: 400,
width: 400,
});
// initial call to load objects in store and render canvas
this.refs.canvasContainer.loadAndRender();
fabricCanvas.on('mouse:up', () => {
store.dispatch({
type: 'OBJECTS_CANVAS_CHANGE',
payload: {
// send complete fabric canvas object to store
canvasObject: fabricCanvas.toObject(),
// also keep lastly active (selected) object
selectedObject: fabricCanvas.getObjects().indexOf(fabricCanvas.getActiveObject())
}
});
this.refs.canvasContainer.loadAndRender();
});
},
render: function() {
return (
<div>
{/* send store and fabricInstance viac refs (maybe not the cleanest way, but I was not able to create global instance of fabric due to use of ES6 modules) */}
<CanvasContainer ref="canvasContainer" canvasObjectState={this.props.objects} fabricInstance={fabricCanvas}/>
</div>
)
}
});
const mapStateToProps = function(store) {
return {
objects: store.canvasObjectState
};
};
// we can not use export default on jsfiddle so we need react class with mapped state in separate constant
const FabricCanvasReduxed = ReactRedux.connect(mapStateToProps)(FabricCanvas);
const CanvasContainer = React.createClass({
loadAndRender: function() {
var fabricCanvas = this.props.fabricInstance;
fabricCanvas.loadFromJSON(this.props.canvasObjectState.canvasObject);
fabricCanvas.renderAll();
// if there is any previously active object, we need to re-set it after rendering canvas
var selectedObject = this.props.canvasObjectState.selectedObject;
if (selectedObject > -1) {
fabricCanvas.setActiveObject(fabricCanvas.getObjects()[this.props.canvasObjectState.selectedObject]);
}
},
render: function() {
this.loadAndRender();
return (
<canvas ref="objectsCanvas">
</canvas>
);
}
});
var App = React.createClass({
render: function() {
return (
<div>
<MyProvider/>
</div>
);
}
});
ReactDOM.render( <App/>, document.getElementById('container'));
<!--
Please use Redux DevTools for Chrome or Firefox to see the store changes and time traveling
https://github.com/zalmoxisus/redux-devtools-extension
Inspired by https://jsfiddle.net/STHayden/2pncoLb5/
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.js"></script>
<div id="container">
</div>
I found some solution. I try to describe, but sorry for english. Because there is no immutabity in Fabric.js it's hard to implement state management with redux. As far I understand default solution is to use fabric.loadFromJson function for push new state and serialization for pull and store for next manipulations such as actions history. But in this case JSON parsing will be bottleneck if you want to work with images, because they will be stored in Base64 data-uri.
The way is a bit hacky, but it works for me. I was replacing inner array of objects of fabric.js (fabric._objects) and invoking render everytime when something happens on canvas, e.g. moving objects by mouse.
First of all, my state is immutable now via Immutable.js, i.e. i have to return immutable List in my reducers. But elements of these lists are not immutable, it is just fabric.js objects stored in order that they should render. My state consist of objects list, selection list and several helpers objects that represent e.g viewport state (zoom, panning). Object state list keys used as ID of objects in actions. There is structure of my root scene reducer.
const sceneReducer = composeReducers(
whetherRecordCurrentState,
combineReducers({
project: undoable(
composeReducers(
projectActions,
combineReducers({
objects,
params,
counters
}),
),
{
limit: historyLimit,
filter: combineFilters(
recordFilter,
excludeAction([
'CREATE_SELECTION',
'CLEAR_SELECTION',
'SET_WORKSPACE_NAME',
'SET_WORKSPACE_ID',
'SET_WORKSPACE_TYPE',
'SET_TAGS',
]),
)
}
),
selection,
meta,
viewport,
recording
}),
selectJustCreatedObject
);
It implements any fabric.js possibilities including async functions such as applying filters. Also I use redux-undoable package and it allows implement unlimitted undo/redo history. It also allows implement not stored actions, such as opacity changing by slider (all intermediate states will be not stored). Since I use immutability I can push new history state with only one changed object to save memory. There is my state
https://i.gyazo.com/fcef421e9ccfa965946a6e5930e42edf.png
See how it works: in fabric.js I handle event with new object state. Then I dispatch action with that state as payload. In my actions I can create new fabric objects or pass updated objects. All async operations (filtering, changing image source) performing in actions and pass to reducer ready new object. In reducers there is access to my fabric.js objects factory that creates deep copy of object with one distinction. I patched fabric.js (monkey patching, but you can use prototype extending) and it does not serialize images to base64 anymore. I implement it by overriding method Object.toDatalessObject(), that returns same json without images data. Instead source data-uri image data it storing link to HTMLElement object by manually setting Image._element. I.e. after changing images coordinates new image object will have same _element. It allows to save memory and accelerate application.
After all, my container for fabric.js is React component. It connects with redux and after commiting change invokes componentWillRecievProps method. In method I catch new state, create copy with my factory (yes, there is double copying, it should be optimized, but it works fine for me) and pass it to fabric._objects and then I invoke render.
I hope it helps.
I'm having issue with generating arc curves with Raphael.
I created a reduced example here: http://jsfiddle.net/vaxilart/m6cHw/3/
As you can see, the first path drawn isn't the same as the second one, and the second one is only a subpath of the first.
Do you know why both are different? And how could I resolve this issue?
Here's the code:
function drawpath( canvas, bg, pathstr, duration, attr, callback ) {
var guide_path = bg;
var path = canvas.path( guide_path.getSubpath( 0, 1 ) ).attr( attr );
var total_length = guide_path.getTotalLength( guide_path );
var last_point = guide_path.getPointAtLength( 0 );
var start_time = new Date().getTime();
var interval_length = 50;
var result = path;
var run = function run() {
var elapsed_time = new Date().getTime() - start_time;
var this_length = elapsed_time / duration * total_length;
var subpathstr = guide_path.getSubpath( 0, this_length );
path.attr({ path: subpathstr });
if ( elapsed_time >= duration ) {
if ( callback != undefined ) callback();
} else {
requestAnimationFrame(run);
}
};
run();
return result;
}
var sequence_path = [
[ "M", 200, 0 ],
[ "V", 200 ],
[ "A", 100, 100, 90, 0, 0, 300, 300 ],
[ "H", 400 ],
[ "A", 100, -100, 90, 0, 0, 500, 400 ],
[ "V", 500 ],
[ "A", 100, -100, 90, 0, 0, 400, 600 ],
[ "H", 200 ],
[ "A", 100, 100, 90, 0, 0, 100, 700 ],
[ "V", 800 ]
];
var paper = Raphael(10, 50, 700, 1000);
var bg = paper.path(sequence_path).attr({
stroke: 'white',
'stroke-width': 64,
'stroke-opacity': 1,
fill: 'none',
'fill-opacity': 0
});
drawpath( paper, bg, sequence_path, 3500, {
stroke: 'orange',
'stroke-width': 64,
'stroke-opacity': 1,
fill: 'none',
'fill-opacity': 0
});
Looks like Raphael's getSubpath method has a bug where it misinterprets the Large Arc Flags and Sweep Flags of a couple of those curves. I might be wrong.
Edit: OK I was wrong. You have some bad Arcs (A) that are breaking something somewhere between Raphael and the browser, not sure where. But the problem is:
You are setting negative y-radius on the two Arcs that get messed up. Radius cant be negative. in your sequence_path definition, change those two -100's to 100 (positive 100 y radius). updated fiddle: http://jsfiddle.net/m6cHw/4/
If you're going to be hand-writing a lot of paths, I suggest you read the standards specs on how to define them: http://www.w3.org/TR/SVG/paths.html. I tried to avoid reading that for a while but eventually I bit the bullet and went through it. It's weird stuff but you need to understand it if you want to make paths do what you want.