问:
Unity UI : How to reenable a dropdown after its panel was deactivated and then reactivated?
I am new to Unity, so this is probably a dumb question but here goes:
I have a Unity app; it has several scenes.  One of those scenes has a Canvas upon which there are several overlapping Panels.  On one of the Panels (PanelA), there is a Dropdown.  When the app first runs PanelA is active and on top by default and the dropdown works fine.  But after I deactivate PanelA with a C# call to

```<code>panelA.SetActive(false);// hides the panel
</code>```

and then later reactivate it like so:

```<code>panelA.SetActive(true); // redisplays the panel
</code>```

The dropdown no longer displays its list of option when clicked on.  The dropdown is still there and still shows its first option "None" and when clicked on the drop-down changes color to indicate that it was touched, but the dropdown does not drop down its list of options.
What am I missing?  Why doesn't the dropdown show the list of options?
Thanks

Windows 10 Pro v1709, unity 2017.1.1f1 Personal

My hierarchy is like so, PanelB is the panel that gets set active after PanelA is inactivated:

The script called when the dropdowns option is selected is called like so in Start():

```<code>PickDropDown.onValueChanged.AddListener(delegate {
            myDropdownValueChangedHandler(PickDropDown);
        });
</code>```

and the called function is:

```<code>    private void myDropdownValueChangedHandler(Dropdown target) {
        Debug.Log("selected: "+target.value);
        stage = 0;

        currentval = PickDropDown.options [PickDropDown.value].text;
        advice.text = "";
        title.text = currentval;
        if (currentval != NONE) {
            advice.text = "You chose to do  "+currentval;
            nextVal();
        }
    }

    void newVal(){
        Debug.Log("newVal  " );

        PanelA.SetActive (true);
        PanelB.SetActive (false);
        Debug.Log("options  count="+ PickDropDown.options.Count );
    }

    void nextVal(){
        Debug.Log("nextSet  " );
        PanelB.SetActive (true);
        /*** next line shows the answer to my problem - from killer_mech **/
        Destroy(PickDropDown.transform.Find("Dropdown List").gameObject);
        /***************************************************************/
        PanelA.SetActive (false);
    }
</code>```

答:
Yes, this is a bug in unity. I can reproduce this now. This is happening because Unity is creating a game Object called "Dropdown List" inside dropdown which should get destroyed after the closing. But I have noticed a slight delay is happening while destroying(I used editor debug mode for this). When you set the game object active flag as false, it somehow stops the destroy object and results in object Dropdown List staying there so next time when you try to interact with it the object will still present. You will also notice a white box below the Dropdown list after this which indicates the dropdown list still is present.

For the solution what I did was just before I was about to turn my gameobject off I used

Destroy(PickDropDown.transform.Find("Dropdown List").gameObject);

Destroying this object solves the problem. I know this is not a good way to do it, but I checked whether any references to options are destroyed while destroying this which resulted in no error for me. And Dropdown creates new "Dropdown List" gameobject. So it is safe to assume that destroying is OK. Well not sure if any other good solution for this is out there but for now you can use this.

Note: I have tested this bug with Panel, Empty Gameobject as parent and finally with Dropdown

This shows what is happening inside the drop-down. 1) During No popup 2) During Open 3)After setactive off before the child is destroyed.

Body:
I am new to Unity, so this is probably a dumb question but here goes:
I have a Unity app; it has several scenes.  One of those scenes has a Canvas upon which there are several overlapping Panels.  On one of the Panels (PanelA), there is a Dropdown.  When the app first runs PanelA is active and on top by default and the dropdown works fine.  But after I deactivate PanelA with a C# call to

panelA.SetActive(false);// hides the panel

and then later reactivate it like so:

panelA.SetActive(true); // redisplays the panel

The dropdown no longer displays its list of option when clicked on.  The dropdown is still there and still shows its first option "None" and when clicked on the drop-down changes color to indicate that it was touched, but the dropdown does not drop down its list of options.
What am I missing?  Why doesn't the dropdown show the list of options?
Thanks

Windows 10 Pro v1709, unity 2017.1.1f1 Personal

My hierarchy is like so, PanelB is the panel that gets set active after PanelA is inactivated:

The script called when the dropdowns option is selected is called like so in Start():

PickDropDown.onValueChanged.AddListener(delegate {
            myDropdownValueChangedHandler(PickDropDown);
        });

and the called function is:

    private void myDropdownValueChangedHandler(Dropdown target) {
        Debug.Log("selected: "+target.value);
        stage = 0;

        currentval = PickDropDown.options [PickDropDown.value].text;
        advice.text = "";
        title.text = currentval;
        if (currentval != NONE) {
            advice.text = "You chose to do  "+currentval;
            nextVal();
        }
    }

    void newVal(){
        Debug.Log("newVal  " );

        PanelA.SetActive (true);
        PanelB.SetActive (false);
        Debug.Log("options  count="+ PickDropDown.options.Count );
    }

    void nextVal(){
        Debug.Log("nextSet  " );
        PanelB.SetActive (true);
        /*** next line shows the answer to my problem - from killer_mech **/
        Destroy(PickDropDown.transform.Find("Dropdown List").gameObject);
        /***************************************************************/
        PanelA.SetActive (false);
    }


来源: stackexchange

问:
Karma Test: PhantomJS: ReferenceError: Can't find variable: Audio
I'm trying to use Karma and PhantomJS to test my app, and I'm getting the error:

```<code>   PhantomJS 1.9.8 (Windows 7) Controller: SongsCtrl should attach a list of awesomeThings to the scope FAILED
ReferenceError: Can't find variable: Audio
</code>```

The offending line in my AngularJS Service is:

```<code>   var audio = new Audio();
</code>```

Which of course runs fine when I run it in a browser, but since it's a native HTML5 element, PhantomJS doesn't seem to recognize it.

Does anyone know how I could fix this?

答:
Audio Mock Object for PhantomJs:</p>

