text:
Q: Cisco AXL updatePhone using python3, suds, SOAP Requests I now got a few SOAP request against my UCM 11.5 test environment working. But i'm struggeling with this one: Update Phone.
import ssl
from suds.client import Client

ssl._create_default_https_context = ssl._create_unverified_context
username = 'Administrator'
passwd = 'Password'
wsdl_url = 'http://host.domain.com/axlsqltoolkit/schema/11.5/AXLAPI.wsdl'
service_url = 'https://host.domain.com/axl/'
cucm_server = Client(wsdl_url, location = service_url, username=username, password=passwd)

def UpdatePhoneByName(cucm_server):
    result = cucm_server.service.updatePhone({'name': 'SEP0023331B4DBB','description': 'Haasdfllo'})
    print(result)
    return
UpdatePhoneByName(cucm_server)

I get the following result:
suds.TypeNotFound: Type not found: 'name'

I will also include output of cucm_server but only updatePhone part.
updatePhone(ns0:String100 name, ns0:XUUID uuid, ns0:UniqueString128 newName, ns0:String128 description, ns0:XFkType callingSearchSpaceName, ns0:XFkType devicePoolName, ns0:XFkType commonDeviceConfigName, ns0:XFkType commonPhoneConfigName, ns0:XNetworkLocation networkLocation, ns0:XFkType locationName, ns0:XFkType mediaResourceListName, ns0:XMOHAudioSourceId networkHoldMohAudioSourceId, ns0:XMOHAudioSourceId userHoldMohAudioSourceId, ns0:XFkType automatedAlternateRoutingCssName, ns0:XFkType aarNeighborhoodName, ns0:XLoadInformation loadInformation, ns0:XVendorConfig vendorConfig, ns0:String128 versionStamp, ns0:boolean traceFlag, ns0:String128 mlppDomainId, ns0:XStatus mlppIndicationStatus, ns0:XPreemption preemption, ns0:XStatus useTrustedRelayPoint, ns0:boolean retryVideoCallAsAudio, ns0:XFkType securityProfileName, ns0:XFkType sipProfileName, ns0:XFkType cgpnTransformationCssName, ns0:boolean useDevicePoolCgpnTransformCss, ns0:XFkType geoLocationName, ns0:XFkType geoLocationFilterName, ns0:boolean sendGeoLocation, ns0:removeLines removeLines, ns0:addLines addLines, ns0:lines lines, ns0:XFkType phoneTemplateName, ns0:speeddials speeddials, ns0:busyLampFields busyLampFields, ns0:XFkType primaryPhoneName, ns0:XStatus ringSettingIdleBlfAudibleAlert, ns0:XStatus ringSettingBusyBlfAudibleAlert, ns0:blfDirectedCallParks blfDirectedCallParks, ns0:addOnModules addOnModules, ns0:XUserLocale userLocale, ns0:XCountry networkLocale, ns0:XInteger idleTimeout, xs:string authenticationUrl, xs:string directoryUrl, xs:string idleUrl, xs:string informationUrl, xs:string messagesUrl, xs:string proxyServerUrl, xs:string servicesUrl, ns0:services services, ns0:XFkType softkeyTemplateName, ns0:XFkType defaultProfileName, ns0:boolean enableExtensionMobility, ns0:XBarge singleButtonBarge, ns0:XStatus joinAcrossLines, ns0:XStatus builtInBridgeStatus, ns0:XStatus callInfoPrivacyStatus, ns0:XStatus hlogStatus, ns0:XFkType ownerUserName, ns0:boolean ignorePresentationIndicators, ns0:XPacketCaptureMode packetCaptureMode, ns0:XInteger packetCaptureDuration, ns0:XFkType subscribeCallingSearchSpaceName, ns0:XFkType rerouteCallingSearchSpaceName, ns0:boolean allowCtiControlFlag, ns0:XFkType presenceGroupName, ns0:boolean unattendedPort, ns0:boolean requireDtmfReception, ns0:boolean rfc2833Disabled, ns0:XCertificateOperation certificateOperation, ns0:XAuthenticationMode authenticationMode, ns0:XKeySize keySize, ns0:XKeyOrder keyOrder, ns0:XECKeySize ecKeySize, ns0:String128 authenticationString, xs:string upgradeFinishTime, ns0:XStatus deviceMobilityMode, ns0:boolean remoteDevice, ns0:XDNDOption dndOption, ns0:XRingSetting dndRingSetting, ns0:boolean dndStatus, ns0:boolean isActive, ns0:XFkType mobilityUserIdName, ns0:XPhonePersonalization phoneSuite, ns0:XPhoneServiceDisplay phoneServiceDisplay, ns0:boolean isProtected, ns0:boolean mtpRequired, ns0:XSIPCodec mtpPreferedCodec, ns0:XFkType dialRulesName, ns0:String50 sshUserId, ns0:String255 sshPwd, ns0:String255 digestUser, ns0:XOutboundCallRollover outboundCallRollover, ns0:boolean hotlineDevice, ns0:String255 secureInformationUrl, ns0:String255 secureDirectoryUrl, ns0:String255 secureMessageUrl, ns0:String255 secureServicesUrl, ns0:String255 secureAuthenticationUrl, ns0:String255 secureIdleUrl, ns0:XStatus alwaysUsePrimeLine, ns0:XStatus alwaysUsePrimeLineForVoiceMessage, ns0:XFkType featureControlPolicy, ns0:XDeviceTrustMode deviceTrustMode, ns0:boolean earlyOfferSupportForVoiceCall, ns0:boolean requireThirdPartyRegistration, ns0:boolean blockIncomingCallsWhenRoaming, xs:string homeNetworkId, ns0:boolean AllowPresentationSharingUsingBfcp, ns0:confidentialAccess confidentialAccess, ns0:boolean requireOffPremiseLocation, ns0:boolean allowiXApplicableMedia, ns0:XFkType cgpnIngressDN, ns0:boolean useDevicePoolCgpnIngressDN, ns0:String128 msisdn, ns0:boolean enableCallRoutingToRdWhenNoneIsActive, ns0:XFkType wifiHotspotProfile, ns0:XFkType wirelessLanProfileGroup, ns0:XFkType elinGroup)

I also tried with uuid, _uuid and _name but nothing seems to work.
Any help would be much appreciated.

A: Did you check the WSDL? Is it correct? Does it define 'name'?
Just had a quick look at the doc. Please include the output of print cucm_server to your question. According to what I see, methods take named parameters, just one dict.
I never got around to use suds anyways. I switched to Zeep a while back, it works like a charm.

A: I think the format is something like
updatePhone = cucm_server.service.updatePhone(uuid=uuid, newName=newname, description= description)

A: Short answer:
Dump suds, it's not actively supported.  Use zeep instead.
If you want a working sample for zeep, here it is:
# -*- coding: utf-8 -*-

from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from requests import Session
from requests.auth import HTTPBasicAuth
import urllib3
from urllib3.exceptions import InsecureRequestWarning

urllib3.disable_warnings(InsecureRequestWarning)

USERNAME = 'administrator'
PASSWORD = 'ciscopsdt'
IP_ADDRESS = "123.123.123.123"
WSDL = 'file://C://path//to//schema//11.5//AXLAPI.wsdl'
BINDING_NAME = "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding"
ADDRESS = "https://{ip}:8443/axl/".format(ip=IP_ADDRESS)

def update_phone_by_name(client, name, description):
    return client.updatePhone(**{'name': name, 'description': description})

def get_phone_by_name(client, name):
    return client.getPhone(name=name)

def main():
    session = Session()
    session.verify = False
    session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
    transport = Transport(cache=SqliteCache(), session=session, timeout=60)
    client = Client(wsdl=WSDL, transport=transport)
    axl = client.create_service(BINDING_NAME, ADDRESS)

    update_phone_by_name(axl, "BOTUSER011", "update my description")
    print(get_phone_by_name(axl, "BOTUSER011"))

if __name__ == '__main__':
    main()

If, however, you must proceed with suds, here's a sample using suds-jurko:
# -*- coding: utf-8 -*-

import ssl
from suds.client import Client

ssl._create_default_https_context = ssl._create_unverified_context
username = 'administrator'
password = 'cisco'
wsdl_url = 'file:///C://path//to//schema//current//AXLAPI.wsdl'
service_url = 'https://123.123.123.123:8443/axl/'

def update_phone_by_name(client, name, description):
    return client.service.updatePhone(**{'name': name, 'description': description})

def get_phone_by_name(client, name):
    return client.service.getPhone(name=name)

def main():
    cucm_server = Client(wsdl_url, location=service_url, username=username, password=password)
    print(get_phone_by_name(cucm_server, 'BOTUSER011'))

if __name__ == '__main__':
    main()

If you look closely, you'll see that your error was due to sending a dictionary, instead of **kwargs in your function update_phone_by_name.


text:
Q: Instantiate abstract class using Anonymous functions in Php In java, there is a possibility to create an object of abstract class if we implement abstract method at the time of object creation by using Anonymous functions, So is it also possible to have the ability in Php.

A: Pre PHP 7 NO. The feature was only added in  PHP 7
https://wiki.php.net/rfc/anonymous_classes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Center one  and float other right I want div "1" to the center and div "2" to the right. what can i do? I have this html

and this css
.1 {
display:inline-block;
width:200px;
height:120px;}
.2 {
display:inline-block;
width:250px;
height:120px;
float:right;}

A: First I know it's just sample but don't use number for first character for classes (Which characters are valid in CSS class names/selectors?).
And this is what I usually use to do that

Right

Middle

#middle {
    background-color: #494949;
    width: 200px;
    height: 120px;
    margin: 0 auto;
}

#right {
    background-color: #949494;
    width: 250px;
    height: 120px;
    float: right;
}

http://jsfiddle.net/index/npq5puc1/.

A: Try this
1.) Change HTML element according to CSS to get desire result

.div1 {
display:inline-block;
width:200px;
height:120px;
  background:red;
  float:right;

}
.div2 {
display:inline-block;
width:250px;
height:120px;
float:right;
  background:blue;
}

div 2 in right

div 1 in center

A: try it like this;
html

css
.div1
{
    display:block;
    background:#333;
    width:200px;
    height:120px;
    margin:auto;
}
.div2
{
    display:block;
    background:red;
    width:250px;
    height:120px;
    float:right;
}

Here's the Fiddle link.

A: Try this
HTML:

CSS:
[class='1'] {
display:inline-block;
width:200px;
height:120px;}
[class='2'] {
display:inline-block;
width:250px;
height:120px;
float:right;}


