text:
Q: Pysnmp: nextCmd() yields to many results for extended script the following code is used to imitate the command (executing a script on 'server')
snmpget server 'NET-SNMP-EXTEND-MIB::nsExtendOutputFull."queryMonitoring"'

Here's the code:
from pysnmp.hlapi import *

for (errorIndication,
     errorStatus,
     errorIndex,
     varBinds) in nextCmd(
                        SnmpEngine(OctetString(hexValue='8000000001020304')),
                        UsmUserData(userName='x', authKey='x', privKey='x'),
                        UdpTransportTarget(('server', 161)),
                        ContextData(),
                        ObjectType(ObjectIdentity('NET-SNMP-EXTEND-MIB', 'nsExtendOutputFull', "queryMonitoring"))):

    if errorIndication:
        print(errorIndication)
        break
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        break
    else:
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))

Here's the problem:
The command above the code yields the expected 279 results which look similar to this:
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".275 = (275, u'14:01:39', u'webserver3', u'0.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".276 = (276, u'14:01:39', u'webserver2', u'0.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".277 = (277, u'14:01:40', u'webserver4', u'1.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".278 = (278, u'14:01:40', u'webserver1', u'76.5')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".279 = (279, u'14:01:40', u'webserver3', u'0.0')

The python script whatsoever yields additional output from different MIB's:
...
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".274 = (274, u'14:01:39', u'webserver1', u'74.5')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".275 = (275, u'14:01:39', u'webserver3', u'0.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".276 = (276, u'14:01:39', u'webserver2', u'0.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".277 = (277, u'14:01:40', u'webserver4', u'1.0')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".278 = (278, u'14:01:40', u'webserver1', u'76.5')
NET-SNMP-EXTEND-MIB::nsExtendOutLine."queryMonitoring".279 = (279, u'14:01:40', u'webserver3', u'0.0')
NET-SNMP-AGENT-MIB::nsCacheDefaultTimeout.0 = 5
NET-SNMP-AGENT-MIB::nsCacheEnabled.0 = false
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.2.2 = 3
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.24.4 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.24.7 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.31.1 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.31.3 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.32 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.34 = 30
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.35 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.36 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.4.37 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.5 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.5.29 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.5.30 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.6 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.6.13 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.6.19 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.6.20 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.7 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.7.5 = 5
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.7.7 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.10.7.2 = 60
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.25.4.2 = 30
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.25.6.3 = 30
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.4.1.8072.1.31 = 5
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.2.2 = cached
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.24.4 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.24.7 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.31.1 = cached
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.31.3 = cached
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.32 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.34 = cached
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.35 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.36 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.4.37 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.5 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.5.29 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.5.30 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.6 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.6.13 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.6.19 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.6.20 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.7 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.7.5 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.7.7 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.10.7.2 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.25.4.2 = expired
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.25.6.3 = empty
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.4.1.8072.1.31 = expired
NET-SNMP-AGENT-MIB::nsDebugEnabled.0 = false
NET-SNMP-AGENT-MIB::nsDebugOutputAll.0 = false
NET-SNMP-AGENT-MIB::nsDebugDumpPdu.0 = false
NET-SNMP-AGENT-MIB::nsLogType.debug."/dev/null" = file
NET-SNMP-AGENT-MIB::nsLogType.debug."snmpd" = syslog
NET-SNMP-AGENT-MIB::nsLogMaxLevel.debug."/dev/null" = emergency
NET-SNMP-AGENT-MIB::nsLogMaxLevel.debug."snmpd" = emergency
NET-SNMP-AGENT-MIB::nsLogStatus.debug."/dev/null" = active
NET-SNMP-AGENT-MIB::nsLogStatus.debug."snmpd" = active
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.7.103.114.112.100.101.109.111.0.3.3.4.114.101.97.100 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.7.103.114.112.100.101.109.111.0.3.3.5.119.114.105.116.101 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.7.103.114.112.100.101.109.111.0.3.3.6.110.111.116.105.102.121 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.50.0.0.1.4.114.101.97.100 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.50.0.0.1.5.119.114.105.116.101 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.50.0.0.1.6.110.111.116.105.102.121 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.51.0.0.1.4.114.101.97.100 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.51.0.0.1.5.119.114.105.116.101 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.8.103.114.112.99.111.109.109.51.0.0.1.6.110.111.116.105.102.121 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.4.114.101.97.100 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.5.119.114.105.116.101 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.4.114.101.97.100 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.5.119.114.105.116.101 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.2.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 2
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.7.103.114.112.100.101.109.111.0.3.3.4.114.101.97.100 = _all_
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.7.103.114.112.100.101.109.111.0.3.3.5.119.114.105.116.101 = _all_
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.7.103.114.112.100.101.109.111.0.3.3.6.110.111.116.105.102.121 = _all_
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.50.0.0.1.4.114.101.97.100 = all
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.50.0.0.1.5.119.114.105.116.101 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.50.0.0.1.6.110.111.116.105.102.121 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.51.0.0.1.4.114.101.97.100 = systemonly
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.51.0.0.1.5.119.114.105.116.101 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.8.103.114.112.99.111.109.109.51.0.0.1.6.110.111.116.105.102.121 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.4.114.101.97.100 = _all_
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.5.119.114.105.116.101 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.4.114.101.97.100 = _all_
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.5.119.114.105.116.101 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.3.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = none
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.7.103.114.112.100.101.109.111.0.3.3.4.114.101.97.100 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.7.103.114.112.100.101.109.111.0.3.3.5.119.114.105.116.101 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.7.103.114.112.100.101.109.111.0.3.3.6.110.111.116.105.102.121 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.50.0.0.1.4.114.101.97.100 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.50.0.0.1.5.119.114.105.116.101 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.50.0.0.1.6.110.111.116.105.102.121 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.51.0.0.1.4.114.101.97.100 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.51.0.0.1.5.119.114.105.116.101 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.8.103.114.112.99.111.109.109.51.0.0.1.6.110.111.116.105.102.121 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.4.114.101.97.100 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.5.119.114.105.116.101 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.4.114.101.97.100 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.5.119.114.105.116.101 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.4.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 4
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.7.103.114.112.100.101.109.111.0.3.3.4.114.101.97.100 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.7.103.114.112.100.101.109.111.0.3.3.5.119.114.105.116.101 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.7.103.114.112.100.101.109.111.0.3.3.6.110.111.116.105.102.121 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.50.0.0.1.4.114.101.97.100 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.50.0.0.1.5.119.114.105.116.101 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.50.0.0.1.6.110.111.116.105.102.121 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.51.0.0.1.4.114.101.97.100 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.51.0.0.1.5.119.114.105.116.101 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.8.103.114.112.99.111.109.109.51.0.0.1.6.110.111.116.105.102.121 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.4.114.101.97.100 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.5.119.114.105.116.101 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.97.117.116.104.79.110.108.121.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.4.114.101.97.100 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.5.119.114.105.116.101 = 1
NET-SNMP-MIB::netSnmpObjects.9.1.1.5.15.103.114.112.105.110.116.101.114.110.97.108.85.115.101.114.0.3.2.6.110.111.116.105.102.121 = 1
SNMPv2-MIB::snmpSetSerialNo.0 = 1369298840
SNMP-FRAMEWORK-MIB::snmpEngineID.0 = 0x80001f88805e2e49072f68445700000000
SNMP-FRAMEWORK-MIB::snmpEngineBoots.0 = 255
SNMP-FRAMEWORK-MIB::snmpEngineTime.0 = 69821
SNMP-FRAMEWORK-MIB::snmpEngineMaxMessageSize.0 = 1500
SNMP-MPD-MIB::snmpUnknownSecurityModels.0 = 0
SNMP-MPD-MIB::snmpInvalidMsgs.0 = 0
SNMP-MPD-MIB::snmpUnknownPDUHandlers.0 = 0
SNMP-TARGET-MIB::snmpTargetSpinLock.0 = 0
SNMP-TARGET-MIB::snmpTargetAddrTDomain."internal0" = SNMPv2-TM::snmpUDPDomain
SNMP-TARGET-MIB::snmpTargetAddrTAddress."internal0" = 0x7f00000100a2
SNMP-TARGET-MIB::snmpTargetAddrTimeout."internal0" = 0
SNMP-TARGET-MIB::snmpTargetAddrRetryCount."internal0" = 0
SNMP-TARGET-MIB::snmpTargetAddrTagList."internal0" = internal0
...

Any ideas how to restrict the scripts output to the intended 279 lines?
thanks

A: nextCmd() is not the right function to perform a single snmpget call.
I figured out that I have to use getCmd()
    for (errorIndication,
         errorStatus,
         errorIndex,
         varBinds) in getCmd(
                SnmpEngine(),
                            UsmUserData(userName='x', authKey='x', privKey='x'),
                            UdpTransportTarget(('server', 161)),
                            ContextData(),
                ObjectType(ObjectIdentity('x'))):
        if errorIndication:
            print(errorIndication)
            break
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(),
                                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            break
        else:
            for varBind in varBinds:


text:
Q: Will a pre-defined Brush follow changes in Windows color scheme? Let's say I have the following code:
  Dim _Brush_Disabled As New SolidBrush(Color.FromKnownColor(KnownColor.GrayText))
  Dim _Brush_Enabled As New SolidBrush(Color.FromKnownColor(KnownColor.WindowText))

  Sub Do_Something()
    '
    ' ... _Brush_Disabled and _Brush_Enabled are repeatedly used in this sub
    '
  End Sub

Will _Brush_Disabled and _Brush_Enabled automatically change their colors if the Windows color scheme changes?
If not, how can I make them 'track' Windows color scheme changes?

A: No, it won't automatically update for you. You can listen for the WM_SYSCOLORCHANGE event on your main window (or where ever your brushes are defined) to know when to update.
More information can be found here and here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: converting hardcode data into dynamic foreach php I have a hardcoded data that I wanted to convert and the problem I am having is the multi dimensional array and that causes me to fail here is the hardcoded :
$query = array(
    'No' => 'test123',
    'list' => array(
        0 => array(
            'title' => 'MR'
        ),
        1 => array(
            'title' => 'MS'
        ),
        2 => array(
            'title' => 'MISS'
        ),
        3 => array(
            'title' => 'MISS'
        ),
    ),
);

I tried converting to dynamic php foreach from the data like this :
  foreach($datas as $data) {
    $num = count($data);
    $newdata = array();
    for($i=0;$i<$num;$i++) {
      $dataid = $data[$i]['target_id'];
      $datainfo = dataget($dataid);
      $title = strtoupper($datainfo->title);

      $datalist[] = array(
            'title' => $title,
          );
    }
  }
  $query = array (
      'No' => $title,
      'list' => $datalist
  );

but its not working, when I submit more then 1 data, it is not working, but when it is only 1 data it is working.
am I doing the refactoring of code correctly? can someone please clarify?
thank you

A: Your foreach use is incorrect. You are mixing data and datas.
foreach($datas as $data)

should be changed to
foreach($data as $datas)

Inside the loop, all occurrence of $data should change to $datas.
I didn't really get what you wanted to do clearly. But using the following code, I was able to print the content of the whole array.
$irr = array(
    'No' => 'test123',
    'list' => array(
        0 => array('title' => 'MR'),
        1 => array('title' => 'MS'),
        2 => array('title' => 'MISS'),
        3 => array('title' => 'MISS')
    ),
    'No2' => 'test2',
    'listo' => array(
        0 => array('title' => 'MR'),
        1 => array('title' => 'MS'),
        2 => array('title' => 'Mato')
    )
);

echo "
";
foreach($irr as $key=>$data) {
    $num = count($data);
    if ($num == 1) {
        echo $key . "=>" . $data."
";
        continue;
    }

    echo $key . "=>
";
    for($i = 0; $i < $num; $i++) {
      $dataid = $data[$i]['title'];
      echo "    ".$dataid."
";
    }
}


text:
Q: Ajax call never gets executed I got a simple php page that executes a Jquery script as follows:
SCRIPT part:

HTML part:
3FE62600AA

sfp-load.php content:
<?php echo $_GET['sfp'];?>

Explanation: everytime I mouse over the HTML part on the page, it executes the sfpRx() function that makes an ajax call to sfp-load.php. This Php page should return "3FE62600AA" to the ajax call, which should get printed in the console.
Problem: the "3FE62600AA" never gets printed in the console but I'm certain that the sfpRx() function is called because it prints "sfpRx Was executed" in the console. What could be happening? Am i forgetting anything? I'am sure the sfp-load.php page is in the NOKIA/ folder. I'am really annoyed with this.


text:
Q: Software rendering doesn't support hardware bitmap in Oreo LinearLayout llQRCodeShare;
try {
    llQRCodeShare.setDrawingCacheEnabled(true);
    llQRCodeShare.buildDrawingCache(true);
    Bitmap b = llQRCodeShare.getDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(b);
    llQRCodeShare.setDrawingCacheEnabled(false);
} catch (IllegalStateException e) {
    LogUtil.e(TAG, e.getMessage());    //Software rendering doesn't support hardware bitmap
}

when execute the code"llQRCodeShare.getDrawingCache()",throws the exception,
Software rendering doesn't support hardware bitmap

on the android8.0.
How to solve it?

A: disable hardware acceleration either for the whole Activity:
android:hardwareAccelerated="false"

or for that one particular View:
llQRCodeShare.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

A: just make the android:hardwareAccelerated="true" in the AndroidManifest.xml under Application tag


text:
Q: db.raw with more than one paremter with knex This actually works in knex:
knex.raw('select * from users where id = ?', [1])

I am trying to use more than one value as parameters, repeating some of them. Something like this:
knex.raw('select * from users where id = 1? and name = 2? and firstName = 2?', [1, 'someName'])

How can I achieve that?

A: It looks like the obvious quick solution is to simply repeat your array elements.
knex.raw('select * from users where id = 1? and name = 2? and firstName = 3?', [1, 'someName', 1])

I don't know knex, but there's nothing wrong with this solution either.
EDIT
A different approach is to use simple string interpolation through a library like kiwi:
var interpolateObject = {
  id: 'some_id',
  name: 'some_name',
  firstName: 'some_first_name'
};

var query = Kiwi.compose(
   "select * from users where id = %{id} and name = %{name} and firstName = %{firstName}",
    interpolateObject
    );

knex.raw(query);

Checkout kiwi.js

A: you can do something like this also:
var params = {x1:1,dude:10};
return knex.raw("select * from foo where x1 = :x1 and dude = :dude",params);

it's not the first example, but it's documented here.


text:
Q: Solve limit without use L'Hopital: $\lim _{x\to 0}\left(\frac{sin\left(2x\right)-2sin\left(x\right)}{x\cdot \:arctg^2x}\right)$ Task:
$$\lim _{x\to 0}\left(\frac{\sin\left(2x\right)-2\sin\left(x\right)}{x\cdot \:arctan^2x}\right)$$
Hello! It is necessary to solve the next limit. I try several methods. For example, if you use the equivalent of small, it turns out:
$$\sin\left(2x\right)\rightarrow 2x$$
$$2\sin\left(x\right)\rightarrow 2x$$
$$x\cdot arc\tan^2\left(x\right)\rightarrow x\cdot x^2$$
Limit obtained indefinite again...(
I have tried to simplify the numerator (only in the numerator as the denominator have no idea what to do):
$$\lim _{x\to 0}\left(\frac{2\sin x\cdot \cos x-2\sin x}{x\cdot arc\tan^2x}\right)=\lim _{x\to 0}\left(\frac{\sin x\left(\cos x-2\right)}{x\cdot arc\tan^2x}\right)=?$$

A: HINT:
$$\dfrac{\sin2x-2\sin x}{x\arctan^2x}=-2\cdot\dfrac{\sin x}x\cdot\dfrac{1-\cos x}{x^2}\cdot\left(\dfrac x{\arctan x}\right)^2$$
and $$\dfrac{1-\cos x}{x^2}=\dfrac1{(1+\cos x)}\cdot\left(\dfrac{\sin x}x\right)^2$$

A: Use  equivalents:
Numerator: $\;\sin 2x-2\sin x=2\sin x(\cos x-1)$, and $\sin x\sim_0 x$, $\;\cos x-1\sim_0 -\dfrac{x^2}2$.
Denominator: $\;\arctan x\sim_0 x$.
Thus: $$\frac{\sin 2x-2\sin x}{x\arctan^2 x}\sim_0\frac{x(-x^2)}{x\cdot x^2}=-1.$$

A: So you have the following limit:
$$\lim _{x\to 0}\left(\frac{\sin\left(2x\right)-2\sin\left(x\right)}{x\cdot \:\arctan^2x}\right)$$
I would suggest using taylor series:
$$\lim _{x\to 0}\left(\frac{\sin\left(2x\right)-2\sin\left(x\right)}{x\cdot \:\arctan^2x}\right) = \frac{\left(2x - \frac{(2x)^3}{3!} + \frac{(2x)^5}{5!} - \ldots\right) - 2\left(x - \frac{x^3}{3!} + \frac{x^5}{5!} - \ldots\right)}{x\left(x - \frac{x^3}{3!} + \frac{x^5}{5!} - \ldots\right)^2} = \frac{-x^3 + \ldots}{x^3 + \ldots}$$
Note that we only care about the lowest power of $x$ on the numerator and the denominator. In this case it is $x^3$. Thus, if we multiply the fraction by $\frac{1}{x^3}$, we end up with:
$$\frac{-x^3 + \ldots}{x^3 + \ldots} = \frac{-1 + 0 + \ldots}{1 + 0 + \ldots} = -1$$
Therefore our answer is $-1$. Comment if you have questions.


text:
Q: How to specify "value" for asp.net mvc Html helper droplist I want to specify a value for each option in the my select list box but I am generating it with an html helper.
So I have this
<%= Html.DropDownList("DropDownList") %>

// controller
ViewData["DropDownList"] = new SelectList(MyClass.GenerateListBox());

// MyClass

        public static List<string> GenerateListBox()
        {
            List<string> listBox= new List<string>();
            listBox.Add("Bye");
            listBox.Add("hi");
            listBox.Add("something");

            return listBox;
        }

So I see that SelectList has a "stringDataField" but it is only a stringnot a list so now really sure what I have to change.
Do I have to make some sort of other list?
Thanks

A: Use this constructor instead:
ViewData["DropDownList"] = new SelectList(GenerateListBox(), "Value", "Text");

public static List<SelectListItem> GenerateListBox()
{
    List<SelectListItem> listBox = new List<SelectListItem>();
    listBox.Add(new SelectListItem { Text = "bye", Value = "byeValue" });
    listBox.Add(new SelectListItem { Text = "hi", Value = "hiValue" });
    listBox.Add(new SelectListItem { Text = "something", Value = "somethingValue" });

    return listBox;
}

A: Use the SelectList constructor that takes two strings.
Specifically, instead of giving it a list of strings, give it a list of some object that has DisplayName and Value properties  (for example, KeyValuePair<String, String>, though I would recommend something more specific), and pass the names of those properties to that constructor.  This will set the DataTextField and DataValueField properties.
EDIT: What I mean is that instead of making your GenerateListBox method return a List<String>, you should make it return a List<YourClass> and make a YourClass class with properties for the DisplayName and the Value.


text:
Q: Switch Case in Razor based on parameters I am implementing tabbed view in mvc4. So i implemented partial view which in turn called in every view for tabbed structure. The below code set active tab based on the parameter passed from the view.

@{ var UserFocus = ""; var CardFocus = ""; var CarrierFocus = ""; }
@{
switch(ViewData["ActiveMenu"].ToString())
{
    case "User":
        UserFocus = "active";
        break;
    case "Card":
        CardFocus = "active";
        break;
    case "Carrier":
        CarrierFocus = "active";
        break;
}
}

User view link

card view link

Carrier view link

And in every view it will called like this based on the view
@Html.Partial("_AdminSettings", new ViewDataDictionary {{ "ActiveMenu", "User" }} )

This is working fine.

*

*I am sure whether the implementation is a standard practice ?

*Any other easy way for this implementation ?

A: Personally I do not like logic in the view.  As a rule of thumb I generally put the logic in the model and pass it down to the view and believe the view is there to display how the data should look, not manipulate the data.
As an alternative approach you could have a Navigation Model and pass:
ViewData["ActiveMenu"]

to your controller and populate the Navigation Model.
public class NavigationModel
{
    public string UserFocus { get; private set; }
    public string CardFocus { get; private set; }
    public string CarrierFocus { get; private set; }

    public NavigationModel(string ActiveMenu)
    {
       // Your switch statement to populate the properties.
    }
}

Your view would look like this:
@Model NavigationModel

User view link

card view link

Carrier view link

Which in my opinion is cleaner.


text:
Q: Duplicity error having to do with python? So I'm having this error which apparently is a known issue. I'm looking for a work-around until it's fixed because I can't afford to go without systems backup.
Traceback (most recent call last):
  File "/usr/bin/duplicity", line 1532, in <module>
    with_tempdir(main)
  File "/usr/bin/duplicity", line 1526, in with_tempdir
    fn()
  File "/usr/bin/duplicity", line 1380, in main
    do_backup(action)
  File "/usr/bin/duplicity", line 1401, in do_backup
    sync_archive(decrypt)
  File "/usr/bin/duplicity", line 1139, in sync_archive
    remote_metafiles, ignored, rem_needpass = get_metafiles(remlist)
  File "/usr/bin/duplicity", line 1029, in get_metafiles
    pr = file_naming.parse(fn)
  File "/usr/lib/python2.7/dist-packages/duplicity/file_naming.py", line 400, in parse
    pr = check_inc()
  File "/usr/lib/python2.7/dist-packages/duplicity/file_naming.py", line 340, in check_inc
    t1 = str2time((m1 or m2).group("start_time"), short)
  File "/usr/lib/python2.7/dist-packages/duplicity/file_naming.py", line 290, in str2time
    t = dup_time.genstrtotime(timestr.upper())
  File "/usr/lib/python2.7/dist-packages/duplicity/dup_time.py", line 295, in genstrtotime
    return override_curtime - intstringtoseconds(timestr)
  File "/usr/lib/python2.7/dist-packages/duplicity/dup_time.py", line 203, in intstringtoseconds
    error()
  File "/usr/lib/python2.7/dist-packages/duplicity/dup_time.py", line 194, in error
    raise TimeException(bad_interval_string % interval_string)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

Related issues:

*

*https://bugs.launchpad.net/ubuntu/+source/deja-dup/+bug/1377873

*https://bugs.launchpad.net/ubuntu/+source/deja-dup/+bug/1422289

*https://stackoverflow.com/questions/9644099/python-ascii-codec-cant-decode-byte

A: The core problem is Unicode strings - you've got them somewhere, and Duplicity (or at least, the version you're using possibly) is not configured to handle Unicode strings properly.  This is due to the caveats of Python 2.

In Python 2, there are two separate "string" type classes:

*

*str - This is the typical standard ASCII codec seen in many systems, and is more or less just the standard A-Z, 0-9, some symbols from the keyboard set of characters.

*unicode - This is the UTF-8 encoding, the UTF-16, etc. encodings, which have a huge range of international characters, emojis, etc.
Whatever is being passed to Duplicity, in this case, us likely using a character from the UTF charsets that is outside the standard ASCII range of characters.  This is why we get a UnicodeDecodeError in the traceback - we're trying to convert Unicode strings to ASCII strings, and we can't due to characters being outside the ASCII character sets.

I would suggest filing a bug in Duplicity to make a note they don't handle Unicode properly, but I would also look at whatever files Duplicity is handling and make sure you don't have any Unicode characters (or hidden secret control characters) in the strings it's trying to work with.

NOTE: According to the bugs linked, this is already fixed; it's possible that this was fixed in a later version of Deja-Dup, but not the version you are using, in which case you would need to find a Backported or Updated version to work around the error.
On one of the bugs, a workaround of renaming filenames with foreign character sets in the Unicode set should be renamed to ASCII-only filenames, for DejaDup to handle them properly.  That's the only known workaround, short of updating to a newer DejaDup verison.

A: Make sure you use the latest release 0.7.12, as there were some improvements in this regard.
Looks like duplicity tries to raise a TimeException, but stumbles over printing the error translation.
The current workaround should be setting LC_ALL env var to prohibit duplicity translating and using the default english strings.
Either export the setting or put it in front of your duplicity call, like so
LC_ALL=C duplicity ...

This of course won't solve the error, but at least show what the error (TimeException) is caused by.
..ede/duply.net


text:
Q: Spring DI : session vise object creation using aop proxy for inherited class In my project i have used struts2 and spring. Spring is used just for DI. I am having all my actions created by sessions and so as model beans via spring DI. Now I want to use inheritance  for my class which will be generated through aop based proxy and it will be per session. Coding goes as below.
<bean id="common.EshopDefaultAction" class="com.common.actions.EshopDefaultAction"   scope="session" >
    <property name="site" ref="master.site" />
    <property name="menu" ref="master.menu" />
    <property name="indexDAO" ref="common.indexDAO" />
    <property name="categoryDAO" ref="master.categoryDAO" />
    <property name="productDAO" ref="master.productDAO" />
</bean>

<bean id="common.IndexAction" parent="common.EshopDefaultAction" class="com.common.actions.IndexAction" scope="session">
    <property name="indexInfo" ref="common.indexInfo" />
    <aop:scoped-proxy />
</bean>

both actions are having pairs of setters and getters.
I want to have site,menu, indexDAO, categoryDAO, productDAO objects created by session for all of its child like IndexAction just shown above. Right now it creates different objects for EshopDefaultAction and IndexAction.
Adding <aop:scoped-proxy /> to EshopDefaultAction bean definition gives error like
Invalid property 'targetBeanName' of bean class [com.common.actions.IndexAction]:
Bean property 'targetBeanName' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?


text:
Q: How to redirect servlet request to a html page in filter I am writing a web app that redirect request (including html request and servlet request, $.post or $.get) a specific web page in a filter. it works for html page request. If I go to a web page I can not access, it redirects as expected. but If i click a button, send a servlet request that I can not access, it
does not redirect. What it does is just return the content of web page REDIRECT_URL and the web page I clicked and sent request still there. Following is the code I am using to do redirection
 httpResponse.setContentType("text/html;charset=UTF-8");
            httpResponse.setHeader("pragma", "no-cache");
            httpResponse.setHeader("Cache-Control", "no-cache");

 httpRequest.getRequestDispatcher(REDIRECT_URL).forward(httpRequest, httpResponse);

How can I do what I expected in filter. I do not want to redirect in web. I want all work done by filter. Thanks..

A: getRequestDispatcher(REDIRECT_URL).forward does not redirect. It does a server-side forward, meaning the container will just make a different internal request behind the scenes.
What you want is HttpServletRequest.sendRedirect:
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)
httpResponse.setContentType("text/html;charset=UTF-8");
httpResponse.setHeader("pragma", "no-cache");
httpResponse.setHeader("Cache-Control", "no-cache");

httpResponse.sendRedirect(REDIRECT_URL);


text:
Q: ¿Cómo creo una tabla con el campo fecha con el formato dd/MM/yyyy? En SQL Server el formato por defecto de DATE es yyyy/MM/dd.
Lo que quiero es cambiar este formato a dd/MM/yyyy al momento de crear la tabla. ¿Es posible? Si es así, ¿cómo?

A: Donde refieres formato por defecto entiendo que te refieras al formato en el que estás recibiendo la fecha en las consultas. Internamente SQL Server se encarga de realizar la codificación necesaria para almacenar la fecha, intentar modificar estos parámetros lo considero personalmente un error.
Lo que yo considero que deberías hacer es utilizar las funciones que provee para obtener la fecha en el formato correcto. Estas dependen de la versión que estés utilizando, a continuación tienes todas las funciones disponibles para cada version: (No olvides seleccionar tu versión para no volverte loco)
CAST y CONVERT (Transact-SQL))
En tu caso si tienes la versión mas reciente de SQL Server podrías utilizar:
SELECT CONVERT(char(10), GetDate(), 101)