```<code>page.onInitialized = function () {
    page.evaluate(function () {
        window.Audio =  function() {
            return {
                play: function() {},
                pause: function() {},
                canPlayType: function() {},
                accessKey: function(){},
                accessibleNode: function(){},
                assignedSlot: function(){},
                attributes: function(){},
                audioTracks: function(){},
                autoplay: function(){},
                baseURI: function(){},
                buffered: function(){},
                childElementCount: function(){},
                childNodes: function(){},
                children: function(){},
                classList: function(){},
                className: function(){},
                clientHeight: function(){},
                clientLeft: function(){},
                clientTop: function(){},
                clientWidth: function(){},
                computedName: function(){},
                computedRole: function(){},
                contentEditable: function(){},
                controls: function(){},
                controlsList: function(){},
                crossOrigin: function(){},
                currentSrc: function(){},
                currentTime: function(){},
                dataset: function(){},
                defaultMuted: function(){},
                defaultPlaybackRate: function(){},
                dir: function(){},
                disableRemotePlayback: function(){},
                draggable: function(){},
                duration: function(){},
                ended: function(){},
                error: function(){},
                firstChild: function(){},
                firstElementChild: function(){},
                hidden: function(){},
                id: function(){},
                inert: function(){},
                innerHTML: function(){},
                innerText: function(){},
                inputMode: function(){},
                isConnected: function(){},
                isContentEditable: function(){},
                lang: function(){},
                lastChild: function(){},
                lastElementChild: function(){},
                localName: function(){},
                loop: function(){},
                mediaKeys: function(){},
                muted: function(){},
                namespaceURI: function(){},
                networkState: function(){},
                nextElementSibling: function(){},
                nextSibling: function(){},
                nodeName: function(){},
                nodeType: function(){},
                nodeValue: function(){},
                nonce: function(){},
                offsetHeight: function(){},
                offsetLeft: function(){},
                offsetParent: function(){},
                offsetTop: function(){},
                offsetWidth: function(){},
                onabort: function(){},
                onauxclick: function(){},
                onbeforecopy: function(){},
                onbeforecut: function(){},
                onbeforepaste: function(){},
                onblur: function(){},
                oncancel: function(){},
                oncanplay: function(){},
                oncanplaythrough: function(){},
                onchange: function(){},
                onclick: function(){},
                onclose: function(){},
                oncontextmenu: function(){},
                oncopy: function(){},
                oncuechange: function(){},
                oncut: function(){},
                ondblclick: function(){},
                ondrag: function(){},
                ondragend: function(){},
                ondragenter: function(){},
                ondragleave: function(){},
                ondragover: function(){},
                ondragstart: function(){},
                ondrop: function(){},
                ondurationchange: function(){},
                onemptied: function(){},
                onencrypted: function(){},
                onended: function(){},
                onerror: function(){},
                onfocus: function(){},
                onfullscreenchange: function(){},
                onfullscreenerror: function(){},
                ongotpointercapture: function(){},
                oninput: function(){},
                oninvalid: function(){},
                onkeydown: function(){},
                onkeypress: function(){},
                onkeyup: function(){},
                onload: function(){},
                onloadeddata: function(){},
                onloadedmetadata: function(){},
                onloadstart: function(){},
                onlostpointercapture: function(){},
                onmousedown: function(){},
                onmouseenter: function(){},
                onmouseleave: function(){},
                onmousemove: function(){},
                onmouseout: function(){},
                onmouseover: function(){},
                onmouseup: function(){},
                onmousewheel: function(){},
                onpaste: function(){},
                onpause: function(){},
                onplay: function(){},
                onplaying: function(){},
                onpointercancel: function(){},
                onpointerdown: function(){},
                onpointerenter: function(){},
                onpointerleave: function(){},
                onpointermove: function(){},
                onpointerout: function(){},
                onpointerover: function(){},
                onpointerup: function(){},
                onprogress: function(){},
                onratechange: function(){},
                onreset: function(){},
                onresize: function(){},
                onscroll: function(){},
                onsearch: function(){},
                onseeked: function(){},
                onseeking: function(){},
                onselect: function(){},
                onselectstart: function(){},
                onstalled: function(){},
                onsubmit: function(){},
                onsuspend: function(){},
                ontimeupdate: function(){},
                ontoggle: function(){},
                ontouchcancel: function(){},
                ontouchend: function(){},
                ontouchmove: function(){},
                ontouchstart: function(){},
                onvolumechange: function(){},
                onwaiting: function(){},
                onwaitingforkey: function(){},
                onwebkitfullscreenchange: function(){},
                onwebkitfullscreenerror: function(){},
                onwheel: function(){},
                outerHTML: function(){},
                outerText: function(){},
                ownerDocument: function(){},
                parentElement: function(){},
                parentNode: function(){},
                paused: function(){},
                playbackRate: function(){},
                played: function(){},
                prefix: function(){},
                preload: function(){},
                previousElementSibling: function(){},
                previousSibling: function(){},
                readyState: function(){},
                remote: function(){},
                scrollHeight: function(){},
                scrollLeft: function(){},
                scrollTop: function(){},
                scrollWidth: function(){},
                seekable: function(){},
                seeking: function(){},
                shadowRoot: function(){},
                sinkId: function(){},
                slot: function(){},
                spellcheck: function(){},
                src: function(){},
                srcObject: function(){},
                style: function(){},
                styleMap: function(){},
                tabIndex: function(){},
                tagName: function(){},
                textContent: function(){},
                textTracks: function(){},
                title: function(){},
                translate: function(){},
                videoTracks: function(){},
                volume: function(){}

            };
        };
    });
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use Karma and PhantomJS to test my app, and I'm getting the error:

   PhantomJS 1.9.8 (Windows 7) Controller: SongsCtrl should attach a list of awesomeThings to the scope FAILED
ReferenceError: Can't find variable: Audio

The offending line in my AngularJS Service is:

   var audio = new Audio();

Which of course runs fine when I run it in a browser, but since it's a native HTML5 element, PhantomJS doesn't seem to recognize it.

Does anyone know how I could fix this?

Body:
Audio Mock Object for PhantomJs:

page.onInitialized = function () {
    page.evaluate(function () {
        window.Audio =  function() {
            return {
                play: function() {},
                pause: function() {},
                canPlayType: function() {},
                accessKey: function(){},
                accessibleNode: function(){},
                assignedSlot: function(){},
                attributes: function(){},
                audioTracks: function(){},
                autoplay: function(){},
                baseURI: function(){},
                buffered: function(){},
                childElementCount: function(){},
                childNodes: function(){},
                children: function(){},
                classList: function(){},
                className: function(){},
                clientHeight: function(){},
                clientLeft: function(){},
                clientTop: function(){},
                clientWidth: function(){},
                computedName: function(){},
                computedRole: function(){},
                contentEditable: function(){},
                controls: function(){},
                controlsList: function(){},
                crossOrigin: function(){},
                currentSrc: function(){},
                currentTime: function(){},
                dataset: function(){},
                defaultMuted: function(){},
                defaultPlaybackRate: function(){},
                dir: function(){},
                disableRemotePlayback: function(){},
                draggable: function(){},
                duration: function(){},
                ended: function(){},
                error: function(){},
                firstChild: function(){},
                firstElementChild: function(){},
                hidden: function(){},
                id: function(){},
                inert: function(){},
                innerHTML: function(){},
                innerText: function(){},
                inputMode: function(){},
                isConnected: function(){},
                isContentEditable: function(){},
                lang: function(){},
                lastChild: function(){},
                lastElementChild: function(){},
                localName: function(){},
                loop: function(){},
                mediaKeys: function(){},
                muted: function(){},
                namespaceURI: function(){},
                networkState: function(){},
                nextElementSibling: function(){},
                nextSibling: function(){},
                nodeName: function(){},
                nodeType: function(){},
                nodeValue: function(){},
                nonce: function(){},
                offsetHeight: function(){},
                offsetLeft: function(){},
                offsetParent: function(){},
                offsetTop: function(){},
                offsetWidth: function(){},
                onabort: function(){},
                onauxclick: function(){},
                onbeforecopy: function(){},
                onbeforecut: function(){},
                onbeforepaste: function(){},
                onblur: function(){},
                oncancel: function(){},
                oncanplay: function(){},
                oncanplaythrough: function(){},
                onchange: function(){},
                onclick: function(){},
                onclose: function(){},
                oncontextmenu: function(){},
                oncopy: function(){},
                oncuechange: function(){},
                oncut: function(){},
                ondblclick: function(){},
                ondrag: function(){},
                ondragend: function(){},
                ondragenter: function(){},
                ondragleave: function(){},
                ondragover: function(){},
                ondragstart: function(){},
                ondrop: function(){},
                ondurationchange: function(){},
                onemptied: function(){},
                onencrypted: function(){},
                onended: function(){},
                onerror: function(){},
                onfocus: function(){},
                onfullscreenchange: function(){},
                onfullscreenerror: function(){},
                ongotpointercapture: function(){},
                oninput: function(){},
                oninvalid: function(){},
                onkeydown: function(){},
                onkeypress: function(){},
                onkeyup: function(){},
                onload: function(){},
                onloadeddata: function(){},
                onloadedmetadata: function(){},
                onloadstart: function(){},
                onlostpointercapture: function(){},
                onmousedown: function(){},
                onmouseenter: function(){},
                onmouseleave: function(){},
                onmousemove: function(){},
                onmouseout: function(){},
                onmouseover: function(){},
                onmouseup: function(){},
                onmousewheel: function(){},
                onpaste: function(){},
                onpause: function(){},
                onplay: function(){},
                onplaying: function(){},
                onpointercancel: function(){},
                onpointerdown: function(){},
                onpointerenter: function(){},
                onpointerleave: function(){},
                onpointermove: function(){},
                onpointerout: function(){},
                onpointerover: function(){},
                onpointerup: function(){},
                onprogress: function(){},
                onratechange: function(){},
                onreset: function(){},
                onresize: function(){},
                onscroll: function(){},
                onsearch: function(){},
                onseeked: function(){},
                onseeking: function(){},
                onselect: function(){},
                onselectstart: function(){},
                onstalled: function(){},
                onsubmit: function(){},
                onsuspend: function(){},
                ontimeupdate: function(){},
                ontoggle: function(){},
                ontouchcancel: function(){},
                ontouchend: function(){},
                ontouchmove: function(){},
                ontouchstart: function(){},
                onvolumechange: function(){},
                onwaiting: function(){},
                onwaitingforkey: function(){},
                onwebkitfullscreenchange: function(){},
                onwebkitfullscreenerror: function(){},
                onwheel: function(){},
                outerHTML: function(){},
                outerText: function(){},
                ownerDocument: function(){},
                parentElement: function(){},
                parentNode: function(){},
                paused: function(){},
                playbackRate: function(){},
                played: function(){},
                prefix: function(){},
                preload: function(){},
                previousElementSibling: function(){},
                previousSibling: function(){},
                readyState: function(){},
                remote: function(){},
                scrollHeight: function(){},
                scrollLeft: function(){},
                scrollTop: function(){},
                scrollWidth: function(){},
                seekable: function(){},
                seeking: function(){},
                shadowRoot: function(){},
                sinkId: function(){},
                slot: function(){},
                spellcheck: function(){},
                src: function(){},
                srcObject: function(){},
                style: function(){},
                styleMap: function(){},
                tabIndex: function(){},
                tagName: function(){},
                textContent: function(){},
                textTracks: function(){},
                title: function(){},
                translate: function(){},
                videoTracks: function(){},
                volume: function(){}

            };
        };
    });
};


问:
Django with huge mysql database
What would be the best way to import multi-million record csv files into django.

Currently using python csv module, it takes 2-4 days for it process 1 million record file. It does some checking if the record already exists, and few others.

Can this process be achieved to execute in few hours.

Can  memcache be used somehow.

Update: There are django ManyToManyField fields that get processed as well. How will these used with direct load.

答:
Like Craig said, you'd better fill the db directly first.
It implies creating django models that just fits the CSV cells (you can then create better models and scripts to move the data)

Then, db feedding : a tool of choice for doing this is Navicat, you can grab a functional 30  days demo on their site. It allows you to import CSV in MySQL, save the importation profile in XML...

Then I would launch the data control scripts from within Django, and when you're done, migrating your model with South to get what you want or , like I said earlier, create another set of models within your project and use scripts to convert/copy the data.

ContentLicense: CC BY-SA 2.5

Title: Django with huge mysql database


问:
GNU argp: How to parse option with only long name?
I want to use argp in my C program to parse command line options.

One requirement is that an option does not have a short name (like -f bar) but only a long name (like --foo=bar).

My approach so far is to set the key field of the argp_option struct to 0 to make it not show a short name.

I have looked at the provided examples and argp.h in detail but I can't find a means to parse an option that only has a long name in the parser function that is given to argp.

What I did find out is that, theoretically, in the parser I could use

```<code>case ARGP_KEY_ARG:
  printf("%s\n", arg);