text:
Q: MVC3 dropdown list value no populating inside editor template I have an editor template with a dropdown:
 @Html.DropDownListFor(m => m.AdmissionState, new List<SelectListItem>()
                                                   {
                                                       new SelectListItem()
                                                           {
                                                               Text = "1",
                                                               Value = "1"
                                                           },
                                                       new SelectListItem()
                                                           {
                                                               Text = "2",
                                                               Value = "2"
                                                           },
                                                       new SelectListItem()
                                                           {
                                                               Text = "3",
                                                               Value = "3"
                                                           },
                                                   }, "- Select -")

I call it from the view:
@Html.EditorFor(m => m.Licenses)

In controller I have following code:
profile.Licenses.Add(new AttorneyLicenseModel()
        {
            AdmissionDate = "06/14/2012",
            AdmissionState = "2",
            AdmissionNumber = "asd",
        });
        profile.Licenses.Add(new AttorneyLicenseModel()
        {
            AdmissionDate = "07/16/2012",
            AdmissionState = "5",
            AdmissionNumber = "qwe",
        });

For each of the licenses I see the fields with a data populated from the model, but not for the dropdown list - there is default value is checked. What am I doing wrong? ofcourse, the code with values is extremely simlified

A: Try like this:
@Html.DropDownListFor(
    m => m.AdmissionState,
    new SelectList(
        new[]
        {
            new { Value = "1", Text = "1" },
            new { Value = "2", Text = "2" },
            new { Value = "3", Text = "3" },
        },
        "Value",
        "Text",
        Model.AdmissionState
    ),
    "- Select -"
)

And if you are interested in understanding why my code works and yours not you could read the following answer I provided yesterday to a similar question: ASP.NET MVC DropDownListFor not selecting value from model


text:
Q: SQL Server query for SSIS transformation timing out due to 174 UNION ALL statements I have a table in Hive and SQL Server with data stored as below. I am using SSIS to move this data in to SQL Server. The query is taking too long. There are about 175 separate values in the Description column, which results in 174 UNION ALL statements due to which the query times out after about 2 hours.

SQL Error [08S01]: org.apache.thrift.transport.TTransportException: java.net.SocketTimeoutException: Read timed out*

Is there a better way to write this query?
Thanks!
Hive:
ID  | Description
----+------------------------------
 1  | Desc1;Desc2;Desc3;Desc4
 2  | Desc1;Desc3;Desc4;Desc5;Desc6
 ...
230 | Desc8;Desc163;Desc9;Desc2;Desc172

SQL Server:
CaseID | GroupID | Description
-------+---------+--------------
   1   |    63   | Desc1
   1   |    44   | Desc2
   1   |    57   | Desc3
   1   |    78   | Desc4
   ...
   2   |    78   | Desc1
   2   |    57   | Desc3

Query:
select
       case
             when cas.description like '%Desc1%' then 63
       end as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from
       svc_case cas
inner join account acc on acc.id = cas.id
where cas.description <> 'NULL' and LENGTH(cas.description) > 0
and acc.recordid = '03443FGT'
union all
select
       case
             when cas.description like '%Desc2%' then 44
       end as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from
       svc_case cas
inner join account acc on acc.id = cas.id
where cas.description <> 'NULL' and LENGTH(cas.description) > 0
and acc.recordid = '03443FGT'
union all
select
       case
             when cas.description like '%Desc3%' then 57
       end as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from
       svc_case cas
inner join account acc on acc.id = cas.id
where cas.description <> 'NULL' and LENGTH(cas.description) > 0
and acc.recordid = '03443FGT'
union all
select
       case
             when cas.description like '%Desc4%' then 78
       end as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from
       svc_case cas
inner join account acc on acc.id = cas.id
where cas.description <> 'NULL' and LENGTH(cas.description) > 0
and acc.recordid = '03443FGT'
...
select
       case
             when cas.description like '%Desc175%' then 12
       end as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from
       svc_case cas
inner join account acc on acc.id = cas.id
where cas.description <> 'NULL' and LENGTH(cas.description) > 0
and acc.recordid = '03443FGT'

A: This is a stab in the dark, but there are 2 things you can do to improve this query. Firstly, let's address all those UNION ALLs. If I understand your query correctly, you can unpivot your data to achieve the same thing:
SELECT V.groupid,
       cas.id AS caseid,
       current_timestamp as INSERT_DT
FROM dbo.svc_case cas
     JOIN dbo.account acc on acc.id = cas.id
     CROSS APPLY (VALUES(CASE WHEN cas.description LIKE '%Desc1%' THEN 63 END),
                        (CASE WHEN cas.description LIKE '%Desc2%' THEN 44 END),
                        (CASE WHEN cas.description LIKE '%Desc3%' THEN 57 END),
                        (CASE WHEN cas.description LIKE '%Desc4%' THEN 78 END),
                        --I assume there are 174 more of these
                        (CASE WHEN cas.description LIKE '%Desc178%' THEN 1 END))V(groupid) --The last one isn't correct, but to show how the `APPLY` ends