de esta forma obtendrías la fecha en el formato que nos comentas.

A: El núcleo de la pregunta

Lo que quiero es cambiar este formato a dd/MM/yyyy al momento de crear la tabla. ¿Es posible? Si es así, ¿cómo?

Respuesta
No es posible si declaras tu columna del tipo DATE o del tipo DATETIME.
¿Por qué no es posible?
Porque una cosa es el formato (que tiene que ver con la manera de presentar los datos) y otra cosa es la manera en que el manejador de base de datos almacena esos datos. En el CREATE TABLE tú no tienes acceso a alterar la forma en que se ha diseñado el manejador para almacenar esos datos (y aunque pudieras no sería para nada conveniente). Si ya es trabajoso mantener por ejemplo un campo VARCHAR que manejase representaciones de fechas (ver final de la respuesta), imagínate la dificultad si se alterase la estructura interna de los datos.
SQL Server almacena los valores DATETIME como un campo de 8 bytes, con un rango entre 1753-01-01 a 9999-12-31, con una precisión de 0.00333 segundos.
Según esta respuesta de Stackoverflow:

Los primeros 4 bytes almacenan el número de días desde la época de SQL
  Server (1 de enero de 1900) y los otros 4 bytes almacenan el número de
  instantes después de la medianoche, donde un "instante" es de 3,3 milisegundos.
  Los primeros cuatro bytes están firmados (pueden ser positivos o
  negativos), lo que explica por qué se pueden representar las fechas
  anteriores a la época (1 de enero de 1900).