</code>```

to find the value of long options (e.g. when called with --foo=bar, bar would be printed here). However, this doesn't seem like the right approach since I don't see a simple way to actually tell which option the value belongs to. and this also shows actual command line arguments (not option values).

I'd be thankful for any tips about where I need to look. Cheers.

答:
From "The GNU C Library: Argp Option Vectors — Specifying Options in an Argp Parser":

int key

The integer key provided by the current option to the option parser.
If key has a value that is a printable ASCII character (i.e.,
isascii (key) is true), it also specifies a short option -char,
where char is the ASCII character with the code key.

In other words, the key field of an option can be any int value, and if isascii(key) is nonzero, then it also specifies a short option—meaning you can use non-ASCII values (values outside the range 0x00..0x7F) to avoid the short option. Despite not being a short option, the value of key is still used as the value of the associated long option (e.g. --foo), so you'd handle it the same as any key/short option.

O/T: I collect all of my option keys in an enum as constants, so I'm not wondering what option 0x100 represents in a switch, e.g. for GNU tar, it might be something like this for its compression options:

```<code>enum compress_options {
    // Archive file extension determines compression program
    COMP_FILTER_AUTO = 'a',
    // Option arg is program used to deal with compression
    COMP_FILTER_ARG = 'I',

    COMP_FILTER_BZIP2 = 'j',
    COMP_FILTER_XZ = 'J',
    COMP_FILTER_GZIP = 'z',
    COMP_FILTER_COMPRESS = 'Z',

    COMP_FILTER_LZIP = 0x100,
    COMP_FILTER_LZMA,
    COMP_FILTER_LZOP,

    // Do not use archive suffix to determine compression program.
    COMP_FILTER_NOAUTO,
};
</code>```

Then you'd just need to ensure that the next set of options uses 0x200, then 0x300, etc. to avoid issues with options having the same value. If you needed, you could also use 0x100, 0x180, 0x200, 0x280, etc. (e.g. 0x100 might represent a subcommand and 0x180 might be the first option for that subcommand).

It's important to group the short options and non-short options separately. The implicitly assigned values in an enum depend upon the value of the last explicitly assigned value. Had I placed COMP_FILTER_NOAUTO immediately after COMP_FILTER_AUTO, the --no-auto-compress long option would have an associated short option -b, which it does not in reality.

Body:
I want to use argp in my C program to parse command line options.

One requirement is that an option does not have a short name (like -f bar) but only a long name (like --foo=bar).

My approach so far is to set the key field of the argp_option struct to 0 to make it not show a short name.

I have looked at the provided examples and argp.h in detail but I can't find a means to parse an option that only has a long name in the parser function that is given to argp.

What I did find out is that, theoretically, in the parser I could use

case ARGP_KEY_ARG:
  printf("%s\n", arg);

to find the value of long options (e.g. when called with --foo=bar, bar would be printed here). However, this doesn't seem like the right approach since I don't see a simple way to actually tell which option the value belongs to. and this also shows actual command line arguments (not option values).

I'd be thankful for any tips about where I need to look. Cheers.

Body:
From "The GNU C Library: Argp Option Vectors — Specifying Options in an Argp Parser":

int key

The integer key provided by the current option to the option parser.
If key has a value that is a printable ASCII character (i.e.,
isascii (key) is true), it also specifies a short option -char,
where char is the ASCII character with the code key.

In other words, the key field of an option can be any int value, and if isascii(key) is nonzero, then it also specifies a short option—meaning you can use non-ASCII values (values outside the range 0x00..0x7F) to avoid the short option. Despite not being a short option, the value of key is still used as the value of the associated long option (e.g. --foo), so you'd handle it the same as any key/short option.

O/T: I collect all of my option keys in an enum as constants, so I'm not wondering what option 0x100 represents in a switch, e.g. for GNU tar, it might be something like this for its compression options:

enum compress_options {
    // Archive file extension determines compression program
    COMP_FILTER_AUTO = 'a',
    // Option arg is program used to deal with compression
    COMP_FILTER_ARG = 'I',

    COMP_FILTER_BZIP2 = 'j',
    COMP_FILTER_XZ = 'J',
    COMP_FILTER_GZIP = 'z',
    COMP_FILTER_COMPRESS = 'Z',

    COMP_FILTER_LZIP = 0x100,
    COMP_FILTER_LZMA,
    COMP_FILTER_LZOP,

    // Do not use archive suffix to determine compression program.
    COMP_FILTER_NOAUTO,
};

Then you'd just need to ensure that the next set of options uses 0x200, then 0x300, etc. to avoid issues with options having the same value. If you needed, you could also use 0x100, 0x180, 0x200, 0x280, etc. (e.g. 0x100 might represent a subcommand and 0x180 might be the first option for that subcommand).

It's important to group the short options and non-short options separately. The implicitly assigned values in an enum depend upon the value of the last explicitly assigned value. Had I placed COMP_FILTER_NOAUTO immediately after COMP_FILTER_AUTO, the --no-auto-compress long option would have an associated short option -b, which it does not in reality.

ContentLicense: CC BY-SA 4.0


问:
Java JUnit profiling on MacOS doesn't work
I'm trying to profile a JUnit test with JavaVisualVM on MacOS El Capitan.
My Java version is 1.8.0_45

So on this machine I do the following:

set up the run configurations of my JUnit test in Eclipse so that it
leaves the VM up after the first run.

set a breakpoint within the code of the unit test, right before the part I want to profile

launch the test in debug mode (Debug As JUnit test). It pauses at the breakpoint

double click on the process in VisualVM, open the profile tab, click  CPU profiling

resum execution in Eclipse.

At this point VisualVM does indeed capture some CPU usage information, but the only methods shown here are those in the org.eclipse.jdt package itself. It doesn't capture information from running my application classes.

The only output I can see is a bunch of warning messages printed to the Eclipse console after I hook VisualVM to the JUnit process:

```<code>objc[89393]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
Profiler Agent: Waiting for connection on port 5140 (Protocol version: 15)
Profiler Agent: Established connection with the tool
Profiler Agent: Local accelerated session
Profiler Agent Warning: JVMTI classLoadHook: class name is null.
Profiler Agent Warning: JVMTI classLoadHook: class name is null.
[... many more like these ...]