Then you have your WHERE, which isn't SARGable due to the LENGTH. LENGTH isn't actually a T-SQL operator, so I hope you are actually using SQL Server (if you're not, this is a waste of an answer, as the above is T-SQL specific). Considering that LEN(NULL) returns NULL, then use <> ''. Considering you already have <> 'NULL' though you can use NOT IN:
WHERE cas.description NOT IN('NULL','')
  AND acc.recordid = '03443FGT'

I do, however, suggest against storing the literal string value 'NULL' in your column, you should fix that and actually store NULL, not 'NULL'; the 2 are different values and behave very differently.

A: Only run the query one time.  So no union all, and leave out the CASE. Use a multicast and split it in SSIS.

A: You can expand the codes and use case to convert to numbers:
select (case when code = 'Desc1' then 63
             when code = 'Desc2' then 44
             . . .
        end) as groupid, -- maps to groupid
       cas.id as caseid, -- maps to caseid
       current_timestamp as INSERT_DT
from svc_case cas join
     account acc
     on acc.id = cas.id lateral view
     explode(split(cas.description, ';')) codes as code
where acc.recordid = '03443FGT';

I don't know why you have description <> 'NULL'.  I am guessing that you really want is not null -- and that is unnecessary with the lateral join.
Also, if you have a reference table, with one row per code and groupid, then the code can be further simplified by joining to that.


text:
Q: Get RHEL version from uname -r | sed I am writing a script that should only be run on RHEL6 or RHEL7 hosts.
I figured it would be easy.  Use uname -r, sed and a clever regex.
Well I can't come up with a the clever regex :( ...
Here are the details of what I am trying to do:
$ uname -r
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed -e's/... clever stuff here .../\1/g'
7

Here's what I have tried, please don't laugh:
$ uname -r | sed -e's/^.*\.el\(\d)\.*$/\1/g'
sed: -e expression #1, char 23: Unmatched ( or \(
$ uname -r | sed -e's/^.*\.el\{1}(\d)\.*$/\1/g'
sed: -e expression #1, char 26: Unmatched \{
$ uname -r | sed -e's/^.*\.el{1}\(\d\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed -e's/^.*\.el\(\d\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed -e's/^.*\.el\(\.\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed 's/\([0-9]\+\.[0-9]\+\)\..*/\1/'
3.10
$ uname -r | sed 's/el+\.[0-9]\+\)\..*/\1/'
sed: -e expression #1, char 24: Unmatched ) or \)
$ uname -r | sed 's/el+\.\([0-9]\+\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed 's/el+\.\([0-9]\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed 's/^.*\.el+\.\([0-9]\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64

A: Well, you have several options.
uname -r | sed 's/^.*\.el\([0-9]*\)\..*$/\1/'

should do the trick.
That says "look for a period followed by 'el' followed by some number of digits followed by a period.  Replace the whole line with just those digits."
Let's go over your attempts.  Mostly you need to understand the difference between different flavors of regular expression syntax; sed is not Perl.
$ uname -r | sed -e 's/^.*\.el\(\d)\.*$/\1/g'
sed: -e expression #1, char 23: Unmatched ( or \(
$ uname -r | sed -e 's/^.*\.el\{1}(\d)\.*$/\1/g'
sed: -e expression #1, char 26: Unmatched \{

In both of these, you used a backslashed opening bracket but tried to close it without the backslash.  In sed, \( is closed by \) and \{ by \}.
$ uname -r | sed -e 's/^.*\.el{1}\(\d\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64

{1} is literal - so you're looking for a literal digit 1 inside literal curly braces.  Since it didn't find any such thing, it didn't make any changes and the line comes out unchanged.
$ uname -r | sed -e 's/^.*\.el\(\d\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64

This would almost work if sed understood \d by default.  But the fact that you have \.* is what messes it up - it only matches 0 or more periods.  You want \..* - a literal period followed by any number of characters.  Also, sed doesn't understand \d by default. You need [0-9] there.
$ uname -r | sed -e 's/^.*\.el\(\.\)\.*$/\1/g'
3.10.0-123.20.1.el7.x86_64

That backslash in front of the dot inside the parentheses means you are looking for a literal period instead of any character.  And you have the \.* again.
$ uname -r | sed 's/\([0-9]\+\.[0-9]\+\)\..*/\1/'
3.10

That did exactly what you asked it to.. what were you looking for here?
$ uname -r | sed 's/el+\.[0-9]\+\)\..*/\1/'
sed: -e expression #1, char 24: Unmatched ) or \)

You have the \) but no \(.
$ uname -r | sed 's/el+\.\([0-9]\+\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed 's/el+\.\([0-9]\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64
$ uname -r | sed 's/^.*\.el+\.\([0-9]\)\..*/\1/'
3.10.0-123.20.1.el7.x86_64

+ matches a literal plus sign.

A: Parsing the kernel version to figure out the RHEL Version is a terrible idea, because what if a kernel is released that doesn't follow the same naming scheme?  While it might work for now, it's a fragile solution.
There are several ways of determining the current RHEL version.
The easiest, as glenn jackman suggested in his comment, may be to parse /etc/redhat-release, which looks like (for RHEL 7):
Red Hat Enterprise Linux Server release 7.2 (Maipo)

And for RHEL 6:
Red Hat Enterprise Linux Server release 6.5 (Santiago)

A slightly better method is to query the version of the installed redhat-release package:
$ rpm -q --qf '%{VERSION}\n' -f /etc/redhat-release
7.2

This says "tell me the version of the package that owns /etc/redhat-release".  The above example was run under RHEL7; the same thing when run under RHEL6 yieilds:
$ rpm -q --qf '%{VERSION}\n' -f /etc/redhat-release
6Server

A: Try this:
$ uname -r | sed 's/.*el\([0-9]\).*/\1/g'

or
$ uname -r | sed -r 's/.*el([0-9]).*/\1/g'


text:
Q: What is the difference in meaning between 'visage' and 'countenance'? Is there any usage or definition difference between visage and countenance? From the dictionary definitions, they appear to be the same.

A: The entires in the Merrian-Webster are the following:

*

*Visage: the face, countenance, or appearance of a person or sometimes an animal

*Countenance:  face, visage; especially :  the face as an indication of mood, emotion, or character
And the entries in the Merriam-Webster Learner's Dictionary

*

*Visage: a person's face

*Countenance: the appearance of a person's face : a person's expression

So they are quit similar, but someones visage is someone's actual face, and someone's countenance is someone's (facial) expression.


text:
Q: How to get search domain of local Chromebook and NS records of that domain for Chrome app? I would like to get the search domain from chromeOS notebook and then NS records of the search domain using javascript for chrome app. The chromeapp will be running on chromeOS.
I am able to get the records using resolveNs method of NodeJs "dns" library but it needs nodeJS. And for that I need to package nodeJS with chrome App? I am new to chrome os.
I tried to browserify that but got several issues. Is there any way to get the search domain and all NS records of a domain using JavaScript?
Or is there a way to browserify the 'dns' module of NodeJS. In my try, browserify does the job but when I open the javascript in chrome, it says: fs.readFile is not a function:
Uncaught TypeError: fs.readFile is not a function
    at Platform.parseResolv (bundle.js:4295)
    at Platform._populate (bundle.js:4248)
    at new Platform (bundle.js:4201)
    at Object.<anonymous> (bundle.js:4409)
    at Object.require.18../utils (bundle.js:4411)
    at s (bundle.js:1)
    at bundle.js:1
    at Object.<anonymous> (bundle.js:3155)
    at Object.require.15../packet (bundle.js:3815)
    at s (bundle.js:1)

Same happens when I replace fs by browserify-fs. My code in nodeJS is (it works fine when I say node filename.js):
var dnsresolve = require('native-dns/lib/client').resolve;
  dnsresolve('xxx.pb1.lan', 'NS', function (err, addresses) {
  if (err) throw err;
  console.log('addresses: ' + JSON.stringify(addresses));
   });


text:
Q: How exactly is the print statement working in these two methods? This is wrt to Binary Search Tree.I  am traversing the tree in 2 ways.1)InOrder Traversal
An inorder traversal of tree t is a recursive algorithm that follows the the left subtree; once there are no more left subtrees to process, we process the right subtree. The elements are processed in left-root-right order.
2)PostOrder Traversal
A postorder traversal of tree t is a recursive algorithm that follows the the left and right subtrees before processing the root element. The elements are processed left-right-root order.
I am confused over how the recursion methods and print statements are working. Could you please enlighten me?
static void inOrder(Leaf root){
    if(root != null){
        inOrder(root.left);
        System.out.print(root.value+" ");
        inOrder(root.right);
    }
}
static void postOrder(Leaf root){
    if(root != null){
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.value+" ");
    }
}

A: The way this works is each function will print out a single, long line containing each of the values if the tree.  As each of the algorithms goes through the tree, it appends the current value of the node to the output along with a space.  For example, if we consider the following tree:

  2
 / \
1   3

The first algorithm will start at the 2, then call itself on the left child, 1.  The function will then call itself on the left child, which is null, so it will return immediately.  The function will then print "1 " to the console.  The function will call itself on the right child, which is null, so it will return immediately.  The function will then return to the 2, and "2 " will be printed to the console.  The function will then call itself on the right child, which is the 3.  The function will call itself on the left child , which returns, then print "3 " to the console, then call itself on the right child, which returns.  The function will then return to the 2, and that will return to whatever called it.  The console at the end will say
1 2 3
A similar thing would happen for the second algorithm, except the function would go to and print the left and right children, 1 and 3, respectively, before printing the root node, 2, resulting in the following output:
1 3 2
If you are having trouble understanding it, it would benefit you to draw yourself a tree and follow the code step by step to see what the computer is doing.

A: As every recursion method, it needs a base case, a condition to stop the recursion. In this case, it's when "root" is null.
Observe that the variable root, will only be the actual root of the Tree at the first call in the method. Consecutive calls are passing the element on it's left or right.
On the method inOrder, it prints the elements that are further down on the left branch of the Tree. So it "goes down a level" on the tree before calling the print. This means that if the element has a leaf on a left branch, it will print said leaf before going to the right branch.
in the postOrder Method, it will go the furthest down on the tree it can go and then print the elements, doing that for both branches ( left and right ). This meaning that the leafs of thre tree will be printed first while the actual root will be the last Element.
If you're having trouble visualizing, i suggest you draw the tree in a paper and run the code with a small sample tree using the Debug on Eclipse, so you can follow the execution line by line and see how the algorithm is traversing the Tree.


text:
Q: Ubuntu 14.04 won-t pass login screen after update and terminal won't accept password So, I've been using Ubuntu 14.04 for several months now [still a newbie] and today, disaster has struck.
I installed an everyday update, not really sure which, the kinds that I'm prompted for all the time, and upon restarting my computer, it goes to the login screen. This is strange because it never actually had gone to this screen before, just logged straight in. There, I try to login, I put in my password, and it says "login failed". I try to log in as a guest, and "login failed". I try to make any changes or fix things via the crtl alt f1 terminal, and it says that my password is incorrect.
And this isn't a case of forgotten password, I assure you. This seems like the final breaking point of the OS, as it was behaving rather weird lately, like slow and glitchy. Basically, the computer has locked me out and I can't do anything. Clearly I'm going to reinstall the OS in the near future, but really don't want to have to redo the last few days of work since my last backup a few days ago.
I would appreciate any help, and if there's no fix for this, at least a way to grab a copy of my hard drive before blowing this OS away... I'm no expert at this, so please be specific with instructions.

A: I think you should try instructions in the link,
Try to change password from recovery mode and then login using new password...
Reset Password


text:
Q: What is the type for "$axios" in Nuxt.js? Summery
Now I implemented RepositoryFactory pattern for API connection.
https://medium.com/canariasjs/vue-api-calls-in-a-smart-way-8d521812c322
In repository.ts, I wrote $axios.
import testRepository from '~/api/testRepository'

export interface Repositories {
  hoge: testRepository
}

export default function ({ $axios }, inject) { # <- error on $axios
  const hoge = new testRepository ($axios)
  const repositories: Repositories = {
    hoge
  }
  inject('repositories', repositories)
}

But it show error message Binding element '$axios' implicitly has an 'any' type.ts(7031).
I want to know what is the correct type for $axios
What I've tried
{ $axios } : any can resolve it, but I want to know exact type for '$axios'.

A: Did you add @nuxt/types and @nuxtjs/axios in your tsconfig.json file?
If you need more information, you can look at: https://axios.nuxtjs.org/setup
{
  "compilerOptions": {
    "types": [
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  }
}

A: I am using Nuxt2 and above solution didn't work for me, this is the way I am using it without any problem.
this.$axios.$post

I am uncertain if this is the best practice, but at least works without any type problem.


text:
Q: How to disable spring cloud zookeeper when executing integration test The integration test tries to connect to zookeeper, when I test my code with TestRestTemplate and spring-cloud-zookeeper-discovery dependency. If zookeeper is not running the test throws an exception.
Here is simple project where you can reproduce the problem https://github.com/DenisGlot/disable-zookeeper-when-testing
How can I make the test skip connecting to zookeeper part?

A: Added bootstrap.properties in test/java/resources and put there
spring.cloud.service-registry.auto-registration.enabled=false
spring.cloud.zookeeper.discovery.enabled=false
spring.cloud.zookeeper.discovery.register=false


text:
Q: How to schedule a JSON file import into the MySQL Workbench? I'm trying to figure out the best way to schedule a job that would import files into MySQL's Database. I'm using MySQL Workbench for that.
As of now, I'm simply using the Import Wizard, but I saw that there is no native scheduler for this task.
I reckon I can use the Task Scheduler on Windows for that, but because I'm fairly new to SQL, I don't know the best query to schedule such job.
I don't know if it makes a difference that one set of files will be JSON formatted while the other will be SQL.


text:
Q: D-Link DIR-615 bricked. Power led stays orange, can't get into emergency flash mode After changing some Wireless settings on my D-Link DIR-615 with custom flashed DD-WRT I might have unplugged the power cord too soon. When I plugged in again it didn't seem to boot. Just an orange power led and orange internet globe led. After plugging it again to my computer to check what's wrong only the power led turns on orange.

I've been trying all sorts of things like the 30/30/30 trick, tried to get it in emergency flash mode but none of those seem to have effect on it. The power led stays orange and it doesn't broadcast a Wireless signal and it doesn't turn on LAN, I can't discover it on both WLAN or LAN.
Any help appreciated!
--
Some more information about the Router itself:

A: Hold in reset, power up. keep holding in reset until power light flashes on/off. It can take up to 30 seconds. Set your computer to static ip 192.168.0.10/255.255.255.0 & DNS 192.168.0.1 - Assuming you have windows, Plugin LAN cable between computer and router, open internet explorer and go to http://192.168.0.1 - You should see the emergency firmware upload page. If you don't, you need to use JTAG, which involves making the cable and soldering on connections. Easier to get another DIR-615.


text:
Q: Force user to reload page Background information:

*

*I have JavaScript that makes an AJAX request.

*I am using a version URL parameter to make sure that when a page loads it gets the latest version of the JavaScript file: /path/to/file.js?v=20160511
That problem I need to solve now is when I make a change to the data that is returned by the AJAX call (I assume this is considered an API break), and the JavaScript file (client). My first thought would be to somehow force the user to reload the page when I release a change to the API. What is a good process to make sure the client and server stay in sync?

A: You can use AJAX to trigger a ''location.reload();'' on the client.

A: Based on Uğurcan's comment and Hullu2000's answer, I added two things to my current implementation. The total necessary items are:

*

*The JavaScript referenced in page has a version URL parameter to make sure that when a page loads it gets the latest version of the JavaScript file: /path/to/file.js?v=20160511

*The API call returns a JSON response with an API version string

*The JavaScript checks the API response version string against a local variable. If they don't match, it calls window.location.reload();


text:
Q: PivotChart (for multi x-axis) in Contour or different way? I do some analysis in Contour and I try to find a way to display into a bar chart, 2 x-axis dimensions as we can do with a PivotChart.
For the moment I can't find a solution for having a second dimension in the x-axis. Adding an overlay does not fit. Any idea?


text:
Q: RSA algorithm PKCS #1.5 padding (not OEAP) password encryption with client certificate public key in Java I am new to RSA algorithm and cryptography in Java. I have a client certificate provided by the 3rd party organization which is in .cer format. Now I need to encrypt my password with the public portion of the password key certificate, using the RSA algorithm and PKCS #1.5 padding - so not OAEP - in Java.
Could you check if the following does perform the above?
Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] input = "Abc123".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
FileInputStream fin = new FileInputStream(new File("/test.cer"));
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
cipher.init(Cipher.ENCRYPT_MODE, pk, new SecureRandom());
byte[] cipherText = cipher.doFinal(input);

A: Yes, the code you provided looks OK.
Note that if you replace "RSA/None/PKCS1Padding" with "RSA/ECB/PKCS1Padding" that you could rely on the default Sun provider instead.

It is important to note that your code generates a "plain" signature; it doesn't include your data or certificate. Generally it is better to create a CMS Signed Data structure, which can for instance include the "leaf" certificate that you used to create the signature.
CMS is a so called cryptographic container format, which can hold structures such as the data, signature and additional information on the signature algorithm, certificates, signer etc.


text:
Q: LCM calculation I wrote code for the problem given in spoj to calculate LCM. I calculated the gcd of 2 numbers and I divided the multiplication of 2 numbers with gcd which gives the lcm of 2 numbers, but it is showing wrong answer.
The problem is at http://www.spoj.com/problems/WPC5I/
import java.math.BigInteger;
import java.util.Scanner;

class Lcm1 {
    public static void main(String args[]) throws Throwable {
        try {
            Scanner s = new Scanner(System.in);
            int siz = s.nextInt();
            for(int i = 0; i< siz; i++) {
                BigInteger a = s.nextBigInteger(), b = s.nextBigInteger();
                System.out.println((a.multiply(b)).divide(a.gcd(b)));
            }
        }
        catch(Exception e){}
    }
}

A: Your logic is partially wrong.Basically you are just calculating the lcm of given numbers but user asks to find least k satisfying given condition.but yours is not least k.
Try for case n=340 and m=230 actual ans is 1564 but your code gives 7820.
Note: lcm will not always be the least k satisfying given conditions in the problem.
Hint:prime factorize m,n and try to get the ans...try few more cases and you will get it.


text:
Q: Attempts to use following-sibling to convert I try to convert my old html by xslt-script to my new xml stucture.
I have a Problem to converting the folowing source to my needed xml structure.
Source

  Example Text

..

..

xml structure
<lq>

Example Text

..

..

</lp>

I tried the following xls, but the div class="collapsed" is not adopted into the lp tag.
<xsl:template match="p/a[@class='DropDown']">
<lp>

<xsl:apply-templates select="text()"/>

  <xsl:if test="/p/a/following-sibling::*[1][self::div]">
     <xsl:apply-templates select="*|text()"/>
  </xsl:if>
</lp>
</xsl:template>

Can anyone tell me what I did wrong ore where the mistake is?
Thanks much

A: IMHO, you want to do:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="p[a/@class='DropDown']">
    <lp>

            <xsl:value-of select="a"/>

        <xsl:copy-of select="following-sibling::*[1][self::div]/node()"/>
    </lp>
</xsl:template>

<xsl:template match="div[preceding-sibling::*[1][self::p/a/@class='DropDown']]"/>

As for your mistake:

*

*You are testing the existence of some p that is the root element
and contains an a whose following sibling is div. None of these are true in the given example;

*xsl:if does not change the context: your <xsl:apply-templates
select="*|text()"/> applies templates to the child nodes of the
current a;

*Presumably you don't want the div to appear again in the original place -
so if you have another template to suppress it, you cannot use
<xsl:apply-templates> to insert it at the place you do want it -
at least not without using another mode.


text:
Q: Can you run NodeJs parallelly in a single-core CPU? I know that a single-core CPU (typically) will be able to have 2 threads running. So does this means you can have NodeJs running parallelly in a single-core CPU?

A: First off, nodejs only runs your Javascript in a single thread, regardless of how many CPUs there are (assuming there are no WorkerThreads being used).  It may use some other threads internally for the implementation of some library functions (like file operations or asynchronous crypto operations).  But, it only ever uses a single thread/CPU to execute your Javascript instructions.

So does this means you can have NodeJs running parallelly in a single-core CPU?

That depends upon what you mean by "parallelly".
Your operating system supports lots of threads, even with only a single CPU.  But, when you only have a single CPU, those threads get time-sliced across the single CPU such that none of them are ever actually running at the same time.
One thread gets to run for a short time, then the OS suspends that thread, context switches to another thread, runs it for a short time, suspends that thread, context switches to another thread and so on.
So, the one CPU is "shared" among multiple threads, but no each thread is still running one at a time (typically for short periods of time).
The more CPUs you have, the more threads can run simultaneously where there is true parallel execution.
This is all managed by the OS, independent of nodejs or any particular app running on the computer.   Also, please be aware that a typical modern OS has a lot of services running in the OS.  Each of these services may also have their own threads that needs to use the CPU from time to time in order to keep the OS and its services running properly.  For example, you might be doing a file system backup while typing into your word processor, while running a nodejs app.  That can all happen on a single CPU by just sharing it between the different threads that all want to have some cycles.   Apps or services that need lots of CPU to do their job will run more slowly when a single CPU is being shared among a bunch of different uses, but they will all still proceed via the time-slicing.
Time-slicing on a single CPU will give the appearance of parallel execution because multiple threads can appear to be making progress, but in reality, one thread may run for a few milliseconds, then the OS switches over to another thread which runs for a few milliseconds and so on.  Tasks get done in parallel (at a somewhat slower rate) even though both tasks are never actually using the CPU at exactly the same moment.


text:
Q: Android : myTextView.getLineCount() / getHeight() = 0? I want to get the height or at least the line count of my text view programatically, but the log says 0. What is wrong ? Here is my code :
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_off);

    titreOff = (TextView) findViewById(R.id.offTitre);
    titreOff.setText("some text"); // displays 2 lines of text with the font size I used
    System.out.println(titreOff.getLineCount() + " and " + titreOff.getHeight());
}