¿Y si de todos modos quiero hacerlo?
Si de todos modos quieres almacenar las fechas en ese formato, tendrás que crear una columna del tipo VARCHAR, y trabajar arduamente durante toda tu aplicación para:

*

*Dar mantenimiento a ese formato

*Controlar errores de inserción (como que alguien quiera poner que nación el 40-50-1845454, el día 40 del mes 50 del año 1845454).

*Hacer cálculos entre fechas (tendrás que hacer conversiones constantes de cadenas a objetos fecha reales para que los cálculos no fallen)

*... y muchos dolores de cabeza más.  Y eso, no hablemos si hay que almacenar valores de horas/minutos/segundos/milisegundos.

Recomendación final
Dejar las cosas como están y valerte de cualquiera de las funciones existentes para presentar tus fechas/horas en el formato que quieras.
DD-MM-YYYY no es más que una representación de los datos y existen múltiples funciones para lograrla con suma facilidad.
Querer alterar la estructura de un campo que maneje fechas tan solo por el formato no tiene sentido. Es como si quisieras que un campo VARCHAR te almacenara las letras en color rojo (el color es un formato, un atributo de salida). Cuando quieras ese texto en negro o en otro color tendrás que añadir un trabajo suplementario para conseguirlo y eso tendrá su precio.

PD: A quienes votan en contra, agradecería un comentario sobre el motivo del voto negativo, para poder mejorar la respuesta.


text:
Q: how to restrict root access to folders on aix? I want to restrict access to certain folder on aix.
even root user should be restricted to access certain folders.
for e..g i have user - aixuser and root on aix 5.3 server
and i have a folder - myfolder.
i want only aixuser to have access to this folder and not root.
how can i do this?