Profiler Agent: Connection with agent closed
Profiler Agent: JNI OnLoad Initializing...
Profiler Agent: JNI OnLoad Initialized successfully
</code>```

This is probably something I'm supposed to investigate, but I don't really know what to do with it.

What bugs me is that I replicated this same process (apparently the same) on a Windows 10 machine and it does profile my application classes.
I don't know what I'm doing wrong on Mac.

Thank you

答: You need to set "Start Profiling from Classes" to [your_package].** and uncheck "Profile new Runnables". More details about profiling settings can be found in Profiling With VisualVM, Part 1 and Profiling With VisualVM, Part 2.

Body:
I'm trying to profile a JUnit test with JavaVisualVM on MacOS El Capitan.
My Java version is 1.8.0_45

So on this machine I do the following:

set up the run configurations of my JUnit test in Eclipse so that it
leaves the VM up after the first run.

set a breakpoint within the code of the unit test, right before the part I want to profile

launch the test in debug mode (Debug As JUnit test). It pauses at the breakpoint

double click on the process in VisualVM, open the profile tab, click  CPU profiling

resum execution in Eclipse.

At this point VisualVM does indeed capture some CPU usage information, but the only methods shown here are those in the org.eclipse.jdt package itself. It doesn't capture information from running my application classes.

The only output I can see is a bunch of warning messages printed to the Eclipse console after I hook VisualVM to the JUnit process:

objc[89393]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
Profiler Agent: Waiting for connection on port 5140 (Protocol version: 15)
Profiler Agent: Established connection with the tool
Profiler Agent: Local accelerated session
Profiler Agent Warning: JVMTI classLoadHook: class name is null.
Profiler Agent Warning: JVMTI classLoadHook: class name is null.
[... many more like these ...]

Profiler Agent: Connection with agent closed
Profiler Agent: JNI OnLoad Initializing...
Profiler Agent: JNI OnLoad Initialized successfully

This is probably something I'm supposed to investigate, but I don't really know what to do with it.

What bugs me is that I replicated this same process (apparently the same) on a Windows 10 machine and it does profile my application classes.
I don't know what I'm doing wrong on Mac.

Thank you


问:
vba Userform macro edits wrong sheet
I have a userform that is supposed to insert a row on Sheet3 and populate some cells in that row with some values. it works great as long as I have sheet3 displayed. (The form is shown modeless to give me access to the sheets).

Anyway, I happened to have another sheet active and ran it again and was surprised to see it inserted the row not in sheet3, but in the one I had displayed... (Thank God I saved first!)

In the code, I specified a range object as follows to find the insertion point: (I'll truncate the code a bit to keep it simple)

```<code>Dim RecordRange As Range
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
</code>```

blah blah blah.
A workaround is to activate the sheet first:

```<code>Sheet3.Activate
</code>```

That at least inserts into the correct sheet, but I'd rather not have sheet3 be displayed when I add the record, so I even surrounded that line with:

```<code>Application.ScreenUpdating = False
Sheet3.Activate
Application.ScreenUpdating = True
</code>```

unfortunately, ScreenUpdating doesn't work from within a Userform Code module, so that bites...

I still don't understand why it chooses to insert the row into whatever sheet is active, when I've already specified sheet3 in the code. I have another Macro very similar that doesn't have this problem.

any ideas?

答:
...so you figure your workaround needs a workaround?  Hmm...  I think that qualifies as a double-negative since a workaround is supposed to, by definition, fix problems rather than cause them...

A workaround is a bypass of a recognized problem in a system. A
  workaround is typically a temporary fix that implies that a genuine
  solution to the problem is needed. But workarounds are frequently as
  creative as true solutions, involving outside the box thinking in
  their creation.

Typically they are considered brittle in that they will not respond
  well to further pressure from a system beyond the original design. In
  implementing a workaround it is important to flag the change so as to
  later implement a proper solution.

Placing pressure on a workaround may result in later system failures.
  For example, in computer programming workarounds are often used to
  address a problem or anti-pattern in a library, such as an incorrect
  return value. When the library is changed, the workaround may break
  the overall program functionality, effectively becoming an
  anti-pattern, since it may expect the older, wrong behaviour from the
  library.  (Wikipedia)

Just sayin'...  :-)

So instead of fixing the workaround, your original issue is (thankfully) straightforward.

You're using Sheet3 as an object, and I suspect you haven't assigned anything (like Worksheets("Sheet3") to an object called Sheet3.

Try this instead:

```<code>Dim RecordRange As Range
Set RecordRange = Worksheets("Sheet3").Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
</code>```

If you indeed intended to use Sheet3 as an object then make sure it's declared as set, so for example you could instead use:

```<code>Dim RecordRange As Range
Dim Sheet3 As Worksheet
Set Sheet3 = Worksheets("Sheet3")
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1, 0).EntireRow.Insert
</code>```

Also, just to point out:  If either of these solves your issue then the problem would've "made itself known", by including one line at the top of every module (at least during development & troubleshooting):

```<code>Option Explicit
</code>```

This link has a short explanation, but basically it forces you to properly declare all variables (thus helping to prevent future workarounds!)

Title: vba Userform macro edits wrong sheet

Body:
I have a userform that is supposed to insert a row on Sheet3 and populate some cells in that row with some values. it works great as long as I have sheet3 displayed. (The form is shown modeless to give me access to the sheets).

Anyway, I happened to have another sheet active and ran it again and was surprised to see it inserted the row not in sheet3, but in the one I had displayed... (Thank God I saved first!)

In the code, I specified a range object as follows to find the insertion point: (I'll truncate the code a bit to keep it simple)

Dim RecordRange As Range
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert

blah blah blah.
A workaround is to activate the sheet first:

Sheet3.Activate

That at least inserts into the correct sheet, but I'd rather not have sheet3 be displayed when I add the record, so I even surrounded that line with:

Application.ScreenUpdating = False
Sheet3.Activate
Application.ScreenUpdating = True

unfortunately, ScreenUpdating doesn't work from within a Userform Code module, so that bites...

I still don't understand why it chooses to insert the row into whatever sheet is active, when I've already specified sheet3 in the code. I have another Macro very similar that doesn't have this problem.

any ideas?

Body:
...so you figure your workaround needs a workaround?  Hmm...  I think that qualifies as a double-negative since a workaround is supposed to, by definition, fix problems rather than cause them...

A workaround is a bypass of a recognized problem in a system. A
  workaround is typically a temporary fix that implies that a genuine
  solution to the problem is needed. But workarounds are frequently as
  creative as true solutions, involving outside the box thinking in
  their creation.

Typically they are considered brittle in that they will not respond
  well to further pressure from a system beyond the original design. In
  implementing a workaround it is important to flag the change so as to
  later implement a proper solution.

Placing pressure on a workaround may result in later system failures.
  For example, in computer programming workarounds are often used to
  address a problem or anti-pattern in a library, such as an incorrect
  return value. When the library is changed, the workaround may break
  the overall program functionality, effectively becoming an
  anti-pattern, since it may expect the older, wrong behaviour from the
  library.  (Wikipedia)

Just sayin'...  :-)

So instead of fixing the workaround, your original issue is (thankfully) straightforward.

You're using Sheet3 as an object, and I suspect you haven't assigned anything (like Worksheets("Sheet3") to an object called Sheet3.

Try this instead:

Dim RecordRange As Range
Set RecordRange = Worksheets("Sheet3").Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert

If you indeed intended to use Sheet3 as an object then make sure it's declared as set, so for example you could instead use:

Dim RecordRange As Range
Dim Sheet3 As Worksheet
Set Sheet3 = Worksheets("Sheet3")
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1, 0).EntireRow.Insert

Also, just to point out:  If either of these solves your issue then the problem would've "made itself known", by including one line at the top of every module (at least during development & troubleshooting):

Option Explicit

This link has a short explanation, but basically it forces you to properly declare all variables (thus helping to prevent future workarounds!)


问:
Using awk to extract lines between patterns
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

```<code>Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$
</code>```

desired output

```<code>Name2
ii
ooo
ppp
$$$$
</code>```

I tried something like this:

```<code>awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile
</code>```

I also tried something like

```<code>awk '/^Name2/,/\\$\\$\\$\\$\\/' input
</code>```

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

答:
Awk solution:

```<code>awk '/^Name2/{ f=1 }f; $1=="$$$$"{ f=0 }' file
</code>```

f variable is a marker indicating the possibility for the current line to be printed

The output:

```<code>Name2
ii
ooo
ppp
$$$$
</code>```

Body:
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$

desired output

Name2
ii
ooo
ppp
$$$$

I tried something like this:

awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile

I also tried something like

awk '/^Name2/,/\\$\\$\\$\\$\\/' input

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

Body:
Awk solution:

awk '/^Name2/{ f=1 }f; $1=="$$$$"{ f=0 }' file

f variable is a marker indicating the possibility for the current line to be printed

The output:

Name2
ii
ooo
ppp
$$$$


问:
How to format date in angularjs
I want to format date as mm/dd/yyyy. I tried the following and none of it works for me.
Can anyone help me with this?

reference: ui-date

```<code><input ui-date ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />

<input type="date" ng-model="valueofdate" />
</code>```

答:
```<code>var app=angular.module('myApp',[]);
        app.controller('myController',function($scope){
              $scope.names = ['1288323623006','1388323623006'];

        });
</code>```

Here Controller name is "myController" and app name is "myApp".

```<code><div ng-app="myApp" ng-controller="myController">
        <ul>
            <li ng-repeat="x in names">
                {{x | date:'mm-dd-yyyy'}}

            </li>

        </ul>
    </div>
</code>```

Result will look like this :-
* 10-29-2010
* 01-03-2013

Title: How to format date in angularjs

Body:
I want to format date as mm/dd/yyyy. I tried the following and none of it works for me.
Can anyone help me with this?

reference: ui-date

<input ui-date ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />

<input type="date" ng-model="valueofdate" />

Body:
var app=angular.module('myApp',[]);
        app.controller('myController',function($scope){
              $scope.names = ['1288323623006','1388323623006'];

        });

Here Controller name is "myController" and app name is "myApp".

<div ng-app="myApp" ng-controller="myController">
        <ul>
            <li ng-repeat="x in names">
                {{x | date:'mm-dd-yyyy'}}

            </li>

        </ul>
    </div>

Result will look like this :-
* 10-29-2010
* 01-03-2013


问:
Deleting rows from multiple data frames with loop in R
I have multiple data frames with the exact same structure.  I'd like to loop through all these data frames and remove rows where the variable "Hat" = D. Below is what I have for a singular instance but would like to write a loop to do this for multiple data frames.   </p>

```<code>final_prices_designations_20161101_20161114.csv <- subset.data.frame(final_prices_designations_20161101_20161114.csv,
    final_prices_designations_20161101_20161114.csv$Hat == "D")