Thanks for your advices

A: In onCreate(), your TextView has not had a layout pass and so currently has a zero width and height. There are a few solutions if you would like to get the dimensions of your TextView:

*

*Add an OnGlobalLayoutListener to your TextView's ViewTreeObserver. (e.g. titreOff.getViewTreeObserver().addOnGlobalLayoutListener(listener) and handle your changes there).

*Override TextView and handle your special case by overriding onLayout() (in which you will have the dimensions of your TextView as parameters.
Alternatively, what is the end goal of your measurements? If you can give some specifics, there may be an easier solution than any of this.

A: Your app doesn't know the actual size of TextView while doing onCreate() method. The solution is to move your output here:
onWindowFocusChanged(boolean hasFocus) {
    if (!hasFocus) {
        titreOff = (TextView) findViewById(R.id.offTitre);
        System.out.println(titreOff.getLineCount() +
        " and " + titreOff.getHeight());
    }
}

A: setText() doesn't immediately update the TextView, it just invalidates it. The new text will be set only on the next repaint. If you try to get the height before you will get the old one.
Instead, you should subclass TextView, override onSizeChanged() and you will be notified each time the size of your TextView changed.


text:
Q: How many asynchronous (not multi-threaded) operations are started at once? Is this configurable?
*

*If I call for example WebClient.DownloadStringTaskAsync() 100 times how many of the Tasks are actually parallelly processed?

*Can I configure it or I need to maintain their number using List<Task> and Task.WaitAny()?

*Is there an easy way to see their number in the debugger?

*What are the best practices in situations like this(processing large number of async tasks)?

Note: I'm not using Task.Run() so no additional threads are started (as far as I know)

A: The degree of parallelism is controlled by the ServicePoint infrastructure which I don't fully understand. The default limit is ServicePointManager.DefaultConnectionLimit. This is what everybody uses. I have never seen someone use ServicePoint.
I recommend disabling the limit and implementing the limiting yourself. Using one global limit for the entire AppDomain doesn't make sense to me. It's also hidden and undocumented to rely on DefaultConnectionLimit. Further, DefaultConnectionLimit defaults to very different default values depending on the environment (2 vs. int.MaxValue!).
(4) There is code floating around that allows you to process a sequence of items asynchronously with a certain degree of parallelism. This is the way to go. Controlled parallelism, async and streaming processing with constant memory usage.


text:
Q: Android: rotary button? I'm trying to create a button that can be rotated by the user, here is my code so far:
    slider.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    startAngle = (float) getAngle(event.getX(), event.getY());
                    break;

                case MotionEvent.ACTION_MOVE:
                    double currentAngle = getAngle(event.getX(), event.getY());
                    sliderRotate((float)currentAngle, slider);
                    Log.v("Current angle:", String.valueOf(currentAngle));
                    startAngle = (float)currentAngle;
                    break;

                case MotionEvent.ACTION_UP:
                    break;
            }

            return true;
        }
    });

    return rootView;
}

