text:
Q: Redux + Thunk + Axios + Consume external API: "Uncaught TypeError: Cannot read property '1' of undefined" I am just starting with Redux and External APIs. For learning, I wanted to consume API from NASA (https://api.nasa.gov/). I don't know what I do wrong. I can't render anything on screen. I get "Uncaught TypeError: Cannot read property '1' of undefined" in the console.
I've read several Q&A in stackoverflow... But I didn't find out where is the problem in my code.
I'd really appreciate any opinion. I need a clue... Thanks in advance.

CONTAINER
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux'
import { showTutusers } from '../actions/index';
import { bindActionCreators } from "redux";

class TutuserListContainer extends Component {

  componentWillMount() {
    this.props.showTutusers()
  }

  render() {
    return (

 { this.props.tutusers.photos[0].id}

 { this.props.tutusers.photos[1].id}

    );
  }
}

function mapStateToProps(state) {
  return {
    tutusers: state.tutuser.tutusers
  }
}

export default connect(mapStateToProps, { showTutusers })(TutuserListContainer)

REDUCERS - INDEX
import {combineReducers} from 'redux';
import { showTutusers } from './tutusers'

const allReducers = combineReducers({
    tutuser: showTutusers,
});

export default allReducers

REDUCER
import { FETCH_TUTUSERS_START, FETCH_TUTUSERS_ERROR, RECEIVED_TUTUSERS } from '../actions/action-types';

const initialState = {
    fetching: false,
    fetched: false,
    tutusers: [],
    error: null
}

export function showTutusers(state = initialState, action) {
    switch (action.type) {
        case FETCH_TUTUSERS_START: {
            return {...state, fetching: true}
            break;
        }
        case FETCH_TUTUSERS_ERROR: {
            return {...state, fetching: false, error: action.payload}
            break;
        }
        case RECEIVED_TUTUSERS: {
            return {...state, fetching: false, fetched: true, tutusers: action.payload}
            break;
        }
    }
    return state

}

ACTION-TYPES
    export const SHOW_TUTUSERS = 'SHOW_TUTUSERS';
    export const FETCH_TUTUSERS_START = 'FETCH_TUTUSERS_START';
    export const FETCH_TUTUSERS_ERROR = 'FETCH_TUTUSERS_ERROR';
    export const  RECEIVED_TUTUSERS = ' RECEIVED_TUTUSERS';

ACTIONS - INDEX
import * as types from '../actions/action-types';
import axios from 'axios';
import store from '../stores/store';

export function showTutusers() {
    return (dispatch, getState) => {
        store.dispatch( { type: types.FETCH_TUTUSERS_START} )
        axios.get('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=_____MY_KEY____')
            .then((response) => {
                store.dispatch( { type: types.RECEIVED_TUTUSERS, payload: response.data } )
               // console.log(">>> response.data", response.data)
            })
            .catch((err) => {
                dispatch({type: "FETCH_TUTUSERS_ERROR", payload: err})
            })
    }

}

STORE
import { createStore, applyMiddleware, compose } from 'redux';
import allReducers from '../reducers';
import thunk from 'redux-thunk';
// import promise from 'redux-promise';
import createLogger from 'redux-logger';
import promise from 'redux-promise-middleware';

const middleware = applyMiddleware(thunk, promise(), createLogger());

const store = createStore(
    allReducers,
    compose(middleware, window.devToolsExtension ? window.devToolsExtension() : f => f)
);

export default store;

A: You need to wait until the response is received and only then try to access the photos, something like this should help:

   {this.props.tutusers.fetched &&

 { this.props.tutusers.photos[0].id}

 { this.props.tutusers.photos[1].id}

}

You also need to pass all the data about the request:
function mapStateToProps(state) {
  return {
    tutusers: state.tutuser
  }
}

A: I got a solution in this  stackoverflow question: react redux-thunk component doesn't render this.props
Basically I only needed an if else statement:
render() {
        var component;
        if (this.props.tutusers) {
            component = this.functionToRenderTutusers()
        } else {
            component =
Loading...
;
        }
        return (

                {component}

        );
    };

 functionToRenderTutusers() {
    return this.props.tutusers.photos.map((tutuser) => {
      return (

{tutuser.id}

      )
    })
 }


text:
Q: Can I use only input form for multiple form? Can I use 1 input field for multiple for multiple form, this my idea but i don't know how to do it.
<form id="form1" method="post">
    <input type="text" form="form1 form2" />
    <input type="submit" value="submit" />
</form>

<form id="form2" method="post">
    <input type="submit" value="submit" />
</form>

Sorry for my bad english.

A: It is possible with PHP for each loop. Put the form around your foreach loop but the submit button outside of your foreach loop and inside your form. You need to assign input value from array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Xml Parsing having CDATA I have below xml, in this need to update value in CDATA section for tag . I tried with element
tree to parse using xpath till vsdata, able to get CDATA and update value of f1.
But the issue is after updating, in updated xml only content of CDATA remains rest of the xml is not
seen.
rootElement=rootElement.findall(xpath)[0] -> Xpath till vsdata.
rootElement=et.fromstring(rootElement.iter().next().text)
for each in rootElement[0]:
  if each.tag == paramname:
     each.text = str(valueToSet)
     print(each.tag, each.text)

<config>
<subconfig>
  First Cell
  Second Cell
  <vsDataContainer>
      <id>0</id>
       <vsData><![CDATA[
          <g>
            <f>
              <f1>10</f1>
              <f2>20</f2>
              <f3>30</f3>
            </f>
          </g>
        ]]></vsData>
    </vsDataContainer>
</subconfig>
</config>

After updating in new xml only following is remained
 <g>
    <f>
       <f1>50</f1>
       <f2>20</f2>
       <f3>30</f3>
    </f>
</g>

But i need it as original with value f1 updated to new value, Could somebody help on this?

<config>
<subconfig>
  First Cell
  Second Cell
  <vsDataContainer>
      <id>0</id>
       <vsData><![CDATA[
          <g>
            <f>
              <f1>50</f1>
              <f2>20</f2>
              <f3>30</f3>
            </f>
          </g>
        ]]></vsData>
    </vsDataContainer>
</subconfig>
</config>

A: Below
import xml.etree.ElementTree as ET

xml = '''<config>
<subconfig>
  First Cell
  Second Cell
  <vsDataContainer>
      <id>0</id>
       <vsData><![CDATA[
          <g>
            <f>
              <f1>10</f1>
              <f2>20</f2>
              <f3>30</f3>
            </f>
          </g>
        ]]></vsData>
    </vsDataContainer>
</subconfig>
</config>'''

f1_new_value = '999'
root = ET.fromstring(xml)
vs_data = root.find('.//vsData')
inner_xml = vs_data.text.strip()
inner_root = ET.fromstring(inner_xml)
inner_root.find('.//f1').text = f1_new_value
vs_data.text = '![CDATA[' + ET.tostring(inner_root).decode('utf-8') + ']]'
root_str = ET.tostring(root)
root_str = str(root_str.decode('utf-8').replace('<', '<').replace('>', '>').replace('\\n', ''))
print(root_str)

output
<config>
<subconfig>
  First Cell
  Second Cell
  <vsDataContainer>
      <id>0</id>
       <vsData>![CDATA[<g>
            <f>
              <f1>999</f1>
              <f2>20</f2>
              <f3>30</f3>
            </f>
          </g>]]</vsData>
    </vsDataContainer>
</subconfig>
</config>


text:
Q: How to draw bitmap and circle at the same point in android I am trying to draw bitmap and circle at the same point using the following code. But circle and bitmap drawn at different places.
canvas.drawBitmap(reSized, 0, 0, null);
pcanvas.drawCircle(stDropCurPoint.x, stDropCurPoint.y, 3, mPaint);
canvas.drawBitmap(bitmap, 0, 0,null);
canvas.save();
canvas.drawBitmap(bmp, stDropCurPoint.x, stDropCurPoint.y, null);
canvas.restore();

My bitmap "bmp" width and height are 50*50 . I am trying to draw a circle of radius 3.
 Kindly let me know how to draw circle and bitmap at the same point .
 Thanks in advance.

A: As the bitmaps x and y coordinates refer to the top left of the image, you might want to offset it half its width and height to center it to the stDropCurPoint.
canvas.drawBitmap(bmp, stDropCurPoint.x - bmp.getWidth()/2, stDropCurPoint.y - bmp.getHeight()/2, null);


text:
Q: PHP + UnixODBC + FreeTDS - SELECT [field] AS [name] does not work I have a unix server which has PHP 5.2.13 installed, and it has access to two SQL servers (one is running MSSQL SERVER 2000 and the other MSSQL 2005).
It uses FreeTDS - details:

*

*Version: freetds v0.82

*freetds.conf directory: /usr/local/etc

*MS db-lib source compatibility: no

*Sybase binary compatibility: no

*Thread safety: yes

*iconv library: yes

*TDS version: 8.0

*iODBC: no

*unixodbc: yes

And I'm using unixODBC-2.3.1
The MSSQL 2000 server is fine, I can run all SQL statements and use mssql_num_rows and mssql_fetch_assoc much as you would with MySQL.
However, the MSSQL 2005 server won't work with mssql_num_rows or mssql_fetch_assoc - you have to use odbc_fetch_row.
That's not really an issue, I assum it's just due to the different server installs.
However, I have a huge issue with the MSSQL 2005 server: I cannot select a field AS another name!
For example:
SELECT
   [EnquiryID] AS "The_Key"
   FROM [db].[dbo].[table]

Works fine in my admin application (ie: NOT PHP), but if I run the same in my PHP environment, I get:
stdClass Object
(
    [PK_EnquiryID] => 1
)

You can see it should be [The_Key] => 1
Has anyone any idea how we can get round this, please?  I'm tearing my hair out!
Cheers
Neil

A: I think this was answered on the freeTDS list, but the problem in is PHP, it makes the wrong call to ODBC so gets the base table name instead of the lable which is what you need in this case.

A: This is by no means a perfect solution, and I would love to learn the proper way to deal with this issue, but in the mean time, add +'' to each column, after the underlying column name, but before the AS alias and you should be able to circumvent this issue.


text:
Q: Bind grails datasource to jndi-name Configuring a Grails v2.2.4 app with mysql database to use JDBC connection pool and JavaMelody monitor. Everything seems to run properly in GGTS v3.4.0 but unable to deploy a WAR file successfully.
Config.groovy contains:
grails.naming.entries = ['jdbc/myDB': [
type: "javax.sql.DataSource",
factory: "org.apache.tomcat.jdbc.pool.DataSourceFactory",
auth: "Container",
driverClassName: 'com.mysql.jdbc.Driver',
username: <username>,
password: <password>,
url: <database_url>,
<connection pool settings> ]  ]

In DataSource.groovy:
dataSource {
jndiName = "java:comp/env/jdbc/myDB"
pooled = true
useUnicode="yes"
characterEncoding="UTF-8"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
dbCreate = 'update' // one of 'create', 'create-drop', 'update', 'validate'
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}

Can somebody provide direction on the proper syntax and location of config statement(s) (within the IDE) to bind dataSource to jndi? This app runs on Cloud Foundry so we need to stuff desired Tomcat settings into the war file (i.e., we cannot change Tomcat xml).
SOLUTION:
Move the grails.naming entries block from config.groovy to web-app\META-INF\context.xml
<Resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
username="[username]" password="[password]" url="[database_url]"
[connection pool settings:  property="value" ]  />


text:
Q: Wifi 6E access point in Linux Context: I'm looking to set up a 6 GHz (Wifi 6E) Access Point in Linux. I have two Intel AX210s (WiFi cards) on two computers.
nmcli only supports 2.4GHz + 5GHz
hostapd seems to support WiFi 6 but doesn't distinguish it from WiFi 6E, meaning the 6 GHz channels can't actually be used.
Linux has had support for WiFi 6E cards since the 5.11 kernel. Am I missing something here? How can I set up a 6 GHz AP on Linux?


text:
Q: Mocha, go to the next file after timeout I'm running my test files with script
"test": "node_modules/.bin/mocha *.test.js

but in the first test I'm sending to my Node.js server while(1); and causing it to timeout, simultaneously failing that test. That's the intended behaviour but how do I make mocha run the rest of the files after that?

A: There is an issue in Mocha's repository for your case.
Infinite loops seem to escape timeouts #1609

TL:DR
This is not possible in mocha(because of how node works).
You can read the interesting discussion about this problem.
The reason it blocks all the code is because of how node works.
The code is executed line by line totally in syncronous way.
The async magic happens with the node event loop .
But when you run infinite  loop the event loop will be blocked because only one event can run at a time, and this event will never end:)