</code>```

答:
```<code>#Install the library 'zonator' for function 'file_path_sans_ext'
install.packages("zonator")
library(zonator)
#Change filesPath with location for your data
filesPath <- "D:/R/Import files/"
#file_path_sans_ext : to read files without extension
files <- file_path_sans_ext(list.files(filesPath))
#loop : I chose a loop to create a physicals tables
for (i in 1:length(files)){
  tempTable=read.csv(paste0(filesPath,files[1],".csv"),sep=';')
  assign(files[i] ,tempTable[tempTable$Hat!='D',])
}
remove(tempTable)# to delete temporary table
</code>```

Body:
I have multiple data frames with the exact same structure.  I'd like to loop through all these data frames and remove rows where the variable "Hat" = D. Below is what I have for a singular instance but would like to write a loop to do this for multiple data frames.

final_prices_designations_20161101_20161114.csv <- subset.data.frame(final_prices_designations_20161101_20161114.csv,
    final_prices_designations_20161101_20161114.csv$Hat == "D")


问:
Angular-Meteor + Ionic: How to decide between Meteor CLI and Ionic CLI?
I'm about to start a project using Meteor, Angular and Ionic as explained in the Angular-Meteor tutorials. However, there are two versions of the tutorial, one using the Meteor CLI and one using the Ionic CLI. I have to decide, which CLI to use for the upcoming project, but could not find information about each's pros and cons. So far, I have worked on the Ionic-CLI tutorial which also seems to be more up-to-date than the other. But I guess, this does not mean this approach is also generally better.

So,

Are there differences between the two CLIs to be considered before a new project?

What are the pros and cons of using the Meteor CLI?

And what are the pros and cons of using the Ionic CLI instead?

Can one say, when to use the one or the other approach or is it just a matter of taste?

答:
that's a very good question.
As always, the answer for your last question is yes - it is a matter of taste, but I will try to expand a bit anyway.

Predicting the future in the Javascript world is very hard or even impossible to do, so I'll just share some thoughts.

All of those CLIs were mocked by the crowd at some point or another, but they all established themselves very well throughout time.

The Meteor CLI is here since 2011, before all of the current tools were even thought about, but through visionary thinking, in 2017, is still relevant, the easiest to use and is making amazing work to keep being up to date with everything that is happening in the Javascript world and innovate on top of it.

At the beginning the Angular CLI started as a very small and weird project (who needs another CLI) but today it is great for the community, it provides great stability and is now a great place to push innovations to the Angular Community (the ABC project, easy SW support, semantics, etc...)

The Ionic CLI, like the Meteor CLI is also trying to help with wrapping Cordova and shipping mobile apps.

Currently, I would recommend to an Angular developer to start with the Angular CLI.  it's just how the Angular community works right now - anything that the Angular team decides to endorse, is becoming the safe standard, whether it's good or not.
That's why I think currently Ionic is a less safe choice, not because their UI or CLI are not good, but because the majority of the community will prefer to use Angular Material and AngularCLI, no matter the actual differences.
I believe that's why Ionic is pushing to become relevant outside of the Angular community, it has become a hard environment to innovate outside of the core team (but I believe the Angular team is working to change that).

But, who knows what will happen in the future?  here are some possibilities:

Meteor is an amazing company, they proved themselves as people who can see the future with a very clear vision.
That's why their Javascript platform vision is still as relevant as ever, that's why they became the industry leader in GraphQL which in my opinion probably the safest choice of tech in your stack going forward.
That means they have the resources and community leadership to keep innovating and making the Meteor CLI even easier and more standard across the whole Javascript community.

I could keep writing so much but I think I should stop.

I would recommend to go with the AngularCLI for now, integrate Apollo and GraphQL as your API layer as much as possible and keep an eye on Meteor, as my answer here will become outdated in 6 months :) as Meteor would release their next versions and Angular would try to go with the ABC project


问:
.htaccess Merge 2 rules into one
I want to merge 2 rules into 1. I want to make sure cause this change will affect around 40 rules.

These are my 2 rules:

```<code>RewriteRule ^award/(\d+)/?$ admin.php?io=award&award=$1 [L]
RewriteRule ^award/add/?$ admin.php?io=award[L]
</code>```

Can i merge them like this:

```<code>RewriteRule ^award/add|(\d+)/?$ admin.php?io=award&award=$1 [L]
</code>```

Is this correct?

答:
You can use:

```<code>RewriteRule ^award/(?:add|(\d+))/?$ admin.php?io=award&award=$1 [L]
</code>```

With an empty parameter award for award/add.

Or:

```<code>RewriteRule ^award/(add|\d+)/?$ admin.php?io=award&award=$1 [L]
</code>```

With award=add for award/add.

Title: .htaccess Merge 2 rules into one

Body:
I want to merge 2 rules into 1. I want to make sure cause this change will affect around 40 rules.

These are my 2 rules:

RewriteRule ^award/(\d+)/?$ admin.php?io=award&award=$1 [L]
RewriteRule ^award/add/?$ admin.php?io=award[L]

Can i merge them like this:

RewriteRule ^award/add|(\d+)/?$ admin.php?io=award&award=$1 [L]

Is this correct?

Body:
You can use:

RewriteRule ^award/(?:add|(\d+))/?$ admin.php?io=award&award=$1 [L]

With an empty parameter award for award/add.

Or:

RewriteRule ^award/(add|\d+)/?$ admin.php?io=award&award=$1 [L]

With award=add for award/add.


问:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero...." using react-native-maps on Android
I get an error:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero. Most likely layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions".

But I set up an alert for getCurrentPosition and I'm receiving coordinates from getCurrentPosition().

import React, { Component } from 'react';
import { View, Dimensions } from 'react-native';
import MapView from 'react-native-maps';

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

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class Map extends Component {

 constructor(props) {
  super(props)

  this.state = {
   isMapReady: false,
   initialPosition: {
    longitude: 0,
    latitude: 0,
    longitudeDelta: 0,
    latitudeDelta: 0
   },

   markerPosition: {
    longitude: 0,
    latitude: 0
   }

  }
 }

 watchID: ?number = null

 componentDidMount() {
  navigator.geolocation.getCurrentPosition((position) => {

   alert(JSON.stringify(position))

   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var initialRegion = {
    latitude: lat,
    longitude: long,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
   }

   this.setState({initialPosition: initialRegion})
   this.setState({markerPosition: initialRegion})
  },

  (error) => alert(JSON.stringify(error)))

  this.watchID = navigator.geolocation.watchPosition((position) => {
   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var lastRegion = {
    latitude: lat,
    longitude: long,
    longitudeDelta: LONGITUDE_DELTA,
    latitudeDelta: LATITUDE_DELTA
   }

   this.setState({initialPosition: lastRegion})
   this.setState({markerPosition: lastRegion})
  })

 }

 componentWillUnmount() {
  navigator.geolocation.clearWatch(this.watchID)
 }

 onMapLayout = () => {
    this.setState({ isMapReady: true });
  }

 render() {

  return (

   <View style={styles.containerStyle}>
    <MapView style={styles.mapStyle} initialRegion={this.state.initialPosition} onLayout={this.onMapLayout}>
     { this.state.isMapReady &&
      <MapView.Marker coordinate={this.state.markerPosition}>
      </MapView.Marker>
     }
    </MapView>
   </View>

   )

 }

}

const styles = {
 containerStyle: {
  flex:1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: 'lightblue'
 },

 mapStyle: {
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  position: 'absolute'
 }

}

export default Map;```

I have no idea what's going wrong to be honest... would really appreciate some help! Thank you!!

答: Change Api Key. That only the reason to show functional map.</p>

Body:
I get an error:
"Error using newLatLngBounds(LatLngBounds, int): Map size can't be zero. Most likely layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions".

But I set up an alert for getCurrentPosition and I'm receiving coordinates from getCurrentPosition().

import React, { Component } from 'react';
import { View, Dimensions } from 'react-native';
import MapView from 'react-native-maps';

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

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class Map extends Component {

 constructor(props) {
  super(props)

  this.state = {
   isMapReady: false,
   initialPosition: {
    longitude: 0,
    latitude: 0,
    longitudeDelta: 0,
    latitudeDelta: 0
   },

   markerPosition: {
    longitude: 0,
    latitude: 0
   }

  }
 }

 watchID: ?number = null

 componentDidMount() {
  navigator.geolocation.getCurrentPosition((position) => {

   alert(JSON.stringify(position))

   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var initialRegion = {
    latitude: lat,
    longitude: long,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
   }

   this.setState({initialPosition: initialRegion})
   this.setState({markerPosition: initialRegion})
  },

  (error) => alert(JSON.stringify(error)))

  this.watchID = navigator.geolocation.watchPosition((position) => {
   var lat = parseFloat(position.coords.latitude)
   var long = parseFloat(position.coords.longitude)

   var lastRegion = {
    latitude: lat,
    longitude: long,
    longitudeDelta: LONGITUDE_DELTA,
    latitudeDelta: LATITUDE_DELTA
   }

   this.setState({initialPosition: lastRegion})
   this.setState({markerPosition: lastRegion})
  })

 }

 componentWillUnmount() {
  navigator.geolocation.clearWatch(this.watchID)
 }

 onMapLayout = () => {
    this.setState({ isMapReady: true });
  }

 render() {

  return (

   <View style={styles.containerStyle}>
    <MapView style={styles.mapStyle} initialRegion={this.state.initialPosition} onLayout={this.onMapLayout}>
     { this.state.isMapReady &&
      <MapView.Marker coordinate={this.state.markerPosition}>
      </MapView.Marker>
     }
    </MapView>
   </View>

   )

 }

}

const styles = {
 containerStyle: {
  flex:1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: 'lightblue'
 },

 mapStyle: {
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  position: 'absolute'
 }

}

export default Map;

I have no idea what's going wrong to be honest... would really appreciate some help! Thank you!!


问:
Linux C Programming - FTP server won't respond through sockets
So I am trying to make my own FTP client, I was able to connect to a ftp server and get the "220" response code but when I try to send ANY command the recv function just gets blocked. This is my code:

I have tried multiple free ftp servers and I was able to connect to all of them and get a 220 response code but from there I couldn't communicate with them at all.

```<code>#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#define ERR(str) {printf("%s errno says: %s\n", str, strerror(errno));}

int getFTPcode(int sock){
    char response[2550];
    if(0 > recv(sock, response, 2550, 0)){
        ERR("ftp response failed to recv");
        return 0;
    }
    printf("%s\n", response);
    while(1){
        char msg[2000];
        printf("Enter command:");
        scanf("%s", msg);
        if(0 > send(sock, msg, strlen(msg), 0)){
            ERR("failed to send to server");
            return 0;
        }

        if(0 > recv(sock, response, 2000, 0)){
            ERR("failed to recv from server");
            return 0;
        }
        printf("Response: %s\n", response);
    }

    printf("%s\n", response);
}

int connToOrig(char* ip, short port){

    struct sockaddr_in addrin;
    memset(&addrin, '0', sizeof(struct sockaddr_in));
    addrin.sin_family = AF_INET;
    addrin.sin_port = htons(port);

    if(inet_pton(AF_INET, ip, &addrin.sin_addr) < 0){
        ERR("inet_pton failed");
        return 0;
    }

    int sock;
    if(0 > (sock = socket(AF_INET, SOCK_STREAM, 0))){
        ERR("socket() failed");
        return 0;
    }

    if(connect(sock, (struct sockaddr*)&addrin, sizeof(addrin)) < 0){
        ERR("connection to the origin server failed");
        return 0;
    }

    printf("connection succesfull\n");
    getFTPcode(sock);
    return 1;
}

int main(int argc, char** argv){

    connToOrig(argv[1], 21);
    return 0;
}
</code>```

答: Well jokes on me, the problem was that I was not appending '\n' to the messages that I was sending to the ftp server</p>

Body:
So I am trying to make my own FTP client, I was able to connect to a ftp server and get the "220" response code but when I try to send ANY command the recv function just gets blocked. This is my code:

I have tried multiple free ftp servers and I was able to connect to all of them and get a 220 response code but from there I couldn't communicate with them at all.

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#define ERR(str) {printf("%s errno says: %s\n", str, strerror(errno));}