private double getAngle(double xTouch, double yTouch) {
    double x = xTouch - (Width / 2d);
    double y = Height - yTouch - (Height / 2d);

    switch (getQuadrant(x, y)) {
        case 1:
            return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
        case 2:
            return 180 - Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
        case 3:
            return 180 + (-1 * Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
        case 4:
            return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
        default:
            return 0;
    }
}

private static int getQuadrant(double x, double y) {
    if (x >= 0) {
        return y >= 0 ? 1 : 4;
    } else {
        return y >= 0 ? 2 : 3;
    }
}

private void sliderRotate(float degrees, ImageView slider) {
    slider.setRotation(degrees);
    Log.v("Rotation:", String.valueOf(degrees));
}

I found it here:http://code.tutsplus.com/tutorials/android-sdk-creating-a-rotating-dialer--mobile-8868


text:
Q: Uncaught TypeError when trying to import Material-UI DatePicker Material-UI v5 Datepickers (MUI X)
When I attempt to add a basic date-picker from the example in the docs, I am met with the following error on page load and a blank screen. Any guidance on how to resolve this would be very appreciated!

Full stacktrace from console
withWidth.js:149 Uncaught TypeError: Cannot read properties of undefined (reading '0')
    at Object.require.1531.dup (withWidth.js:149:1)
    at s (_prelude.js:1:1)
    at _prelude.js:1:1
    at Object.<anonymous> (withWidth.js:22:1)
    at Object.require.1186.../styles/useTheme (withWidth.js:149:1)
    at s (_prelude.js:1:1)
    at _prelude.js:1:1
    at Object.<anonymous> (HiddenJs.js:14:1)
    at Object.require.1183.../styles/useTheme (HiddenJs.js:169:1)
    at s (_prelude.js:1:1)
require.1531.dup    @   withWidth.js:149
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
(anonymous) @   withWidth.js:22
require.1186.../styles/useTheme @   withWidth.js:149
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
(anonymous) @   HiddenJs.js:14
require.1183.../styles/useTheme @   HiddenJs.js:169
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
(anonymous) @   Hidden.js:18
require.1181../HiddenCss    @   Hidden.js:177
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.1185../Hidden   @   index.js:15
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.1445../Accordion    @   index.js:1709
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.1657.../internals/components/PickersToolbar @   DatePickerToolbar.js:20
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
(anonymous) @   DesktopDatePicker.js:20
require.1660.../DatePicker/DatePickerToolbar    @   DesktopDatePicker.js:465
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.1661../DesktopDatePicker    @   index.js:13
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
(anonymous) @   DatePicker.js:22
require.1656.../DesktopDatePicker   @   DatePicker.js:485
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.1658../DatePicker   @   index.js:13
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.222.@mui/material/TextField @   MaterialDatePickerInput.jsx:5
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.540.../../../common/actions/AttachmentActions   @   AddTask.jsx:8
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.544.../../../common/constants/ToastTypes.js @   TasksWidget.jsx:4
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.526.../../common/stores/SettingStore.js @   DashboardController.jsx:5
s   @   _prelude.js:1
(anonymous) @   _prelude.js:1
require.695.../dashboard/views/DashboardController.jsx  @   dashboard.js:3
s   @   _prelude.js:1
e   @   _prelude.js:1
(anonymous) @   _prelude.js:1

Below, I am using the basic datepicker code example from the docs:
import * as React from "react";
import TextField from "@mui/material/TextField";
import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

const MaterialDatePickerInput = () => {
  const [value, setValue] = React.useState(null);

  return (
    <LocalizationProvider dateAdapter={AdapterMoment}>
      <DatePicker
        label="Basic example"
        value={value}
        onChange={(newValue) => {
            setValue(newValue);
        }}
        renderInput={(params) => <TextField {...params} />}/>
    </LocalizationProvider>
  );
};

module.exports = React.memo(MaterialDatePickerInput);

I'm not sure where things are going wrong here, but in chrome dev tools this is the last place in my code where the stacktrace hits: import { DatePicker } from "@mui/x-date-pickers/DatePicker";
Here are my relevant packages in package.json:
"dependencies": {
    ...
    "@date-io/moment": "2.13.2",
    "@emotion/react": "11.9.0",
    "@emotion/styled": "11.8.1",
    "@mui/material": "5.6.4",
    "@mui/x-date-pickers": "^5.0.0-alpha.2",
    "moment": "2.24.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
   ...
}

Gulpfile if relevant
var babelify = require("babelify");
var fancyLog = require("fancy-log");
var glob = require("glob");
var gulp = require("gulp");
var gulpSass = require("gulp-sass");
var rename = require("gulp-rename");
var sass = require("sass");
var sourcemaps = require("gulp-sourcemaps");
var uglify = require("gulp-uglify");
var gwfb = require("gulp-watchify-factor-bundle");
var path = require("path");
var buffer = require("vinyl-buffer");
const { parallel } = require("gulp");

gulpSass.compiler = sass;

/*
 * Common options and setup for the bundler
 */
function createBundler(debug, done) {
  return gwfb.create({ cache: {}, debug: debug, packageCache: {} })
    .transform("babelify", { presets: ["@babel/preset-env", "@babel/preset-react"] }) // JSX -> JS and ES6 -> ES5
    .on("error", function(error) { fancyLog("Browserify Error"); fancyLog(error.message); done(); })
    .on("log", fancyLog);
}

/*
 * Write an individual bundle given a readable stream from the bundler
 */
function writeBundle(stream, outputDest, debug, done) {
  stream = stream
    .on("error", function(error) { fancyLog("Browserify Error"); fancyLog(error.message); })
    .pipe(buffer());

  if (debug) {
    // Create sourcemaps for debugging as original files
    stream = stream
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write("."));
  } else {
    // Minify for production
    stream = stream
      .pipe(uglify())
      .on("error", function(error) { fancyLog("Uglify Error"); fancyLog(error.message); done(); });
  }

  // Rename to change "./main/file.js" to "file.js", then write to the output directory
  return stream
    .pipe(rename({ dirname: "./" }))
    .pipe(gwfb.dest(outputDest));
}

function buildBundles(globPattern, watch, debug, done) {
  glob(globPattern, function(error, files) {
    if (error)
      done(error);

    var isPublic = globPattern.search("public") !== -1;

    var outputDest = "./bundles";
    if (isPublic) {
      outputDest += "/public";
    }

    var outputs = files.map(function(file) {
      return path.basename(file);
    });

    var bundleFunc = watch ? gwfb.watch : gwfb.bundle;

    // factor-bundle returns a readable stream for the common.js bundle
    // All the other bundles (after factoring) are written out to the specified outputs
    var stream = gwfb.src(globPattern, { cwd: "./" })
      .pipe(bundleFunc(createBundler(debug, done), { common: "common.js", outputs: outputs }));

    // For one-time build, just write the stream
    if (!watch)
      return writeBundle(stream, outputDest, debug, done).on("end", done);

    // Set up event listener for watch
    return stream
      .on("bundle", function(newStream) {
        fancyLog("Rebundling " + (isPublic ? "public" : "internal") + "...");

        // Write out common bundle
        writeBundle(newStream, outputDest, debug, done);
      });
  });
}

/*
 * Helper function with common functionality between watch and one-time build
 */
function bundle(watch, debug, done) {
  // Make sure we only call the done() handler once
  var bundlesLeft = 2;
  function customDone(error) {
    if (--bundlesLeft === 0) {
      done();
    }
  }

  // For security, the public bundles (e.g. login page) are built separately from the internal
  // bundles. This leads to some extra overall data but allows us to only expose what we absolutely
  // need to on public pages.
  buildBundles("./main/public/*.js", watch, debug, customDone);
  buildBundles("./main/*.js", watch, debug, customDone);
}

/*
 * Helper tasks
 */
gulp.task("js-debug", function(done) {
  bundle(false, true, done);
});

gulp.task("js-release", function(done) {
  bundle(false, false, done);
});

gulp.task("sass", function() {
  // We could minify the CSS with "compressed" instead of "expanded", but it only saves a couple
  // dozen KB.
  return gulp.src([ "../Css/**/*.scss", "!../Css/Sass/*.scss" ])
    .pipe(gulpSass({ outputStyle: "expanded" }).on("error", gulpSass.logError))
    .pipe(gulp.dest("../Css"));
});

gulp.task("sass-watch", function() {
  gulp.watch([ "../Css/*.scss", "../Css/React/*.scss", "../Css/React/Material/*.scss", "!../Css/Sass/*.scss" ], gulp.series("sass"));
});

gulp.task("watch", function(done) {
  bundle(true, true, done);
});

// For non-local builds, we need to run both JS transpile and SCSS compile
gulp.task("Debug", gulp.parallel("js-debug", "sass"));
gulp.task("QA", gulp.parallel("js-debug", "sass"));
gulp.task("Release", gulp.parallel("js-release", "sass"));

// For local development, SCSS compile is handled by the Rider File Watcher
gulp.task("default", gulp.series("watch"));

// For local development with SCSS compiler
gulp.task("dev", gulp.parallel("watch", "sass-watch"));

I'm unable to reproduce this in a sandbox environment currently. Which leads me to believe there is a package conflict of some kind going on and/or something odd with our bundling method (see gulpfile above).
Not sure if relevant either, but here is the theme file wrapping around the component from a parent. Though worth noting I still get the same error regardless.
import React from "react";
import StyledEngineProvider from "@mui/material/StyledEngineProvider";
import { ThemeProvider, createTheme } from "@mui/material/styles";

const theme = createTheme({
    palette: {
        primary: {
            main: "#3F8F24" // Colors.leaf
        }
    },
    typography: {
        fontFamily: 'Prompt, sans-serif'
    }
});

const TestTheme = (props) => {
    return (
        <StyledEngineProvider injectFirst>
            <ThemeProvider theme={theme}>
                {props.children}
            </ThemeProvider>
        </StyledEngineProvider>
    );
};

export default TestTheme;

  `npx @mui/envinfo`

```
   System:
    OS: Windows 10 10.0.19043
  Binaries:
    Node: 14.17.0 - C:\Program Files\nodejs\node.EXE
    Yarn: Not Found
    npm: 6.14.13 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: Version 100.0.4896.127
    Edge: Spartan (44.19041.1266.0), Chromium (101.0.1210.39)
  npmPackages:
    @emotion/react: 11.9.0 => 11.9.0
    @emotion/styled: 11.8.1 => 11.8.1
    @mui/base:  5.0.0-alpha.79
    @mui/material: 5.6.4 => 5.6.4
    @mui/private-theming:  5.6.2
    @mui/styled-engine:  5.6.1
    @mui/system:  5.6.4
    @mui/types:  7.1.3
    @mui/utils:  5.6.1
    @mui/x-date-pickers: ^5.0.0-alpha.2 => 5.0.0-alpha.2
    @types/react:  17.0.39
    react: 17.0.2 => 17.0.2
    react-dom: 17.0.2 => 17.0.2
```


text:
Q: How do I apply no signaling condition for the given Quantum Adder problem The Unitary transformation for the Imperfect Quantum Adder problem is such:

Both the states belong to two Hilbert Spaces and we are trying to add both states to one system using Ancillary qubit.
I am trying to think in the direction of the  Quantum Cloning without Signaling by N.Gisin for the No Signaling approach. Can I use the generic approach here? Can someone help me regarding the mathematics of no signaling and how one applies it depending on the problem?


text:
Q: Recover PHP file from CentOS? I've just accidentally overwritten a PHP file on my centOS Server and i don't have a backup of that file, Is there anyway i can recover the old revision of the file some how ?
Thanks

A: If you overwrote the file (and not just deleted it), your only hope is that your editor saved a backup file of the original. If not, it's gone.
If I may, I recommend using a Source Control Management (such as Git, SVN etc.) if you need versions of your source files preserved.