A: No, this cannot be done. The whole concept of the root user relies on unfettered access. You can quite easily protect your files from other regular users, using either the user/group/other paradigm or access control lists but, once someone has root powers, you cannot restrict them at all.
There's a good reason for this - if you lost access to your files somehow, how would you expect the administrators to recover them for you?
The way of dealing with your concerns is to either restrict the number of people with root access or somehow encrypt your files. But even that latter suggestion wouldn't stop a determined root user who can look inside your process address spaces or intercept your input stream to grab your passwords if need be.
The only workable security will be having your own box with only you having the root powers. Then you can treat a root user on a different box as just a regular user on yours.

A: You cannot exclude root access to any file on any local file system.

A: as paxdiablo is saying, root user privilege is the ultimate thing in AIX (infact any UNIX/Linux machine). In RBAC, setting the role permissions to aix (in the mkrole command) will give you permissions to do everything a root user can do but nothing more than the root user.
Having UID=0, GID=0 gives root all the access it needs on a machine.

A: Actually I believe you can do it with the encrypted file system.  I have not done it.  Sorry for the vague reply.  But I believe EFS has two modes.  One is to trust root and the other is to not trust root.
From https://www.ibm.com/developerworks/aix/library/au-efs/index.html
AIX® EFS encryption is at the file system level. Each file is protected with a unique file key, and protection is created against malicious root.

If you really think about it, encryption is the only choice you have.  Root can open up the hard disk and copy it over to another drive, then go monkey with the file system itself do what it pleases.  The only way to protect against root is via encryption.


text:
Q: How to execute javascript from html page I am making a request and reading the HTML content. The problem is that 90% of the content is JavaScript. How can I make the request and not get the JavaScript?
You can see here that CurrentHtml (the contents of the response) has JavaScript that contains elements that I need:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                    © BBVA S.A.

A: When you get a Page Source you will get everything which is on the page, that's obvious.
There are 2 things you can do!

*

*Remove Javascript from main page and put in a .Js file and reference it on your HTML, so you will finally receive a html with just single line

*Remove Javascript tag from HTML after you receive response

Something like this
 node.parentNode.removeChild(node);

A: you can't request a page without JS from a server separately. because it's a file that the server send to clients. unless there is a web service that make it to you.
but you can parse the HTML file and clear JS tags easily.
a wonderful parser


text:
Q: How to mutate with SWR only for specific ID? I've tried to look everywhere online and I can't seem to find any documentation on this which is strange because I thought it would be a popular need.
If we are trying to for example get the post with a specific id:
const { data } = useSWR(`/api/post/${id}`, fetcher)

And then maybe we have a form that edits the post, when we do mutate:
mutate(`/api/post/${id}`)

To force revalidation on a specific id, nothing happens. What would be the correct way to do it in this case?
And just to mention, doing SWR fetching without an id and something like /api/comments, where all the comments are fetched, then mutate has no problem revalidating when doing mutate('/api/comments')
Hopefully this made sense. What i'm basically trying to achieve is, to do a POST request after updating a post with some id, and then I want to re-render the page with the updated data.
I'm getting the impression that mutate doesn't recognize the key when the id value is dynamic

A: just import mutate function from the hook, its bounded with that key.
const { data, mutate } = useSWR(`/api/post/${id}`, fetcher)

then just call mutate()


text:
Q: Convert code snippets into a string representation for populating a code editor I'm trying to write a code-editor using react-live.
The following works, where I hardcode the sample code into a string:
const code="
hello</div";
...
<LiveProvider code={code}>
  <LiveEditor />
  <LiveError />
  <LivePreview />
</LiveProvider>

But, for more advanced usages (when there is more than a trivial amount of example code), it is not efficient to write code inside a string.
So, my underlying question is how can we effectively write example code which populates a code-editor?
Ideally, we could write the sample code in a separate module, as actual code, and then somehow read it in when setting up the code-editor component.
However, this doesn't work:
import sampleCode from "./sampleCode.jsx";
const code = sampleCode.toString(); // '[object Object]'

Additionally, defining the sample code right there within the file doesn't work:
const code =
hi
;
code.toString(); // '[object Object]'

How can I convert actual code snippets into a string representation?

A: What if you create a sample string and export it from a js file then import it and pass it in the code prop. I don't see an issue here. You can also lazily import samples.
Here's a simple use case:
// codeSamples.js
export const sample = `
const Sample = (props) => {
    return (

Sample!

    );
}
`.trim();

// Component.js
import { sample } from "./codeSample";

...
<LiveProvider code={sample}>
  <LiveEditor />
  <LiveError />
  <LivePreview />
</LiveProvider>


text:
Q: Is there an IntelliJ action or shortcut that allows creating a new separate file from existing code I quite often create multiple classes in one file and then split that file into multiple based on the classes or functions I have created.  Is there a way to extract a selection of code and create a new file from it in IntelliJ?  Part of the refactoring stuff maybe?  (I think this is possible in resharper)

A: You can use Refactor | Move Class to move the class into a separate file:


text:
Q: SwiftUI: master details default to item when not on iPhone? The following code:
struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>
    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    NavigationLink {
                        Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                    } label: {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            Text("Select an item")
        }
    }
    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)
            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}
private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

Renders to this:

I would like the details to default to the first item in the list by default when the app first runs, but only if the details is showing, so, on an iPhone for example I don't want it to be pushed automatically.
How can the details screen automatically show the first item in the list and not say "Select an item" when master-details is showing and not just master (left view)?


text:
Q: Worldspace 2d texture displacemet in Unity Shader Graph I am working on a 2d top-down game. I have an object that moves on a single large texture and casts shadow on it (just a blurry dark sprite). However I found out that since my texture has bumps, rocks, creases etc. it looks like the shadow sprite just hovers above the ground.
So I figured out that I could use my texture as a displacement map to distort the shadow sprite depending on the surface of the texture. I'm trying to implement that in Shader Graph but I can't manage to get proper position and scale of the underlying texture to project the shadow on.
I tried to implement a simplified version of the shader that precisely reproduces the part of the Ground Texture that it hovers above.

In this case scaling seems to be off, the resulting texture is a lot smaller than the original one. I'm not sure about the position but it seems to be off as well. Am I missing out something? Or is there an easier appreach to implement this?
Thanks in advance.

A: I'm not sure whether it is the most elegant solution but I found one.
I should have used Tiling and Offset node to scale and shift the UV of the ground texture. Here's the shader graph:

Right now this shader makes the object project the part of the ground texture it is placed on onto itself. It seems to be perfectly aligned with the texture.
Ground position is calculated in code:
[RequireComponent(typeof(SpriteRenderer))]
public class displaced_shadow : MonoBehaviour
{
    SpriteRenderer sr;
    Rect rect;
    MaterialPropertyBlock material_properties;
    float pixels_per_unit;

    public Vector2 Size //get size of the texture in Unity units
    {
        get { return new Vector2(rect.width * transform.localScale.x/ pixels_per_unit, rect.height * transform.localScale.y/ pixels_per_unit); }
    }

    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
        rect = sr.sprite.rect;
        pixels_per_unit = sr.sprite.pixelsPerUnit;
        material_properties = new MaterialPropertyBlock();
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 relative_position = CalculateRelativePostion();
        FeedMaterial(relative_position);
    }

    private Vector2 CalculateRelativePostion() //calculate the position relative to the background in [0,1] range
    {
        if (background_floor.This == null) return Vector3.zero;

        Vector2 bg_position = background_floor.This.Position; //get the size and position of the background texture
        Vector2 bg_size = background_floor.This.Size;

        float origin_x1 = transform.position.x - Size.x/2f; //calculate the top left corner positions in case textures have their origins in the center
        float origin_y1 = transform.position.y - Size.y / 2f;
        float origin_x2 = bg_position.x - bg_size.x / 2f;
        float origin_y2 = bg_position.y - bg_size.y / 2f;

        float x = (origin_x1 - origin_x2) / bg_size.x; //get the [0,1] position of the object relative to the ground texture
        float y = (origin_y1 - origin_y2) / bg_size.y;

        return new Vector2(x, y);
    }

    private void FeedMaterial(Vector2 relative_position)
    {
        sr.GetPropertyBlock(material_properties);
        material_properties.SetVector("_GroundPosition", relative_position);
        sr.SetPropertyBlock(material_properties);
    }
}


text:
Q: Meaning of the Reduced Density Operator I am confused about what it is exactly that a reduced density operator describes. To illustrate, I came across the following seemingly paradoxical argument.
Consider a bipartite system $AB$, described by the pure state:
$$| \psi \rangle = \sum_{a,b} \psi(a,b) |ab \rangle$$
Its density matrix is defined as:
$$\rho \equiv | \psi \rangle \langle \psi |$$
With reduced density operators:
$$\rho_A = tr_B(\rho) \qquad \rho_B = tr_A(\rho)$$
We can construct a new operator:
$$\rho_{AB} = \rho_A \otimes \rho_B$$
Which is only equal to $\rho$ if $|\psi\rangle$ is a separable state (no correlations between $A$ and $B$). Another way to say this is:
$$0 = S(\rho) \leq S(\rho_A) + S(\rho_B) = S(\rho_A \otimes \rho_B) = S(\rho_{AB})$$
Because if $A$ and $B$ are entangled, then $\rho$ contains information about these correlations, but $\rho_{AB}$ does not (is this wrong?).
So say $A$ and $B$ are entangled, then $\rho_{AB}$ does not contain that information, but I was under the impression that $\rho_A$ ánd $\rho_B$ do contain (some, all?) of this correlation information; otherwise both $A$ and $B$ should be described by pure states. I realise that $\rho_{AB}$ has no physical meaning in the case of entanglement, but even as a purely mathematical construct I don't see how that information can just vanish.
I guess my question is this: what information exactly does the reduced density operator encompass? And, if any of it is related to the correlations, how can this be reconciled with the argument in the paragraph above?

A: The reduced density operator of A contains all of the information about that system you can get by measuring that system alone. It does not contain information about what systems A is entangled with. For that, you would need the density operator of set of all systems with which A is entangled. The information about correlations is also contained in A's Heisenberg picture observables, see http://xxx.lanl.gov/abs/quant-ph/9906007.


text:
Q: How to list all azure virtual machine images using Python code I can't able to list all azure vm images using Python code
I can only list specific location , offers like that..I need to list all vm images in Python script