int getFTPcode(int sock){
    char response[2550];
    if(0 > recv(sock, response, 2550, 0)){
        ERR("ftp response failed to recv");
        return 0;
    }
    printf("%s\n", response);
    while(1){
        char msg[2000];
        printf("Enter command:");
        scanf("%s", msg);
        if(0 > send(sock, msg, strlen(msg), 0)){
            ERR("failed to send to server");
            return 0;
        }

        if(0 > recv(sock, response, 2000, 0)){
            ERR("failed to recv from server");
            return 0;
        }
        printf("Response: %s\n", response);
    }

    printf("%s\n", response);
}

int connToOrig(char* ip, short port){

    struct sockaddr_in addrin;
    memset(&addrin, '0', sizeof(struct sockaddr_in));
    addrin.sin_family = AF_INET;
    addrin.sin_port = htons(port);

    if(inet_pton(AF_INET, ip, &addrin.sin_addr) < 0){
        ERR("inet_pton failed");
        return 0;
    }

    int sock;
    if(0 > (sock = socket(AF_INET, SOCK_STREAM, 0))){
        ERR("socket() failed");
        return 0;
    }

    if(connect(sock, (struct sockaddr*)&addrin, sizeof(addrin)) < 0){
        ERR("connection to the origin server failed");
        return 0;
    }

    printf("connection succesfull\n");
    getFTPcode(sock);
    return 1;
}

int main(int argc, char** argv){

    connToOrig(argv[1], 21);
    return 0;
}


问:
Unpacking values from list in Python 2.7
Python Newbie here:
Given a list and a value, how can I unpack the list into separate objects and prepend a value.  Length of the array isn't known, unlike in code below:

```<code>x = [1,2,3,4]
y = 0,x
y
</code>```

Current Output:

```<code>(0, [1, 2, 3, 4])
</code>```

Desired Output:

```<code>(0, 1, 2, 3, 4)
</code>```

I know it can be done easily in Python 3 using y = 0,*x but how can it be done in Python 2.7?

Thanks

答:
You could do it with parameter unpacking.

```<code>>>> (lambda *a: a)(0, *x)
(0, 1, 2, 3, 4)
</code>```

But don't.

Body:
Python Newbie here:
Given a list and a value, how can I unpack the list into separate objects and prepend a value.  Length of the array isn't known, unlike in code below:

x = [1,2,3,4]
y = 0,x
y

Current Output:

(0, [1, 2, 3, 4])

Desired Output:

(0, 1, 2, 3, 4)

I know it can be done easily in Python 3 using y = 0,*x but how can it be done in Python 2.7?

Thanks

Body:
You could do it with parameter unpacking.

>>> (lambda *a: a)(0, *x)
(0, 1, 2, 3, 4)

But don't.


问:
Returning Wingdings characters within a text with an Excel formula
I want return appropriated Wingdings character at end of a string, with a formula as shown below:

enter image description here

Which formula can I write to return the shown Wingdings characters at the end of the regular string in a cell? (Instead of "?" character): Solid circle character for return in true situation of formula and hollow circle character return in false situation, so these two characters are in green range.

答:
You can get a fair approximation to it by using char(149) •
 / lower case o in one of the regular fonts</p>

```<code>=IF(VALUE(RIGHT(C4,1))>=5,"Selected "&CHAR(149),"Selected o")
</code>```

Body:
You can get a fair approximation to it by using char(149) •
 / lower case o in one of the regular fonts

=IF(VALUE(RIGHT(C4,1))>=5,"Selected "&CHAR(149),"Selected o")


问:
Add separator to string at every N characters?
I have a string which contains binary digits. How to separate string after each 8 digit?

Suppose the string is:

```<code>string x = "111111110000000011111111000000001111111100000000";
</code>```

I want to add a separator like ,(comma) after each 8 character.

output should be :

```<code>"11111111,00000000,11111111,00000000,11111111,00000000,"
</code>```

Then I want to send it to a list<>  last 8 char 1st then the previous 8 chars(excepting ,) and so on.

How can I do this?

答:
I am more than late with my answer but you can use this one:</p>

```<code>    static string PutLineBreak(string str, int split)
    {
        for (int a = 1; a <= str.Length; a++)
        {
            if (a % split == 0)
                str = str.Insert(a, "\n");
        }

        return str;
    }
</code>```

Body:
I have a string which contains binary digits. How to separate string after each 8 digit?

Suppose the string is:

string x = "111111110000000011111111000000001111111100000000";

I want to add a separator like ,(comma) after each 8 character.

output should be :

"11111111,00000000,11111111,00000000,11111111,00000000,"

Then I want to send it to a list<>  last 8 char 1st then the previous 8 chars(excepting ,) and so on.

How can I do this?

Body:
I am more than late with my answer but you can use this one:

    static string PutLineBreak(string str, int split)
    {
        for (int a = 1; a <= str.Length; a++)
        {
            if (a % split == 0)
                str = str.Insert(a, "\n");
        }

        return str;
    }


问:
Why do I segfault?
Here is my code, I'm getting a segmentation fault and I don't know why...
I'm creating a grid which n is its size, tab is an array which his type is cellule : a cell has 2 values. So I'm creating in the function creer_grille an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the creer_grille function.

```<code>typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}
</code>```

答:
```<code>g->n = n;
</code>```

This is accessing an uninitalized value - invoking Undefined Behavior in your code. Move the line to after you allocate using malloc.

Also g = malloc(sizeof(int) * (n*n)); is wrong you don't want grille* to point to a chunk which is allocated for int's. because in case there is not enough memory there will be undefined behavior acessing memory out of your allocation.

```<code>g = malloc(sizeof(*g) * (n));
</code>```

As you have allocated the n*n locations for storing grille you should access them by indexing

```<code>      for (i = 0; i < n; i++)
      {
        // for some x
        g[i].tab[x].val = -1;
        g[i].tab[x].initial = 0;
      }
</code>```

Again g->tab[i].val = -1; this is wrong because of the same reason pointed earlier. You have to allocate memory to g[i].tab. Otherwise it's undefined behavior. You have to allocate memory for g[i].tab.

```<code>   g[i].tab = malloc(sizeof *g[i].tab * someSize);
</code>```

Also there is a flaw in your logic. First of all allocating nxn memory doesn't mean you have nxn grid. The method you followed will give you a contiguous chunk of nxn elements and that will not be of that use. (You can make a use of it but that's an overkill).

The best thing you can do is a jagged array and it's example is shown here.

Example code:-

```<code>grille  *creer_grille(int n)
{
  grille *g;

  g = malloc(sizeof *g * n);
  if( g == NULL){
    fprintf(stderr,"%s\n","Error in malloc");
    exit(1);
  }

  for (size_t i = 0; i < n; i++)
  {
    g[i].tab = malloc(sizeof *g[i].tab * n);
    if( g[i].tab == NULL){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }
    g[i].n   = n;
    for(size_t j = 0; j < n; j++){
        g[i].tab[j].val = -1;
        g[i].tab[j].initial = 0;
    }
  }
  return g;
}
</code>```

You have to free the dynamically allocated memory after you are done working with it. The free logic would be something like - you will first free the memory allocated in tab and then after all of those memory is freed, you will free memory allocated in g.

Title: Why do I segfault?

Body:
Here is my code, I'm getting a segmentation fault and I don't know why...
I'm creating a grid which n is its size, tab is an array which his type is cellule : a cell has 2 values. So I'm creating in the function creer_grille an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the creer_grille function.

typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}

Body:
g->n = n;

This is accessing an uninitalized value - invoking Undefined Behavior in your code. Move the line to after you allocate using malloc.

Also g = malloc(sizeof(int) * (n*n)); is wrong you don't want grille* to point to a chunk which is allocated for int's. because in case there is not enough memory there will be undefined behavior acessing memory out of your allocation.

g = malloc(sizeof(*g) * (n));

As you have allocated the n*n locations for storing grille you should access them by indexing

      for (i = 0; i < n; i++)
      {
        // for some x
        g[i].tab[x].val = -1;
        g[i].tab[x].initial = 0;
      }

Again g->tab[i].val = -1; this is wrong because of the same reason pointed earlier. You have to allocate memory to g[i].tab. Otherwise it's undefined behavior. You have to allocate memory for g[i].tab.

   g[i].tab = malloc(sizeof *g[i].tab * someSize);

Also there is a flaw in your logic. First of all allocating nxn memory doesn't mean you have nxn grid. The method you followed will give you a contiguous chunk of nxn elements and that will not be of that use. (You can make a use of it but that's an overkill).

The best thing you can do is a jagged array and it's example is shown here.

Example code:-

grille  *creer_grille(int n)
{
  grille *g;

  g = malloc(sizeof *g * n);
  if( g == NULL){
    fprintf(stderr,"%s\n","Error in malloc");
    exit(1);
  }

  for (size_t i = 0; i < n; i++)
  {
    g[i].tab = malloc(sizeof *g[i].tab * n);
    if( g[i].tab == NULL){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }
    g[i].n   = n;
    for(size_t j = 0; j < n; j++){
        g[i].tab[j].val = -1;
        g[i].tab[j].initial = 0;
    }
  }
  return g;
}

You have to free the dynamically allocated memory after you are done working with it. The free logic would be something like - you will first free the memory allocated in tab and then after all of those memory is freed, you will free memory allocated in g.


问:
Validate DateTimeOffset and TimeSpan using Attribute Validators in ASP.NET MVC
So I've got entities set up with Entity Framework that have some properties of types String, DateTimeOffset and TimeSpan. For performing validation on the Strings, I've used fairly straightforward attributes like "[Required]" or "[StringLength]", and the control used is a textbox.

My issue now is for the DateTimeOffset and TimeSpan, I'm uncertain what control to use, but even more uncertain about what attributes to use to validate the input.