text:
Q: Printing to console in Pycharm Django views.py I am new to Pycharm (v2019.2) and Django (2.2.4). I am trying to understand pieces of code in various files and am trying to print data to the windows at the bottom of Pycharm, i.e. Run, manage.py, Terminal, Python Console.
I've tried various solutions. I've added LOGGING to settings.py file according to the Django tutorial and importing logging. Nothing came out. I've also tried editing Run > Configurations in Pycharm but to no avail.
#views.py

from django.shortcuts import render, redirect
from .models import Customer

def index(request):
    if request.user.is_authenticated:
        groups = Customer.objections.select_related('group').values('name', 'address', 'group__name', 'group__limit')
        print(groups)
        for item in groups:
            print(item)
        context = {'group_list': {'data': list(groups)}}
        return render(request, 'index.html', context, request.user)
    else:
        return redirect('/accounts/login')

My page loads fine but I just don't see any output to my consoles.

A: Try this:
#views.py

import logging
from django.shortcuts import render, redirect
from .models import Customer

def index(request):
    if request.user.is_authenticated:
        groups = Customer.objections.select_related('group').values('name', 'address', 'group__name', 'group__limit')
        print(groups)
        for item in groups:
            logging.info('Your message')
            print(item)
        context = {'group_list': {'data': list(groups)}}
        logging.debug('Your message')
        return render(request, 'index.html', context, request.user)
    else:
        logging.info('Your message')
        return redirect('/accounts/login')

docs: https://docs.python.org/3/howto/logging.html


text:
Q: NameError for Pyspark model from pyspark.sql.window import Window
from pyspark.sql.functions import rank
from pyspark.sql.functions import col, max as max_

DL=merged[merged['method']=='D/L']
sum1=DL.groupBy(['match_id','bowler']).agg(max_('is_wicket'))

window = Window.partitionBy('match_id').orderBy(col(agg(max_('is_wicket'))).desc())
res_4=sum1.withColumn('rank',rank().over(window))
res_4.filter(res_4.rank==1).show()

In this code, I am getting NameError: name 'agg' is not defined.

A: you have not imported agg from pyspark.sql.functions.
A better approach would be to rename column and then use it.
sum1=DL.groupBy(['match_id','bowler']).agg(max_('is_wicket').alias('max_is_wicket'))

window = Window.partitionBy('match_id').orderBy(col('max_is_wicket').desc())
res_4=sum1.withColumn('rank',rank().over(window))
res_4.filter(res_4.rank==1).show()


text:
Q: Why does putExtra take a key value pair and not just a value? I am going through some of the Android development tutorials, and I just came up with this general question:
Why is it that the intent.putExtra method takes a key value pair and not just a value?
If I want to pass a string to the new Intent, why not just pass the String? What benefits does the key have?

A: You can add more than one object to your Intent so you could do this:
intent.putExtra("name", "My Name");
intent.putExtra("age", 30);

If you want to get the some of the data back you need to specify which using the key:
intent.getStringExtra("name"); // returns "My Name"
intent.getIntExtra("age");     // returns 30

A: Quite simply: keys allows you to pass more than one String (or Integer, Parcalable, etc) and keep them separate.


text:
Q: Perfectly correlated random variables I have a set of identically distributed Weibull's (or pick any other dist.) and they are all perfectly correlated. Can I treat them as a single Weibull with the same parameters as as a single Weibull, in order to determine moments and probabilities?

A: Usually, if all variables are perfectly correlated, only one variable is needed to explain the data because other variables are redundant, but if all variables are uncorrelated we need all the variables to explain the data.


text:
Q: Could jquery's dialog modal change page inside modal? Hello I try to make the jquery dialog popup(modal) can change to other page in the popup (load other page in exist popup)
but I don't know how to load the test3.php inside modal  by coding in test2.php
here is my try
test1.php
 <!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

 <button id="btn">Click to Popup</button>

  here

test2.php
this is test2.php page

 Go to Page test3.php

test3.php

 this is test3.php page

A: Try This in test1.php
$(function () {
    $("#dialog").dialog({
        open: function(event, ui) {
        $('#dialog').load('test2.php', function() {
            $('#mylink').click(function(){
                $('#dialog').load('test3.php', function() {
                      alert('Load was performed.');
                });
             });
         });
       },
        modal: true,
        autoOpen: false,
        title: "jQuery Dialog",
        width: 600,
        height: 350
    });

    $("#btn").click(function(){
        $('#dialog').dialog('open');
    });
});

test2.php

this is test2.php page

<button id="mylink">Go to Page test3.php</button>

A: Try using below code:
$(document).ready(function() {

     var dlg=$('#dialog').dialog({
        title: "jQuery Dialog",
        resizable: true,
        autoOpen:false,
        modal: true,
        hide: 'fade',
        width:350,
        height:275
     });

     $('#btn').click(function(e) {
         e.preventDefault();
         dlg.load('test3.php', function(){
             dlg.dialog('open');
         });
      });
});


text: Q: Подходящий http код ответа Сервер проверяет запрос не является ли он повтором - сравнивает уникальный ключ, передающийся в запросе с предыдущим. В случае если запрос является дубликатом, нужно выдать соответствующую ошибку. Вопрос: какой код HTTP подойдёт лучше всего для этой цели?


text:
Q: How to remove keys from array to create list of values only in PHP? I have a method that passes in an array, and requires a list of int numbers separated by commas to be taken from the passed in array. When I pass in the array, I obviously see the key=>value relationship like:
0 => 38
1 => 39
2 => 40
3 => 41

But in my method, I need to remove the key for each item in the array, and build a literal list of int numbers - not a string - to be used in my method like the following:
[38, 39, 40, 41]

I can't do a foreach and simply echo each value, as my method only runs once and requires a literal list of ints followed by commas to be used further down deep in my method. When I iterate through the array to build a new array, keys are created there too. I can't simply pass in a string, as that would have quotes at the beginning and end of the string. I'm a bit confused how to approach this. Any help would be greatly appreciated.

A: $array = [1,2,3,4];
$new_value = implode(',',$array);

A: Both your arrays are same,
[38, 39, 40, 41]. Here 38 is at index 0, 39 at 1.
you can use array_values if you want to pick only array values or reset your index values if they are not aligned ie 0,1,2.
With implode, you will be converting your array to string which will not include [ ]. So you can pass your complete array as it is in your further methods.
  If you want to output it is a string [38, 39, 40, 41] then this can be achieved like this.

   echo '['.implode(", ",$arr).']';


text:
Q: JAXB multiple xsd I have two XSD that I generated through JAXB's xjc command.
http://www.imsglobal.org/xsd/imscp_v1p1.xsd
and
http://www.mmtech.ru/adlcp_v1p3.xsd
I am trying to use the Item object from the first xsd like

ItemType item = factory.createItemType();
DataType dataType = factory.createDataType();
MapType mapType = factory.createMapType();
dataType.getMap().add(mapType);
item.getAny().add(dataType);

Note that DataType and MapType are both from the two XSD.
I can generate the xml file expect for one problem, it is giving the error
Caused by: com.sun.istack.SAXException2: unable to marshal type "packagename.DataType" as an element because it is missing an @XmlRootElement annotation
So I tried adding the @XmlRootElement to the DataType class and instead of it creating ns2:dataType, it creates the XML below.
        <item>
            <dataType>
                <ns2:map targetID="targetid" writeSharedData="false"/>
            </dataType>
        </item>

Please help. Thank you

A: to answer my own question.
We should convert the DataType class to a JAXBElement.
JAXBElement dataTypeElement = factory.createData(dataType);
item.getAny().add(dataTypeElement);


text:
Q: Display database search result in html using php? I'm attempting to create a page, where I can search for case files from my database, however, I can't get my code to work.
I already have pages showing all content of the database and where I can add new content.
I've read guides, tutorials and questions on stackoverflow, but can't find an answer on how to proceed.
I have the following php code in searchcasescript.php
<?php

$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or
die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");

if(isset($_GET["form_submit"]))
{
    $journalnummer =$_GET["journalnummer"];

    $stmt = $conn->prepare("select * from testcases where journalnummer=? ");

        $stmt->bind_param("s",$journalnummer);

        $stmt->execute();
    $val = $stmt->get_result();
    $row_count= $val->num_rows;

    if($row_count >0)
    {
        $result =$val->fetch_assoc();

        print_r($result);
    }
    else{
        echo "wrong number";
    }

    $stmt->close();
    $conn->close();
}

?>

and my html:

    <form action="searchcasescript.php" method="post">
    Journalnummer:
    <input type="text" name="journal" class="form-control" required>

    <input type="submit" name="form_submit" class="btn btn-basic" value="Søg">
</form>

I've had different results depending on my changes to the php, but currently I'm getting nothing. Pressing search opens a new, blank page.
What I would like to end up with was being able to enter full or part of a case number and the search results being displayed on the same or a new page.
Can anyone point me in the right direction to read more about this and/or where to proceed with my code?
And apologies, if I've somehow missed the answer in one of the questions here.
UPDATED WITH "LIKE":
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer LIKE ?");

        $stmt->bind_param("s", '%' . $journal . '%');

A:    $journalnummer =$_GET["journalnummer"];

Your looking for journalnummer but your input has a name of journal
<input type="text" name="journal" class="form-control" required>
$_POST['journal'];

This is what should contain the number .


text:
Q: Remove an object from a list of objects I basically have 3 classes. Card, Deck, and Player. The Deck is a list of cards. I am trying to remove a card from the deck. But I am getting a ValueError saying that the card is not in the list. From my understanding, it is and I am passing the correct object through the removeCard function. I am not sure why I am getting a ValueError. So in short, the problem is that I need to remove an object (Card) from a list of Cards.
My issue is that when I try to remove a card from the deck I get an error like this:
ValueError: list.remove(x): x not in list

This is what I have so far:
Card class:
import random

class Card(object):
    def __init__(self, number):
        self.number = number

Deck class (the error is thrown here, in the removeCard function):
class Deck(object):
    def __init__(self):
        self.cards = []
        for i in range(11):
            for j in range(i):
                self.cards.append(Card(i))

    def addCard(self, card):
        self.cards.append(card)

    def removeCard(self, card):
        self.cards.remove(card)

    def showCards(self):
        return ''.join((str(x.number) + " ") for x in self.cards)

Player class:
class Player(object):
    def __init__(self, name, hand):
        self.name = name
        self.hand = hand