A: There is no list method in Python that returns all virtual machine images without using any filters such as offers or publishers. When using virtual machine images.list(), You must pass options such as location, offers, and publishers. Otherwise, it throws an error because there are not enough required parameters to get the desired outcome.

Supported list() Methods:

After workaround on this, I could be able to get the results using below script:
from  itertools  import  tee
from  azure.identity  import  DefaultAzureCredential
from  azure.mgmt.compute  import  ComputeManagementClient
credentials = DefaultAzureCredential()
subscription_ID = '<subscriptionID>'
client = ComputeManagementClient(credentials, subscription_ID)
vmlist = client.virtual_machine_images.list(location="eastus")

There are no virtual machine images in my environment that match the specified filters. As an outcome, it was successfully debugged.
Output:
DefaultAzurecredential Auth:

Service Principal Credentials Authentication:
Note: Register a new application to get the client_ID, client_secret details under Azure Active Directory.

Refer SO by @Peter Pan.

A: As Jahnavi pointed out, there is no way to list all images without specifying the corresponding filters. Not all images are available in all regions and for all customers. However, if you want to list all images, you could iterate through the corresponding lists by fist listing publishers, then offers, then skus and finally images. However, there are A LOT of images, so this will take A LOT of time - and I strongly recommend to filter for at least one of the aforementioned criteria.
The below code should list all images in a given region and a given subscription. Note that it is using the AzureCliCredential class from the Azure Identity library. This requires you to be logged in to Azure through the Azure CLI and should only be used for testing. You can pick another appropriate authentication class from the library if desired.
from azure.identity import AzureCliCredential
from azure.mgmt.compute import ComputeManagementClient

credential = AzureCliCredential()
subscription_id = "{your-subscription-id}"
my_location = "{your-region}"

compute_client = ComputeManagementClient(credential=credential, subscription_id=subscription_id)

results = []

# Get all Publishers in a given location
publishers = compute_client.virtual_machine_images.list_publishers(location=my_location)

for publisher in publishers:
    offers = compute_client.virtual_machine_images.list_offers(location=my_location, publisher_name=publisher.name)
    for offer in offers:
        skus = compute_client.virtual_machine_images.list_skus(location=my_location,publisher_name=publisher.name, offer=offer.name)
        for sku in skus:
            images = compute_client.virtual_machine_images.list(location=my_location, publisher_name=publisher.name, offer=offer.name, skus=sku.name)
            for image in images:
                image_dict = dict({
                    'publisherName' : publisher.name,
                    'offerName' : offer.name,
                    'skuName': sku.name,
                    'imageName': image.name
                })

                results.append(image_dict)

This will leave you with a dictionary that could be used for further processing. For example, you could load it into a Pandas DataFrame:
import pandas as pd
df = pd.DataFrame(results)

Potential output:
       publisherName           offerName                                         skuName imageName
...
17101    f5-networks      f5-big-ip-good  f5-bigip-virtual-edition-10g-good-hourly-po-f5  16.1.202000
17102    f5-networks      f5-big-ip-good  f5-bigip-virtual-edition-10g-good-hourly-po-f5  16.1.300000
17103    f5-networks      f5-big-ip-good  f5-bigip-virtual-edition-10g-good-hourly-po-f5  16.1.301000
...

But really, this is only food for thought as it will be pretty bad performancewise and will take a lot of time - and is probably not intended to be used this way. The better option would be to filter for certain publishers first - just sayin'. :-)


text:
Q: How to get listbox column text with xul I am new with xul,
I want to know how to get listbox column text with xul,
I search about listbox method and property, but I can't find about that
please help!
Thanks a lot!

A: You can see the reference page listbox - XUL
If you want to get the  selected item, there is a property of the listbox called  selectedItem that will return it.
Your listitem can be composed with multiple  elements.
<listbox id="list">
    <listitem class="listitem">
        <listcell class="column1" value="value1" width="100"/>
        <listcell class="column2" value="value2" width="100"/>
    </listitem>
</listbox>

If you give this  elements a class, you can access them doing the following:
var list = document.getElementById("list");
var listItem = list.selectedItem;
var column1Value = listItem.getElementsByClassName("column1")[0].getAttribute("value");
var column1Value = listItem.getElementsByClassName("column2")[0].getAttribute("value");


text:
Q: Is there is any way to get the appcenter config from env file in React Native One of my android application is developed using React-Native and I have plans to distribute this using app-center as this app is for Internal users. In App-Center I have different projects (created new app) for the different environments - one for dev, one for uat and one for production.
My issue here is whenever I create build package (apk file) to deploy to App Center project, I need to manually change the app-center config. I have used .env config file to get config for different environment. But I can't use this to set app-center config. Can anyone guide me how I can automate this process by either configuring the app-center in .env file or somewhere in code?

A: If you want to use a specific configuration for each build with the same code, you should use the appcenter's environment variable.
Just add an "app_secret" environment variable, and use a pre build script to create a appcenter-config.json file containing the app_secret


text:
Q: How to get coordinates of a point on a Bezier curve for a certain time in cocos2d? I have a sprite moving along a Bezier curve. Full time of the movement let us say is 5 seconds. what i wanna know is how can i get position of my sprite after 1.5 or 2.347 seconds of movement. Is there any standard cocos2d function for calculating this?

A: I don't think there is specific way.. Just call a method after a specific time and calculate the position... I don't think you can disturb bezier action in between and calculate the position.. Hope this helps :)


text:
Q: Uncaught TypeError: Cannot read property 'substr' of undefined Pardon me for not being clear, but have thia script that is really long. When I have it live, I get this error in Chrome's Console.

Uncaught TypeError: Cannot read property 'substr' of undefined

here is the snippet of code where it is reading from.
var formIddd = $('select[class~="FormField"]').get(numSelec).name.substr($('select[class~="FormField"]').get(numSelec).name.length-3,2);

I looked up substr on google and it appears to be a known property. I also found the classes. I have played with the lengths, but still getting stuck. It used to work until BigCommerce did an update.
Any advice much appreciated, cheers.

A: You are not populating your array. The if check is false.

so basically you are doing this
var arrayOfSelectOfCountry = [];
var numSelec = arrayOfSelectOfCountry[-1];  //undefined

which results in the error above.

A: maybe at some point the substr() is called on a null reference
so before using it check that reference for nullity  like that
function(jsonDate) {

     if (jsonDate!=null) {
        //if the variable is not null you can use substr with no problems
         var date = new Date(parseInt(jsonDate.substr(6)));
        //.....
}

take look at my full snippet from Datatable
 columns: [
                        { 'data': 'ID' },
                        { 'data': 'Name' },
                        {
                            'data': 'DateCreated',
                            'render': function(jsonDate) {
                                if (jsonDate!=null) {
                                    var date = new Date(parseInt(jsonDate.substr(6)));
                                    return date.toLocaleDateString();
                                }
                                return "-";
                            }
                        },

A: Instead of:
variable.substring(0, 7)

Do:
variable && variable.substring(0, 7)

This is how you check for nullity like Basheer mentioned


text:
Q: What kind of different request and response scopes are there in PHP? I slightly remember from my age old Java days, that there was an RequestScope object and a Response object. RequestScope contained the POST headers sent from browsers and the GET arguments. Well, it's a few years ago, might be inaccurate.
What kind of scopes for request and response are there in PHP environment? Well I think there's a $_GET and $_POST (sorry if wrong, I'm just a few days new to PHP). Is that the only thing? Where does the output go?

A: This works a bit differently in most PHP environments than you're describing from Java.  PHP uses several "super-global" arrays to contain request, environment and system information: $_GET, $_POST, $_COOKIE, $_REQUEST, $_SESSION, $_SERVER, $_FILE.
In general, the response is simply the output you write to STDOUT as the script processes.  It is possible to use output buffering to help control what is sent to the client, but there is no native support for a response "scope" or "object".

A:
RequestScope contained the POST
  headers sent from browsers and the GET
  arguments.

FYI, There is a super-global that contains both the $_GET and $_POST. It is $_REQUEST.


text:
Q: Where to initialize a GraphQL Client inside Django App I'm building an API with Django, I want to query the Github GraphQL API, and I found this GraphQL client for python that suits my needs.
But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure:
.
├── LICENSE
├── README.md
├── api
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── portfolio
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
└── setup.py

Thanks in advance!

A: As per definition a graphql client needs it's own configuration, modules and error handling I would suggest you to create a namespace adjacent to your other projects. Django uses the concept of Applications which is providing seperated configuration, logging and error handling for this case. You define additional Applications in your project in your settings.py in INSTALLED_APPS (Docs). Your project structure would then look smth like:
.
├── LICENSE
├── README.md
├── graphql-client
│   ├── __init__.py
│   ├── main.py
│   ├── client.py
│   ├── ressources
│   │   ├── __init__.py
│   ├── ├── repository.py
│   │   └── user.py
│   ├── settings.py
│   └── views.py
├── api
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── portfolio
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
└── setup.py

A: TLDR: instantiate new client right in the view method = new client for each request. (good option - overriding initial view method). Improve later.

It depends.
If there are no request / user options for the client (= client is the same for every request / user):

*

*import one from submodule as @ElPapi42 suggested (= same as instantiate new client in views.py globally, not as part of method logic)

*or instantiate new client right in the view method - new client for each request
If there are request / user specific options (i.e. client need to have request.user specific options / credentials):

*instantiate new client right in the view method

Option 1 - Client is instantiated once per worker view. Although it provides some performance benefits they are subtle and obscured:

*

*you may not know what it means: shared client => possibly use methods that modify client state for different requests / users that rely on the state

*worker lifetime is (should be) actually not that long

*hard to assess performance benefits with hard to assess proper implementation

In reality you may want to connect to github with some current request.user specific options, perform multiple requests (= cookies may be involved and auto-added in subsequent requests => client cannot be shared with multiple users) = at least separate client for each user.

A: I ended up creating a python module in the /api Application called graphql.py that init the graphql client. from here, it is easily importable.
I decide not to create a separate Django Application for this because that will be overkill on this context, due to the simplicity of the code:
in graphql.py:
from gql import Client
from gql.transport.requests import RequestsHTTPTransport
from django.conf import settings

# Instaciate a graphql client
client = Client(
    transport=RequestsHTTPTransport(
        url='https://api.github.com/graphql',
        headers={'Authorization': 'bearer {token}'.format(token=settings.GITHUB_TOKEN)},
        verify=False,
        retries=3,
    ),
    fetch_schema_from_transport=True,
)


text:
Q: Why is 'http://dd ' a valid URL? I'm writing a .NET 3.5 app and using URI.IsWellFormedUriString(string uriString, UriKind uriKind) to verify user-inputted URIs; using UriKind.Absolute. I was just playing with the application and I'm a bit worried and confused as to why something like:
http://ddd
is a valid URI?  What gives?  I know it's because it's part of the RFC, but why is it valid in the first place?
The only time I've ever seen URIs like that is for corporate, internal Intranets like
http://companyinet
or
http://localhost  (which is very popular, but also a special case)
I do not want to have to use my own regular expression as there are so many varying URI regexs.  However, I do not really want users entering URIs like that that aren't publically accessible.
Any idea or thoughts? Thanks.

A: Because it conforms to RFC 1738 (as well as the URI specification of RFC 2396).
The RFC makes specific allowances for resource paths that only consist of a scheme and a scheme specific element - in this case a hostname. As long as it identifies a unique resources and conforms to the syntax of URIs it is valid.

A: You answered the question yourself. It's a "valid" (well-formed) URI by the RFC spec's definition ipso facto.
To help solve your required task, do some addition checks in your regex for the one or more dots (don't forget to escape them!) or possibly try to hit the resource itself to see if it actually responds.

A:  is valid because it does point to a Unique Resource. In this case, it points to the webserver (hopefully) of the computer 'ddd' on the local network.
URI is unique resource identifier, not unique world wide web resource identifier. file:///blah.txt is also a valid URI

A: It is a valid URI because it follows the syntax of URIs: it has a scheme, and a scheme-specific component ('http' being the scheme', ':' separating the two, and '//ddd' is the scheme-specific part.)
In the case of a HTTP URI, it also follows the syntax for those, with 'ddd' being a valid host name.
The syntax of URIs is defined in http://www.ietf.org/rfc/rfc2396.txt

A: That's because it IS a perfectly valid URI, as you mention.
I'd alter your strategy slightly... If you want URIs that are not only valid (as in well-formed), but also valid, in the sense that they actually point to a site, you'll have to add one more step.
After the string validation, issue a HEAD request to ping the URL. If it returns a 2xy status code, you're probably good to go. This will work in most situations, but is not without caveats and exceptions.

A: Here is a simple experiment to see why that URL is valid:
0) use the dig or ping utility to get the IP address of google.com. I got: 74.125.53.100
1) Edit your /etc/hosts file (on Windows it is something like C:\Windows\system32\drivers\etc\hosts, and you might need to create it).  In your hosts file, add a line like this:
74.125.53.100 ddd
Don't forget to save your edits.
2) In a web browser, go to this URL: http://ddd
3) You just accessed Google using the URL.  That's why it's a valid URL.