Any suggestions?

答: I don't believe there is a way to infer the data type from input. Treating it as needed by business logic seems to be the only path.</p>


问:
Creating account.move by code - Odoo v8
I'm new into the account.account model of Odoo.

I wonder, is there some example on how to create an account.move on Odoo v8? (New API)

For example, suppose I have these models:

```<code>class model1(models.Model):

    field1 = fields.Float(string="Field 3")
    field2 = fields.Float(string="Field 3")
    field3 = fields.Float(string="Field 3", compute="compute")
    partner_journal = fields.Many2one('account.account', string="Journal")
    state = fields.Selection([
        ('draft','Draft'),
        ('awaitingraw','Awaiting raw materials'),
        ('work_in_progress','Print in Progress'),
        ('delivered','Delivered'),
        ('cancel','Cancel'),
    ], string="State")
    csheet = fields.One2many('model2', 'sheets', string="Sheets")

    @api.depends('field1','field2','field3')
    def compute(self):
        if self.field1 or self.field2:
            self.field3 = self.field1 + self.field2

class model2(models.Model):

    field4 = fields.Float(string="Field 4")
    field5 = fields.Float(string="Field 5")
    field6 = fields.Float(string="Field 6")
    sheets = fields.Many2one('model1', string="Sheets")
</code>```

From model2 I need to create an account.move into a journal, let's say, I need field3 should be the credit on whatever journal is selected on partner_journal field.

I've tried something like this:

```<code>@api.multi
@api.depends('field1', 'field2', 'field3', 'state', 'csheet')
def accounting_scenarios(self):
    for record in self:
        if not len(record.partner_journal):
            raise Warning('Please Enter Journal !')
        if record.state in ('awaitingraw'):
            record.partner_journal.debit = record.csheets.field4
</code>```

But, it obviously doesn't works, because we need to create an account.move and with this method, what I was trying was to write directly on partner_journal on debit field, the field4 quantity.

So, I'll need to create an account.move to make it work.

Any example or ideas?

答:
What you asking is not that easy you need to learn accounting module of Odoo and how Odoo handle accounting.

So first of all i recommend you to read Book "Working with Odoo" there is a small chapter that will give you a very good idea about account module.

Than see the codes in Odoo modules Ex: when you confirm a sale.order and how Odoo create a account.move that contains two move.line.

You will understand what is account.account and account.move and account.move.line , journal entry.

But the general idea : you need to create an acount.move and his account.move.line.

In account.move you need to specify what journal this transation are related to and some other useful information.
   In account.move.line this where you define all data related to the transaction. currency, partner(if There is one), account, debit and credit.

Same example Odoo 8.0:

      # List of move.line
      move_lines = [
                    (0, 0, {
                        'name': libelle, # a label so accountant can understand where this line come from
                        'debit': self_debit, # amount of debit
                        'credit': self_credit, # amount of credit
                        'account_id': account_id, # account
                        'date': date,
                        'partner_id': partner_id, # partner if there is one
                        'currency_id': currency_id or (account.currency_id.id or False),
                    }),
                    (0, 0, {
                        'name': libelle,
                        'debit': debit,
                        'credit': credit,
                        'account_id': writeoff_acc_id,
                        'analytic_account_id': context.get('analytic_id', False),
                        'date': date,
                        'partner_id': partner_id,
                        'currency_id': currency_id or (account.currency_id.id or False),
                    })
                ]

        # Create account move
        self.pool.get('account.move').create(cr, uid, {
                        'period_id': period_id, #Fiscal period
                        'journal_id': journal_id, # journal ex: sale journal, cash journal, bank journal....
                        'date':date,
                        'state': 'draft',
                        'line_id': move_lines, # this is one2many field to account.move.line
                    })
```

Title: Creating account.move by code - Odoo v8

Body:
I'm new into the account.account model of Odoo.

I wonder, is there some example on how to create an account.move on Odoo v8? (New API)

For example, suppose I have these models:

class model1(models.Model):

    field1 = fields.Float(string="Field 3")
    field2 = fields.Float(string="Field 3")
    field3 = fields.Float(string="Field 3", compute="compute")
    partner_journal = fields.Many2one('account.account', string="Journal")
    state = fields.Selection([
        ('draft','Draft'),
        ('awaitingraw','Awaiting raw materials'),
        ('work_in_progress','Print in Progress'),
        ('delivered','Delivered'),
        ('cancel','Cancel'),
    ], string="State")
    csheet = fields.One2many('model2', 'sheets', string="Sheets")

    @api.depends('field1','field2','field3')
    def compute(self):
        if self.field1 or self.field2:
            self.field3 = self.field1 + self.field2

class model2(models.Model):

    field4 = fields.Float(string="Field 4")
    field5 = fields.Float(string="Field 5")
    field6 = fields.Float(string="Field 6")
    sheets = fields.Many2one('model1', string="Sheets")

From model2 I need to create an account.move into a journal, let's say, I need field3 should be the credit on whatever journal is selected on partner_journal field.

I've tried something like this:

@api.multi
@api.depends('field1', 'field2', 'field3', 'state', 'csheet')
def accounting_scenarios(self):
    for record in self:
        if not len(record.partner_journal):
            raise Warning('Please Enter Journal !')
        if record.state in ('awaitingraw'):
            record.partner_journal.debit = record.csheets.field4

But, it obviously doesn't works, because we need to create an account.move and with this method, what I was trying was to write directly on partner_journal on debit field, the field4 quantity.

So, I'll need to create an account.move to make it work.

Any example or ideas?


问:
Responsive 3 columns using table-cell doesn't work for me
I have this CSS Code

```<code>#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display:table;
}

#sidebar {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

#content {
    overflow: hidden;
    display:table-cell;
}

#sidecontent {
    width:250px;
    vertical-align:top;
    display:table-cell;
}
</code>```

and the HTML Code looks like this

```<code><div id="wrapper>
     <div id="sidebar">
          sidebar
     </div> <!-- sidebar -->
     <div id="content">
          content
     </div> <!-- content -->
     <div id="sidecontent">
          sidecontent
     </div> <!-- sidecontent -->
</div> <!-- wrapper -->
</code>```

in desktop resolution does 3 columns

```<code>[sidebar-fixed][content-fluid][sidecontent-fixed]
</code>```

i think i tried everything to make it look like this in laptop/mobile resolution

```<code>[sidebar-fixed][content-fluid]
[----- sidecontent-fluid ----]
</code>```

i don't know what do to next, please help.

答:
Why not using flex grid?</p>

```<code>#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display: flex;
    flex-direction: row;
}

#sidebar {
    flex-basis: 250px;
}

#content {
    overflow: hidden;
    flex: 1;
}

#sidecontent {
    flex-basis: 250px;
}
</code>```

Body:
I have this CSS Code

#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display:table;
}

#sidebar {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

#content {
    overflow: hidden;
    display:table-cell;
}

#sidecontent {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

and the HTML Code looks like this

          sidebar

          content

          sidecontent

in desktop resolution does 3 columns

[sidebar-fixed][content-fluid][sidecontent-fixed]

i think i tried everything to make it look like this in laptop/mobile resolution

[sidebar-fixed][content-fluid]
[----- sidecontent-fluid ----]

i don't know what do to next, please help.

Body:
Why not using flex grid?

#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display: flex;
    flex-direction: row;
}

#sidebar {
    flex-basis: 250px;
}

#content {
    overflow: hidden;
    flex: 1;
}

#sidecontent {
    flex-basis: 250px;
}


问:
Where can I log an ASP.NET Core app's start/stop/error events?
In old ASP.NET, in the Global.asax.cs class, I would log when the app starts, stops and throws unhandled exceptions:

Application_Start()

Application_End()

Application_Error()

How do I do the same in ASP.NET Core? It has a Startup class, but it is for configuration.

Where do I hook into the app's start/stop/error events?

答:
Please see CaptureStartupErrors and the method .CaptureStartupErrors(true) that will help you find issues.

This is especially handy when something runs perfect on localhost but fails in Azure.

Here is my usual config for NetCore Web Apps:

```<code>public static IWebHost BuildWebHost(string[] args) => WebHost
            .CreateDefaultBuilder(args)
            .CaptureStartupErrors(true)
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseAzureAppServices()
            .Build();
</code>```

In Azure App Service you can then find the logs in the log stream in Kudu Tools https://<appname>.scm.azurewebsites.net/api/logstream

Body:
Please see CaptureStartupErrors and the method .CaptureStartupErrors(true) that will help you find issues.

This is especially handy when something runs perfect on localhost but fails in Azure.

Here is my usual config for NetCore Web Apps:

public static IWebHost BuildWebHost(string[] args) => WebHost
            .CreateDefaultBuilder(args)
            .CaptureStartupErrors(true)
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseAzureAppServices()
            .Build();

In Azure App Service you can then find the logs in the log stream in Kudu Tools https://<appname>.scm.azurewebsites.net/api/logstream


问:
Docker_Host on Jenkins with mvn fabric8:build
I am trying to setup Jenkins build for my simple java microservice with Kubernetes cluster.

mvn clean package fabric8:build

I've defined DOCKER_HOST environment variable within Jenkins
DOCKER_HOST=tcp://192.168.20.1:2375

My build fails with the following error after successfully building the fat JAR

[ERROR] Failed to execute goal io.fabric8:fabric8-maven-plugin:3.5.31:build (default-cli) on project echo: Cannot create docker access object: Cannot extract API version from server http://192.168.20.1:2375 : No route to host -> [Help 1]

My Docker host runs on linux. I changed the daemon.json to add the following and restarted docker host

{
  "ipv6": false ,
  "live-restore": true,

  "hosts" : ["tcp://192.168.20.1:2375"]
}

Still the issue persists:

Couple of questions:

Why is fabric8 resolving tcp to http? Pls looks at the error message.

What else needs to be done on Docker host to serve requests on tcp://192.168.20.1:2375?

TIA

答:
This is purely a Docker host setup issue.
To access Docker daemon remotely, tcp socket should be enabled. More details here: https://docs.docker.com/engine/reference/commandline/dockerd/#examples

Based on our setup, I had edited the /etc/docker/daemon.json to add the "hosts" parameter

{
  "ipv6": false ,
  "live-restore": true,
  "hosts" : ["tcp://192.168.20.1:2375"]
}

Restart docker daemon using the command
systemctl restart docker.service

Make sure docker daemon is listening to port 2375
netstat -tunlp | grep 2375
tcp        0      0 192.168.20.1:2375      0.0.0.0:*               LISTEN      14648/dockerd

If after doing the above if you are still not able to access Docker daemon remotely, check if there are any firewalls that are blocking the external requests.

You can either stop them or set up a rule to allow the traffic based on your configuration.

Hope this helps


问:
Wrapping a DOM element inside a JavaScript object
I've noticed a common pattern in the JavaScript I've been writing and was wondering if there is already a pattern out there that defines something similar as best practice? Essentially, it's how to get a DOM element and wrap it inside / associate it with a JavaScript object. Take this example, where you need a filter in your web app. Your page looks like this:

```<code><html>
<head></head>
<body>
    <div id="filter"></div>