main function:
def main():
    deck = Deck()
    handA = [Card(6), Card(5), Card(3)]
    handB = [Card(10), Card(6), Card(5)]
    playerA = Player("A", handA)
    playerB = Player("B", handB)

    print("There are " + str(len(deck.cards)) + " cards in the deck.")
    print("The deck contains " + deck.showCards())

    for i in handA:
        deck.removeCard(i)
    print("Now the deck contains " + deck.showCards())

main()

A: When you call list.remove, the function searches for the item in the list, and deletes it if found. When searching, it needs to perform a comparison, comparing the search item to every other list item.
You're passing an object to remove. A user defined object. They do not behave the same way as, say, integers would, when performing comparisons.
For example, object1 == object2, where object* are objects of the Card class, by default are compared against their unique id values. Meanwhile, you want a comparison to be performed against the card number, and removal done accordingly.
Implement an __eq__ method in your class (python-3.x) -
class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

Now,
len(deck.cards)
55

for i in handA:
    deck.removeCard(i)

len(deck.cards)
52

Works as expected. Note that in python-2.x, you'd implement __cmp__ instead.


text:
Q: How to compare old value and new value in triggers and then mark as insert/update/delete in audit table CREATE TABLE source_det (
det_id number(10) by default IDENTITY
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    ref_id     NUMBER(10),
    sys_other  VARCHAR2(30)
);

INSERT INTO source_det VALUES(1,11,'SOURCE',992,null);
INSERT INTO source_det VALUES(2,11,'SOURCE',637,null);
INSERT INTO source_det VALUES(3,11,'SOURCE',null,'Manual');
INSERT INTO source_det VALUES(4,11,'TARGET',637,null);
INSERT INTO source_det VALUES(5,12,'TARGET',637,null);
Audit table:

CREATE SEQUENCE audit_tab_sq;
CREATE TABLE audit_tab (
    a_id       NUMBER(10) default audit_tab_sq.nextval,
    l_transaction varchar2(20),--INSERT, UPDATE, DELETE
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    value_old  VARCHAR2(20),
    value_new  VARCHAR2(20)
);
I need to create a trigger that will get fired whenever there is new event occurred on the main table i.e source_det

My Attempt:
create or replace trigger audit_tab_trg
AFTER INSERT OR DELETE OR UPDATE ON source_det
FOR EACH ROW
BEGIN
  --Need to insert records into the audit table whenever there is a new entry
  IF inserting THEN
    --new ref_id value
     INSERT INTO audit_tab (a_id,l_transaction,e_id, sys_name,value_old,value_new)
     VALUES (audit_tab_sq.NEXTVAL,'INSERT',:new.e_id,:new.sys_name,NULL,:new.ref_id);

    --new sys_other
     INSERT INTO audit_tab (a_id,l_transaction,e_id, sys_name,value_old,value_new)
     VALUES (audit_tab_sq.NEXTVAL,'INSERT',:new.e_id,:new.sys_name,NULL,:new.sys_other);
  END IF;
END;

When I have inserted one record for ref_id into the table source_Det then in the audit table I am getting two records but ideally, it should check and load only that value which is newly inserted.
Current Output:
+------+---------------+------+----------+-----------+-----------+
| a_id | l_transaction | e_id | sys_name | value_old | value_new |
+------+---------------+------+----------+-----------+-----------+
|    1 | INSERT        |   13 | TARGET   | null      | 637       |
|    2 | INSERT        |   13 | TARGET   | null      | null      |
+------+---------------+------+----------+-----------+-----------+

Expected Output:
+------+---------------+------+----------+-----------+-----------+
| a_id | l_transaction | e_id | sys_name | value_old | value_new |
+------+---------------+------+----------+-----------+-----------+
|    1 | INSERT        |   13 | TARGET   | null      |       637 |
+------+---------------+------+----------+-----------+-----------+

Basically, I need to check two columns ref_id and sys_other. If only ref_id entered by user or modified by user or deleted by user then it should get marked as inserted/updated/deleted into the audit table.
And If only sys_other entered by user or modified by user or deleted by user then it should get marked as inserted/updated/deleted into the audit table.

A: Why you didn't listen to my previous suggestion? You should really add new pair of new/old columns into the audit table, not put everything into value_old/value_new because - as you don't store information what it represents - you'll have to guess (and that's the way to problems).
BTW, what will you do if you - in the same statement - modify both REF_ID and SYS_OTHER? You'll have to check what you did first, and then insert (or not) a row. Too much code for a little benefit.
if :new.ref_id is not null then
  INSERT INTO audit_tab (a_id,l_transaction,e_id, sys_name,value_old,value_new)
     VALUES (audit_tab_sq.NEXTVAL,'INSERT',:new.e_id,:new.sys_name,NULL,:new.ref_id);
elsif :new.sys_other is not null then
  INSERT INTO audit_tab (a_id,l_transaction,e_id, sys_name,value_old,value_new)
     VALUES (audit_tab_sq.NEXTVAL,'INSERT',:new.e_id,:new.sys_name,NULL,:new.sys_other);
end if;


text:
Q: How to Create an Erlang property list from Elixir I am trying to write tests in Elixir that call Erlang code similar to this:
foo([{property_one = P1, property_two = P2}|_] = Rows) when P1 =/= P2 ->
erlang:display("function head one"),

foo(Rows) ->
erlang:display("function head two"),
Rows.

I think that an Elixir keyword list would be the correct data type to pass to this function, but I cannot seem to construct it properly. This is the code I'm trying to call it with:
:module.foo([[property_one: "A", property_two: "B"]])