text:
Q: How to combine jquery.validate plugin with jquery.serialize() I have tried to validate the form using the jquery.validate plugin before being executed by ajax, but it failed because the ajax submit is working when using validate function.
Here is my form:
<form>

Name*<input id="cname" name="name" size="25" class="required" minlength="2" />

E-Mail*<input id="cemail" name="email" size="25"  class="required email" />

URL<input id="curl" name="url" size="25"  class="url" value="" />

Your comment*<textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>

<input class="submit" type="submit" value="Submit"/>

 </form>

And my jquery code:
$('form').validate();
$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

here is my fiddle: http://jsfiddle.net/ongisnade/tzFzR/
How to make form validate before ajax submited?

A: Use .valid() to check before using .serialize().
// Initialize
$('form').validate();

// Bind
$('form').submit(function() {
    if($('form').valid())
        alert($(this).serialize());
    else
        alert("Invalid");
    return false;
});

Fiddle: http://jsfiddle.net/eHD4g/
Or as Sparky672 said, use the submitHandler attribute:
$('form').validate({
    submitHandler: function(form) {
        alert($('form').serialize());
        return false;
    }
});

Fiddle: http://jsfiddle.net/eHD4g/2/


text:
Q: Full Native Implementation I am designing an application through JNI in order to prevent third party edits. I have moved forth towards registering native methods in order to remove jni bridge linkages, but as you can see, methods with override attribute still need to exist within the java code as native linked. Is there a way to fully port the remaining java code for this specific file?
Java:
@Override
protected native void onCreate(Bundle savedInstanceState);

CPP:
void onCreate(JNIEnv *env, jobject classObject, jobject bundle) {
    /**super.onCreate**/
    gObjects[0] = env->NewGlobalRef(classObject);
    gClasses[0] = env->GetObjectClass(gObjects[0]);
    jclass s_Class = env->GetSuperclass(gClasses[0]);
    jmethodID oc_ID = env->GetMethodID(s_Class, "onCreate", "(Landroid/os/Bundle;)V");
    env->CallNonvirtualVoidMethod(gObjects[0], gClasses[0], oc_ID, bundle);
}

extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *curVM_, void *reserved) {
    curVM = curVM_;
    curVM->GetEnv((void **) &environments[0], JNI_VERSION_1_6);

    /**Start of Native Method Registers**/
    JNINativeMethod natives[1];
    uint64_t pCount = sizeof(natives) / sizeof(natives[0]);
    jclass klass = environments[0]->FindClass("com/company/app/Activity");
    natives[0] = {"onCreate", "(Landroid/os/Bundle;)V", (void *)onCreate};
    environments[0]->RegisterNatives(klass , natives, pCount);\
    for (uint64_t i = 0; i < pCount; i++) natives[i] = {"", ""};\

    return JNI_VERSION_1_6;
}

A: It does seem quite silly to think I can simply remove the native linkage between the activity and lib. Instead, I will be utilizing BaseDexClassLoader to sideload my dex file during runtime. I will not be giving up my code, but further information about this can be founded at: https://developer.android.com/reference/dalvik/system/BaseDexClassLoader


text:
Q: Display array data in horizontal order using smarty I'm unable to get the output in proper order so as to align it in this format as apple.com/sitemap. Problem I'm facing is it with  tags which is used while displaying the values, I'm unable to put it in proper place.
Right now, the output is:

Parent 1

Sub Cat 1

Sub Cat 2

Parent 2

Sub Cat3

Sub Cat 4

Parent 3

If you see the ul tag is not closing properly because of which I'm unable to implement CSS..
I have created table as:
id | parent | name | url

1  |  0  | Parent1 | Link
2  |  1  | Sub Cat1| Link
3  |  2  | Sub Cat2| Link
4  |  0  | Parent2 | Link

MySQL Query to fetch the values:
$sql = 'SELECT parent,name, url FROM sitemap ORDER BY CASE WHEN parent =0 THEN id ELSE parent END , CASE WHEN parent =0 THEN 0 ELSE id END';

Lines to display the data on Page:
{foreach from=$sitemap item=c name=sitemap}

{ assign var="tmp" value= $c.parent  }
{ if $tmp==0}

{$c.name}

{else}

{$c.name}

{/if}
{/foreach}

A: You're probably looking for something along the lines of
{foreach from=$sitemap item=c name=sitemap}
    {* open
 on first element, only if it is has a parent *}
    {if $smarty.foreach.sitemap.first && $c.parent}
{/if}

    {if !$c.parent}
        {* if this is not the first element, close previous
 *}
        {if !$smarty.foreach.sitemap.first}
{/if}
        {* output headline for this
 *}

{$c.name}

        {* open new
 *}

    {else}

{$c.name}

    {/if}

    {* close
 after last element *}
    {if $smarty.foreach.sitemap.last}
{/if}
{/foreach}


text:
Q: sql server how to add a column to a view A view is created use the following sql:
create view [dbo].[tblDimSession] AS
    SELECT *
    FROM OPENQUERY(CDH_DEV_BJ_LS, 'select * from Session')

This view is created by accessing data with Hive.
I want to add a new column named sessionID, int type, must be an auto-increased column.
How to alter the view, or could the column be added when creating the view?
Thank you.

A: If you just want additional column to the view, it can be done during CREATE VIEW or ALTER VIEW in your case of adding auto-increment column it should be done on the table and than just added to view. But if you must add it to the view you can do it the following way.
CREATE VIEW MyView as Select *, MyExtraColumn From MyTable unlike ALTER TABLE you do not need to specify ADD or DROP statement, modifying view can be compared more to altering SP or table function. To add column that auto-increments you can do this
ALTER VIEW MyView as SELECT *, ROW_NUMBER() OVER (ORDER BY MyUniqueColumn) AS sessionID FROM MyTable
Note if you doing ORDER BY a column that is not unique your number could change every time you execute it.


text:
Q: Reading XML file from php I am downloading and reading XML file from email using this code:
<?php
require_once("attachmentread.class.php");
$host="{imap.gmail.com:993/imap/ssl}INBOX"; // pop3host
$login="axxxxxxxx@gmail.com"; //pop3 login
$password="whxxxxxxx"; //pop3 password
$savedirpath="" ; // attachement will save in same directory where scripts run othrwise give abs path
$jk=new readattachment(); // Creating instance of class####
$jk->getdata($host,$login,$password,$savedirpath); // calling member function

$xml=simplexml_load_file("/data/www/Message14.xml");
$message=$xml->TEMPLATE;
$mobile= $xml->MESSAGES->MESSAGE->RECIPIENT_NUM;

$mobile1=str_replace("050", "97150", $mobile);
?>

My original Message14.xml look like this
<?xml version="1.0" ?>
<DOCUMENT><VERSION>2.0</VERSION><INVOICE_NUM>30</INVOICE_NUM><PIN>14567894</PIN><MESSAGE_TYPE>INSTANT_SEND</MESSAGE_TYPE><COUNTRY_CODE>971</COUNTRY_CODE><TEMPLATE> Hi xxxxxx
</TEMPLATE><DATABASEINFO><DATABASE_NAME>Sys2000</DATABASE_NAME><CLINIC_ID>1</CLINIC_ID></DATABASEINFO><MESSAGES><MESSAGE><SEND_DATE>2013-07-02</SEND_DATE><ENTITY_ID>0</ENTITY_ID><RECIPIENT_NUM>xxxxxxxxx</RECIPIENT_NUM><MESSAGE_PARAMS/></MESSAGE></MESSAGES><CSUM>dcb4855eccf730e3668a386acaaf7d60</CSUM></DOCUMENT>