</body>
</html>
</code>```

You'd then wrap the element like so:

```<code>var myFilter = new Filter({
    elem: document.getElementById('filter'),
    prop: 'stacks-test',
    someCallback: function() {
        // specify a callback
    }
});
</code>```

And the JavaScript (where spec is an object passed to the constructor):

```<code>var Filter = function(spec) {
    this.elem = spec.elem;
    this.prop = spec.prop;
    this.callback = spec.someCallback;
    this.bindEvents();
};

Filter.prototype.bindEvents = function() {
    var self = this;
    $(this.elem).click(function(e) {
        self.updateFeed();
    };
};

Filter.prototype.updateFeed = function() {
    this.prop; // 'stacks-test'
    this.callback();
    // ...
    // code to interact with other JavaScript objects
    // who in turn, update the document
};
</code>```

What is this kind of approach called, and what are the best practices and caveats?

答:
You might be interested in Dojo's widget library, Dijit - if I'm understanding your question correctly, it essentially does what you're asking, and a whole lot more.

In Dijit, a widget essentially encapsulates a DOM node, its contents, any JavaScript that defines its behavior, and (imported separately) CSS to style its appearance.

Widgets have their own lifecycle, registry, and events (including many which simply map to DOM events on a node within the widget, e.g. myWidget.onClick could effectively call myWidget.domNode.onclick).

Widgets can (but don't have to) have their initial contents defined in a separate HTML template file, through which it's also possible to bind events on nodes within the template to widget methods, as well as set properties on the widget that reference particular nodes in the template.

I'm barely scratching the surface here.  If you want to read more on this, you can start with these reference pages:

http://dojotoolkit.org/reference-guide/dijit/info.html

http://dojotoolkit.org/reference-guide/dijit/_Widget.html (the base that all widgets extend)

http://dojotoolkit.org/reference-guide/dijit/_Templated.html (RE the HTML templating)

http://dojotoolkit.org/reference-guide/quickstart/writingWidgets.html (useful information when starting to write your own widgets)

http://dojotoolkit.org/reference-guide/dijit/ (for a bunch more info)

All said, I don't know what you're ultimately aiming for, and maybe this is all a bit much for your purposes (considering I'm throwing an entire other library at you), but figured it might pique your interest at least.

Body:
I've noticed a common pattern in the JavaScript I've been writing and was wondering if there is already a pattern out there that defines something similar as best practice? Essentially, it's how to get a DOM element and wrap it inside / associate it with a JavaScript object. Take this example, where you need a filter in your web app. Your page looks like this:

You'd then wrap the element like so:

var myFilter = new Filter({
    elem: document.getElementById('filter'),
    prop: 'stacks-test',
    someCallback: function() {
        // specify a callback
    }
});

And the JavaScript (where spec is an object passed to the constructor):

var Filter = function(spec) {
    this.elem = spec.elem;
    this.prop = spec.prop;
    this.callback = spec.someCallback;
    this.bindEvents();
};

Filter.prototype.bindEvents = function() {
    var self = this;
    $(this.elem).click(function(e) {
        self.updateFeed();
    };
};

Filter.prototype.updateFeed = function() {
    this.prop; // 'stacks-test'
    this.callback();
    // ...
    // code to interact with other JavaScript objects
    // who in turn, update the document
};

What is this kind of approach called, and what are the best practices and caveats?


问:
How do I use Unicode to line up latin chord names over right-to-left text?
I would like to display some chords over some lyrics in Arabic. In English, I am using a commonly-used system of using a monospaced font, and using spaces to line up the chords, like this:

```<code> G    C      D
 From all my heart
</code>```

In Arabic, there are difficulties doing this, because the Arabic is right-to-left, but the chords are left-to-right. This is the result that I'm looking for, in an image:

What's more, I would like the user to be able to type out the chords and lyrics in logical order. The user should type the G first, followed by the C, then by the D. I'm OK with using special Unicode characters, but not with changing logical order.

I've tried this:

  G
  C
  D

من كل قلبي

```

(I've taken advantage of HTML treating newlines as a space in this example, to make it obvious in what order the chords are.)

As you can see when you run the snippet, the chords, typed in logical order, show up in the wrong order. The Unicode algorithm recognises that these are left-to-right words separated by spaces, and so displays them left-to-right, even though the overall context is right-to-left. Is there any way I can turn off this behaviour in Unicode?

答:
Let's try using U+202B RIGHT-TO-LEFT EMBEDDING, terminating the block using U+202C POP DIRECTIONAL FORMATTING:

  G
  C
  D

من كل قلبي

```
</div>
</div>
</p>

<p>Nope, this doesn't work. U+202B only affects <em>weak</em> characters, characters like <code>!</code> and <code>.</code> that don't have inherit directionality. The characters <code>G</code>, <code>C</code> and <code>D</code> have inherit left-to-right directionality, and so they aren't affected.</p>

<p>OK, then, let's try using U+202E RIGHT-TO-LEFT OVERRIDE instead, terminating the block using U+202C again:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div dir="rtl" style="font-family: monospace">

  G
  C
  D

  <br>
من كل قلبي
</div></code>```

Woohoo! This at last works, giving a result like the one in the image of the question. Unfortunately, it doesn't quite work, as it forces characters within the same word to go right-to-left, which is a problem for minor chords:

  Gm
  Cm
  Dm

من كل قلبي

```
</div>
</div>
</p>

<p>To get around this, you need to use U+202D LEFT-TO-RIGHT OVERRIDE, in addition, ending up with code like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div dir="rtl" style="font-family: monospace">

  Gm
  Cm
  Dm

  <br>
من كل قلبي
</div></code>```

Body:
I would like to display some chords over some lyrics in Arabic. In English, I am using a commonly-used system of using a monospaced font, and using spaces to line up the chords, like this:

 G    C      D
 From all my heart

In Arabic, there are difficulties doing this, because the Arabic is right-to-left, but the chords are left-to-right. This is the result that I'm looking for, in an image:

What's more, I would like the user to be able to type out the chords and lyrics in logical order. The user should type the G first, followed by the C, then by the D. I'm OK with using special Unicode characters, but not with changing logical order.

I've tried this:

  G
  C
  D

من كل قلبي

(I've taken advantage of HTML treating newlines as a space in this example, to make it obvious in what order the chords are.)

As you can see when you run the snippet, the chords, typed in logical order, show up in the wrong order. The Unicode algorithm recognises that these are left-to-right words separated by spaces, and so displays them left-to-right, even though the overall context is right-to-left. Is there any way I can turn off this behaviour in Unicode?

Body:
Let's try using U+202B RIGHT-TO-LEFT EMBEDDING, terminating the block using U+202C POP DIRECTIONAL FORMATTING:

<div dir="rtl" style="font-family: monospace">
  &#x202B;
  G
  C
  D
  &#x202C;
  <br>
من كل قلبي
</div>

Nope, this doesn't work. U+202B only affects weak characters, characters like ! and . that don't have inherit directionality. The characters G, C and D have inherit left-to-right directionality, and so they aren't affected.

OK, then, let's try using U+202E RIGHT-TO-LEFT OVERRIDE instead, terminating the block using U+202C again:

<div dir="rtl" style="font-family: monospace">
  &#x202E;
  G
  C
  D
  &#x202C;
  <br>
من كل قلبي
</div>

Woohoo! This at last works, giving a result like the one in the image of the question. Unfortunately, it doesn't quite work, as it forces characters within the same word to go right-to-left, which is a problem for minor chords:

<div dir="rtl" style="font-family: monospace">
  &#x202E;
  Gm
  Cm
  Dm
  &#x202C;
  <br>
من كل قلبي
</div>

To get around this, you need to use U+202D LEFT-TO-RIGHT OVERRIDE, in addition, ending up with code like this:

<div dir="rtl" style="font-family: monospace">
  &#x202E;
  &#x202D;Gm&#x202C;
  &#x202D;Cm&#x202C;
  &#x202D;Dm&#x202C;
  &#x202C;
  <br>
من كل قلبي
</div>


问:
.NET datetime Millisecond precision issue when converting from string to datetime

Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

```<code>string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }
</code>```

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?

答: According to Custom Date and Time Format Strings docs, 7 is maximum supported digits of second fraction.</p>

Body:
Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?