But this code goes direct to function head two. Where am I going wrong?
Update: Going to git history for the file revealed that a record declaration had been dropped somewhere along the way. Modifying the code to:
foo([#record{property_one = P1, property_two = P2}|_] = Rows)
fixed all problems

A: There are two problems with your code. One as bitwalker mentioned is in your elixir code where you wrap your proplist into a list. The other one in your erlang code:
[property_one: "A", property_two: "B"]

translates to the following proplist in erlang:
[{property_one, <<"A">>}, {property_two, <<"B">>}]

What you probably mean to match in your erlang code is this (although it is hard to guess what exactly you want there):
foo([{property_one, P1}, {property_two, P2}|_] = Rows) when P1 =/= P2

In general Keyword in elixir can not be translated to erlang' proplists since keys in erlang can be of any type but in elixir they have to be atoms.
If you have to have more general way of passing erlang proplists from elixir to erlang there is nothing stopping you from constructing them manually in elixir. This will work for example:
[{property_one, "A"}, {"property_two", "B"}]

Although above is not Keyword list it is still an erlang proplist.

A: It looks to me like you are wrapping the argument in an extra list when calling foo - the function matches on a proplist, not a list of proplists.


text:
Q: Private NPM library raise error "Module parse failed" I'm trying to create my libary with React and to use it locally (with my company git repository).
I can test my app while developping with npm run start. My app is running.
But when I want to use it in an other project, I got this error :

ERROR in ./node_modules/mylib/src/views/calendar.jsx
  Module parse failed: Unexpected token (10:53)
You may need an appropriate loader to handle this file type.

The line involved is :
const Calendar = ({ month = moment(), dayCellTitle = <DayCellTitle />, header = <CalendarHeader/>, children }) => {

The package is imported like that :
"mylib": "git+ssh://git@gitlab.mycompany.ch:mylib/mylib.git"

I try this, but I got worst :

Plugin/Preset files are not allowed to export objects, only functions.
  In
  /home/xxxxx/Documents/workspaces/react-calendar/node_modules/babel-preset-stage-0/lib/index.js

Here the files of my package :
webpack.config.js
const path = require('path');
const pkg = require('./package.json');
const libraryName= pkg.name;
module.exports = {
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'react-calendar.js',
    library: libraryName,
    libraryTarget: 'umd',
    publicPath: '/dist/',
    umdNamedDefine: true
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    alias: {
      'react': path.resolve(__dirname, './node_modules/react'),
      'react-dom': path.resolve(__dirname, './node_modules/react-dom'),
    }
  },
  externals: {
    // Don't bundle react or react-dom
    react: {
      commonjs: "react",
      commonjs2: "react",
      amd: "React",
      root: "React"
    },
    "react-dom": {
      commonjs: "react-dom",
      commonjs2: "react-dom",
      amd: "ReactDOM",
      root: "ReactDOM"
    }
  }
};

package.json
{
  "name": "react-calendar",
  "version": "0.0.1",
  "description": "React Calendar UI by",
  "main": "./dist/lib/index.js",
  "scripts": {
    "start": "./node_modules/.bin/parcel docs/index.html",
    "build": "./node_modules/.bin/webpack --mode=production",
    "build:docs": "./node_modules/.bin/parcel build docs/index.js -d ./dist/docs && cp docs/index.html dist/docs/index.html",
    "test": "jest",
    "tdd": "jest --watch"
  },
  "author": "Xero",
  "license": "MIT",
  "dependencies": {
    "lodash": "^4.17.11",
    "mobx": "^5.9.0",
    "mobx-react": "^5.4.3",
    "moment": "^2.24.0",
    "moment-range": "^4.0.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^0.85.0",
    "settings": "^0.1.1"
  },
  "peerDependencies": {
    "lodash": "^4.17.11",
    "mobx": "^5.9.0",
    "mobx-react": "^5.4.3",
    "moment": "^2.24.0",
    "moment-range": "^4.0.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^0.85.0",
    "settings": "^0.1.1"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0-0",
    "@babel/plugin-proposal-class-properties": "^7.3.0",
    "@babel/plugin-proposal-decorators": "^7.3.0",
    "@babel/preset-env": "^7.3.1",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "babel-plugin-module-resolver": "^3.1.3",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.8.0",
    "enzyme-adapter-react-16": "^1.9.1",
    "jest": "^24.1.0",
    "parcel-bundler": "^1.6.2",
    "react-test-renderer": "^16.8.0",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12",
    "webpack-node-externals": "^1.6.0"
  },
  "jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/spec/javascript/__mocks__/fileMock.js",
      "\\.(css|scss|less)$": "<rootDir>/spec/javascript/__mocks__/styleMock.js"
    },
    "roots": [
      "src",
      "tests"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "setupFiles": [
      "<rootDir>/tests/setup.js"
    ]
  }
}

.babelrc
{
  "presets": ["@babel/preset-env", "@babel/preset-react",],
  "plugins":  [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

Side question :
Is there a way to know if the library will be imported without error BEFORE doing the importation in an other project
Edit
I have added yarn run build to my package.json, and launching it do not raise any errors :
Entrypoint main [big] = react-calendar.js
 [45] (webpack)/buildin/module.js 497 bytes {0} [built]
 [48] (webpack)/buildin/global.js 472 bytes {0} [built]
[244] ./node_modules/moment/locale sync ^\.\/.*$ 3 KiB {0} [optional] [built]
[368] ./src/index.js + 52 modules 182 KiB {0} [built]
      | ./src/index.js 65 bytes [built]
      | ./src/views/calendar.jsx 1.17 KiB [built]
      | ./src/views/day_cell_title.jsx 358 bytes [built]
      | ./src/views/calendar_header.jsx 1.15 KiB [built]
      | ./src/store/calendar_store.js 3.85 KiB [built]
      | ./src/views/calendar_grid.jsx 1.49 KiB [built]
      | ./src/views/calendar_navigation_button.jsx 928 bytes [built]
      | ./src/views/calendar_title.jsx 290 bytes [built]
      | ./src/generators/month_generator.js 556 bytes [built]
      | ./src/painters/day_cell_color.js 593 bytes [built]
      | ./src/views/day_cell_content.jsx 547 bytes [built]
      | ./src/settings.js 332 bytes [built]
      | ./src/painters/event_color.js 374 bytes [built]
      | ./src/painters/range_color.js 591 bytes [built]
      | ./src/views/empty_day_cell_content.jsx 340 bytes [built]
      |     + 38 hidden modules
    + 743 hidden modules

A: You're redistributing your sources that contain JSX syntax. Usually, before publishing, you'll need to transform these. If not, then your dependents will need to configure their babel-loader with React support and ensure that they're not excluding your package modules.
So your configuration looks alright, except for the exclusion match:
 module: {
  rules: [
    { test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader']
    }
  ]
 }

I would recommend that you use { include } and list out the paths that should explicitly match. To find the path at which your package sources are located, use path.dirname(require.resolve('@yours/package-name')).

A: The issue was 2 things :
1. Build forgotten and not commited
I was not building my project (with yarn run build), and most of all, I was not commiting the compiled file (dist/main.js)
2. The import was wrong
Given the point 1., my import were wrong.
I was doing :
import {Calendar} from "project-react-calendar/src/views/calendar";

instead of :
import {Calendar} from "project-react-calendar";

That can be available, with this index.js :
import { Calendar } from './views/calendar'

export {
    Calendar
}

A: Your npm run start script seems to use parcel, not webpack I guess webpack.config.js simply doesn't affect it? Maybe you should make sure that proper loader is indeed launched by parcel.
"start": "./node_modules/.bin/parcel docs/index.html", // <- invokes parcel bundler
"build": "./node_modules/.bin/webpack --mode=production",

Try npm run build and if it succeeds, that will be exactly the case.


text:
Q: how can sed match pattern delete line plus one and insert diferent file I believe i'm pretty close but there is 1 command missing..
i have file1.txt
rrrrrrrrrrrrrrrrr
dddddddddddddddddd
id="8" efwef
aaaaaaaaaaaaaaaaaaa
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx

file2.txt
123

123

what i need is :
rrrrrrrrrrrrrrrrr
dddddddddddddddddd
123

123
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx

explained: find pattern (id="8")
delete pattern line +1
insert into file1.txt content of file2.txt
i got this sed command
sed -e '/id="8"/,+1{' -e 'r /tmp/file2.txt' -e 'd' -e '}' -i /tmp/file1.txt

it does all i need ... except it inserts file2.txt twice...
probably because the ,+1 but i tryed several combos but can't get to it

A: Instead of trying to specify the next line via an address range, try using N to pull it into the pattern space before the d:
$ sed -e '/id="8"/{r file2.txt' -e 'N;d;}' file1.txt
rrrrrrrrrrrrrrrrr
dddddddddddddddddd
123

123
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx


text:
Q: Is querying the model from the viewmodel anti-pattern? I use Linq-to-SQL to create my models. I have a Movies table that lists all of the users' favorite movies.
In my VM, I'll have access to a current user. I want to call to my linq entity to get all the users favorite movies. Is it bad practice to have the actual linq query to the Movies table directly in a method in my VM?
Public Class MyVM
    Public Sub GetMovies()
        'some linq query to get the movies based on the user's id
    End Sub
    ...more stuff...
End Class

Or, should I have that method in my model  and only call a GetAll(ByVal id as Integer) function from the model or a repository?
I'm pretty new to patterns. I know patterns are more of a guide, but I'd like to follow it correctly before I make those determinations when the situation arises.

A: A view model is there to represent your data, for example on a view (in ASP.NET MVC).
For example lets say you have a view that has to display user data.  You will return a User object by ID from a service or repository call (to a database).  You will then map this User object to the view model.  Then you would return this view model to the view and the view will use it to display the user's data to the client.
If I could then I could show you some C# code.  I don't have time to go look up the VB.NET equivalent.

A: You should neither write any logic for populating the data from database in Model nor in  ViewModel, if you want to follow good architecture.
You should use DataServiceAgent to load data. For more information on DataServiceAgent Visit the this link.
Service Agent introduce one more layer on the top of the application to interact with database and web services.

A: You are mixing your DataAccess Layer with Presentation Layer. So yes, it is anti-pattern.

A: For me. ViewModel and Model are same. The Model layer it´s a mirror of you View... then Why use ViewModel rather than Model? it´s a just naming conflict


text:
Q: When deploying a web application I get the exception NoClassDefFoundError:LocalizableImpl I have a standard J2EE web application that includes web services. I'm using the webservices-rt library to host the services. [See the maven dependency below]. However, I get the following exception at run time:
SEVERE: Exception sending context initialized event to listener instance of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
java.lang.NoClassDefFoundError: com/sun/xml/ws/util/localization/LocalizableImpl
    at com.sun.xml.ws.util.exception.JAXWSExceptionBase.<init>(JAXWSExceptionBase.java:63)
    at com.sun.xml.ws.transport.http.servlet.WSServletException.<init>(WSServletException.java:47)
    at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:118)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [...]
    at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.util.localization.LocalizableImpl
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    ... 33 more

Maven WS Dependency
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>webservices-rt</artifactId>
        <version>1.4</version>
        <scope>compile</scope>
    </dependency>

Am I missing a library? I've tried adding jaxws-rt. However, that requires an additional repo [jboss]. I'm a bit leery of that, as that it introduces a lot of new libraries into the project.

A: If you are using Maven, add below to your project should solve your problem:
<dependency>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-rt</artifactId>
    <version>2.3.2</version>
</dependency>

You don't have to add others jar because it will automatically pull the rest of dependencies. I prefer to add the jar to my war instead of Tomcat lib. I think it is more portable.

A: try
The JAX-WS dependency library "jaxws-rt.jar" is missing.
Go here http://jax-ws.java.net/.
Download JAX-WS RI distribution.
Unzip it and copy "jaxws-rt.jar" to Tomcat library folder "{$TOMCAT}/lib".
Restart Tomcat.

A: For a maven, tomcat application try these dependencies in your pom.xml
<dependencies>
    <!-- jax-ws maven dependency -->
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.2.8</version>
    </dependency>
    <!-- servlet provided by tomcat -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.2.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.xml.stream.buffer/streambuffer -->
    <dependency>
        <groupId>com.sun.xml.stream.buffer</groupId>
        <artifactId>streambuffer</artifactId>
        <version>1.5.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.2.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.sun.xml.ws/policy -->
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>policy</artifactId>
        <version>2.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.glassfish.gmbal/gmbal-api-only -->
    <dependency>
        <groupId>org.glassfish.gmbal</groupId>
        <artifactId>gmbal-api-only</artifactId>
        <version>3.2.0-b003</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.glassfish.ha/ha-api -->
    <dependency>
        <groupId>org.glassfish.ha</groupId>
        <artifactId>ha-api</artifactId>
        <version>3.1.9</version>
    </dependency>
</dependencies>

I hope this works for new people who will face this issue
Regards

A: Declaring the JBoss repo doesn't automatically import the repo libraries. It simply makes the libraries available for importing.
Bottom line is that if you want to use a class that's in a library, then you have to pull the library into your project. If the library is in the JBoss repo, then you have to declare the JBoss repo.


text:
Q: Getting error: "bad token exception" while using preferences I am trying to add a preference page to my application. The preference screen contains two list preferences and one check box.
But when I try to click the list preference, the application crashes. I don't know how to solve this issue. Can anyone please help me....
Source:
package com.emergencyappbgi;

import com.emergencyappbgi.R;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Preferences extends PreferenceActivity
{

    static public final String PREF_RECORD_CALLS = "PREF_RECORD_CALLS";
    static public final String PREF_AUDIO_SOURCE = "PREF_AUDIO_SOURCE";
    static public final String PREF_AUDIO_FORMAT = "PREF_AUDIO_FORMAT";

    SharedPreferences prefs;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.userpreferences);
    }
}

XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="PREF_RECORD_CALLS"
        android:summary="Turn on recording of all calls"
        android:title="Enable recording" />

    <ListPreference
        android:defaultValue="1"
        android:dialogTitle="Audio source"
        android:entries="@array/audio_source_options"
        android:entryValues="@array/audio_source_values"
        android:key="PREF_AUDIO_SOURCE"
        android:summary="Select the audio source to record from during calls"
        android:title="Audio source" />
    <ListPreference
        android:defaultValue="1"
        android:dialogTitle="Audio format"
        android:entries="@array/audio_format_options"
        android:entryValues="@array/audio_format_values"
        android:key="PREF_AUDIO_FORMAT"
        android:summary="Select the file format to use for call recordings"
        android:title="Recording file format" />

</PreferenceScreen>

Log cat:
12-13 08:38:00.310: E/AndroidRuntime(2301): FATAL EXCEPTION: main
12-13 08:38:00.310: E/AndroidRuntime(2301): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@41522060 is not valid; is your activity running?
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.view.ViewRootImpl.setView(ViewRootImpl.java:567)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.app.Dialog.show(Dialog.java:281)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.preference.DialogPreference.showDialog(DialogPreference.java:308)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.preference.DialogPreference.onClick(DialogPreference.java:266)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.preference.Preference.performClick(Preference.java:949)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:215)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.widget.AbsListView$1.run(AbsListView.java:3423)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.os.Handler.handleCallback(Handler.java:725)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.os.Looper.loop(Looper.java:137)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at android.app.ActivityThread.main(ActivityThread.java:5041)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at java.lang.reflect.Method.invokeNative(Native Method)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at java.lang.reflect.Method.invoke(Method.java:511)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-13 08:38:00.310: E/AndroidRuntime(2301):     at dalvik.system.NativeStart.main(Native Method)