问:
Actor model with Akka.NET: how to prevent sending messages to dead actors
I am using Akka.NET to implement an actor system in which some actors are created on demand and are deleted after a configurable idle period (I use Akka's "ReceiveTimeout" mechanism for this). Each of these actors is identified by a key, and there should not exist two actors with the same key.

These actors are currently created and deleted by a common supervisor. The supervisor can be asked to return a reference to the actor matching a given key, either by returning an existing one or creating a new one, if an actor with this key doesn't exist yet. When an actor receives the "ReceiveTimeout" message, it notifies the supervisor who in turn kills it with a "PoisonPill".

I have an issue when sending a message to one of these actors right after it has been deleted. I noticed that sending a message to a dead actor doesn't generate an exception. Worse, when sending an "Ask" message, the sender remains blocked, waiting indefinitely (or until a timeout) for a response that he will never receive.

I first thought about Akka's "Deatchwatch" mechanism to monitor an actor's lifecycle. But, if I'm not mistaken, the "Terminated" message sent by the dying actor will be received by the monitoring actor asynchronously just like any other message, so the problem may still occur in between the target actor's death and the reception of its "Terminated" message.

To solve this problem, I made it so that anyone asking the supervisor for a reference to such an actor has to send a "close session" message to the supervisor to release the actor when he doesn't need it anymore (this is done transparently by a disposable "ActorSession" object). As long as there are any open sessions on an actor, the supervisor will not delete it.

I suppose that this situation is quite common and am therefore wondering if there isn't a simpler pattern to follow to address this kind of problem. Any suggestion would be appreciated.

答:
I solved this problem with entity actors created through Akka's Cluster Sharding mechanism:

If the state of the entities are persistent you may stop entities that are not used to reduce memory consumption. This is done by the application specific implementation of the entity actors for example by defining receive timeout (context.setReceiveTimeout). If a message is already enqueued to the entity when it stops itself the enqueued message in the mailbox will be dropped. To support graceful passivation without losing such messages the entity actor can send ShardRegion.Passivate to its parent Shard. The specified wrapped message in Passivate will be sent back to the entity, which is then supposed to stop itself. Incoming messages will be buffered by the Shard between reception of Passivate and termination of the entity. Such buffered messages are thereafter delivered to a new incarnation of the entity.


来源: stackexchange

问:
jquery ui datepicker select only current and previous month
Hello folks and thanks for reading.

I am trying to implement jquery ui datepicker and what i am trying to do is the following ;

Allow the user to selct only the current and previous months

The full month should be selectable( i used minDate:-1m , but this allows you to select only certain days in the month not all of the dates)

This is the configuration i have so far , any input would be much appreshiated :

```<code>'options'=>array(
                        'dateFormat'=>'yy-mm-dd',
                        'defaultDate'=>$model->dataCaricamento,
                        'showAnim'=>'fold',
                        'showButtonPanel'=>false,
                        'changeYear'=>false,
//                          'monthRange'=>'-1:+1',
//                          'defaultDate'=>'+0',
//                            'maxDate'=>'+1m',
//                            'minDate'=>'-1m',
//                            'selectOtherMonths'=>false,
//                            'showOtherMonths'=>false,
//                             'numberOfMonths'=>[ 1, 2 ],
//                             'stepMonths'=>0
                              'changeMonth'=> true,
//        'minDate'=> '-1m',
//        'maxDate'=> '0',   //add this
</code>```

答:
$( "#datepicker" ).datepicker({
minDate: '-30',
maxDate: '0'
});</p>

ContentLicense: CC BY-SA 3.0

Body:
Hello folks and thanks for reading.

I am trying to implement jquery ui datepicker and what i am trying to do is the following ;

Allow the user to selct only the current and previous months

The full month should be selectable( i used minDate:-1m , but this allows you to select only certain days in the month not all of the dates)

This is the configuration i have so far , any input would be much appreshiated :

'options'=>array(
                        'dateFormat'=>'yy-mm-dd',
                        'defaultDate'=>$model->dataCaricamento,
                        'showAnim'=>'fold',
                        'showButtonPanel'=>false,
                        'changeYear'=>false,
//                          'monthRange'=>'-1:+1',
//                          'defaultDate'=>'+0',
//                            'maxDate'=>'+1m',
//                            'minDate'=>'-1m',
//                            'selectOtherMonths'=>false,
//                            'showOtherMonths'=>false,
//                             'numberOfMonths'=>[ 1, 2 ],
//                             'stepMonths'=>0
                              'changeMonth'=> true,
//        'minDate'=> '-1m',
//        'maxDate'=> '0',   //add this


问:
Unity3d android 2d sprites placement
Please take a look at this picture

It's a final look of the game exported from photoshop

I marked the ui sprites with red marker and the gameplay sprites with blue marker

My question is how should i correctly use these sprites in unity3d 2d game development.

This is the ways i can think of:

Use the red sprites in a canvas as Image component inside a layout group (vertical or horizontal, so i can place them in in the corner and it will work with every resolution)

Use blue sprites outside of a canvas and obviously via a Sprite Renderer component

Use blue sprites in canvas viaSprite Renderer component and set the canvas render mode to Screen Space - Camera

Use blue sprites in canvas via Image component

These ways all might be wrong but these are all i can think of right now.

I'm open to all of your suggestions.

My unity version is 2017.2.0f and i want the game to work with every resolution.

答:
To add upon Xarbrough's great answer:

Don't put SpriteRenderer in a Canvas. Use the Image component instead, you will have a lot more control on the actual size/ordering of the images.

If you will only handle default UI events of components like Button/ScrollView etc., use a Screen Space - Overlay canvas. This way you don't have to bind a camera to each canvas and can easily separate your UI into another scene, and later Load Scene Additive them into your main scene as needed. This allow for less cluttered and more organized scenes (imagine having to put options, shop, inventory, achievement etc. canvases all in one scene).

If you need to handle complex events on the UI (drag'n'drop, transform on mouse hover, most things that require you to extends the EventTrigger class), you will want to use Screen Space - Camera because it's much easier to works with mouse coordinate in this mode.

If you have a canvas that should move together with a sprite (e.g. chat bubble in RPG), use World Space.

Title: Unity3d android 2d sprites placement


问:
Changing CKEDITOR value removes event listener
I have a page with several CKEDITOR fields, where I catch a click event.
When clicking a certain button, the field is cleared, which unfortunately also removes the event listener.

This seems to be a known issue.
I have tried solutions provided elsewhere, but I'm still stuck.

code:

```<code>var aInst = CKEDITOR.instances;
for (var key in aInst){
    CKEDITOR.instances[key].on('contentDom', function() {
        console.log('initial or change');
        this.editable().attachListener(this.document,'click', function(){
            console.log('iframe click');
        });
    });
}
</code>```

clicking in the initial, unchanged field will get me the 'iframe click' log.

when

```<code>CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');
</code>```

is activated, I get the 'initial or change' log, but clicking in the field isn't caught anymore.

This is already a version changed to a solution elsewhere (not working for me), because originally this.editable().attachListener(this.document,'click', function(){ was simply this.document.on('click', function(){

CKEDITOR v4.6.2

JQuery v3.1.1

答:
I solved it in a hacky way. First of all, I replaced

```<code>CKEDITOR.instances[key].on('contentDom', function() {
</code>```

with

```<code>CKEDITOR.instances[key].on('instanceReady', function() {
</code>```

so the original attaching of the listener happens only on loading the page.

I removed

```<code>CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');
</code>```

completely and replaced with my 'hacky' solution: I removed everything inside the wrapper around the editor and textarea, refilled it with the 'original' code, re-activated the ckeditor on it and then attached the listener, works like a charm:

```<code>(var reFill = original html with textarea)

$('#'+cpdId+'_flip_text').empty();
$('#'+cpdId+'_flip_text').html(reFill);
$('#'+cpdId+'_flip_text').find('textarea').ckeditor(function(){
    var CKedit = CKEDITOR.instances[cpdId+'_flip_text_input'];
    CKedit.editable().attachListener(CKedit.document,'click', function(){
        //stuff to do on click
    });
});
</code>```

Body:
I have a page with several CKEDITOR fields, where I catch a click event.
When clicking a certain button, the field is cleared, which unfortunately also removes the event listener.

This seems to be a known issue.
I have tried solutions provided elsewhere, but I'm still stuck.

code:

var aInst = CKEDITOR.instances;
for (var key in aInst){
    CKEDITOR.instances[key].on('contentDom', function() {
        console.log('initial or change');
        this.editable().attachListener(this.document,'click', function(){
            console.log('iframe click');
        });
    });
}

clicking in the initial, unchanged field will get me the 'iframe click' log.

when

CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');

is activated, I get the 'initial or change' log, but clicking in the field isn't caught anymore.

This is already a version changed to a solution elsewhere (not working for me), because originally this.editable().attachListener(this.document,'click', function(){ was simply this.document.on('click', function(){

CKEDITOR v4.6.2

JQuery v3.1.1

Body:
I solved it in a hacky way. First of all, I replaced

CKEDITOR.instances[key].on('contentDom', function() {

with

CKEDITOR.instances[key].on('instanceReady', function() {

so the original attaching of the listener happens only on loading the page.

I removed

CKEDITOR.instances[cpdId+'_flip_text_input'].setData('');

completely and replaced with my 'hacky' solution: I removed everything inside the wrapper around the editor and textarea, refilled it with the 'original' code, re-activated the ckeditor on it and then attached the listener, works like a charm:

(var reFill = original html with textarea)

$('#'+cpdId+'_flip_text').empty();
$('#'+cpdId+'_flip_text').html(reFill);
$('#'+cpdId+'_flip_text').find('textarea').ckeditor(function(){
    var CKedit = CKEDITOR.instances[cpdId+'_flip_text_input'];
    CKedit.editable().attachListener(CKedit.document,'click', function(){
        //stuff to do on click
    });
});


问:
C# - Add common behaviour in abstract class after calling individual behaviours in subclasses
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

```<code>abstract class A
{
    IEnumerable<int> Foo { get; }
}
</code>```

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

```<code>abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}
</code>```

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.

答:
This approach is just fine.

You have a behavior common to all derived classes (.Where()) in base class that conforms to DRY principle.

Then you have behavior specific to each derived class in those classes.

It feels especially clunky if I have some classes between which also
  have to filter it because I'd just have to add more and more members
  based on the amount of layers I have.

Well, it's perfectly fine if you're required to have different logic for different cases.

Body:
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

abstract class A
{
    IEnumerable<int> Foo { get; }
}

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.


问:
android's graphical layout
seems like the Android ADT's new graphical layout has changed, but it's a pain to add/drop stuff, especially because I do not have control over the layout on the outline where I can drop something inside a linearlayout for example. Does anyone know if it's possible to come back to the old graphical layout?</p>

答: Probably you should try ADT 9.0.0 Preview-3.</p>

ContentLicense: CC BY-SA 2.5

Title: android's graphical layout


问:
makefile for CGAL (libcgal8)
I don't know why, but at each new version of CGAL, the procedure to compile completely changes. So, it's not even possible to recompile old piece of code (6 months old) because it doesn't work like that anymore.

I'm frankly very tired of redoing all the makefile of my projects that use CGAL each time. This time, for libcgal8, I don't find any simple substitute. Here's the makefile I was normally using:

```<code>ifndef CGAL_MAKEFILE
CGAL_MAKEFILE = /usr/local/cgal/share/cgal/cgal.mk
endif
include $(CGAL_MAKEFILE)

LIBPATH = \
          $(CGAL_LIBPATH)

LDFLAGS = \
          $(LONG_NAME_PROBLEM_LDFLAGS) \
          $(CGAL_LDFLAGS)

COMP=-frounding-math -fopenmp -std=c++0x -l json -L$(LIBPATH) $(LDFLAGS)
EXEC=../crender

all: main.o
    g++ -fPIC main.o $(EXEC) $(COMP)

main.o: main.cpp ../common/common.hpp
    g++ -c main.cpp $(COMP) -o main.o
</code>```

So, what do I have to change to make it work again ? If possible, a solution that will survive to the future changes of CGAL.

If it can help, here's the kind of error that I get:

In function CGAL::Gmpq_rep::Gmpq_rep()':

      main.cpp:(.text._ZN4CGAL8Gmpq_repC2Ev[_ZN4CGAL8Gmpq_repC5Ev]+0x14): undefined reference to__gmpq_init'

And I get these kind of errors for other functions like "__gmpg_add", "__gmpq_sub" and "__gmpq_mul."

SOLUTION:
You need to add "-lgmp" in the compilation instruction. It's sad that it's not done by default by the makefile provided by CGAL!

答:
This is my makefile for linux and mac os x (no using cmake):

```<code>CPP        := g++
OPCJE      := -W -Wall -pedantic -O0 -Wno-c++11-extensions
BIBLIOTEKI := -lboost_math_c99 -lboost_thread -lm -lCGAL -lmpfr -lgmp
PISZ := echo -e
UNAME_S := $(shell uname -s)
</code>```

on Mac os X some library are different name (brew install)

```<code>ifeq ($(UNAME_S),Darwin)
 BIBLIOTEKI = -lboost_math_c99 -lboost_thread-mt -lm -lcgal -lmpfr -lgmp
 PISZ = echo
endif
</code>```

all source
    SRC = $(wildcard *.cpp)
    OBJ = $(addsuffix .o, $(basename $(SRC)))

```<code>BIN_DIR  = ./bin
W_ZRODLA = $(wildcard *.cpp)
PROGRAMY = ${W_ZRODLA:%.cpp=$(BIN_DIR)/%}

$(BIN_DIR)/%: %.cpp
    @mkdir -p ./bin
    $(CPP) $(OPCJE) $< -o $@ $(BIBLIOTEKI)

wszystkie: $(PROGRAMY)
    @echo

clean:
    rm -f ./bin/*

mem: 01
    valgrind -v --tool=memcheck --leak-check=full ./01
</code>```

Title: makefile for CGAL (libcgal8)

Body:
I don't know why, but at each new version of CGAL, the procedure to compile completely changes. So, it's not even possible to recompile old piece of code (6 months old) because it doesn't work like that anymore.

I'm frankly very tired of redoing all the makefile of my projects that use CGAL each time. This time, for libcgal8, I don't find any simple substitute. Here's the makefile I was normally using:

ifndef CGAL_MAKEFILE
CGAL_MAKEFILE = /usr/local/cgal/share/cgal/cgal.mk
endif
include $(CGAL_MAKEFILE)

LIBPATH = \
          $(CGAL_LIBPATH)

LDFLAGS = \
          $(LONG_NAME_PROBLEM_LDFLAGS) \
          $(CGAL_LDFLAGS)

COMP=-frounding-math -fopenmp -std=c++0x -l json -L$(LIBPATH) $(LDFLAGS)
EXEC=../crender

all: main.o
    g++ -fPIC main.o $(EXEC) $(COMP)

main.o: main.cpp ../common/common.hpp
    g++ -c main.cpp $(COMP) -o main.o

So, what do I have to change to make it work again ? If possible, a solution that will survive to the future changes of CGAL.

If it can help, here's the kind of error that I get:

In function CGAL::Gmpq_rep::Gmpq_rep()':

      main.cpp:(.text._ZN4CGAL8Gmpq_repC2Ev[_ZN4CGAL8Gmpq_repC5Ev]+0x14): undefined reference to__gmpq_init'

And I get these kind of errors for other functions like "__gmpg_add", "__gmpq_sub" and "__gmpq_mul."

SOLUTION:
You need to add "-lgmp" in the compilation instruction. It's sad that it's not done by default by the makefile provided by CGAL!

Body:
This is my makefile for linux and mac os x (no using cmake):

CPP        := g++
OPCJE      := -W -Wall -pedantic -O0 -Wno-c++11-extensions
BIBLIOTEKI := -lboost_math_c99 -lboost_thread -lm -lCGAL -lmpfr -lgmp
PISZ := echo -e
UNAME_S := $(shell uname -s)

on Mac os X some library are different name (brew install)

ifeq ($(UNAME_S),Darwin)
 BIBLIOTEKI = -lboost_math_c99 -lboost_thread-mt -lm -lcgal -lmpfr -lgmp
 PISZ = echo
endif

all source
    SRC = $(wildcard *.cpp)
    OBJ = $(addsuffix .o, $(basename $(SRC)))

BIN_DIR  = ./bin
W_ZRODLA = $(wildcard *.cpp)
PROGRAMY = ${W_ZRODLA:%.cpp=$(BIN_DIR)/%}

$(BIN_DIR)/%: %.cpp
    @mkdir -p ./bin
    $(CPP) $(OPCJE) $< -o $@ $(BIBLIOTEKI)

wszystkie: $(PROGRAMY)
    @echo

clean:
    rm -f ./bin/*

mem: 01
    valgrind -v --tool=memcheck --leak-check=full ./01


问:
How to Copy from IPython session without terminal prompts
Frequently, my workflow involves data cleaning/munging in an IPython shell. This has become particularly wonderful since IPython version 5.0 with all the great upgrades to the terminal interface. So, let's say I make an attempt at sprucing up some piece of unstructured data:

```<code>In [11]: for i, (num, header, txt) in enumerate(data):
    ...:     header = [e.strip() for e in header.strip().split('\n')]
    ...:     header[4] = header[4].strip(',').split(',')
    ...:     data[i] = (num, header, txt)
    ...:
</code>```

Fantastic, it works! But now, I would really like to add this to a script in my editor. If I copy and paste from my terminal, I capture all the junk on the left. I can clean this up more-or-less easily in an editor, but it would be great if I could copy the code directly to my clipboard from the terminal without touching the mouse and without grabbing the extra stuff either. Is there such a functionality in IPython?

答:
The save magic command [documentation] saves the input lines you want to a file; the -a option is for "append" mode so that the lines are added at the end of the file instead of overwriting the file. I use it all the time.

With your example:

```<code>%save -a myfile.py 11
# the '%' is not necessary
save -a myfile.py 11
</code>```

Then you can keep coding in IPython.

When there is another command you want to write to the same file, you can just type save then use the up arrow to bring back the last use of "save" (so that the -a option and the filename are already there) and just edit the line number.

Note that you can give several lines to save and also line ranges:

```<code>save -a myfile.py 15 18 19-25
</code>```

Body:
Frequently, my workflow involves data cleaning/munging in an IPython shell. This has become particularly wonderful since IPython version 5.0 with all the great upgrades to the terminal interface. So, let's say I make an attempt at sprucing up some piece of unstructured data:

In [11]: for i, (num, header, txt) in enumerate(data):
    ...:     header = [e.strip() for e in header.strip().split('\n')]
    ...:     header[4] = header[4].strip(',').split(',')
    ...:     data[i] = (num, header, txt)
    ...:

Fantastic, it works! But now, I would really like to add this to a script in my editor. If I copy and paste from my terminal, I capture all the junk on the left. I can clean this up more-or-less easily in an editor, but it would be great if I could copy the code directly to my clipboard from the terminal without touching the mouse and without grabbing the extra stuff either. Is there such a functionality in IPython?

Body:
The save magic command [documentation] saves the input lines you want to a file; the -a option is for "append" mode so that the lines are added at the end of the file instead of overwriting the file. I use it all the time.

With your example:

%save -a myfile.py 11
# the '%' is not necessary
save -a myfile.py 11

Then you can keep coding in IPython.

When there is another command you want to write to the same file, you can just type save then use the up arrow to bring back the last use of "save" (so that the -a option and the filename are already there) and just edit the line number.

Note that you can give several lines to save and also line ranges:

save -a myfile.py 15 18 19-25


问:
Autohotkey script to open command prompt
I've collected a script from the AutoHotKey forum which lets me open a command prompt at the location I'm open in windows explorer. If the current window is not a explorer window then the prompt opens at the location where the script is present. I would like to change this behavior and make it open from C:\ if the current window is not a explorer window. I've tried to edit the script but its not working as desired.

```<code>#ifwinactive, ahk_class CabinetWClass
ControlGetText, address , edit1, ahk_class CabinetWClass
if (address <> "") {
Run, cmd.exe, %address%
}
else {
Run, cmd.exe, "C:"
}
ExitApp
#ifwinactive
</code>```

答:
Couldn't get other answers to work (it has been a few years since they've been written).

I ended up writing this script:

```<code>#o::
    Send {Alt down}D{Alt up}cmd{enter}
return
</code>```

Body:
I've collected a script from the AutoHotKey forum which lets me open a command prompt at the location I'm open in windows explorer. If the current window is not a explorer window then the prompt opens at the location where the script is present. I would like to change this behavior and make it open from C:\ if the current window is not a explorer window. I've tried to edit the script but its not working as desired.

#ifwinactive, ahk_class CabinetWClass
ControlGetText, address , edit1, ahk_class CabinetWClass
if (address <> "") {
Run, cmd.exe, %address%
}
else {
Run, cmd.exe, "C:"
}
ExitApp
#ifwinactive

Body:
Couldn't get other answers to work (it has been a few years since they've been written).

I ended up writing this script:

#o::
    Send {Alt down}D{Alt up}cmd{enter}
return


问:
C string initializer doesn't include terminator?
I am a little confused by the following C code snippets:

```<code>printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes
</code>```

This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.

```<code>printf("Hello '%s'\n", "Peter");
</code>```

The printf function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...

```<code>char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);
</code>```

Here, printf prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?

答:
Alterenatively, you can use:

```<code>char* myString[2] = {"123456789", "123456789" };
</code>```

Like this, the initializer computes the right size for your null terminated strings.

OwnerDisplayName: Peter

Body:
I am a little confused by the following C code snippets:

printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes

This tells me that when C compiles a string in double quotes, it will automatically add an extra byte for the null terminator.

printf("Hello '%s'\n", "Peter");

The printf function knows when to stop reading the string "Peter" because it reaches the null terminator, so ...

char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);

Here, printf prints all 18 characters because there's no null terminators (and they wouldn't fit without taking out the 9's). Does C not add the null terminator in a variable definition?

Body:
Alterenatively, you can use:

char* myString[2] = {"123456789", "123456789" };

Like this, the initializer computes the right size for your null terminated strings.

OwnerDisplayName: Sébastien Rocca-Serra


问:
gwt-popup in wrong position for latest chrome version
With the latest version of chrome: Version 61.0.3163.79 (Official Build) (64-bit), as well as Chromium: Version 61.0.3163.100 (Official Build) Built on Ubuntu , running on Ubuntu 16.04 (64-bit)
I have an issue where when creating a gwt-SuggestBoxPopup, the position coordinates being passed are incorrect.

I've tested this against all the other browsers, IE, Firefox and Safari, they all work there, even the older version of chrome (Version 60.0.3112.78) worked fine. I've also tested this on a Linux, Windows and Mac machines Nothing has changed on my end so I know for a fact something has changed on Chrome's end with the new update.

The only thing now is trying to figure out of this is a bug or a Chrome change, and if it is a chrome change, where that is documented.

答: This bug has been fixed in GWT version 2.8.2. Its release notes state that "Chrome 61 removed functionality that had been used for reading the absolute top/left values. The internal implementation has been updated to reflect modern standards.".</p>


问:
How to update after "php bin/console security:check"
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

```
/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)
```

答:
The security check complains about the package dompdf/dompdf being outdated. So you have to find out which dependency is responsible for this package being installed. You can use composer for this:

```<code>composer why dompdf/dompdf
</code>```

Once you find out why it's installed you can either check if you can update that dependency to a version supporting/requiring a newer dompdf version or if you installed it by requiring it yourself just update it.

Alternatively you can also ask composer why it won't install a new version by using:

```<code>composer why-not dompdf/dompdf "^0.8"
</code>```

If you can't update whatever dependency depends on the outdated dompdf version you might have to resort to either create a PR in that project for a newer version or forking the project and updating the composer.json yourself (not recommended though, because of the additional work of keeping it up to date).

edit: It looks like akeneo itself is responsible for pinning the version as you can see in the repo: https://github.com/akeneo/pim-community-dev/blob/2.0/composer.json#L41

Maybe you can create a PR updating the composer.json and maybe loosening the version restriction for dompdf.

Body:
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

Body:
The security check complains about the package dompdf/dompdf being outdated. So you have to find out which dependency is responsible for this package being installed. You can use composer for this:

composer why dompdf/dompdf

Once you find out why it's installed you can either check if you can update that dependency to a version supporting/requiring a newer dompdf version or if you installed it by requiring it yourself just update it.

Alternatively you can also ask composer why it won't install a new version by using:

composer why-not dompdf/dompdf "^0.8"

If you can't update whatever dependency depends on the outdated dompdf version you might have to resort to either create a PR in that project for a newer version or forking the project and updating the composer.json yourself (not recommended though, because of the additional work of keeping it up to date).

edit: It looks like akeneo itself is responsible for pinning the version as you can see in the repo: https://github.com/akeneo/pim-community-dev/blob/2.0/composer.json#L41

Maybe you can create a PR updating the composer.json and maybe loosening the version restriction for dompdf.


问:
how to put background image path from remote web site?
I need grab images from Imgur to My web page background image

```<code> <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
</code>```

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

答:
Update image url  like this</p>

```<code><div style="background-image:url('https://i.imgur.com/QdMWFHZ.jpg'); background-repeat:no-repeat; width:100%; height:100%;" class="zoom" >
</code>```

Body:
I need grab images from Imgur to My web page background image

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

Body:
Update image url  like this

<div style="background-image:url('https://i.imgur.com/QdMWFHZ.jpg'); background-repeat:no-repeat; width:100%; height:100%;" class="zoom" >


问:
Angular 4 - Close iframe after redirect
I have an angular 4 app.
I'm using a third party payment system (named Tranzila). Tranzila provide a easy integration using an iframe. Within the iframe, the user is performing the payment in Tranzila domain, which saving me the time to build the form and handle the credit card numbers.
Tranzila provide me the ability to configure the success and error post requests after the user submit the request.
My problem is that I want to close the iframe after a successfull payment request, and redirect the user to a page in my site (not inside the iframe).
I'm trying to find the best way to close the iframe after the request. Since the payment page can not be customized with javascript, I can't manipulate their page to close the iframe after a successfull request.

I thought about 2 options:
1.Use Tranzila default "Payment success" page and trying to listen to iframe src change from my site.
2. Customize their page to navigate to a "Payment Success" page in my domain.
Add a route to a page in my domain that will call a function declared in parent, which will close the iframe and navigate to a success route.

For now,
I implement app-payment-order as follow:

 import { Credentials } from '../_models/credentials.model';

import { CredentialsStorageService } from '../_services/credentials-storage.service';
import { ItemOverview } from '../_models/item-overview.interface';
import { OrderItemsOverview } from '../_models/order-overview.interface';
import { OrderDto } from '../_models/order-dto.model';
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-order-payment',
  templateUrl: './order-payment.component.html',
  styleUrls: ['./order-payment.component.scss']
})
export class OrderPaymentComponent {
  @Input('order')
  public order:OrderDto;

  constructor(private readonly credentials: CredentialsStorageService) {
  //Option 2 - Add function to window. this function will be called from the iframe after loading a special page from my domain which will call parent.paymentSuccess
    window.paymentSuccess = () => {
    //Redirect to success page
     }
  }

  get iframeSrc(): string {
    let userCredentials: Credentials = this.credentials.get();
    return "https://myTranzilaMockUrl.com/iframe.php?sum={0}&currency=1&cred_type=1&orderId={1}&email={2}"
      .format(this.order.price.toString(), this.order.id, userCredentials && userCredentials.email);
  }

  //Option 1 - try to listen to iframe source change
  onIframeSrcChange() {
      //if iframe source changed to success page than redirect
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="order-payment-container" *ngIf="order != null">
 <!-- <iframe [src]="iframeSrc | safe" scrolling="no" class="app-tranzila-iframe" ></iframe>-->
</div></code>```

Sorry about the mess, I hope I succeeded to describe the issue well.

答:
You should always use their "success" or "failure" callback to handle the end of the transaction, it's there for a reason.

callback and there do whatever you need to on the parent page.
you should also consider using this page to tell your server the new status of the transaction.

Title: Angular 4 - Close iframe after redirect

Body:
I have an angular 4 app.
I'm using a third party payment system (named Tranzila). Tranzila provide a easy integration using an iframe. Within the iframe, the user is performing the payment in Tranzila domain, which saving me the time to build the form and handle the credit card numbers.
Tranzila provide me the ability to configure the success and error post requests after the user submit the request.
My problem is that I want to close the iframe after a successfull payment request, and redirect the user to a page in my site (not inside the iframe).
I'm trying to find the best way to close the iframe after the request. Since the payment page can not be customized with javascript, I can't manipulate their page to close the iframe after a successfull request.

I thought about 2 options:
1.Use Tranzila default "Payment success" page and trying to listen to iframe src change from my site.
2. Customize their page to navigate to a "Payment Success" page in my domain.
Add a route to a page in my domain that will call a function declared in parent, which will close the iframe and navigate to a success route.

For now,
I implement app-payment-order as follow:

 import { Credentials } from '../_models/credentials.model';

import { CredentialsStorageService } from '../_services/credentials-storage.service';
import { ItemOverview } from '../_models/item-overview.interface';
import { OrderItemsOverview } from '../_models/order-overview.interface';
import { OrderDto } from '../_models/order-dto.model';
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-order-payment',
  templateUrl: './order-payment.component.html',
  styleUrls: ['./order-payment.component.scss']
})
export class OrderPaymentComponent {
  @Input('order')
  public order:OrderDto;

  constructor(private readonly credentials: CredentialsStorageService) {
  //Option 2 - Add function to window. this function will be called from the iframe after loading a special page from my domain which will call parent.paymentSuccess
    window.paymentSuccess = () => {
    //Redirect to success page
     }
  }

  get iframeSrc(): string {
    let userCredentials: Credentials = this.credentials.get();
    return "https://myTranzilaMockUrl.com/iframe.php?sum={0}&currency=1&cred_type=1&orderId={1}&email={2}"
      .format(this.order.price.toString(), this.order.id, userCredentials && userCredentials.email);
  }

  //Option 1 - try to listen to iframe source change
  onIframeSrcChange() {
      //if iframe source changed to success page than redirect
  }

}

Sorry about the mess, I hope I succeeded to describe the issue well.


问:
Shortcuts or autofill for contact info in UITextFields
When I'm in Safari in iOS, and I hit a form that requires I enter name and address, I get shortcuts in the keyboard area. For example, here is the keyboard when the focus is in a first name field. I can tap "Robert" instead of typing a name.

A similar thing happens for fields for last name, phone, email, zip code.

Can I get a similar thing in a native iOS app, in a UITextField? Is there a way to mark a field so that the keyboard will offer these shortcut suggestions?

答:
You can turn on or off it by set autocorrectionType of UITextField. Default value of autocorrectionType is UITextAutocorrectionTypeDefault . It means you don't need to do anything, by default it will be showed.

UITextAutocorrectionTypeYes; // Turn on

UITextAutocorrectionTypeDefault; // Turn on

UITextAutocorrectionTypeNo; // Turn off

But beside of set autocorrectionType value, you need to make sure Predictive in Keyboards Setting of device is turned on. If Predictive is turned off, suggestion won't be displayed even you changed autocorrectionType to UITextAutocorrectionTypeYes.

UPDATE

You can change textContentType to choose with type of suggestion will be shown. Suggestions are from the Contacts. For example, you want phone suggestion

```<code>textField.textContentType = UITextContentTypeTelephoneNumber;
</code>```

Body:
You can turn on or off it by set autocorrectionType of UITextField. Default value of autocorrectionType is UITextAutocorrectionTypeDefault . It means you don't need to do anything, by default it will be showed.

UITextAutocorrectionTypeYes; // Turn on

UITextAutocorrectionTypeDefault; // Turn on

UITextAutocorrectionTypeNo; // Turn off

But beside of set autocorrectionType value, you need to make sure Predictive in Keyboards Setting of device is turned on. If Predictive is turned off, suggestion won't be displayed even you changed autocorrectionType to UITextAutocorrectionTypeYes.

UPDATE

You can change textContentType to choose with type of suggestion will be shown. Suggestions are from the Contacts. For example, you want phone suggestion

textField.textContentType = UITextContentTypeTelephoneNumber;


问:
How many white spaces is the best for ssh config
For Ruby, using 2 spaces is the best.
For Python, using 4 spaces is the best.

But for ssh config file, how many spaces is the best?

答:
The configuration files (for ssh or other programs) do not need indentation.

They contain lines of type name=value.

Some programs allow spaces around the equal sign, others are more strict and do not accept them.

ssh accepts spaces around the equal sign but they are ignored. Use how many of them you like but don't abuse them and let the file be readable.

A small fragment from the documentation:

The file contains keyword-argument pairs, one per line. Lines starting with # and empty lines are interpreted as comments. Arguments may optionally be enclosed in double quotes (") in order to represent arguments containing spaces. Configuration options may be separated by whitespace or optional whitespace and exactly one =; the latter format is useful to avoid the need to quote whitespace when specifying configuration options using the ssh, scp, and sftp -o option.


问:
Looking foward or back in a foreach loop
I am rendering navigation from a 2 dimensional array, using lists, as shown:

```<code><ul> <li>parent
<ul> <li>level 1</li> <li>level 1

<ul> <li>level 3</li> </ul>

</li> </ul>

<li> </ul>

</li> </ul>
</code>```

Anyway to close the
 and
 correctly I find I need some data from the next array in the foreach sequence. How can I retrieve this?

答:
Found the answer staring me in the face. Retrieved the arrays I need like this:

foreach ($tree as $key => $link) {

$level = $link['level'];

$next_key = $key+1;

$prev_key = $key-1;

$next_array = $tree[$next_key];

$prev_array = $tree[$prev_key];

And then I could test the level property (indicating deph inside the navigation tree) with a buch of if statements to correctly insert the closing markup.

Messy code and I'm not proud of it, but it works!

Quite angry with myself for not seeing it before.

Body:
I am rendering navigation from a 2 dimensional array, using lists, as shown:

parent

level 1

level 1

level 3

Anyway to close the
 and
 correctly I find I need some data from the next array in the foreach sequence. How can I retrieve this?


问:
sql query with two joins and a simple logic
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code>| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')
</code>```

答:
You must join tables with user id like below:

LEFT JOIN friends_list f ON f.user_id=u.ID

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
    LEFT JOIN friends_list f ON f.user_id=u.ID
    WHERE f.status  NOT IN ('P', 'B')
</code>```

Add two records at friends_list table with  Q and Z status for testing

```<code>INSERT INTO `friends_list` (`id`, `user_id`, `Friend_id`, `status`) VALUES
(80, 1, 26, 'P'),
(79, 18, 26, 'P'),
(78, 1, 24, 'P'),
(79, 20, 24, 'Q'),
(80, 21, 24, 'Z');
</code>```

sqlfiddle working example

Body:
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')

Body:
You must join tables with user id like below:

LEFT JOIN friends_list f ON f.user_id=u.ID

select DISTINCT u.ID, u.user_nicename from wp_users u
    LEFT JOIN friends_list f ON f.user_id=u.ID
    WHERE f.status  NOT IN ('P', 'B')

Add two records at friends_list table with  Q and Z status for testing

INSERT INTO `friends_list` (`id`, `user_id`, `Friend_id`, `status`) VALUES
(80, 1, 26, 'P'),
(79, 18, 26, 'P'),
(78, 1, 24, 'P'),
(79, 20, 24, 'Q'),
(80, 21, 24, 'Z');

sqlfiddle working example


问:
How do I make an array with unique elements (i.e. remove duplicates)?
I have this code:

```<code>var ar = [10,7,8,3,4,7,6];

function isin(n,a){
  for (var i=0;i<a.length;i++){
    if (a[i]== n) {
      var b = true;
      return b;
    } else {
      var c = false;
      return c;
   }
  }
}

function unique(a){
  var arr = [];
  for (var i=0;i<a.length;i++){
    if (!isin(a[i],arr)){
      arr.push(a[i]);
    }
  }

 return arr;
}

alert(unique(ar));
</code>```

In this code, I try to create new unique array (without duplicates) out of the original one.
But I still get the original array! Where's my mistake?

答:
I've done a similar search, I found this answer really good:

Unique values in an array [duplicate]

You can re-use those function on other code.
This is also good approach where it is compatible with many browsers.

Cheer.

Body:
I have this code:

var ar = [10,7,8,3,4,7,6];

function isin(n,a){
  for (var i=0;i<a.length;i++){
    if (a[i]== n) {
      var b = true;
      return b;
    } else {
      var c = false;
      return c;
   }
  }
}

function unique(a){
  var arr = [];
  for (var i=0;i<a.length;i++){
    if (!isin(a[i],arr)){
      arr.push(a[i]);
    }
  }

 return arr;
}

alert(unique(ar));

In this code, I try to create new unique array (without duplicates) out of the original one.
But I still get the original array! Where's my mistake?


问:
Size of networkx.Graph() object?
I have pandas dataframe with 2 columns: col1, col2.
sys.getsizeof(dataframe) shows 495137153 bytes.

Then i grow a graph:

```<code>G = networkx.Graph()
G.add_edges_from(zip(data['col1'], data['col2']))
</code>```

And now i want to check size of my graph, but sys.getsizeof(G) show 64 bytes

How to get real size of object G?

Update: I checked size of G.edges + size G.nodes, it's about 0.2 GB. But growing graph adds ~5 GB to my used RAM. Why so?

答:
You can estimate the size by adding the size of edge list and node list as shown below. The answer is here

sys.getsizeof(G.edge) + sys.getsizeof(G.node)

Title: Size of networkx.Graph() object?

Body:
I have pandas dataframe with 2 columns: col1, col2.
sys.getsizeof(dataframe) shows 495137153 bytes.

Then i grow a graph:

G = networkx.Graph()
G.add_edges_from(zip(data['col1'], data['col2']))

And now i want to check size of my graph, but sys.getsizeof(G) show 64 bytes

How to get real size of object G?

Update: I checked size of G.edges + size G.nodes, it's about 0.2 GB. But growing graph adds ~5 GB to my used RAM. Why so?


问:
How to connect to Websocket API?
The API I am trying query from is: https://socket.etherdelta.com

Documentation for the API here:https://github.com/etherdelta/etherdelta.github.io/blob/master/docs/API.md

When I try to to do a simple get request: https://socket.etherdelta.com/getmarkets it gives me an error message saying "Cannot GET /getmarkets"

This is the code I am trying to use to get market information:

```<code>var request = require('request');
var url = 'https://socket.etherdelta.com/getMarket';

request(url , (err, res, body) => {
try{
var json = JSON.parse(body);
console.log(json);

}catch(err){
console.log('parsing error');
console.log(body);
}
});
</code>```

edited it to this:

```<code>var WebSocket = require('ws')
var ws = new WebSocket('wss://socket.etherdelta.com')

ws.onopen = function(){
ws.send(JSON.stringify("getMarket"))

};

ws.onmessage = function(msg){
var response = JSON.parse(msg.data);
console.log(response);
};
</code>```

答:
It seems like this API operates on WSS protocol rather than HTTPS. Could you please try a web socket client library like ws with below URL

wss://socket.etherdelta.com

Title: How to connect to Websocket API?

Body:
The API I am trying query from is: https://socket.etherdelta.com

Documentation for the API here:https://github.com/etherdelta/etherdelta.github.io/blob/master/docs/API.md

When I try to to do a simple get request: https://socket.etherdelta.com/getmarkets it gives me an error message saying "Cannot GET /getmarkets"

This is the code I am trying to use to get market information:

var request = require('request');
var url = 'https://socket.etherdelta.com/getMarket';

request(url , (err, res, body) => {
try{
var json = JSON.parse(body);
console.log(json);

}catch(err){
console.log('parsing error');
console.log(body);
}
});

edited it to this:

var WebSocket = require('ws')
var ws = new WebSocket('wss://socket.etherdelta.com')

ws.onopen = function(){
ws.send(JSON.stringify("getMarket"))

};

ws.onmessage = function(msg){
var response = JSON.parse(msg.data);
console.log(response);
};


问:
When I Want to Take Value From Shared Preferance then i Get Error
This Is The Code When I save My Value

```<code> public static final String
 MyPREFERENCES = "MyPrefs" ;
 public SharedPreferences sharedpreferences;
 public static final String p = "pickLoc";
 public static final String Phone = "dropLoc";
 String pickLoc = pickupEt.getText().toString().trim();
 String dropLoc = dropEt.getText().toString().trim();
 sharedpreferences = getSharedPreferences(BookMyRide.this.MyPREFERENCES,
Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedpreferences.edit();
         editor.putString(p, pickLoc);
         editor.putString(Phone, dropLoc);
         editor.commit();
</code>```

This Is The Code When i Want to Get Value

```<code>         try{
      sharedpreferences  = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
      sharedpreferences.getString("pickLoc" ,"");
      sharedpreferences.getString("dropLoc","");
  }catch (Exception e){
      e.printStackTrace();
  }
</code>```

Then it Throws the Exception :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Thanks In Advance For Helping Me

答:
Check this

The Context in your activity may be null

SharedPreference without PreferenceManager !!!

Check this sample

To save urValue in SharedPreferences:

```<code>SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString(key, urValue);
        editor.apply();
</code>```

To get name from SharedPreferences:

```<code>SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String urValue = sharedPreferences.getString(key, "default value");
</code>```

For more check this link

Body:
This Is The Code When I save My Value

 public static final String
 MyPREFERENCES = "MyPrefs" ;
 public SharedPreferences sharedpreferences;
 public static final String p = "pickLoc";
 public static final String Phone = "dropLoc";
 String pickLoc = pickupEt.getText().toString().trim();
 String dropLoc = dropEt.getText().toString().trim();
 sharedpreferences = getSharedPreferences(BookMyRide.this.MyPREFERENCES,
Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedpreferences.edit();
         editor.putString(p, pickLoc);
         editor.putString(Phone, dropLoc);
         editor.commit();

This Is The Code When i Want to Get Value

         try{
      sharedpreferences  = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
      sharedpreferences.getString("pickLoc" ,"");
      sharedpreferences.getString("dropLoc","");
  }catch (Exception e){
      e.printStackTrace();
  }

Then it Throws the Exception :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Thanks In Advance For Helping Me

Body:
Check this

The Context in your activity may be null

SharedPreference without PreferenceManager !!!

Check this sample

To save urValue in SharedPreferences:

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString(key, urValue);
        editor.apply();

To get name from SharedPreferences:

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String urValue = sharedPreferences.getString(key, "default value");

For more check this link


问:
Arranging numbers within the digits in descending order without using arrays
I want to arrange the digits of a number in descending order without using arrays. When I am using String it gives run time error.
For example:

```<code>Input: 2436
Output: 6432
</code>```

Here is what I wrote but the problem is the first digit isn't getting printed which is not the expected output.

```<code>public static void main (String[] args) throws java.lang.Exception {
    Scanner sc = new Scanner(System.in);
    int num,n,r=0,FinalNo=0;
    System.out.println("Enter any number");
    num=sc.nextInt();
    n=num;
    while(n>0) {
        r=n%10;
        n=n/10;
        FinalNo=(FinalNo*10)+r;
    }
    System.out.println("The number in descending order is "+FinalNo);
}
</code>```

答:
Assuming that your number is not greater than Integer.MAX_VALUE you can use Redix Sort algorithm. It works fine with the complexity of O(n). Here, you can find the solution in following code, that doesn't use any array or lists and Strings.

```<code>public static void main(String[] args) {
        int number = 45322;
        int sortedNumber = 0;

    /*
     * This loop checks for each digit starting from 9 to 0.
     * In case of ascending order it should be 0 to 9.
     */
    for (int i = 9; i >= 0; i--) {
        int tmpNumber = number;
        while (tmpNumber > 0) {
            int digit = tmpNumber % 10;
            // Check for the greatest digit in the given number
            if (digit == i) {
                sortedNumber *= 10;
                sortedNumber += digit;
            }
            tmpNumber /= 10;
        }
    }
    System.out.println(sortedNumber); // prints 54322.
}
</code>```

I think that should work for you.

ContentLicense: CC BY-SA 4.0

Body:
I want to arrange the digits of a number in descending order without using arrays. When I am using String it gives run time error.
For example:

Input: 2436
Output: 6432

Here is what I wrote but the problem is the first digit isn't getting printed which is not the expected output.

public static void main (String[] args) throws java.lang.Exception {
    Scanner sc = new Scanner(System.in);
    int num,n,r=0,FinalNo=0;
    System.out.println("Enter any number");
    num=sc.nextInt();
    n=num;
    while(n>0) {
        r=n%10;
        n=n/10;
        FinalNo=(FinalNo*10)+r;
    }
    System.out.println("The number in descending order is "+FinalNo);
}

Body:
Assuming that your number is not greater than Integer.MAX_VALUE you can use Redix Sort algorithm. It works fine with the complexity of O(n). Here, you can find the solution in following code, that doesn't use any array or lists and Strings.

public static void main(String[] args) {
        int number = 45322;
        int sortedNumber = 0;

    /*
     * This loop checks for each digit starting from 9 to 0.
     * In case of ascending order it should be 0 to 9.
     */
    for (int i = 9; i >= 0; i--) {
        int tmpNumber = number;
        while (tmpNumber > 0) {
            int digit = tmpNumber % 10;
            // Check for the greatest digit in the given number
            if (digit == i) {
                sortedNumber *= 10;
                sortedNumber += digit;
            }
            tmpNumber /= 10;
        }
    }
    System.out.println(sortedNumber); // prints 54322.
}

I think that should work for you.


问:
playing with java Operators (XOR and AND/OR)
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

```<code> // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }
</code>```

2.

```<code>  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }
</code>```

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

答:
How about this?

```<code>if(isCorrect(a) != isCorrect(b))
{
  //problem
}
else
{
  //not a problem
}
</code>```

You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.

Body:
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

 // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }

2.

  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

Body:
How about this?

if(isCorrect(a) != isCorrect(b))
{
  //problem
}
else
{
  //not a problem
}

You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.


问:
I keep getting errors when I try to use JavaScript array methods
I am doing a quiz on JavaScript on repl.it but for some reason I keep getting errors even though I am pretty sure my syntax is correct. I am using array methods from JavaScript MDN.

Can you please point out my mistakes?

Question: add item to front of array.
My code:

```<code>function addItemToFront(arr, item) {
  // code here
  const newItem = [1, 2, 3];
  newItem.unshift(0);
  return newItem;
}

addItemToFront(newItem);
</code>```

Question: testScores is an array.  Iterate over testScores and compute and return the average.

My code:

```<code>function averageTestScore(testScores) {
  // code here
  testScores = [97, 100, 80, 55, 72, 94];
  let count = count.length;
  scores = scores.reduce((previous, current) => current += previous);
  scores /= count;
  return scores;
}

averageTestScores(testScores);
</code>```

Question: Return true if num is inside of arr, otherwise return false.

My code:

```<code>function contains(arr, item) {
  // code here
  const string = ['hello', 'world'];
  if(string.includes('hello')){
    return true
  } else {
   return false;
  }
}

contains('hello');
</code>```

Question: words is an array of strings.  Return a string that is all of the words concatenated together.

My code:

```<code>function wordsToSentence(words) {
  // code here
  words = ['hello', 'world', 'computer', 'science', 'Lambda'];
  words.join(' ');
  return words;
}

wordsToSentence(words);
</code>```

答:
All four solutions share the same problem.

You are calling the functions with wrong, nonexistant parameters. The first piece doesn't even need the parameters (they are not used).

Second one, calls the method with an undefined variable.

Third one, ignores the passed variables, so your code can't really work.

Fourth one, calls the method with an undefined variable.

Dude, this is probably some homework, it looks to me, like you should really try to figure this out, as your code has many issues.

If you want to figure out the erros, look at the Chrome console.

Body:
I am doing a quiz on JavaScript on repl.it but for some reason I keep getting errors even though I am pretty sure my syntax is correct. I am using array methods from JavaScript MDN.

Can you please point out my mistakes?

Question: add item to front of array.
My code:

function addItemToFront(arr, item) {
  // code here
  const newItem = [1, 2, 3];
  newItem.unshift(0);
  return newItem;
}

addItemToFront(newItem);

Question: testScores is an array.  Iterate over testScores and compute and return the average.

My code:

function averageTestScore(testScores) {
  // code here
  testScores = [97, 100, 80, 55, 72, 94];
  let count = count.length;
  scores = scores.reduce((previous, current) => current += previous);
  scores /= count;
  return scores;
}

averageTestScores(testScores);

Question: Return true if num is inside of arr, otherwise return false.

My code:

function contains(arr, item) {
  // code here
  const string = ['hello', 'world'];
  if(string.includes('hello')){
    return true
  } else {
   return false;
  }
}

contains('hello');

Question: words is an array of strings.  Return a string that is all of the words concatenated together.

My code:

function wordsToSentence(words) {
  // code here
  words = ['hello', 'world', 'computer', 'science', 'Lambda'];
  words.join(' ');
  return words;
}

wordsToSentence(words);


问:
How to setup external products in woocommerce to that product details page is bypassed?
I want to setup a woocommerce website with external products. I want to take the customer to the main website of the product (external link) on clicking the product without showing them the product details page.

Bypass the product details page by clicking the product thhumbnail and opening the external link in new tab.

How can i do this ?

答:
This is how this code works, I override the default loop product link and associate it with my own custom field that appears under the General TAB when you edit the product called "External URL".  When an external URL is entered the link will take the user to another website and when no external URL is present it links the user to the details page.  I took some of this code from this great article about creating custom product fields.

Paste this code into your functions.php file.

```<code>remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_before_shop_loop_item', 'modify_woocommerce_template_loop_product_link_open', 10 );

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {
    global $woocommerce, $post;

    echo '<div class="options_group">';

    woocommerce_wp_text_input(
        array(
            'id'          => '_external_url',
            'label'       => __( 'External URL', 'woocommerce' ),
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the external URL here.', 'woocommerce' )
        )
    );

    echo '</div>';
}

function woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_external_url'];

    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_external_url', esc_attr( $woocommerce_text_field ) );

}

function modify_woocommerce_template_loop_product_link_open() {
    $product_url =  get_post_meta( get_the_ID(), '_external_url', true );

    if( empty( $product_url) )
        echo '<a href="' . esc_url( get_the_permalink() ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
    else
        echo '<a href="' . esc_url( $product_url ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
}
</code>```

Body:
This is how this code works, I override the default loop product link and associate it with my own custom field that appears under the General TAB when you edit the product called "External URL".  When an external URL is entered the link will take the user to another website and when no external URL is present it links the user to the details page.  I took some of this code from this great article about creating custom product fields.

Paste this code into your functions.php file.

remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_before_shop_loop_item', 'modify_woocommerce_template_loop_product_link_open', 10 );

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );

function woo_add_custom_general_fields() {
    global $woocommerce, $post;

    echo '<div class="options_group">';

    woocommerce_wp_text_input(
        array(
            'id'          => '_external_url',
            'label'       => __( 'External URL', 'woocommerce' ),
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the external URL here.', 'woocommerce' )
        )
    );

    echo '</div>';
}

function woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_external_url'];

    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_external_url', esc_attr( $woocommerce_text_field ) );

}

function modify_woocommerce_template_loop_product_link_open() {
    $product_url =  get_post_meta( get_the_ID(), '_external_url', true );

    if( empty( $product_url) )
        echo '<a href="' . esc_url( get_the_permalink() ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
    else
        echo '<a href="' . esc_url( $product_url ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
}


问:
Multiple dependencies won't work
Hello I'm trying to create a SPA with AngularJS and need to call a SOAP request. But as soon as i add another dependency beside ngRoute, my views won't load anymore.

Index.html

```<code>    <!DOCTYPE html>
    <html class="no-js">
        <head>
            <script src="./angular/soapclient.js"></script>
            <script src="./angular/angular.soap.js"></script>
            <script src="./angular/angular.min.js"></script>
            <script src="./angular/angular-route.min.js"></script>
            <script src="./angular/app.js"></script>
        </head>
        <body data-t-name="ContentPage" ng-app="myApp">
            <div class="page">
                <div class="page-content">
                    <div class="container" id="Dialog1" >
                        <div ng-view ng-controller="MainCtrl"></div>
                    </div>
                </div>
            </div>
        </body>
    </html>
</code>```

app.js

```<code>    var myApp = angular.module("myApp", ['ngRoute']);

    myApp.config(["$routeProvider","$locationProvider",function($routeProvider,$locationProvider) {
        $routeProvider
        .when("/", {
            templateUrl : "views/Hauptseite.html"
        })
        ...
        ...
    }]);
</code>```

Changed into

```<code>var myApp = angular.module("myApp", ['ngRoute','angularSoap']);
</code>```

Any suggestions ?

答:
Change the order of dependencies, any dependent library should be after angular.js reference</p>

```<code><script src="./angular/angular.min.js"></script>
<script src="./angular/soapclient.js"></script>
<script src="./angular/angular.soap.js"></script>
<script src="./angular/angular-route.min.js"></script>
<script src="./angular/app.js"></script>
</code>```

Title: Multiple dependencies won't work

Body:
Hello I'm trying to create a SPA with AngularJS and need to call a SOAP request. But as soon as i add another dependency beside ngRoute, my views won't load anymore.

Index.html

    <!DOCTYPE html>

app.js

    var myApp = angular.module("myApp", ['ngRoute']);

    myApp.config(["$routeProvider","$locationProvider",function($routeProvider,$locationProvider) {
        $routeProvider
        .when("/", {
            templateUrl : "views/Hauptseite.html"
        })
        ...
        ...
    }]);

Changed into

var myApp = angular.module("myApp", ['ngRoute','angularSoap']);

Any suggestions ?

Body:
Change the order of dependencies, any dependent library should be after angular.js reference

<script src="./angular/angular.min.js"></script>
<script src="./angular/soapclient.js"></script>
<script src="./angular/angular.soap.js"></script>
<script src="./angular/angular-route.min.js"></script>
<script src="./angular/app.js"></script>


问:
How can I edit a non-string data value in a data frame?
Consider a data set with a number of columns.

```<code>> data <- import.csv("data.csv")
> head(data[1])

> Output:

    Sex
1   M
2   M
3   F
4   M
5   I
6   I
</code>```

(Isolating the first column of my data set.) I want to change the F to M in all cases.

So I try the following:

```<code>> for (i in 1:6) {
      if (data[i, 1] == F) {
          data[i, 1] = M)
      }
  }
</code>```

This leaves the data unchanged. So I tried to import the data like so:

```<code>> data <- import.csv("data.csv", stringsAsFactors = FALSE)
</code>```

The loop method works now, but this is not OK because with the F, M, and I as strings I cannot perform the logistic regression that I need to.

Any suggestions on changing F to M but not introducing strings?

答:
Change all rows in data where Sex is equal to the string 'F':

data[data$Sex == 'F',] <- 'M'

You haven't told us what these variable types should be. Are they objects? Should they be of a certain type?

Body:
Consider a data set with a number of columns.

> data <- import.csv("data.csv")
> head(data[1])

> Output:

    Sex
1   M
2   M
3   F
4   M
5   I
6   I

(Isolating the first column of my data set.) I want to change the F to M in all cases.

So I try the following:

> for (i in 1:6) {
      if (data[i, 1] == F) {
          data[i, 1] = M)
      }
  }

This leaves the data unchanged. So I tried to import the data like so:

> data <- import.csv("data.csv", stringsAsFactors = FALSE)

The loop method works now, but this is not OK because with the F, M, and I as strings I cannot perform the logistic regression that I need to.

Any suggestions on changing F to M but not introducing strings?


问:
Step definition is not getting recognized in test runner
``In  My Java cucumber setup -test runner Step definitions are not running.
Please find attached the screenshot of runner class,feature file and step definition locations.I am just launching the application
<img src="https://i.stack.imgur.com/LCTXy.png" alt="Stepdefinitions"> </p>

```<code>  package com;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;

public class StepDefinition {
    WebDriver driver;
    @Before

    public void setUp(){
         driver=new FirefoxDriver();

    }

    @After
    public void tearDown(){
        driver.quit();
    }

    @Given("^Launch the application$")
    public void loadUrl() throws Throwable {
        driver.get("https://www.google.com");

        throw new PendingException();
    }

}
</code>```

答:
glue path argument to be either a package name or a class path(not a file system path). For example,

```<code>glue = {"com"}
</code>```

or

```<code>glue = {"classpath:com"}
</code>```

You are pointing to java file. change it accordingly.

Body:
``In  My Java cucumber setup -test runner Step definitions are not running.
Please find attached the screenshot of runner class,feature file and step definition locations.I am just launching the application

  package com;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;

public class StepDefinition {
    WebDriver driver;
    @Before

    public void setUp(){
         driver=new FirefoxDriver();

    }

    @After
    public void tearDown(){
        driver.quit();
    }

    @Given("^Launch the application$")
    public void loadUrl() throws Throwable {
        driver.get("https://www.google.com");

        throw new PendingException();
    }

}

Body:
glue path argument to be either a package name or a class path(not a file system path). For example,

glue = {"com"}

or

glue = {"classpath:com"}

You are pointing to java file. change it accordingly.


问:
android iterate through objects on xml and find the type
Is there a way to iterate through the objects on a form and find all the types.  In VBNet you would do something like:

```<code>For each control on form
  print typename(control)
</code>```

What I mean by a form is the UI that the user can see, I guess that is the Context?  If I have an XML that say has 2 buttons and a textview, is there a way from the java code to see what all of the object are that has been loaded from the XML.

I am trying to make a generic class that I can use on all UI classes that will look through every object and if its a button then change the colors on that button.

Alternately I could do this manually for every UI and object.

答:
a normal "java for" :

```<code>for( Control c : ArrayList<Control> controlList){
    System.out.println(c.getTypeName();
}
</code>```

hope it helps.

Body:
Is there a way to iterate through the objects on a form and find all the types.  In VBNet you would do something like:

For each control on form
  print typename(control)

What I mean by a form is the UI that the user can see, I guess that is the Context?  If I have an XML that say has 2 buttons and a textview, is there a way from the java code to see what all of the object are that has been loaded from the XML.

I am trying to make a generic class that I can use on all UI classes that will look through every object and if its a button then change the colors on that button.

Alternately I could do this manually for every UI and object.

Body:
a normal "java for" :

for( Control c : ArrayList<Control> controlList){
    System.out.println(c.getTypeName();
}

hope it helps.


问:
How to hide navbar in login page in react router
I want to hide the navbar in a login page.

I did it actually, but I can't see the navbar on other pages.

This code is part of My App.jsx file.

I make history in App's state. And I hide navbar, when this pathname is '/' or '/login'.

It works!

But then I typed the ID and password, and clicked the login button, got 'success' result, and navigated to '/main'.

Now I can't see navbar in main component too.

How can I do this?

Sorry about my short english. If you can't understand my question, you can comment.

constructor(props) {
  super(props);
  this.state = {
    isAlertOpen: false,
    history: createBrowserHistory(),
  };
  this.toggleAlert = this.toggleAlert.bind(this);
}

<BrowserRouter>

    {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null
      : }

      {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null
        : <Navbar />}
      <Route exact path="/" render={() => <Redirect to="/login" />} />
      <Route path="/login" component={Login} />
      <Route path="/main" component={Main} />
      <Route path="/user" component={User} />
      <Route path="/hw-setting" component={Setting} />
      <Route path="/hw-detail/:id" component={HwDetail} />
      <Route path="/gas-detail/:id" component={GasDetail} />
      {this.state.isAlertOpen ? <Alert /> : null}

</BrowserRouter>
```

<p>
</p>

```login(event) {
  event.preventDefault();
  userService.login(this.state.id, this.state.password).subscribe(res => {
    if (res.result === 'success') {
      global.token = res.token;
      this.props.history.push('/main');
    } else {
      alert(`[ERROR CODE : ${res.statusCode}] ${res.msg}`);
    }
});
```

答:
You could structure your Routes differently so that the Login component doesn't have the Header Like

```<code><BrowserRouter>
  <Switch>
  <div className="App">
    <Route exact path="/(login)" component={LoginContainer}/>
    <Route component={DefaultContainer}/>

  </div>
  </Switch>
</BrowserRouter>

const LoginContainer = () => (
  <div className="container">
    <Route exact path="/" render={() => <Redirect to="/login" />} />
    <Route path="/login" component={Login} />
  </div>
)

 const DefaultContainer = () => (
    <div>
    <Header toggleAlert={this.toggleAlert} />
    <div className="container">
      <Navbar />
      <Route path="/main" component={Main} />
      <Route path="/user" component={User} />
      <Route path="/hw-setting" component={Setting} />
      <Route path="/hw-detail/:id" component={HwDetail} />
      <Route path="/gas-detail/:id" component={GasDetail} />
      {this.state.isAlertOpen ? <Alert /> : null}
    </div>
    </div>
 )
</code>```

Body:
I want to hide the navbar in a login page.

I did it actually, but I can't see the navbar on other pages.

This code is part of My App.jsx file.

I make history in App's state. And I hide navbar, when this pathname is '/' or '/login'.

It works!

But then I typed the ID and password, and clicked the login button, got 'success' result, and navigated to '/main'.

Now I can't see navbar in main component too.

How can I do this?

Sorry about my short english. If you can't understand my question, you can comment.

constructor(props) {
  super(props);
  this.state = {
    isAlertOpen: false,
    history: createBrowserHistory(),
  };
  this.toggleAlert = this.toggleAlert.bind(this);
}

<BrowserRouter>

    {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null
      : }

      {this.state.history.location.pathname === '/' || this.state.history.location.pathname === '/login' ? null
        : <Navbar />}
      <Route exact path="/" render={() => <Redirect to="/login" />} />
      <Route path="/login" component={Login} />
      <Route path="/main" component={Main} />
      <Route path="/user" component={User} />
      <Route path="/hw-setting" component={Setting} />
      <Route path="/hw-detail/:id" component={HwDetail} />
      <Route path="/gas-detail/:id" component={GasDetail} />
      {this.state.isAlertOpen ? <Alert /> : null}

</BrowserRouter>

login(event) {
  event.preventDefault();
  userService.login(this.state.id, this.state.password).subscribe(res => {
    if (res.result === 'success') {
      global.token = res.token;
      this.props.history.push('/main');
    } else {
      alert(`[ERROR CODE : ${res.statusCode}] ${res.msg}`);
    }
});

Body:
You could structure your Routes differently so that the Login component doesn't have the Header Like

<BrowserRouter>
  <Switch>
  <div className="App">
    <Route exact path="/(login)" component={LoginContainer}/>
    <Route component={DefaultContainer}/>

  </div>
  </Switch>
</BrowserRouter>

const LoginContainer = () => (
  <div className="container">
    <Route exact path="/" render={() => <Redirect to="/login" />} />
    <Route path="/login" component={Login} />
  </div>
)

 const DefaultContainer = () => (
    <div>
    <Header toggleAlert={this.toggleAlert} />
    <div className="container">
      <Navbar />
      <Route path="/main" component={Main} />
      <Route path="/user" component={User} />
      <Route path="/hw-setting" component={Setting} />
      <Route path="/hw-detail/:id" component={HwDetail} />
      <Route path="/gas-detail/:id" component={GasDetail} />
      {this.state.isAlertOpen ? <Alert /> : null}
    </div>
    </div>
 )


问:
ion-button menuToggle disappears on dashboard page when i login and navigate to dashboard page, why ? - IONIC
When i open my app, the 1st page which appears is Login.html , after filling the form, it navigates to dashboard.html

Problem: When it goes to Dashboard.html , it does not shows menuToggle ion-button. Please help me resolve this issue

This is the code i am using for navigation in login.ts:

```<code>if(data[0].USR==1)
       {
         this.navCtrl.push(DashboardPage);

       }
</code>```

my code in dashboard.html

```<code><ion-header>
  <ion-navbar hideBackButton="true">
    <button ion-button icon-only menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>dashboard..</ion-title>
  </ion-navbar>
  </ion-header>
</code>```

Please help me resolve this issue

Please note:
When i normally navigate from menu to dashboard page, it shows the menu toggle button.

答:
Would you like to try following html code for your menuToggle?

```<code><ion-header>
  <ion-navbar hideBackButton="true">

    <button ion-button menuToggle start>
        <ion-icon name="menu"></ion-icon>
    </button>

    <ion-title>dashboard..</ion-title>
  </ion-navbar>
</ion-header>
</code>```

Also note, if there isn't any back possibility from this dashboard view to your login view, I guess you would rather like to set it as root instead of pushing it. Therefore I would suggest to modify:

```<code>this.navCtrl.push(DashboardPage);
</code>```

into

```<code>this.navCtrl.setRoot(DashboardPage);
</code>```

Body:
When i open my app, the 1st page which appears is Login.html , after filling the form, it navigates to dashboard.html

Problem: When it goes to Dashboard.html , it does not shows menuToggle ion-button. Please help me resolve this issue

This is the code i am using for navigation in login.ts:

if(data[0].USR==1)
       {
         this.navCtrl.push(DashboardPage);

       }

my code in dashboard.html

<ion-header>
  <ion-navbar hideBackButton="true">
    <button ion-button icon-only menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>dashboard..</ion-title>
  </ion-navbar>
  </ion-header>

Please help me resolve this issue

Please note:
When i normally navigate from menu to dashboard page, it shows the menu toggle button.

Body:
Would you like to try following html code for your menuToggle?

<ion-header>
  <ion-navbar hideBackButton="true">

    <button ion-button menuToggle start>
        <ion-icon name="menu"></ion-icon>
    </button>

    <ion-title>dashboard..</ion-title>
  </ion-navbar>
</ion-header>

Also note, if there isn't any back possibility from this dashboard view to your login view, I guess you would rather like to set it as root instead of pushing it. Therefore I would suggest to modify:

this.navCtrl.push(DashboardPage);

into

this.navCtrl.setRoot(DashboardPage);


问:
Undefined is not an object (evaluating '_react2.PropTypes.number')
After installing react-native-md-textinput when i tried to start the app getting the following error.
Undefined is not an object (evaluating 'React.PropTypes.Number')
underline.js

Below is my package.json

"react": "16.0.0",
"react-native": "^0.49.5",
"react-native-md-textinput": "^2.0.4",
"react-navigation": "^1.0.0-beta.19"

答:
Solved it by importing PropTypes from 'prop-types' instead of 'react'

```<code>import React, {Component } from "react";
import PropTypes from 'prop-types';
</code>```

Body:
Solved it by importing PropTypes from 'prop-types' instead of 'react'

import React, {Component } from "react";
import PropTypes from 'prop-types';


问:
How to join big dataframes in Spark SQL? (best practices, stability, performance)
I'm getting the same error than Missing an output location for shuffle when joining big dataframes in Spark SQL. The recommendation there is to set MEMORY_AND_DISK and/or spark.shuffle.memoryFraction 0. However, spark.shuffle.memoryFraction is deprecated in Spark >= 1.6.0 and setting MEMORY_AND_DISK shouldn't help if I'm not caching any RDD or Dataframe, right? Also I'm getting lots of other WARN logs and task retries that lead me to think that the job is not stable.

Therefore, my question is:

What are best practices to join huge dataframes in Spark SQL >= 1.6.0?

More specific questions are:

How to tune number of executors and spark.sql.shuffle.partitions to achieve better stability/performance?

How to find the right balance between level of parallelism (num of executors/cores) and number of partitions? I've found that increasing the num of executors is not always the solution as it may generate I/O reading time out exceptions because of network traffic.

Is there any other relevant parameter to be tuned for this purpose?

My understanding is that joining data stored as ORC or Parquet offers better performance than text or Avro for join operations. Is there a significant difference between Parquet and ORC?

Is there an advantage of SQLContext vs HiveContext regarding stability/performance for join operations?

Is there a difference regarding performance/stability when the dataframes involved in the join are previously registerTempTable() or saveAsTable()?

So far I'm using this is answer and this chapter as a starting point. And there are a few more stackoverflow pages related to this subject. Yet I haven't found a comprehensive answer to this popular issue.

Thanks in advance.

答:
That are a lot of questions. Allow me to answer these one by one:

Your number of executors is most of the time variable in a production environment. This depends on the available resources. The number of partitions is important when you are performing shuffles. Assuming that your data is now skewed, you can lower the load per task by increasing the number of partitions.
A task should ideally take a couple of minus. If the task takes too long, it is possible that your container gets pre-empted and the work is lost. If the task takes only a few milliseconds, the overhead of starting the task gets dominant.

The level of parallelism and tuning your executor sizes, I would like to refer to the excellent guide by Cloudera: https://blog.cloudera.com/blog/2015/03/how-to-tune-your-apache-spark-jobs-part-2/

ORC and Parquet only encode the data at rest. When doing the actual join, the data is in the in-memory format of Spark. Parquet is getting more popular since Netflix and Facebook adopted it and put a lot of effort in it. Parquet allows you to store the data more efficient and has some optimisations (predicate pushdown) that Spark uses.

You should use the SQLContext instead of the HiveContext, since the HiveContext is deprecated. The SQLContext is more general and doesn't only work with Hive.

When performing the registerTempTable, the data is stored within the SparkSession. This doesn't affect the execution of the join. What it stores is only the execution plan which gets invoked when an action is performed (for example saveAsTable). When performining a saveAsTable the data gets stored on the distributed file system.

Hope this helps. I would also suggest watching our talk at the Spark Summit about doing joins: https://www.youtube.com/watch?v=6zg7NTw-kTQ. This might provide you some insights.

Cheers, Fokko


问:
How can I repeat an image in CSS3 with multiple backgrounds?

i am working on a project in which I have to put a curve image on the background of the container. I am using three images for that — I use a top image, a middle image which is repeatable on the y-axis, and a bottom image. The problem is that the container width (1028px) is fixed but the height is expandable.

So, the middle image comes over the top of the bottom image of the container, which looks like this.

But i want it look like this.

Here are my top, middle and bottom images:

top-image

mid-image

bottom-image

I’m using the CSS3 multiple background image property.

HTML:

```<code><div class="map clearfix">
      <div class="mpbg"></div>
</div>
</code>```

CSS:

```<code>.map {
  float: left;
  background:url("../../img/mpbg-bt-1028-205.png") no-repeat left bottom, url("../../img/mpbg-top-1028-205.png") no-repeat left top;
  margin: -30px 0 20px 0;
  z-index:999;
  width: 1028px;
}

.map .mpbg {
  float: left;
  margin:10px 0 20px 0;
  background: url('../../img/googlemap-996-380.jpg') no-repeat 17px 0, url("../../img/mpbg-mid-1028.png") repeat-y;
  width: 1028px;
  height: 380px;
}
</code>```

答: Backgrounds are not meant for this kind of styling in CSS3, it's just a hack from the CSS 2.1 days. Use border-image instead http://css-tricks.com/understanding-border-image/</p>

Body:
i am working on a project in which I have to put a curve image on the background of the container. I am using three images for that — I use a top image, a middle image which is repeatable on the y-axis, and a bottom image. The problem is that the container width (1028px) is fixed but the height is expandable.

So, the middle image comes over the top of the bottom image of the container, which looks like this.

But i want it look like this.

Here are my top, middle and bottom images:

top-image

mid-image

bottom-image

I’m using the CSS3 multiple background image property.

HTML:

CSS:

.map {
  float: left;
  background:url("../../img/mpbg-bt-1028-205.png") no-repeat left bottom, url("../../img/mpbg-top-1028-205.png") no-repeat left top;
  margin: -30px 0 20px 0;
  z-index:999;
  width: 1028px;
}

.map .mpbg {
  float: left;
  margin:10px 0 20px 0;
  background: url('../../img/googlemap-996-380.jpg') no-repeat 17px 0, url("../../img/mpbg-mid-1028.png") repeat-y;
  width: 1028px;
  height: 380px;
}


问:
Android Realm getInstance performance
I am using Realm on Android. Is it an expensive operation to call Realm.getDefaultInstance();? Would I be fine calling it each time I want to access the db from my intent service?

答: Yes you can use Realm.getDefaultInstance(); each operations. But you have to sure closed realm when using loop statements.</p>

Title: Android Realm getInstance performance


问:
Access state inside a function to dynamically set drawer width
I want to dynamically change the drawer width when the device orientation changes. This is my code

```<code>updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }
</code>```

I call updateWidth when componentDidMount and onLayout functions are called.

In the drawerNavigator declaration, I set drawerWidth: this.state.drawerWidth . Here I get an error telling me that drawerWidth: this.state.drawerWidth  is undefined. How can I solve this issue?

Edit:
This is the component code overview

```<code>const { width } = Dimensions.get('window');

const AppDrawer = DrawerNavigator(
{
  Category: {
    path: '/bla',
    screen: bla,
  },
},
{
  drawerWidth: this.state.drawerWidth ,
  contentComponent: test,
  initialRouteName: 'tets',
  contentOptions: {
    activeTintColor: '#fd67d3',
  },
}
);

const AppNavigator = StackNavigator({
...
})

class RootContainer extends Component {
 constructor(props) {
  super(props);
  this.state = {
      drawerWidth: 30
  }
}

  onLayout(e) {
    const {width, height} = Dimensions.get('window')
    this.updateWidth(width);
  }

  updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

  componentDidMount() {
    this.updateWidth(width);
}
</code>```

答: Your drawer component is a stateless component. Recreate it as a class based component and then you can have state in it. Stateless components can only grab props passed down to them, but they can not store any state.</p>

Body:
I want to dynamically change the drawer width when the device orientation changes. This is my code

updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

I call updateWidth when componentDidMount and onLayout functions are called.

In the drawerNavigator declaration, I set drawerWidth: this.state.drawerWidth . Here I get an error telling me that drawerWidth: this.state.drawerWidth  is undefined. How can I solve this issue?

Edit:
This is the component code overview

const { width } = Dimensions.get('window');

const AppDrawer = DrawerNavigator(
{
  Category: {
    path: '/bla',
    screen: bla,
  },
},
{
  drawerWidth: this.state.drawerWidth ,
  contentComponent: test,
  initialRouteName: 'tets',
  contentOptions: {
    activeTintColor: '#fd67d3',
  },
}
);

const AppNavigator = StackNavigator({
...
})

class RootContainer extends Component {
 constructor(props) {
  super(props);
  this.state = {
      drawerWidth: 30
  }
}

  onLayout(e) {
    const {width, height} = Dimensions.get('window')
    this.updateWidth(width);
  }

  updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

  componentDidMount() {
    this.updateWidth(width);
}


问:
Configuration of luminoth training/evaluation job for Google Cloud ML using voc2012
How to configure a luminoth training job (on Google Cloud ML) and tensorboard? I transformed voc2012 to tfrecord format and uploaded to a bucket.
So now I want to train the default model (FasterRCNN) using the voc2012 dataset.

Which config file should I use? sample_config.yml or the base_config.yml file in the fasterrcnn directory?
How do I submit an evaluation job?

Anything to consider for the Tensorboard usage?

答:
To submit an evaluation job:

```<code>lumi cloud gc evaluate
</code>```

Options:

```<code>--job-id TEXT               // JobId for saving models and logs. [required]
--service-account-json TEXT // [required]
--bucket TEXT               // Where to save models and logs.
--split TEXT                // Dataset split to use.
--region TEXT               // Region in which to run the job.
--scale-tier [BASIC|STANDARD_1|PREMIUM_1|BASIC_GPU|CUSTOM]
--rebuild                   // Rebuild and upload package.
--postfix TEXT              // Postfix for the evaluation job name.
-h, --help                  // Show this message and exit.
</code>```

Body:
To submit an evaluation job:

lumi cloud gc evaluate

Options:

--job-id TEXT               // JobId for saving models and logs. [required]
--service-account-json TEXT // [required]
--bucket TEXT               // Where to save models and logs.
--split TEXT                // Dataset split to use.
--region TEXT               // Region in which to run the job.
--scale-tier [BASIC|STANDARD_1|PREMIUM_1|BASIC_GPU|CUSTOM]
--rebuild                   // Rebuild and upload package.
--postfix TEXT              // Postfix for the evaluation job name.
-h, --help                  // Show this message and exit.


问:
Choose cell contents based on MAX result
Long time reader of SO but my first time posting a question. Hoping you can help with my dilemma and understand my formatting (not a coder!)

I have three rows of numbers. The first is a date, the second is a target number, the third is an

Date     01/11   02/11   03/11

Target      10      20          30

Actual      11    100        30

I have a formula to highlight the max number (we have a 'best ever' type celebration)

It's basic and pulls back the number: "=MAX(B3:CI3)". So above this would give me '100' as the result.

What I want to be able to do is have it pull back the associated date so I don't have to update it manually.

So I would end up with something like the below in the summary sheet I'm doing...

Best Date:  02/11

Best Score: 100

...where the '02/11' is automatically calculated.

Can someone help me pick the value? Struggling to do it at the moment. I have tried using R1C1 references and doing things like =RC[-2] and trying to get that in the MAX formula but just can't make it work.

Many thanks

答:
For anyone else looking at this, the result that worked is as follows:

=INDEX(2:2,MATCH(MAX(4:4),4:4,0))

the 2:2 selection is over the date row. the 4:4 options bits are over the Actual row. I had to drag what the formula highlights to get them to the right place (my brain struggles with all the formulas!)