but now its includeing 3D,ect it looks like this
?xml version=3D3D"1.0" ?>
<DOCUMENT><VERSION>2.0</VERSION><INVOICE_NUM>30</INVOICE_NUM><PIN>1456789=
=3D
4</PIN><MESSAGE_TYPE>INSTANT_SEND</MESSAGE_TYPE><COUNTRY_CODE>971</COUNTR=
=3D
Y_CODE><TEMPLATE> Hi xxxxxxxxx
</TEMPLATE><DATABASEINFO><DATABASE_NAME>Sys2000</DATABASE_NAME><CLINIC_ID=
=3D
>1</CLINIC_ID></DATABASEINFO><MESSAGES><MESSAGE><SEND_DATE>2013-07-02</SE=
=3D
ND_DATE><ENTITY_ID>0</ENTITY_ID><RECIPIENT_NUM>0xxxxxxxxx</RECIPIENT_NUM>=
=3D
<MESSAGE_PARAMS/></MESSAGE></MESSAGES><CSUM>dcb4855eccf730e3668a386acaaf7=
=3D
d60</CSUM></DOCUMENT>

Can anyone guide me how to download as the original file not inculding 3d .thanks

A: The "3D" refers to the character code for an equal sign.  The inclusion of this in your XML code indicates that double encoding or other encoding problems occurred.  You can use PHP's quoted_printable_decode function to fix the issue.  PHP's manual here
You can try: file_put_contents("/data/www/Message14.xml", quoted_printable_decode(file_get_contents("/data/www/Message14.xml")));
Put that just before you use the simplexml_load_file function.


text:
Q: Multi-threads slower than single threads? I am trying to find out how to speed up a certain part of my code. I've got three float variables: var1, var2, var3.
in sequential mode ...
       double start1, end1, t1;
       start1= (double)cvGetTickCount();

    var1= tester->predict(videocapture, params1, image);
    var2= tester->predict(videocapture, params2, image);
    var3= tester->predict(videocapture, params3, image);

    end1= (double)cvGetTickCount();
    t1= (end1-start1)/((double)cvGetTickFrequency()*1000.);
    printf( "Time1  = %g ms\n", t1 );

it seems to be slightly faster than parallel threads ...
double start2, end2, t2;
start2= (double)cvGetTickCount();
mp_set_dynamic(0);     // Explicitly enable/disable dynamic teams
omp_set_num_threads(3); // Use 3 threads for all consecutive parallel regions
#pragma omp parallel num_threads(3)
{
   #pragma omp sections //nowait
      {

         #pragma omp section
      {
            #pragma omp critical
     {
              var1= tester->predict(videocapture, params1, image);
               }
       }

         #pragma  omp section
          {
            #pragma omp critical
             {
              var2= tester->predict(videocapture, params2, image);
               }

       }

         #pragma omp section
          {
           #pragma omp critical
           {
              var3= tester->predict(videocapture, params3, image);
               }

       }
          }
        }
     }

    end2= (double)cvGetTickCount();
    t2= (end2-start2)/((double)cvGetTickFrequency()*1000.);
    printf( "Time2  = %g ms\n", t2 );

Can someone please help me speed up the process of finding those three variables and tell me what I am doing wrong

A: Look at the specification of the critical pragma here.
There are three crucial points here:
1) If you don't give the critical pragma a name, it's mapped to some unspecified name, and the same name is used for all unnamed critical sections.
2) Only one thread at a time can be in any critical section with a given name.
3) When a thread encounters a critical section, it waits there until no other threads are active in it before moving into it.
Thus your code tells all your threads to wait while they all take turns executing one item of your code at a time. This is equivalent to doing the operations serially, except that it requires the overhead of generating the threads in the first place (and whatever overhead occurs due to the waiting, which might be busy-waiting).


text:
Q: Display voxels using shaders in openGL I am working on voxelisation using the rendering pipeline and now I successfully voxelise the scene using vertex+geometry+fragment shaders. Now my voxels are stored in a 3D texture which has size, for example, 128x128x128.
My original model of the scene is centered at (0,0,0) and it extends in both positive and negative axis. The texure, however, is centered at (63,63,63) in tex coordinates.
I implemented a simple ray marcing for visualizing but it doesn't take into account the camera movements (I can render only from very fixed positions because my ray have to be generated taking into account the different coordinates of the 3D texture).
My question is: how can I map my rays so that they are generated at point Po with direction D in the coordinates of my 3D model but intersect the voxels at the corresponding position in texture coordinates and every movement of the camera in the 3D world is remapped in the voxel coordinates?
Right now I generate the rays in this way:
create a quad in front of the camera at position (63,63,-20)
cast rays in direction towards (63,63,3)

A: I think you should store your entire view transform matrix in your shader uniform params. Then for each shader execution you can use its screen coords and view transform to compute the view  ray direction for your particular pixel.
Having the ray direction and camera position you just use them the same as currently.
There's also another way to do this that you can try:
Let's say you have a cube (0,0,0)->(1,1,1) and for each corner you assign a color based on its position, like (1,0,0) is red, etc.
Now for every frame you draw your cube front faces to the texture, and cube back faces to the second texture.
In the final rendering you can use both textures to get enter and exit 3D vectors, already in the texture space, which makes your final shader much simpler.
You can read better descriptions here:
http://graphicsrunner.blogspot.com/2009/01/volume-rendering-101.html
http://web.cse.ohio-state.edu/~tong/vr/


text:
Q: Need a video format that will play on Windows XP/7 out of the box I am distributing an exe file that contains a video that needs to be able to be played on Windows XP & Windows 7 without ANY other software or codecs installed. This includes Windows Media Player, which many of my customers don't have installed.
Formats – bear with me, I mostly develop apps for other platforms. I don't normally deal with a/v stuff or Windows stuff so my terminology is probably off – I've tried and had no success with:

*

*.mp4

*.ogv