text:
Q: Firebase Authentication via Google and Apple work only when installed directly through an APK? When I build a generate a signed APK and install it on my Android device authentication works as expected, however when I generate a signed app bundle and deploy to playstore then install through the test channel the authentication stops working.
For google it will show the account picker but after selecting an account the picker dissapears and nothing happens (no error logged in logcat).
When using Apple nothing happens at all and I get an error in logcat: "INVALID_CERT_HASH 400".
I've doulbe/triple checked my cert hashes against the signing key and I'm sure I've set the correct ones. Have added both the debug and release sha1 and sha256 to the firebase console, downloaded the google-services.json and used that when running.
It works fine if I build a signed release apk and manually install it on the phone or I run it via android studio - but it doesn't work when going through the playstore.
This is the full output when choosing to sign in with apple:
2022-08-16 00:36:06.428 1973-1973/? W/adbd: timeout expired while flushing socket, closing
2022-08-16 00:36:06.743 2790-3875/? I/HbmSvManager:  Request state 2 req 0
2022-08-16 00:36:07.035 1186-1569/? V/DisplayPowerController[0]: Brightness [0.06408318] reason changing to: 'automatic', previous reason: 'automatic [ dim ]'.
2022-08-16 00:36:07.049 504-504/? I/display: level=88, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.065 504-504/? I/display: level=96, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.081 504-504/? I/display: level=103, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.083 1071-1071/? D/AOC: A3:MSG: tmd3719_sensor.cc, 281: USF: TMD3719: brightness:103 refresh_rate:60 status:1
2022-08-16 00:36:07.099 504-504/? I/display: level=111, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.115 504-504/? I/display: level=119, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.132 504-504/? I/display: level=128, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.149 504-504/? I/display: level=137, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.163 1186-2628/? I/ActivityTaskManager: START u0 {act=com.google.firebase.auth.internal.NONGMSCORE_SIGN_IN pkg=redacated.myapp.com cmp=redacated.myapp.com/com.google.firebase.auth.internal.GenericIdpActivity (has extras)} from uid 10250
2022-08-16 00:36:07.170 504-504/? I/display: level=146, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.172 1186-2628/? W/ActivityTaskManager: Tried to set launchTime (0) < mLastActivityLaunchTime (15219249)
2022-08-16 00:36:07.180 12284-12896/? W/System: Ignoring header X-Firebase-Locale because its value was null.
2022-08-16 00:36:07.184 504-504/? I/display: level=155, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.190 504-504/? I/display: level=159, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.198 1186-1543/? I/ActivityTaskManager: Displayed redacated.myapp.com/com.google.firebase.auth.internal.GenericIdpActivity: +35ms
2022-08-16 00:36:07.199 504-504/? I/display: level=165, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.217 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.onFinishInput():3273
2022-08-16 00:36:07.218 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.updateDeviceLockedStatus():2165 repeatCheckTimes = 0, unlocked = true
2022-08-16 00:36:07.218 504-504/? I/display: level=175, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.218 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.onStartInput():1956 onStartInput(EditorInfo{inputType=0x0(NULL) imeOptions=0x0 privateImeOptions=null actionName=UNSPECIFIED actionLabel=null actionId=0 initialSelStart=-1 initialSelEnd=-1 initialCapsMode=0x0 hintText=null label=null packageName=redacated.myapp.com fieldId=-1 fieldName=null extras=null}, false)
2022-08-16 00:36:07.218 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.shouldHideHeaderOnInitialState():4081 ShouldHideHeaderOnInitialState = false
2022-08-16 00:36:07.218 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.updateDeviceLockedStatus():2165 repeatCheckTimes = 2, unlocked = true
2022-08-16 00:36:07.233 504-504/? I/display: level=185, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.248 504-504/? I/display: level=196, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.271 504-504/? I/display: level=211, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.273 1071-1071/? D/AOC: A3:MSG: tmd3719_sensor.cc, 281: USF: TMD3719: brightness:211 refresh_rate:60 status:1
2022-08-16 00:36:07.289 504-504/? I/display: level=215, DimmingOn=1, HbmMode=0, LhbmOn=0
2022-08-16 00:36:07.578 12284-12896/? E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
2022-08-16 00:36:07.660 1186-1617/? W/InputManager-JNI: Input channel object '24df3cb redacated.myapp.com/com.google.firebase.auth.internal.GenericIdpActivity (client)' was disposed without first being removed with the input manager!
2022-08-16 00:36:07.666 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.onFinishInput():3273
2022-08-16 00:36:07.667 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.updateDeviceLockedStatus():2165 repeatCheckTimes = 0, unlocked = true
2022-08-16 00:36:07.667 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.onStartInput():1956 onStartInput(EditorInfo{inputType=0x0(NULL) imeOptions=0x12000000 privateImeOptions=null actionName=UNSPECIFIED actionLabel=null actionId=0 initialSelStart=-1 initialSelEnd=-1 initialCapsMode=0x0 hintText=null label=null packageName=redacated.myapp.com fieldId=2131231160 fieldName=null extras=null}, false)
2022-08-16 00:36:07.667 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.shouldHideHeaderOnInitialState():4081 ShouldHideHeaderOnInitialState = false
2022-08-16 00:36:07.667 1851-1851/? I/GoogleInputMethodService: GoogleInputMethodService.updateDeviceLockedStatus():2165 repeatCheckTimes = 2, unlocked = true
2022-08-16 00:36:07.890 2790-3875/? I/HbmSvManager:  Request state 2 req 0
2022-08-16 00:36:07.919 2790-3875/? I/HbmSvManager:  Request state 2 req 0

A: Looks like this is a lesson in reading documentation more carefully - when uploading an app bundle to play services google looks to be resigning the app: https://developers.google.com/android/guides/client-auth

If you've published your app using Play App Signing, a requirement
when using Android App Bundle, you can get your SHA-1 from the Google
Play Console on the Release > Setup > App Integrity page.

Adding the sha-1/256 keys from there to firebase fixed the issue. Previously I was only adding the release keys from the certificate I had created locally.