*.wmv (ironic, isn't it?)

I have been able to play the video in a .mpg format, but it has two issues:

*

*Audio doesn't play

*The file is really big. It's 80 MB and I'd rather have it be no more than 30 MB. I'm okay with putting it in a zip to keep the size down, but that only gets it down to 50 MB.

When I open the file on my Mac, it plays, audio and all.
This is what the QuickTime X movie inspector says about the file format:
MPEG-1 Video, 1,280 x 720
MPEG Layer 3, 48000 Hz, Stereo (L R)

I'd like an FFMPEG command that I can feed my video to and end up with an outputted file that will play on Windows 7, both audio and visual, without any dependencies on other codecs or applications. I'd like it if it also played on fresh installs of Windows XP although I can live with it if it doesn't, and ideally I'd like it to also be within my size constraints.
Edit with details on the output of ffmpeg when I attempted to follow Darth Android's answer:
ffmpeg version 2.0.1 Copyright (c) 2000-2013 the FFmpeg developers
built on Aug 15 2013 10:56:46 with llvm-gcc 4.2.1 (LLVM build 2336.11.00)
configuration: --prefix=/Volumes/Ramdisk/sw --enable-gpl --enable-pthreads
--enable-version3 --enable-libspeex --enable-libvpx --disable-decoder=libvpx
--enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libx264
--enable-avfilter --enable-libopencore_amrwb --enable-libopencore_amrnb
--enable-filters --enable-libgsm --arch=x86_64 --enable-runtime-cpudetect

libavutil      52. 38.100 / 52. 38.100
libavcodec     55. 18.102 / 55. 18.102
libavformat    55. 12.100 / 55. 12.100
libavdevice    55.  3.100 / 55.  3.100
libavfilter     3. 79.101 /  3. 79.101
libswscale      2.  3.100 /  2.  3.100
libswresample   0. 17.102 /  0. 17.102
libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'my-video.mp4':
Metadata:
major_brand     : mp42
minor_version   : 0
compatible_brands: mp42isomavc1
creation_time   : 2013-06-10 18:21:11
encoder         : HandBrake 0.9.9 2013051800
Duration: 00:01:33.95, start: 0.000000, bitrate: 954 kb/s
Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 813 kb/s, 29.97 fps, 29.97 tbr, 90k tbn, 180k tbc
Metadata:
  creation_time   : 2013-06-10 18:21:11
Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 136 kb/s
Metadata:
  creation_time   : 2013-06-10 18:21:11
[vob @ 0x7f8278821000] VBV buffer size not set, muxing may fail
Output #0, vob, to 'my-video.mpg':
Metadata:
major_brand     : mp42
minor_version   : 0
compatible_brands: mp42isomavc1
encoder         : Lavf55.12.100
Stream #0:0(und): Video: mpeg2video, yuv420p, 1280x720 [SAR 1:1 DAR 16:9], q=2-31, 200 kb/s, 90k tbn, 29.97 tbc
Metadata:
  creation_time   : 2013-06-10 18:21:11
Stream #0:1(eng): Audio: mp2, 48000 Hz, stereo, s16, 128 kb/s
Metadata:
  creation_time   : 2013-06-10 18:21:11
Stream mapping:
Stream #0:0 -> #0:0 (h264 -> mpeg2video)
Stream #0:1 -> #0:1 (aac -> mp2)
Press [q] to stop, [?] for help
frame=  182 fps=0.0 q=24.8 size=     528kB time=00:00:06.25 bitrate= 691.6kbits
frame=  380 fps=379 q=31.0 size=    1076kB time=00:00:12.97 bitrate= 679.4kbits
frame=  548 fps=364 q=31.0 size=    1704kB time=00:00:18.49 bitrate= 754.8kbits
frame=  692 fps=345 q=31.0 size=    2390kB time=00:00:23.26 bitrate= 841.4kbits
frame=  815 fps=325 q=31.0 size=    3170kB time=00:00:27.30 bitrate= 951.2kbits
frame=  950 fps=316 q=24.8 size=    4146kB time=00:00:31.78 bitrate=1068.4kbits
frame= 1079 fps=307 q=31.0 size=    5154kB time=00:00:36.13 bitrate=1168.5kbits
frame= 1242 fps=309 q=31.0 size=    5868kB time=00:00:41.65 bitrate=1154.0kbits
frame= 1413 fps=313 q=31.0 size=    6586kB time=00:00:47.31 bitrate=1140.2kbits
frame= 1587 fps=316 q=31.0 size=    7346kB time=00:00:53.14 bitrate=1132.2kbits
frame= 1753 fps=318 q=31.0 size=    8026kB time=00:00:58.66 bitrate=1120.7kbits
frame= 1925 fps=320 q=31.0 size=    8798kB time=00:01:04.35 bitrate=1119.9kbits
frame= 2091 fps=321 q=31.0 size=    9646kB time=00:01:10.02 bitrate=1128.5kbits
frame= 2226 fps=317 q=31.0 size=   10484kB time=00:01:14.48 bitrate=1153.0kbits
frame= 2386 fps=317 q=31.0 size=   11232kB time=00:01:19.86 bitrate=1152.1kbits
frame= 2554 fps=318 q=31.0 size=   11852kB time=00:01:25.40 bitrate=1136.8kbits
frame= 2759 fps=324 q=31.0 size=   12396kB time=00:01:32.14 bitrate=1102.0kbits
frame= 2813 fps=325 q=31.0 Lsize=   12546kB time=00:01:33.94 bitrate=1094.0kbits/s
video:10904kB audio:1468kB subtitle:0 global headers:0kB muxing overhead 1.402856%

A: Try:
ffmpeg.exe -i "C:/Path/to/your/video.mkv" -vcodec mpeg2video -acodec mp2 -f vob -y "C:/Path/to/output/video.mpg"

where video.mkv is your source file and and video.mpg is your output.
-vcodec mpeg2video sets the output video format to MPEG2
-acodec mp2 sets the output audio format to MPEG2
-f vob sets the output container/file format to Vob (*.mpg)
-y overwrites target file.

A: I finally found a format that worked for me on a fresh install of Windows 7 without Windows Media Player or any other codecs:
MPEG-1 Video, 1,280 x 720
MPEG Layer 3, 48000 Hz, Mono

(Note the only change was from Stereo to Mono compared to what I had been using when I first posted the question.)
To get it I typed:
ffmpeg -i my-video.mp4 -vcodec mpeg1video -acodec mp2 -ac 1 -f vob my-video-mono.mpg

I'd like to thank Darth Android whose answer greatly helped me with learning more about the arguments I needed to provide to ffmpeg.


text:
Q: How can edit web page content in browsers without textarea or textfield? Is there any javascript solution to show a cursor on pages, move it around with arrow keys, edit directly without switching to a textarea interface? I need javascript to manipulate pages, then pass the modified content to server to save to database.

A: Yes there is, you can set a contenteditable flag as a html attribute, which makes text editable in situ.
For example, text written in

 tags.
Reference HTML Contenteditable

A: Expanding on the contenteditable theme suggested by others, there is a very good tutorial on how to implement some of the more advanced features of this here


text:
Q: Проблема передачи объектов из Hibernate на клиент, через Spring В процессе изучения java программирования, пишу для себя небольшой RESTful сервис с которым возникла проблема.
Для разработки RESTful сервиса использую Spring Boot и Hibernate. Суть проблемы: после введения связи один-к-многим между сущностями БД я не могу передать объекты считанные из БД на клиент. При записи в БД проблем нет.
Вот графическая схема БД:

При исполнение метода передачи объекта, возникает ошибка.
2016-06-15 20:24:36.631  WARN 1372 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandler ExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: could not extract ResultSet (through reference chain: prodinfo.models.Avtor["lkat"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: prodinfo.models.Avtor["lkat"])

Сам метод запроса и передачи объекта:
@RequestMapping(value="/getlist")
@ResponseBody
public Avtor avtorout(String urladdress) {

    List<Avtor> avtorlist = avtorDao.getByUrladdress(urladdress);
    Avtor avtor = avtorlist.get(0);

    return avtor;
}

Метод getByUrladdress() из avtorDao:
public List<Avtor> getByUrladdress(String urladdress) {
    return entityManager.createQuery(
        "from Avtor where urladdress = :urladdress")
        .setParameter("urladdress", urladdress)
        .getResultList();
}

Модель сущности Avtor:
@Entity
@Table(name="Avtor"
,schema="public"
)
public class Avtor implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@NotNull
@Type(type = "text")
private String urladdress;

@Type(type = "text")
private String avtorname;

private String update_avtor;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "title_lkat")
private Set<Lkat> lkat = new HashSet<>();

public Set<Lkat> getLkat() {
    return this.lkat;
}

public void setLkat(Set<Lkat> lkat) {
    this.lkat = lkat;
}

public void addLkat(Lkat lkat) {
    lkat.setAvtor(this);
    this.lkat.add(lkat);
}

public Avtor() {
}

public Avtor(long id) {
    this.id = id;
}

public Avtor(String urladdress) {
    this.urladdress = urladdress;
}

public Avtor(String avtorname, String update_avtor) {
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
}

public Avtor(long id, String avtorname, String update_avtor) {
    this.id = id;
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
}

public Avtor(String urladdress, String avtorname, String update_avtor) {
    this.urladdress = urladdress;
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
}

public Avtor(long id, String urladdress, String avtorname, String update_avtor) {
    this.id = id;
    this.urladdress = urladdress;
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getUrladdress() {
    return urladdress;
}

public void setUrladdress(String urladdress) {
    this.urladdress = urladdress;
}

public String getAvtorname() {
    return avtorname;
}

public void setAvtorname(String avtorname) {
    this.avtorname = avtorname;
}

public String getUpdate_avtor() {
    return update_avtor;
}

public void setUpdate_avtor(String update_avtor) {
    this.update_avtor = update_avtor;
}

}

Т.к. без связи один-к-многим объекты передаются без проблем, возникает вопрос как правильно передавать объекты из БД со связями сущностей?

A: При добавлении связей один-к-многим допустил ошибку в маппинге сущностей БД.
Часть кода с ошибкой:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "title_lkat")
private Set<Lkat> lkat = new HashSet<>();

В следствии чего запись данных в сущность Lkat проводилась без ошибок, т.к. в аннотации @ManyToOne не было привязки по атрибуту, а считать из БД Hibernate не мог, т.к. был указан не тот атрибут.
Исправленный код:
Сущность Avtor:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "avtor")
@JsonManagedReference
private Set<Lkat> lkat = new HashSet<>();

Сущность Lkat:
@ManyToOne()
@JoinColumn(referencedColumnName = "id")
@JsonBackReference
private Avtor avtor;

UPDATE
Для того что бы отправлять только необходимые данные, ввел три класса DTO для каждой сущности БД, пример реализации класса AvtorDTO:
public class AvtorDTO {

private String urladdress;

private String avtorname;

private String update_avtor;

private Set<LkatDTO> lkatDTO = new HashSet<>();

public Set<LkatDTO> getLkatDTO() {
    return this.lkatDTO;
}

public void setLkatDTO(Set<LkatDTO> lkatDTO) {
    this.lkatDTO = lkatDTO;
}

public AvtorDTO() {
}

public AvtorDTO(String urladdress) {
    this.urladdress = urladdress;
}

public AvtorDTO(String avtorname, String update_avtor) {
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
}

public AvtorDTO(String urladdress, String avtorname, String update_avtor, Set<LkatDTO> lkatDTO) {
    this.urladdress = urladdress;
    this.avtorname = avtorname;
    this.update_avtor = update_avtor;
    this.lkatDTO = lkatDTO;

}

public String getUrladdress() {
    return urladdress;
}

public void setUrladdress(String urladdress) {
    this.urladdress = urladdress;
}

public String getAvtorname() {
    return avtorname;
}

public void setAvtorname(String avtorname) {
    this.avtorname = avtorname;
}

public String getUpdate_avtor() {
    return update_avtor;
}

public void setUpdate_avtor(String update_avtor) {
    this.update_avtor = update_avtor;
}

}

Так же изменил метод передачи объекта, в котором сразу реализовал формирование объекта класса DTO (возможно это не правильно и стоит реализовать другим способом, но в данном случае все работает), получился следующий код:
@RequestMapping(value="/getlist")
@ResponseBody
public AvtorDTO getAvtorInClient(String urladdress) {
    List<Avtor> avtorlist = avtorDao.getByUrladdress(urladdress);
    Avtor avtor = avtorlist.get(0);
    Set<LkatDTO> lkatsetDTO = new HashSet<>();
    Set<Lkat> lkatset = avtor.getLkat();
    Iterator<Lkat> itrlkat = lkatset.iterator();
while(itrlkat.hasNext()) {
        Lkat lkat = itrlkat.next();
        Set<Lwork> lworkset = lkat.getLwork();
        Iterator<Lwork> itrlwork = lworkset.iterator();
        Set<LworkDTO> lworksetDTO = new HashSet<>();
        while(itrlwork.hasNext()) {
            Lwork lwork = itrlwork.next();
            LworkDTO lworkDTO = new LworkDTO(lwork.getUrl_lwork(), lwork.getTitle_lwork(), lwork.getDescription_lwork(), lwork.getSize_lwork(), lwork.getUpdate_lwork(), lwork.getAdditional_info(), lwork.getDate_create());
            lworksetDTO.add(lworkDTO);
        }
        LkatDTO lkatDTO = new LkatDTO(lkat.getTitle_lkat(), lkat.getUrl_lkat(), lworksetDTO);
        lkatsetDTO.add(lkatDTO);
    }

    AvtorDTO avtorDTO = new AvtorDTO(avtor.getUrladdress(), avtor.getAvtorname(), avtor.getUpdate_avtor(), lkatsetDTO);

    return avtorDTO;
}


text:
Q: PDES - from Vector fields whose inner product with their vector Laplacian equals norm of the vector field Let $g(x_{1},........,x_{n}) = \sum_{i=1}^{n}g_{i}(x_{1},\cdots,x_{n})e_{i}$ be a function in $\mathbb{C}^n$ ($e_{i}$ are the standard bases).
Let $\nabla^{2}$ be the vector Laplacian. Let $<\cdot,\cdot>$ be inner product between two vectors.

Consider the PDE $<{g},{\nabla^2(g)}> = <{g},{g}>$.
$(A)$ What is such a class of equation formally called in the literature (it seems to be inner product of a field with its vector Laplacian)?
$(B)$ What are the solutions to the above pde?
$(C)$ What are the solutions of $g$ if $g_{i}(x_{1},\cdots,x_{n}) \in [0,1]$ $\forall i$?
$(D)$ What are the solutions for the special case $g_{i}(x_{1},\cdots,x_{n}) = g_{i}(x_{i})$?
$(E)$ What happens if I replace $\mathbb{C}^{n}$ by:

$(1)$ a torus $\mathbb{C}^{n}/L$ where $L$ is a lattice
$(2)$ a sphere centered at $(\frac{1}{2}, \frac{1}{2}, \cdots,\frac{1}{2})$ and radius $\frac{\sqrt{n}}{2}$.
$(3)$ a cube given by the $0-1$ combinations of the standard bases $e_{i}$ (or its closest smooth approximation) enclosing the above sphere.

$(F)$ Does anything interesting happen as limit $n\rightarrow\infty$.

I feel this is a standard pde. However, since I am not in the math field, I do not know the keywords or whether there are standard solutions? Where should I look for them?