text:
Q: What permissions are needed to delete an object from a specific bucket in S3 I am trying to create an IAM policy for a lambda role which will give permissions to delete an object. If I do not specify the resource this policy works, but I would like to limit it to the specific bucket:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::bucketname/*",
                "arn:aws:s3:::bucketname"
            ]
        }
    ] }

What am I missing here?

A: From the documentation
        {
    "Version":"2012-10-17",
    "Statement":[
        {
            "Effect":"Allow",
            "Action":["s3:ListBucket","s3:GetBucketLocation"],
            "Resource":"arn:aws:s3:::awsexamplebucket1"
        },
        {
            "Effect":"Allow",
            "Action":[
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource":"arn:aws:s3:::awsexamplebucket1/*"
        }
    ]
    }

Make sure, the IAM role for your lambda has trust policy setup.

A:
In my case I am not able to delete object .  But can upload object .So I update my bucket policy after that working fine.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": [
            "s3:ListBucket",
            "s3:GetBucketLocation"
        ],
        "Resource": "arn:aws:s3:::YourBucketName"
    },
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": [
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:DeleteObject"
        ],
        "Resource": "arn:aws:s3:::YourBucketName/*"
    }
]

}


text:
Q: How to update the client side javascript based on something on the server? I've researched this, but it's hard to find something when you don't know the best way to do it or even how to begin. I don't have any code obviously, so i'll describe my issue and hopefully someone can point me to the correct way to solve this :
ok let's say I have a page with a javascript function called "myfunction1" that fires off every x seconds by using setinterval in js. What I want it to do is, (using AJAX perhaps?) when "myfunction1" is called, call a php script that will check something in the database. If a certain condition is TRUE, I want a specific function to be called in javascript on the client side. If FALSE, I want it to call a different function.
My intuition makes me think the way to do it is to have the ajax call the php checking script, then echo the proper javascript code based on if true or false. But how would I go about doing that? I know how to use ajax to change the .innerhtml of a tag, but can you use it in this way to rewrite inside a script tag?? My head's spinning, hope I made some sense and one of you can point me the right way

A: AJAX would probably be the simplest solution and can be used to evaluate returning script or you can manually validate/display the response from the XmlHttpRequest that the server processed.
For example when using jQuery.ajax You can change the dataType option to script.
Otherwise you can manually program the validation in the success callback, like below, using JSON.
javascript (jQuery)
jQuery(function($) {
   'use strict';
   var element = $('#myElement');
   var ajax = null;
   var ajaxTimeout = 0;

   function myFunction1() {
       if (null !== ajax) {
          //prevent overlapping ajax requests
          ajax.abort();
          ajax = null;
       }
       ajax = $.ajax({
         url: '/response.php',
         method: 'post',
         dataType: 'json',
         success: function(data) {
            //parse the server side response
            if (data.result === true) {
               trueFunction(data);
            } else {
               falseFunction(data);
            }
            ajax = null;
         }
      });
   }

   //custom functions for true or false and setInterval.
   function trueFunction(data) {
      element.html('Success: ' + data.value);
   }

   function falseFunction(data) {
      element.html('Failed: ' + data.value);
   }

   ajaxTimeout = window.setInterval(myFunction1, 1000);
});

response.php
<?php

header('Content-Type: application/json');
$date = new \DateTime;
echo json_encode((object) [
    'value' => 'Hello World ' . $date->format('Y-m-d h:i:s a'),
    'result' => true
]);
exit;


text:
Q: saving NSString to files which remain even when the app is killed by iOS I would like to implement an iOs App which stores (text) data depending on certain locations. My problem is that if my app get killed by iOS all the data are lost. Right now I am using document directory to store my txt files. No problem as long as app is alive...
My question is where should i store my txt files to keep it even in case of app gets terminated?

A: Mappet?
By "killed" do you mean "stopped, no longer running" or "removed from the iOS-device"?
The reply from Priyatham51 reflects on your App on longer running, but still being on the iOS device (and a user could start it again).
If you want the data to survive the App being remove from the Device you may want to look into storing the NSString into iCloud (you could start with something like https://developer.apple.com/icloud/index.php).
Bart-Jan.

A: Data saved in the Document directory should be alive even after your app gets killed. You might be doing something wrong in your code.
From Apple Doc
Application_Home>/Documents/
Use this directory to store critical user documents and app data files. Critical data is any data that cannot be recreated by your app, such as user-generated content.
The contents of this directory can be made available to the user through file sharing. The contents of this directory are backed up by iTunes.
https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

A: Try below code that writes string to text file. I have also used NSDocumentoryDirectory. Please let me know if you still find a problem in writing to text file.
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"Documents directory %@",documentsDirectory);
NSString *fileName = [NSString stringWithFormat:@"%@/Test.txt",
                      documentsDirectory];
NSString *content=@"Hello World";
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];


text:
Q: Selecting rows where price changed I have a problem much like this one
SQL: selecting rows where column value changed from previous row
Although not in mysql in SQL Server. i tried ypercube's first answer jiri's answer and egor's as well. All of them just run for over 5 min with no results (one i let run over 10min). The table contains over a million records so i know this is a big part of the problem. I have a feeling ypercube's second answer might work well but don't know how to change this variable driven mysql query to SQL.
Any help would be appreciated.
SQL version 2008 r2
Basically i need to determine when a price has changed on table containing the price,productID, serialnumber and a datestamp.
I can get a quick list of what productids/serial numbers need to be checked to compare against. Sorry i did not include this earlier i was thinking i could just adapt a solution to fit it.

A: A common table expression should do it fairly efficiently;
WITH cte AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY system ORDER BY timestamp) rn
  FROM TableX
)
SELECT a.timestamp, a.system, a.statusa, a.statusb
FROM cte a JOIN cte b ON a.system = b.system AND a.rn = b.rn+1
WHERE a.statusa <> b.statusa

An SQLfiddle to test with.


text:
Q: Hashlib produces different results on Ubuntu and Windows via GitHub actions I have created a test, to ensure that the content of the license file does not change. The test looks like the following:
    license_file = context.root_dir.joinpath("LICENSE")

    with open(license_file, "rb") as license_fd:
        content = license_fd.read()
    license_hash = hashlib.sha224(content).hexdigest()

    # Compare to "sha224sum LICENSE" of initial commit
    # TODO: Figure out why Windows gives another hash
    # assert license_hash == "45fd0b382919a02f391b9ce13e70ed703b9569cce812332d03c514a2"

In GitHub I'm running the test in a matrix with the os set to "ubuntu-latest", "macos-latest", and "windows-latest". Version of Python is set to 3.8.
For both Ubuntu and MacOS the test is passing. But the assertion fails on Windows.
I have read that open replaces line endings on Windows, if the mode is set to r. But opening the file with rb should not alter the file. I have also tried to replace the mode with r+b. The tests pasases on both Unix systems, but not Windows.
Are hashlib working different on Windows? It shouldn't. Are the pipeline altering files? It shouldn't.
I don't have a Windows machine to validate which part is altering the file or if hashlib have a bug in the Windows implementation. Most likely the first part.
Am I missing the obvious?

A:
Are the pipeline altering files? It shouldn't.

Following Iłya Bursov's advice showed that the checkout of source code changed file endings as default on Windows.
It's a known hurdle (but not a bug): https://github.com/actions/checkout/issues/135#issuecomment-602171132
Fixed using:
    steps:
      - name: Set git to use LF
        run: |
          git config --global core.autocrlf false

      - uses: actions/checkout@v2

However I didn't force line endings to be lf as posted in the answer on GitHub.


text:
Q: iOS - How To Position a View Fixed Within a Certain Area On a Background Image This is the layout that I am trying to achieve.

I want to position the circular yellow button within the small circular area of the background in any iPhone. The circular area is not centred in that image.
This is so far what I tried:

*

*First, I added a UIView with 1px x 1px, transparent background colour to the centre of the whole layout. I call that the center point

*Then I will set vertical spacing between centre point and the yellow button.

*I will also set leading constraint between the yellow button and the super view.

*Then, I will set aspect ratio (yellow button width to yellow button height).

*Another aspect ratio (yellow button to background image).

However, the outcome is really not what I expect it should be. It is alright that if the background image is distorted, I just want the yellow button to stay inside the circular area of the background image.
Thanks!

A: To position your circle relative to the background, set a constraint to align the trailing edge of the circle with the trailing edge of the image view, and then set the multiplier to an appropriate value like 214:640.  This will cause the circle to move right by the correct amount as the screen size increases.
Likewise, align the circle bottom to the image view bottom and set the multiplier to an appropriate value like 478:900 and it will keep your circle aligned as the screen grows.
Play with the ratios until they look good on one phone size (like the iPhone 5S), then they'll work for the 6S and 6S Plus.
Set the circle width equal to the image view width and set the multiplier to 100:320.

A: I would not go that far, I would make one button that fits the entire screen, set the button image to be the whole image including the yellow circle. Then use similar code below:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];

  // Get the specific point that was touched
  CGPoint point = [touch locationInView:self.view];
  if (point.x * 100 / parentView.width in range (0-100) && point.y*100 / parentView.heiht in range (0-100)){
       // write your button event handler here.
  }

}


text:
Q: Extjs6 Update doesn't clear dirty flag I have a view containing 2 grids. The grids are backed by 2 models. The relationship between the 2 models is one to many(keyless association).
Models:
Ext.define('TestApp.model.association.Project', {
    extend: Ext.data.Model,
    fields: [
        {
            type: 'int',
            name: 'id'
        }, {
            type: 'string',
            name: 'project'
        }, {
            type: 'number',
            name: 'allocation'
        }, {
            type: 'string',
            name: 'comments'
        }, {
            type:'string',
            name:'state'
        }
    ]
});

Ext.define('TestApp.model.association.User', {
    extend: Ext.data.Model,
    fields: [{
        type: 'int',
        name: 'id'
    }, {
        type: 'string',
        name: 'employee'
    }, {
        type: 'string',
        name: 'location'
    }, {
        type: 'string',
        name: 'department'
    }, {
        type: 'string',
        name: 'manager'
    }, {
        type: 'number',
        name: 'allocation'
    }],
    hasMany: [{
        model: 'TestApp.model.association.Project',
        // Note: use of 'role' is preferred over 'name'
        role: 'projects',
        // Define role for inverse association
        inverse: {
            role: 'user'
        }
    }]
});

After I edit one row from the child part, I set the parent record as dirty (dirty=true) and then I sync the store. After I do the necessary work on the server I send back the response. After I receive the response the dirty flag on the child part remains true.
When having no association, after receiving the response from the server, the dirty flag is clear automatically.
I've created a fiddle for more details.
How to clear the dirty flag from an association after an update?
Edit
I've updated the fiddle to better show my problem.
Steps to reproduce:

*

*Select John Doe record from the top panel

*Select Apple from the bottom panel

*Edit allocation and comments column (row edit plugin available). Press Ok

*Press the Save button from the toolbar of the second grid

The request is sent to the server. The server respond with a json (the server response is hardcoded an will always be the same).
The client is unable to set the child record received in the response and clear the dirty flag.
Why is doing this? Is this a bug?

A: While setting up associations, all associated models must belong to the same schema. With reference to this, I have made some changes to your code. Please check if the Save button is working now. I have also commented out some parts of your code for initial test.
Find the code here


text:
Q: C++ WInApi thread on button "start" I doing thread
HANDLE  hThread1;
case butStart:
hThread1=CreateThread(NULL, 0, func_pressF1, NULL, NULL, NULL);
break;
case butStop:
//code
break;

how can I free thread on button stop? I think with this functions can help
VOID WINAPI ExitThread(
 __in DWORD dwExitCode
 );

 BOOL WINAPI GetExitCodeThread(
 __in HANDLE hThread,
 __out LPDWORD lpExitCode
 );

but I don't know what I must write here __out LPDWORD lpExitCode.
Maybe someone can write code for my example

A: You should signal your thread to exit using some mechanism such as an event. After that the main thread should join the thread and then acquire the exit code (if needed). You should never force a thread to exit since resources might not get freed and mutexes might deadlock (if owned by the thread), for example.

A: Try WaitForSingleObject to wait until the thread completes, GetExitCodeThread to get the exit code (or just use a global variable), then CloseHandle to free the handle.
LPDWORD is just the address (a pointer) of a DWORD variable.  Call like:
DWORD exit_code;
if (!GetExitCodeThread(hThread1, &exit_code)) // handle failure

A: __out LPDWORD lpExitCode means that you are providing a pointer to a DWORD in which the function will place the exit code for you, like a second return-value!
DWORD ec;
GetExitCodeThread(hThread, &ec);

A: ExitThread must be called by the thread itself. You can use TerminateThread which takes a thread-id as an argument and kills another thread.


text:
Q: CentOS 6.6, Limits of user-specific environment So I'll add context, but my BLUF is this:
In an organization that actively prefers "old, known, stable" (CentOS 6.6, highly curated Repo, etc...) to "modern, efficient, effective", but allows me substantial latitude inside my own profile, how far can I (or should I) go in creating my own environment inside my profile, and what's the most sensible approach to making that happen?
An easy example of what I'm talking about is Python.  System wide I'm limited to 2.6, but no one cares if I run 2.7 or 3.4 for my own purposes, but even building them manually (never mind using tools like pyenv, etc) hasn't been successful (though it always seems just outside the reach of my skillset)
So no one has a problem with me compiling new code, or running packages from sensible sources.  Nothing I'm doing will be running in a SU context, etc, but I seem to be spending incredible amounts of time spinning my wheels here.  I can't install RPMs because I can't even run the damn tools (even in a user context), etc...  I imagine there's a way for them to fix the permissions to allow me to do that (without permitting me to make system wide changes), but before I go asking for stuff like that, I need to know that it's the best (or at least a viable) solution to my problem.
What route should I take to try and make this happen?  And beyond what I can do, I actually DO want to obey the general intent of these policies, so I'd like to avoid doing anything that really does introduce any security implications, so are there limits to how far I should take this?
Is using the package manager at all viable?  Building a functional build environment?  etc.
And of course, if there's a primer out there somewhere I should be reading, a link would be greatly appreciated.  My google-fu has failed me here (probably because I have a hard time succinctly describing the problem).

A: Ok so this is what I got from your question. You want to have an environment that would contain any of versions of any of the packages that you feel are required correct? Should that be the case, you have no issues doing that since Linux actually supports that. There is few limits as to what you cannot do as your user.
For your first example, python. Sys admin refrain(explicitly) from upgrading this because it is very very essential for YUM and breaking it will leave the server non-updateable. This however does not stop you from creating sub folders in your home directory and bringing in an tar ball which has the required binaries. Just go here Python Download and pick a tar ball. Unzip it in your home and add a export PATH=/location_to_bin_folder_for python:$PATH in your .bashrc and you are good to go.
This is completely acceptable in the world of Linux(companies could have restrictions on what you install) and tar balls are generally the way to go for closed infrastructures. Package managers are generally something that are used by Admins and you would not be privy to that unless you have something specific in mind like a php version that comes from Red Hat or other 3rd party repo providers.
So as a summary, you are limited by the rules set by your admins. In closed infrastructures, security is not really a big problem. You can take it a step further and make RPMs if you needed to with tar balls as updates and you can subscribe to updates to keep the RPM updated. I would find out how much they would want to limit you but practically all dev tools are available as tar archives for this purpose.
EDIT :
The easiest way to achieve what you are looking for is the way alternatives is done. You can do that bu creating a folder in your home like
/home/user/bin
Install python and something else, like say Java in two seperate folders
/home/user/python and /home/user/java.
In your bin folder, create symlinks to the desired binaries
$ ls -l /home/user/bin
lrwxrwxrwx. 1 user user 13 May 19 19:59 java -> /home/user/java/bin/java
lrwxrwxrwx. 1 user user 13 May 19 19:59 javac -> /home/user/java/bin/javac
lrwxrwxrwx. 1 user user 15 May 19 19:59 python -> /home/user/python/bin/python

Add this to your .bashrc
export PATH=/home/user/bin:$PATH

Open a new terminal session and try
which python
It should say /home/user/bin/python
Add any additional binaries you see fit with the versions of your choice and it will work as expected


text:
Q: Mirror vim actions across multiple files (like multi-cursor mode in VS Code) I have two files that start with the same multiple line header. What I want is to open both, make changes to the first header and have those changes propagate to the second file. Sort of like how multi-cursor mode in VS Code or Sublime repeats your actions in multiple locations. Is there a quicker way to do this than recording a macro or using a replace command?

A: Ctrl+V will allow you get into block visual mode, where you can edit multi lines at the same time.
Otherwise if you want to select same words and edit them together just like VS code or Sublime text, there is a plugin for that:
https://github.com/terryma/vim-multiple-cursors

A: You can also use macros to this
for eg: you have multiple buffers open and you want to change the first line in each buffer to: "Created By Me".
You can easily achieve this by usign macros like this:

*

*start recording in a macro

qq

*enter the next buffer by entering the following command in command mode and
press enter key

:bn

*Now go to the top of the file and enter insert mode by pressing following keys

ggi

*Now make your changes

"Created By Me"

*press <esc> key

*save the file

:w

*stop macro recording by pressing q

*Now play the macro for n times (n denotes the no. of files in buffer, suppose 9
files are there in buffer)

9@q


text:
Q: Finding points on curves in HTML 5 2d Canvas context Given lines drawn by 2d canvas context functions bezierCurveTo, quadraticCurveTo or arcTo, how can I find points along those lines?
My intent is to draw an object at the midpoint of a curve.  Using the SVG DOM, I can do this with methods getPointAtLength & getTotalLength, but I can't see an equivalent in HTML canvas.

A: A Bezier Curve is calculated Mathematically with this formula

Where P0 is the startpoint, P1 and P2 are the control points and P3 is the end point.
To calculate the halfwaypoint you can just use t = 0.5.
Similar for the Quadratic Curve:

Source and further Information

A: You find them the hard way :(
There isn't an equivalent in HTML canvas. You have to find the midpoints yourself with plain old math.
I did an example of how to find midpoint of bezier curves for you. See it live at jsFiddle here. A copy of the javascript is pasted below.
Real curve is red, midpoint is the tiny green rectangle. Everything else is just a visual aid.
var ctx = $("#test")[0].getContext("2d")
function mid(a,b) {
 return (a+b) / 2;
}

var cp1x = 100;
var cp1y = 150;
var cp2x = 175;
var cp2y = 175;
var x = 200;
var y = 0;

ctx.lineWidth = 4;
ctx.strokeStyle = "red";
ctx.fillStyle = "rgba(0,0,0,0.6)";

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
ctx.stroke();

//line goes from start to control point 1
ctx.strokeStyle = "rgba(0,0,200,0.4)";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(cp1x , cp1y);
ctx.stroke();

//line goes from end to control point 2
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(cp2x , cp2y);
ctx.stroke();

//line goes from control point to control point
ctx.strokeStyle = "rgba(200,0,200,0.4)";
ctx.beginPath();
ctx.moveTo(cp1x, cp1y);
ctx.lineTo(cp2x , cp2y);
ctx.stroke();

// now find the midpoint of each of those 3 lines
var ax = mid(cp1x,0);
var bx = mid(cp2x,x)
var cx = mid(cp1x,cp2x)

var ay = mid(cp1y,0)
var by = mid(cp2y,y)
var cy = mid(cp1y,cp2y)

// draw midpoints for visual aid
// not gonna look exact 'cause square
// will be drawn from top-right instead of center
ctx.fillRect(ax, ay, 4, 4);
ctx.fillRect(bx, by, 4, 4);
ctx.fillRect(cx, cy, 4, 4);

//now draw lines between those three points. These are green
ctx.strokeStyle = "rgba(0,200,0,0.4)";
ctx.beginPath();
ctx.moveTo(ax, ay);
ctx.lineTo(cx , cy);
ctx.stroke();

ctx.beginPath();
ctx.moveTo(bx, by);
ctx.lineTo(cx , cy);
ctx.stroke();

//now the midpoint of the green lines:
// so g1 and g2 are the green line midpoints
var g1x = mid(ax,cx);
var g2x = mid(bx,cx);

var g1y = mid(ay,cy);
var g2y = mid(by,cy);

//draw them to make sure:
ctx.fillRect(g1x , g1y, 4, 4);
ctx.fillRect(g2x , g2y, 4, 4);

//now one final line, in gray
ctx.strokeStyle = "rgba(20,20,20,0.4)";
ctx.beginPath();
ctx.moveTo(g1x , g1y);
ctx.lineTo(g2x , g2y);
ctx.stroke();

//whew! We made it!
var FinallyTheMidpointx = mid(g1x,g2x);
var FinallyTheMidpointy = mid(g1y,g2y);

//draw something at the midpoint to celebrate
ctx.fillStyle = "rgba(0,255,0,1)";
ctx.fillRect(FinallyTheMidpointx, FinallyTheMidpointy, 4, 4);

A: Check out http://pomax.github.io/bezierjs/
There's a bunch of handy functions there, the one you want to use is .get(t) where t=0.5


text:
Q: I got error when try to run docker-compose up -d Im just getting started with Golang and am trying to build go gin with docker-compose.
Here is my Dockerfile
FROM golang:1.18

WORKDIR /docker-go

# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
# COPY all file go ./

COPY ./app/main.go ./
COPY . /docker-go
# To initialize a project with go module, create go.mod

RUN go mod init shipping-go

# Add missing and/or remove unused modules
RUN go mod tidy

# This will bring all the vendors to your projects /vendor directory so that
# you don't need to get the modules again if working from another machine on this project.
RUN go mod vendor

RUN go mod download && go mod verify

COPY . .
RUN go build -v -o /docker-go/app .

RUN chmod +x /docker-go
USER root

and my docker-compose
version: "3.7"
services:
  go-web:
    build:
      context: ./
      dockerfile: Dockerfile
    restart: 'no'
    working_dir: /docker-go
    ports:
      - "8080:8080"
    entrypoint: ["./start.sh"]
    volumes:
      - ./:/docker-go

And i got error when i check logs container with command
docker logs learn-docker-go_go-web_1

/docker-go
go: cannot find main module, but found .git/config in /docker-go
    to create a module there, run:
    go mod init
/docker-go

its seem go can't find module file but i have install in Dockerfile.
For Detail i push code in my repository here
https://github.com/duyanh1904/learn-docker-go

A: There are multiple issues with your Dockerfile and docker-compose.yml and I have been unable to replicate the issue you are seeing (but your setup does not work for me either). A few of the problems I see are:

*

*COPY . /docker-go will copy the current folder (including subfolders) into the image at /docker-go/. This will result in a folder /docker-go/app. The existence of this folder means that go build -v -o /docker-go/app . will store the executable as /docker-go/app/shipping-go (you are trying to execute a folder).

*Your intention is for the executable to be in /docker-go but you then obscure that folder with a mount (./:/docker-go). As per the docs "If you bind-mount into a non-empty directory on the container, the directory's existing contents are obscured by the bind mount.".

*Your start.sh (not shown in the question) is not starting the executable (see the docs).

*in main.go (also not shown in the question) replace router.Run("127.0.0.1:8080") with router.Run(":8080"). Listening on 127.0.0.1 means that only local connections will be accepted; within a container that means only connections from the container itself.

Here is a working setup to get you going (this is probably not optimal but should provide a starting point that will enable you to experiment further). Note that you need to make the above change in main.go first.
Dockerfile
FROM golang:1.18

WORKDIR /docker-go

# Note: A better solution would be to copy an existing go.mod into the image
RUN go mod init shipping-go
COPY ./app/main.go ./
# Determine required modules and download them
RUN go mod tidy
RUN go build -v -o /docker-go/app
RUN chmod +x /docker-go/app

docker-compose.yml
version: "3.7"
services:
  go-web:
    build:
      dockerfile: Dockerfile
    restart: 'no'
    ports:
      - "8080:8080"
    command: ["./app"]


text:
Q: Angular Material Radio Button Outer Circle not align I am trying to add some radio button to my angular form. I went to the material.angular.io site and used their code. However, the radio buttons do not look right. There is an outer and inner circle next to each other. So, I went here and found someone else's code and copied/pasted and got the same issue. Here is the code
 <mat-radio-group formControlName="options">
                        <mat-radio-button value="1">Option 01</mat-radio-button>
                        <mat-radio-button  value="2">Option 02</mat-radio-button>
                      </mat-radio-group>

In my angular module.ts, I added the MatRadioModule. I am not sure why I am getting this strange error. Has  anyone here ever seen this? Any help is greatly appreciated.

A: You have to import built-in css style in styles.css.
eg.@import '@angular/material/prebuilt-themes/indigo-pink.css';
Here is the more details Doc


text:
Q: how to get the unique item from array ignore string encode in php? By using array_unique() I want to get unique German words from $vocaulary.
but some of the item encoded in utf-8, and some encoded in ASCII,
I tried using utf8_encode() to force them encode to utf-8, but not work.
in this array, "Handelsbilanz" is not unique, but when I print it out, they are same strings.
file is here.
$volcabulary =array (
      0 => 'Handelsfreiheit',
      1 => 'Handel (Händler)',
      2 => 'Handel, auswärtiger',
      3 => 'Handelsbilanz',
      4 => 'Handelskapital',
      5 => 'Zweck',
      6 => 'Zyklus, industrieller',
      7 => 'Handelsbilanz',
    );
How to get the unique German words from array ignore string encoding?


text:
Q: Trying to run demo app using Bonjour, but it can't discover the server running on the same host I've successfully compiled the demo app from a tutorial on using Bonjour from Qt, but when the client runs, it can't find the server, even though the server is running on the same computer!
Both the client and server use only dnssd.dll. Am I missing something? Do I need to have some sort of a daemon running?
I have no experience with Bonjour so it's entirely possible I've missed something obvious.

A: I found the answer at https://stackoverflow.com/a/1975685/492336
It turns out I need to download and run the Bonjour Installer from Apple.
After I installed Bonjour Printer Services, the demo client discovers the demo server.


text:
Q: Python regarding f.tell() I am working through a tutorial on searching an .html file using regular expressions (the re module).  I am using the interpreter.
I opened the file and preformed my search.  After each attempt, I used f.seek(0) to return to the beginning of the file for the next attempt.  I confirmed my location in the file using f.tell().
The first few time that I did this, the location of the file (in bytes) was returned without an L appended to it.  But after several attempts, f.tell() returned the location with an L appended.
I understand that the L signifies that the file location (in bytes) is a long number.  But why would f.tell() suddenly begin to return the L, when it had not on prior occasions?
I then closed and re-opened the file, and f.tell() returned the long number from the onset?

A: Yes, the L signifies a long (which is practically only limited by the memory and computation time).
Python in general does automatic promotions of ints to longs as soon as the value exceeds the range the int type can handle.  Also, if some operation with another long takes place, the result always is a long (0 + 0L → 0L).
In your case I can only speculate what caused this effect.  Maybe reading beyond a certain limit caused the promotion, maybe some internal handling (which does not always take place) was the reason.
I don't think that it will matter to you.


text:
Q: Is it possible to use if..else statment inside for loop condition?

for(var i = n1;
    if(n3>0){i<=n2}
    else if(n3<0){i>=n2}
    else{window.alert('error')};
    i += n3){
   nArr.push(i);
}

This is code i want to run.. somehow.. i want to do range function that writes from-to numbers with step into array.. i accomplished to do it in positive way but when i want negative i'd like only to invert "i<=n2" sign to "i>=n2" and not writing another loop.. is this possible?
Thanks in advance,
chiff :)

A: you can combine your statements like this:
for(var i = n1; n3>0 && i<=n2 || n3<0 && i>=n2; i += n3){
      nArr.push(i);
}

but I wouldn't recommend that for the sake of readability
also, be advised that you are checking n3 condition on every loop iteration, which is not good as it could be done only once

A: You can accomplish what you're trying to do like this:
if (n3 === 0) {
    // show error
    return;
}

for(var i = n1; n3 > 0 && i < n2 || n3 < 0 && i >= n2; i += n3) {
    nArr.push(i);
}

A: if in JS isn't an expression, so I guess nope. An IIFE could do the trick, though:

var a = 5;
for (var i = 0; (function() {
  if (a > 3)
    return i < 2;
  else
    return i < 4;
})(); i++) {
  document.write(i);
}

You could make it vastly cleaner and clearer by putting the loop inside of the if, though.

A: No, you should not use an if-else statement within the body of a for loop. Especially if it contains an alert() window.
In your particular case it would be better to use a while statement.
var i = n1;
while ((n3 > 0 && i <= n2) || (n3 < 0 && i >= n2)) {
  nArr.push(i);
  i += n3;
}

I do not know exactly what you want to achieve but this is a jist of it.


text:
Q: tocbibind.sty on CentOS 8 A latex build lacks tocbibind.sty on my CentOS 8 box. Doing
$ sudo dnf install 'tex(tocbibind.sty)'

did not find it. Neither
$ sudo dnf whatprovides tocbibind.sty

has found it. I did a
$ sudo dnf install texlive-*

before. Also a
$ sudo dnf update

How can I install the sought tocbibind.sty onto my CentOS?


text:
Q: php mail + utf-8 = problem in Internet explorer I have a form on a page that sends data to php file via ajax request. The data is then collected into a single variable and sent to email specified in the php file. The data is in slovenian an uses a lot of letters that use diacritics (š,ć,ž). Everything works fine when the form is submitted from any browser that isn't Internet Explorer, but when sent from IE, email contains some gibberish charachters instead of letters with diacritics...
I specified mail headers in php file like this:
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html;charset=UTF-8' . "\r\n";
$headers .= 'From: xxx@yyy.si' . "\r\n";

the form is:
        <form id="order" class="order" name="form299" action="orderForm.php" method="POST">
            <fieldset>

Ime Priimek / Naziv

    podjetja:

 .....

Naslov / Sedež podjetja:

Did anyone encounter this problem?

A: I found a cause of this problem, it's urlencoding in javascript... Beginner's mistake :)
I just added
encodeURI('element.value')

for each field that I am sending via ajax, and it worked perfectly


text:
Q: php, soap, SOAP-ERROR: Parsing WSDL у меня есть данный код
try{
    $SoapClientOCR = new SoapClient (
    "http://www.ocrwebservice.com/services/OCRWebService.asmx?WSDL"
    array(
        "trace"=>1,
        "exceptions"=>1
    )
);

}catch (Exception $e){
    echo $e;
}
exit;

Но я получаю ошибку
SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.ocrwebservice.com/services/OCRWebService.asmx?WSDL' : failed to load external entity "https://www.ocrwebservice.com/services/OCRWebService.asmx?WSDL"

Подскажите, что не так и как реализовать код чтобы работало
в php ini я включил
extension=php_openssl.dll
extension=php_curl.dll
extension=php_xmlrpc.dll

все таже ошибка

A: Я без проблем загрузил и создал SoapClient на сервере OpenServer v5.2.2 с PHP 7.2, с расширениями XML, XSL, SimpleXML, SOAP, XMLRPC, XMLReader, XMLWriter и др., используя ваш код:
<?php

try{
    $SoapClientOCR = new SoapClient (
    "http://www.ocrwebservice.com/services/OCRWebService.asmx?WSDL",
    array(
        "trace"=>1,
        "exceptions"=>1
    ));
    echo 'Successfully loaded SOAP' . PHP_EOL;
}catch (Exception $e){
    echo $e;
}


text:
Q: Spring cloud stream + spring retry, How to add recovery callback and disable logic that send to DLQ? I'm using spring cloud stream + rabbit mq binder.
In my @StreaListener I want to apply retry logic on specific exceptions using RetryTemplate. After retries are exhausted or not retriable error is thrown, I would like to add a recovery callback that will save a new record with an error message to my Postgres DB and finish with the message (move to the next).
Here what I got so far:
  @StreamListener(Sink.INPUT)
  public void saveUser(User user) {
    User user = userService.saveUser(user); //could throw exceptions
    log.info(">>>>>>User is created successfully: {}", user);
  }

  @StreamRetryTemplate
  public RetryTemplate myRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());

    Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
    retryableExceptions.put(ConnectionException.class, true);
    retryTemplate.registerListener(new RetryListener() {
      @Override
      public <T, E extends Throwable> boolean open(RetryContext context,
        RetryCallback<T, E> callback) {
        return true;
      }

      @Override
      public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
        Throwable throwable) {
        //could add recovery logic here, like save error to db why sertain user was not saved
        log.info("retries exausted");
      }

      @Override
      public <T, E extends Throwable> void onError(RetryContext context,
        RetryCallback<T, E> callback, Throwable throwable) {
        log.error("Error on retry", throwable);
      }
    });

    retryTemplate.setRetryPolicy(
      new SimpleRetryPolicy(properties.getRetriesCount(), retryableExceptions, true));
    return retryTemplate;
  }

from properties, I only have these  (no any dlq configuration)
spring.cloud.stream.bindings.input.destination = user-topic
spring.cloud.stream.bindings.input.group = user-consumer

And after retries are exhausted I get this log.
2020-06-01 20:05:58.674  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:56722]
2020-06-01 20:05:58.685  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Created new connection: rabbitConnectionFactory.publisher#319c51b0:0/SimpleConnection@2a060201 [delegate=amqp://guest@127.0.0.1:56722/, localPort= 50728]
2020-06-01 20:05:58.697  INFO 18524 --- [idge-consumer-1] c.e.i.o.b.c.RetryConfiguration           : retry finish
2020-06-01 20:05:58.702 ERROR 18524 --- [127.0.0.1:56722] o.s.a.r.c.CachingConnectionFactory       : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'DLX' in vhost '/', class-id=60, method-id=40)

After RetryListener close method triggered, I can see that listener tries to connect to DLX probably to publish an error message. And I don't want it to do that as well as observe this error message in the log each time.
So my questions are:
1) Where to add RecoveryCalback for my retryTemplate? Supposedly I could write my recover logic with saving error to db in RetryListener#close method, but there definetely should be more appropriate way to do that.
2) How to configure rabbit-mq binder not to send messages to DLQ, maybe I could override some method? Currently, after retries are exhausted (or not retriable error is coming) listener tries to send a message to DLX and logs error that couldn't find it. I don't need any messages to be sent to dlq in scope of my application, I only need to save it to DB.

A: There is currently no mechanism to provision a custom recovery callback.
Set republishToDlq to false (it used to be). It was changed to true, which is wrong if autoBindDlq is false (default); I will open an issue for that.
Then, when retries are exhausted, the exception will be thrown back to the container; you can use a ListenerContainerCustomizer to add a custom ErrorHandler.
However, the data you get there will be a ListenerExecutionFailed exception with the raw (unconverted) Spring AMQP Message in its failedMessage property, not your User object.
EDIT
You can add a listener to the binding's error channel...
@SpringBootApplication
@EnableBinding(Sink.class)
public class So62137618Application {

    public static void main(String[] args) {
        SpringApplication.run(So62137618Application.class, args);
    }

    @StreamListener(Sink.INPUT)
    public void listen(String in) {
        System.out.println(in);
        throw new RuntimeException("test");
    }

    @ServiceActivator(inputChannel = "user-topic.user-consumer.errors")
    public void errors(String in) {
        System.out.println("Retries exhausted for " + new String((byte[]) in.getFailedMessage().getPayload()));
    }

}


text:
Q: SharedPreferences Android - Saving and editing one string only using two activities I have a single string which the user will edit and will be displayed back to him when he uses the app.  He can edit the string at any time.  I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better.  However, after following two different tutorials, I am unable to get it so save the data.  In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities.  Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {

TextView textSavedMem1;

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.mission_view);

           textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);

           LoadPreferences();

           textSavedMem1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    finish();
                    return;
                }});

       };

       private void LoadPreferences(){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        String strSavedMem1 = sharedPreferences.getString("MEM1", "");

        textSavedMem1.setText(strSavedMem1);

       }

      }

Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {

EditText editText1;
Button buttonSaveMem1;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.mission_edit);

       editText1 = (EditText)findViewById(R.id.editText1);
       buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);

       buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);

   }

   Button.OnClickListener buttonSaveMem1OnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   SavePreferences("MEM1", editText1.getText().toString());
   viewStatement();
  }

   };

   private void SavePreferences(String key, String value){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
   }

   protected void viewStatement() {
        Intent i = new Intent(this, MissionOverviewActivity.class);
        startActivity(i);
      }

}

If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks

A: getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
      "yourfilename", Context.MODE_PRIVATE);

and use the same method when you want to reload it. here the doc for getPrerences(int)


text:
Q: Ruby on Rails5: Filtering users by City / Country what is the best way to structure Location information for users? I need to be able filter hundreds of users by City/Country.
Currently I have created a free-text string for location as I could not find any gem for whole cities grouped under countries. Btw this is a custom scaffold, not devise.

Should I just enter as free-text as in city, country and then filter based on that string with alike?
Thank you

A: If you have structured data (i.e., address, city, state, country) for your users, you can filter on those. For example:
WHERE city || ', ' || country ILIKE ?

If you don't, you can still try that assuming freeform location information on your users table (you weren't clear on the database schema):
WHERE location ILIKE ?

Ideally you'd split up the city and country and filter separately:
WHERE city ILIKE ? AND country ILIKE ?

Hundreds shouldn't be much of a performance issue but you can definitely build indexes for either of those:
CREATE INDEX city_country_on_users ON users(city || ', ' || country);
CREATE INDEX city_country_on_users ON users(location);
CREATE INDEX city_country_on_users ON users(city, country);

respectively

A: I don't recommend usage of free-tex input because you will get different possible entries for the same city and country which will make filteration an impossible task. It is always better to use a drop down list.
Here is a full list of countries and cities using java script.
change the location attribute with two attributes country and state and use the previous list to fill them.


text:
Q: How to pass parameters to a method using blocks I know If I have a method like this
-(void) myMethod:(myCompletion) compblock{
//do stuff
compblock(YES);
}

I can call to that method using a block like this
[self myMethod:^(BOOL finished) {
if(finished){
    NSLog(@"success");
}
}];

If this myMethodhave several parameters like this
-(void)myMethod :(NSMutableURLRequest *)request :(BOOL)isGet :(NSMutableDictionary *)jsonBody :(myCompletion) compblock

How can I modify the above block in order to pass several parameters
Please help me

A: Try like this:
-(void)myMethodWithRequest:(NSMutableURLRequest *)request myBool:(BOOL)isGet dictionary:(NSMutableDictionary *)jsonBody  block:(void (^)(NSMutableURLRequest *, BOOL, NSMutableDictionary *))compblock;

-(void)myMethodWithRequest:(NSMutableURLRequest *)request myBool:(BOOL)isGet dictionary:(NSMutableDictionary *)jsonBody  block:(void (^)(NSMutableURLRequest *, BOOL, NSMutableDictionary *))compblock {

compblock(request, isGet, jsonBody);

}

Not tested in XCode though. Also, don't leave parameters in your method unnamed, it's a nightmare to read.
I often forget how to properly declare a block, gladly there's a nice website for that!


text:
Q: How to save changes and installed packages so I can install them in other systems I want to format my system, but I don't want to lose my updates and installed packages. I also want the same packages on other systems as well.

A: Backing up should be:
dpkg --get-selections > ~/Package.list
sudo cp /etc/apt/sources.list ~/sources.list
sudo apt-key exportall > ~/Repo.keys

and restoring should be
sudo apt-key add ~/Repo.keys
sudo cp ~/sources.list /etc/apt/sources.list
sudo apt-get update
sudo apt-get install dselect
sudo dpkg --set-selections < ~/Package.list
sudo apt-get dselect-upgrade -y

...If I'm not mistaken.


text:
Q: div do not align as row using display: flex I try to align three div on the same row but div only display one by row, as if I was using column. Any idea on what's my error ?
Do not hesitate to tell me if you think the error could come somehow from the 'header.php' which is the only other part of my work so far. I'll post HTML and CSS of it here if asked to.

body {
  background-color: #F1F1F1;
  font-family: 'robotolight';
  margin-top: 0px;
  margin-right: 0px;
  margin-left: 0px;
}
.container {
  padding: 0;
  margin: 0;
  background-color: #ffffff;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  flex-flow: row nowrap;
  -webkit-flex-flow: row wrap;
  jusitify-content: space-around;
}
.mydiv {
  background-color: #ffffff;
  -moz-box-shadow: 1px 1px 1px 0px #999999;
  -webkit-box-shadow: 1px 1px 1px 0px #999999;
  -o-box-shadow: 1px 1px 1px 0px #999999;
  box-shadow: 1px 1px 1px 0px #999999;
  width: 30%;
  height: 30%;
}

    first div left

    second div center

    third div right

A: *

*You havn't a .container element, you have a #container element.

*It's justify-content and not jusitify-content.

Example:

.container {
  align-items: center;
  border: 3px solid #CCC;
  border-radius: 5px;
  display: flex;
  justify-content: space-around;
  padding: .5rem;
  width: 210px;
}
.box {
  background-color: #ddd;
  height: 60px;
  line-height: 60px;
  text-align: center;
  width: 60px;
}

1

2

3


text:
Q: PIL.ImageDraw.Draw.text prevent the text running out of the scope I'm trying to "draw" text onto pitures with a python script using PIL.
The code looks like following:
    text = TextBoxDedication.get("1.0",END).split("\n")

    # Text auf dem Hintergund platzieren
    lineCnt = 0
    for line in text:
        draw = ImageDraw.Draw(BackgroundDummy)
        draw.text((IMG_POSITIONS[4][0],IMG_POSITIONS[4][1]+80*lineCnt), line, font=font)
        print draw.size
        lineCnt = lineCnt +1

    BackgroundDummy = BackgroundDummy.resize(IMG_SIZES[2])
    photo = ImageTk.PhotoImage(BackgroundDummy)

The Problem is: if the text results in a overlay which is to wide the text reaches the right border of the picture below.
Does someone see a possibility to have a kind of "auto-newline" if the text would be to wide?
Or can I at least determine the resulting size (in px) of a given text to estimate if it would fit onto the background or not?
thanks a lot in advance!
BR DaZeller


text:
Q: Variable thats defined in if is later not defined I thought I can define a var in an if statement and use it later in the following code. Why is this not working in my example?

let a = prompt('1', '');

if (a == 1) {
  let x = 10;
  let y = 20;
  let z = x + y;
} else {
  let z = 50;
}

alert(z);

I'm pretty new to JS, thats why this error comes up for me. What would be the correct way to override z if the if is false?

A: It is because z is out of scope. If you want to use it outside if, you need to declare them out of if condition

let a = prompt('1', '');
let x, y, z;

if (a == 1) {
  x = 10;
  y = 20;
  z = x + y;
} else {
  z = 50;
}

alert(z);


text:
Q: SQL 'After insert trigger' complains of unknown column 'currentId' in field list, which is cursor I have 2 tables.
create table comments (
    id int auto_increment primary key,
    task_id int not null,
    foreign key fk_comment_task(task_id) references tasks(id),
    user int not null,
    foreign key fk_comment_user(user) references users(id),
    comment varchar(1000) not null,
    comment_date date not null,
    viewed tinyint(1) not null default 0,
    deleted tinyint(1) not null default 0
) engine = InnoDB;

and a second one:
create table viewed_comments (
    id int auto_increment primary key,
    comment int not null,
    foreign key fk_viewed_comment(comment) references comments(id),
    viewer int not null,
    foreign key fk_viewed_viewer(viewer) references users(id),
    unread tinyint(1) not null default 0,
    deleted tinyint(1) not null default 0
) engine = InnoDB;

I want to create a trigger that says when a comment is inserted into the 'comments' table, the 'viewed_comments' table creates rows for that comment for all users except the one submitting the comment.
At the moment, I have a trigger:
delimiter |
create trigger ins_views after insert on comments
for each row
    begin
        DECLARE finished INT DEFAULT 0;
        DECLARE id INT DEFAULT 0;

        DECLARE currentId CURSOR FOR SELECT id FROM users WHERE id != NEW.user;

        DECLARE CONTINUE HANDLER
            FOR NOT FOUND SET finished = 1;

        OPEN currentId;

        update_views_loop: LOOP
            FETCH currentId INTO id;
            IF finished = 1 THEN LEAVE update_views_loop;

            END IF;
            INSERT INTO viewed_comments (comment, viewer) VALUES (NEW.id, currentId);

        END LOOP update_views_loop;

     CLOSE currentId;

    END;
|

delimiter ;

When I do an insert into the such as 'insert into comments (task_id, user, comment, comment_date) values (24, 4, 'test', '2018-3-5'); as an example, I get the following response.
ERROR 1054 (42S22): Unknown column 'currentId' in 'field list' which is the cursor.  How do I fix this?

A:  INSERT INTO viewed_comments (comment, viewer) VALUES (NEW.id, id);

Because you read the value into the variable id. Use this value and not the cursor.
 FETCH currentId INTO id;


text:
Q: Rebuilding directory tree (and/or inodes) Problem
My Armbian based Orange Pi webserver crashed (probably because of a power loss). I thought it would be fine since ext4 is more resilient and it usually has been in the past, but for some reason, this time, it didn't reboot, it hung. When I checked, it seems the "drive" (actually a memory-card) "does not have a valid filesystem".
I pulled the card and made a backup image (amounting to ~4.5GB out of the 32GB space on the card) and examined it in a hex-editor and various programs. I also burned an Armbian ISO to an identical memory-card to compare metadata values.
I do have a copy of the system from a couple of years ago on a different (non-identical card), but the server has changed a fair bit since then. Hopefully it can at least provide some more information to compare.
Observations
I've noticed several issues:

*

*Most programs are unable to detect the card as containing a filesystem. No, fsck, testdisk, etc. don't work, they complain about a bad magic number, or wrong fs type, bad option, bad superblock, or missing codepage, or filesystem seems damaged, or bad relative sector, or other blocking errors.

*The superblock is damaged (and I couldn't find backups); it looks like most of the entries are okay, but the following definitely have unusual/invalid values. I compared the values of the broken system with the new one, leaving out values like partition size or mount count which will naturally differ. Expected values with a question mark are ones which I'm not sure are specific to the drive or not, that is, I don't know if they're incorrect.

Field
Actual value
Expected value

Blocks per group
0
32768

Fragments per group
0
32768

inodes per group
5680
? 8160

Maximal mount count
0x7777
0xffff

Magic signature
0x6753
0xef53

File system state
 ‽‽‽ 0x03
0x00 or 0x01

First inode number
3
? 11

Compatible features
0x34
? 0x3c

Incompat features
0x246
? 0x242

R0 comp features
0x63
? 0x7b

*

*Searching the drive with a hex-editor, I'm able to find various directories and files, but examining it with some programs seems to indicate that at least some inodes seem to be wiped/zeroed out.

*If I modify some of the superblock values (specifically the …per group values, magic signature, and file system state, then programs can see it, but with the following problems:

*

*They still complain about things like it being an invalid filesystem or partition type

*Some programs can list the root directory, but only show a few subdirectories (bin, boot, dev, lib, lost+found)

*Contents of displayed directories are incorrect (eg only a few Python files in /boot)

*Other subdirectories (etc, mnt, …, usr, var) are shown as broken/unknown files instead of directories

*At least one subdirectory (home) isn't listed at all—though that might be because home is a symlink to somewhere in one of the broken directories

*One program's validation routine shows the following problems:

*

*Integrity status: invalid

*inodes count is valid: no

*SuperSector copy exists and matched: no (is that supposed to be superblock? )

*Most programs are showing the root-directory as ' instead of /.

*The damaged card has ~300MB of unallocated space after the ~29GB partition. That may or may not have been like that before the corruption. I distinctly recall a Pi setup tutorial saying to run a command to expand the partition to the full size of the drive/card after burning the ISO and booting the first time, but I just can't seem to find the tutorial or command . When I burned the new card and expanded the partition, it used the the whole card. It does seem like the old version on the old card also has a ~290mb unallocated chunk at the end.

*Sometimes I get the sense that something was deleting everything on the card, but that doesn't make sense because it wasn't a virus that crashed it, it was a faulty power-supply.
Resources
Here are some resources I have available at my disposal:

*

*Original corrupted card with minimal modifications (which I can reverse)

*Cloned image of corrupted card

*Previous version of the system from 2019 before it was transferred to a new card (though I can't for the life of me remember if I cloned it to the new card and then updated it or just burned a new ISO from scratch and transferred some files —I know I started with Jesse, updated to Stretch somehow, and was using Buster before the crash)

*Another identical memory-card that (should) have identical parameters (eg sector count)

*Free or trial versions of as many data-recovery and/or forensic programs as I could find (I'd consider purchasing a license to something if it's not too expensive and it'll definitely help restore the server)

*A WordPress SQL dump from two months before the crash (but it doesn't contain external files like graphics files )

*Backups of the etc, home, var/lib/mysql, and var/www directories from a couple of years ago—I could swear I made a more recent backup of at least etc but can't seem to find it anywhere

*ISOs of various versions of Armbian

*Various screenshots

*Unfortunately, I'm not too knowledgeable about ext* (yet; I'm reading up on it now), but I am very familiar with FAT* and have done a lot of data-recovery with that over the years, so hopefully my skills can transfer to this filesystem

*I'm happy to provide any other information or answer any other questions needed

Desire/Requirements/Question
Ideally, I'd like to be able to modify a couple of values to fix the filesystem so that it's all fixed like nothing happened, but it looks like that's not going to happen.
As a last resort, I can restore the image from late 2019 and try to manually restore/re-inject the other individual backups, at the risk of possibly losing a couple of years of work.
At a minimum, I need to recover:

*

*At least a few things from etc (mostly text files)

*Any new files in root/home since last version (mostly text files)

*Any new files in var/www since the last version (mostly graphics files—WITH FILENAMES)

*Ideally var/lib/mysql (binary files) to avoid losing two months since last SQL dump

*List of installed packages (where does Linux keep the list? please be a text-file) Remeber, this is offline, so I can't run a command to dump it (though I swear I did recently, but again, I can't seem to find it )

(You know, looking at it like this, it doesn't seem so disastrous anymore; it feels like time and work but seems doable. )
Question
Is there a way/program that will let me rebuild the directory tree or inode chains? That is, some way to look for directories and files (eg a string/byte search), then fill in the sector/cluster/inode of the start of the item, then have the program rebuild the inode chain based on that and the length of the file/directory?
The card was at least 80% empty and there wasn't too much delete/write activity, so most of the files and directories should be unfragmented, so it should be sufficient for most of them to just know the start and length to be able to restore the directory or copy the whole file.
Note
A regular content-based file-recovery scan isn't going to be of much use since it would just dump a ton of files with no filenames or directory structure, which is useless here since many of the files will be similar and/or binary, and thus very difficult to rename or locate their appropriate directories.
Tangential question
How does the system know if the partition is ext2/ext3/ext4 if they all use the same partition identifier of 83/0x53? I couldn't find another field to identify it it.

A: The ext2/3/4 filesystems are just different variants of the same filesystem, with newer features being added, so much on the on-disk structure is the same. That is why there is only a single magic value for all three variants of the filesystem. The major new feature in ext3 is has_journal, while ext4 added extents and several other features.
You may consider to download and build the e2fsprogs sources (on a different system/card) to get a copy of the findsuper program.  It will do a sector scan of the device looking for the ext2/3/4 magic value in the superblock, regardless of whether the partition table is corrupted or not. This will identify the start offset (in bytes) of the partition where each filesystem is located, which may help you rebuild/recover the partition.

A: As discussed ext/ext2/3/4 are very much the same derived from UFS/FFS (see also 1 and 2) they order the data in the same way in terms of inodes, blocks and pointers (indirect blocks etc), which are all common to FFS - the first filesystem for Unix. Linux is a derivative of unix and ext is FFS with some additional features. The linux filesystem API is built into the kernel and is compatible with all versions of ext
In terms of recreating the inode table the core of the filesystem is a list of pointers to blocks containing the data of each file. Without this list the blocks corresponding to each file can only be guessed. Ext4 in particular is good at allocating blocks that are contiguous (it incorporates a 'multiple block allocation' or mballoc feature) so this guess may be fine. But for large files where there  may be fragmentation the task becomes difficult and as far as I know there is no known tool that can reconstruct a file from blocks that are fragmented. I would reiterate that ext2 is good at allocating contiguous blocks (blocks of a given file are almost always close together). you may read about the low level structure of ext2/3/4 here. In the case of fragmentation you would have to manually locate the blocks yourself which for a large file would be extremely difficult. Larger files are more likely to be fragmented.
The metadata (the inode corresponding to each file) is as important as the data itself and without the metadata your data can no longer be considered present - even if it is still present unchanged on the disk - strictly speaking there is no ability to reconstruct the blocks in order so a large fragmented file is as good as lost without the inode table
The only options are to use a data carving tool (such as PhotoRec or foremost) alongside your own heuristics of what the data consists of, which may help to reconstruct your files.
Given how important the metadata is and how easy it can be corrupted, you may consider regularly scheduling e2image which allows backup of only metadata - which is a fraction of the size of a full backup. Of course if the filesystem changes after the backup the metadata will become irrelevant


text:
Q: How to add default value in input text field using js I bought a plugin ,the plugin is fine but I want to modify a feature ,but the support team seem too busy to help. What I'm going to do is add default value "+886" in the start of the text field.I tried add defaultValue: "+886"in the code, but unfortunately not work. This problem has bothered me for 20 days , Can anyone give some hints?
wp.element.createElement("label", null, window.vibephoneauth.translations.enter_mobile_no_with_code), wp.element.createElement("input", {
            className: "input",
            type: "tel",
            value: _,
            onChange: function(e) {
                E(e.target.value)
            }
        })

original code
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(0);function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,a=!1,o=void 0;try{for(var i,l=e[Symbol.iterator]();!(r=(i=l.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){a=!0,o=e}finally{try{r||null==l.return||l.return()}finally{if(a)throw o}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return l(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return l(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var c=wp.element,u=c.useState,s=c.useEffect,p=c.Fragment,m=wp.data.select,d=function(e){var t=i(u(),2),n=t[0],r=t[1],o=i(u(""),2),l=(o[0],o[1],i(u(""),2)),c=l[0],d=l[1],f=i(u(""),2),b=f[0],h=f[1],w=i(u(),2),v=w[0],y=w[1],g=i(u(""),2),_=g[0],E=g[1],O=i(u(),2),N=O[0],j=O[1],S=i(u(!1),2),P=S[0],k=S[1],T=i(u(""),2),C=T[0],I=T[1],x=i(u(""),2),M=x[0],L=x[1],A=i(u(!1),2),q=A[0],D=A[1],J=i(u(!1),2),U=J[0],$=J[1],F=i(u(!1),2),R=F[0],H=F[1],V=function(e){L(e),setTimeout((function(){L("")}),5e3)};s((function(){y(!0)}),[]);var W=function(e){return new Promise((function(t,n){fetch("".concat(window.vibephoneauth.api.url,"/phone_auth_login?client_id=").concat(window.vibebp.settings.client_id),{method:"post",body:JSON.stringify({social:e.credential.signInMethod,client_id:window.vibebp.settings.client_id,user:{email:e.user.email,password:e.user.password,uid:e.user.uid,name:e.user.displayName,avatar:e.user.photoURL,phoneNumber:e.user.phoneNumber,last_login:e.user.metadata.lastSignInTime,create_time:e.user.metadata.creationTime},idToken:e.idToken})}).then((function(e){return e.json()})).then((function(e){t(e)}))}))},z=function(e){fetch("".concat(window.vibebp.api.validate_token,"?client_id=").concat(window.vibebp.settings.client_id),{method:"post",body:e.token}).then((function(e){return e.json()})).then((function(t){if(t.hasOwnProperty("data")&&t.data.data.user){localforage.setItem("bp_login_token",e.token),localforage.setItem("bp_user",JSON.stringify(t.data.data.user)),sessionStorage.setItem("bp_user",JSON.stringify(t.data.data.user)),m("vibebp").setToken(e.token),m("vibebp").setUser(t.data.data.user),document.querySelector("body").classList.add("vibebp-logged-in"),window.location.href=t.data.data.user.profile_link;var n=new CustomEvent("userLoaded",{detail:{userLoaded:!0}});document.dispatchEvent(n)}}))};return wp.element.createElement("div",{className:"vibebp_phoneauth_wrapper"},M?wp.element.createElement("div",{className:"vbp_message"},M):"",wp.element.createElement("div",{id:"phone-auth-recaptcha-container",className:P?"hidden":"visible"}),wp.element.createElement("div",{className:"vibebp_phoneauth_form_wrapper"},wp.element.createElement("div",{className:"vibebp_phoneauth_form loginform"},v?wp.element.createElement(p,null,wp.element.createElement("div",{className:"field"},wp.element.createElement("div",{className:"control"},wp.element.createElement("label",null,window.vibephoneauth.translations.enter_mobile_no_with_code),wp.element.createElement("input",{className:"input",type:"tel",value: _,onChange:function(e){E(e.target.value)}}))),_&&/^\+(?:[0-9] ?){6,14}[0-9]$/.test(_)?wp.element.createElement("a",{className:q?"button is-primary is-loading":"button is-primary",onClick:function(){D(!0);var e=new firebase.auth.RecaptchaVerifier("phone-auth-recaptcha-container");firebase.auth().signInWithPhoneNumber(_,e).then((function(e){y(!1),j(e),k(!0),D(!1)})).catch((function(e){D(!1),V(window.vibephoneauth.translations.error_occured)}))}},window.vibephoneauth.translations.login):""):"",N?wp.element.createElement(p,null,wp.element.createElement("div",{className:"field"},wp.element.createElement("div",{className:"control"},wp.element.createElement("label",null,window.vibephoneauth.translations.enter_otp),wp.element.createElement("input",{className:"input",type:"text",value:C,onChange:function(e){I(e.target.value)}}))),C?wp.element.createElement("a",{className:U?"button is-primary -is-loading":"button is-primary",onClick:function(){$(!0),N.confirm(C).then((function(e){j(!1),k(!0);var t=e.user,n=a(a({},e.credential),{},{signInMethod:"phone_auth"});t.getIdToken().then((function(o){var i=a(a({},e),{},{user:t,credential:n,idToken:o});W(i).then((function(e){$(!1),e.status?z(e):"not_registered"==e.code&&(r(i),V(window.vibephoneauth.translations.phone_no_not_linked))}))}))})).catch((function(e){V(window.vibephoneauth.translations.code_not_confirmed)}))}},window.vibephoneauth.translations.connfirm_code):""):"",n?wp.element.createElement(p,null,wp.element.createElement("div",{className:"field"},wp.element.createElement("div",{className:"control"},wp.element.createElement("label",null,window.vibephoneauth.translations.enter_email),wp.element.createElement("input",{className:"input",type:"email",value:c,onChange:function(e){d(e.target.value)}}))),wp.element.createElement("div",{className:"field"},wp.element.createElement("div",{className:"control"},wp.element.createElement("label",null,window.vibephoneauth.translations.enter_password),wp.element.createElement("input",{className:"input",type:"password",value:b,onChange:function(e){h(e.target.value)}}))),b&&c&&function(e){return!!/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(e)}(c)?wp.element.createElement("a",{className:R?"button is-primary is-loading":"button is-primary",onClick:function(){var e,t;e=a({},n),t=a(a({},e),{},{user:a(a({},e.user),{},{email:c,password:b})}),H(!0),W(t).then((function(e){H(!1),e.status?(r(!1),document.querySelector("body").classList.add("loading"),z(e)):e.hasOwnProperty("message")&&V(e.message)})).catch((function(e){V(window.vibephoneauth.translations.error_occured)}))}},window.vibephoneauth.translations.register):""):"")))},f=wp.element,b=(f.createElement,f.render);f.useState,f.useEffect,f.Fragment,f.useContext;window.vibephoneauth.settings.enable&&document.addEventListener("login_with_mobile",(function(e){var t=document.querySelector("#login_with_mobile");if(!t){var n=document.createElement("div");n.innerHTML='

',document.querySelector(".login_popup_content").appendChild(n)}(t=document.querySelector("#login_with_phone_auth"))&&b(wp.element.createElement(d,null),t)}))}]);

A: As far as i could see, the _ receives the phone number. Try something like this.
wp.element.createElement("label", null, window.vibephoneauth.translations.enter_mobile_no_with_code), wp.element.createElement("input", {
            className: "input",
            type: "tel",
            value: '+886' + _, // Append the desired number
            onChange: function(e) {
                E(e.target.value)
            }
        })


text:
Q: How to obtain $n$ maximally different binary vectors with equal number of zeros and ones? Imagine the set of all binary vectors of length $2m$ where each of the vectors has $m$ ones and $m$ zeros.
I want to select some $n$ of these vectors such that the shortest distance among all pairs of vectors from this set of $n$ vectors is maximized. In other words I want a set of vectors which are maximally distant from each other.
I define distance by the number of positions at which the corresponding digits are different. For example distance between vectors $[1,0,0,1,1,0]$ and $[1,1,0,0,0,1]$ is $4$.
For example for $m=4$ and $n=2$ the solution can be $[1,1,1,1,0,0,0,0]$ and $[0,0,0,0,1,1,1,1]$.
How can I find a solution for arbitrary $m$ and $n$?

A: As Gerry Myerson observed, this is a relatively extensively studied open problem in coding theory. The topic is known as constant-weight codes.
Brouwer has a table of upper bounds for the sizes of constant-weight codes (among other things). In my experience his tables are well maintained, often cited, frequently updated and reflect the current state of research. Wikipedia also gives a link Agrell's table of lower bounds.

A: Unfortunately I solved the problem of minimizing distances
Let $A$ be a set of $2m$ elements, given a vector of length $2m$ with $m$ ones transform it into a subset of $A$ with $m$ elements where the elements are the positions that have a $1$. given vectors $v$ and $u$ transform them into subsets $v'$ and $u'$. Then the distance between $v$ and $u$ is equal to $2m-|u'\cap v'|$. Then what we want is to find the minimum $t$ so that there is a $t$-intersecting family $\mathcal F\subset \binom{A}{m}$ of size $n$.
You can use Erdős Ko Rado (see result 1.6) which tells you the maximum size of a $t$-intersecting family of subsets of $2m$ of size $m$ is $\binom{2m-t}{m-t}$ when $(m-t+1)(t+1)\geq 2m$, which in this case is for all $t$.
Therefore given $n$ find the largest $t$ so that $\binom{2m-t}{m-t}\geq n$, this is going to be the largest $t$ so that you can find a $t$ intersecting family of size $t$. when you convert the family into vectors you get a family of vectors such that the minimum distance between vectors is $2m-2t$.

The Problem of Maximizing Distances:
For this problem you can do the same translation, only this time you want a family of subsets that have small intersection, apparently this is open. The question has been asked before here and it includes an algorithm for constructing such sets.


text:
Q: "Undefined reference to" errors using numpy array in C++ I'm trying to compile some C++ code into a dll to import into Python for the first time. I want to be able to return a Numpy array from one of the functions, with an example line that looks like lNumpyArray = PyArray_SimpleNewFromData( 2, lDimensions, NPY_UINT8, (void*)lImage->GetDataPointer() );
At the start of the code I have included Python.h and arrayobject.h.
Using GCC (working on Windows) I have been able to compile the code to a .O file without errors. However, when trying to go to a dll, I'm getting a lot of errors like undefined reference to '__imp__Py_Dealloc'. From my limited understanding, it might be because I'm missing a library somewhere in the linker. Is there some other library I need to include for using Numpy arrays in C, or should I be looking elsewhere? The gcc command I've been using is included below.
gcc -Wall -shared Pipeline.cpp -I"C:/Python38/include" -I"C:/Program Files/Pleora Technologies Inc/eBUS SDK/Includes" -I "C:/Python38/Lib/site-packages/numpy/core/include" -L"C:/Python38/libs" -L"C:/Program Files/Pleora Technologies Inc/eBUS SDK/Libraries" -o lib.dll -lPvBuffer64 -lPvDevice64 -lPvStream64 -lPvAppUtils64 -lPvSystem64 -lSimpleImagingLib64 -lPvGenICam64 -lPvSerial64 -lPvBase64 -lPtUtilsLib64

A: I would avoid using the C Python interface to numpy and use a library link xtensor (found here).


text:
Q: TypeLoadException before executing the code in Windows Runtime 8.1 I am initializing log as below.
protected void InitializeLogging (string logFolderStoragePath)
{
    if (string.IsNullOrEmpty (logFolderStoragePath)) {
        logFolderStoragePath = _externalStorageFolderPath;
    }

    string settingsIniFilePath = Path.Combine (logFolderStoragePath, _settingsFileName);

     if (_fileSystem.FileExists(settingsIniFilePath))
     {
        FileIniDataParser iniFile = new FileIniDataParser();
        IniData data = iniFile.ReadFile(settingsIniFilePath);
     }
 }

I am calling function as:
InitializeLogging (logFolderStoragePath);

While executing above line, I am getting exception as:

An exception of type 'System.TypeLoadException' occurred in
  App.Forms.WindowsPhoneShared.DLL but was not handled in user code
       Additional information: Could not load type 'System.ICloneable' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=7cec85d7bea7798e'.

Even though I have set break-point in InitializeLogging function, its not even entering that function, its throwing exception before that. To find exactly where its breaking I commented one by one and found because of below line.
IniData data = iniFile.ReadFile(settingsIniFilePath);

If you see, I am reading iniFile only if settingsIniFilePath exist, but the file itself doesn't exist, still it throws exception.